Repository navigation
SDPA: attend packed rows per segment instead of under a dense mask (2.9x less memory, 2.5x faster without flash-attn / xformers) - #12740
Conversation
…iagonal mask Without flash-attn or xformers, padding-free / packed batches went through SDPA with a dense (T, T) mask. A mask rules out the flash kernel and, with enable_gqa, also the memory-efficient one, so the math kernel held every (T, T) score: 1 GiB per layer for a 2 x 2048 Qwen3 batch. Each segment now runs its own causal SDPA call (equal-length runs batched), with a per-segment window mask only where a segment is longer than the sliding window. UNSLOTH_SDPA_PACKED_SEGMENTS=0 restores the dense-mask path.
Codex Review SummaryThis 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 |
|
@codex security review |
|
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". |
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
…2761) #12740 added test_peak_memory_is_linear_in_tokens behind skipif(not torch.cuda.is_available()). tests/_zoo_aggressive_cuda_spoof.py patches that probe to True process-wide, so on a CPU runner sharing a session with the compat suites the test un-skips and allocates on cuda. test_accelerator_skip_guards catches exactly this and is red on main. Use has_real_cuda() like the sibling utils tests.
…#13265) - test_varlen_int32_overflow_guard: since #12740 SDPA attends packed rows one segment length at a time, so the guarded fallback is two SDPA calls (the one-token documents and the padded tail). Assert that only SDPA ran. - compare_installer_evidence: drop a full winget download bar that repeats the line right before it. A staging run of the same uv download left it once on one side and twice on the other. - test_studio_api test_help_output: render help at 200 columns. At Rich's 80-column default the option cell is cut to --max-seq-lengt...
|
This breaks QLoRA training on an RX 9060 XT (gfx1200, Linux, torch 2.11.0+rocm7.14.0). Bisect in #18403: the parent commit trains, this one fails at the first step with |
…heck out of Unsloth's attention (unslothai#18453) Addresses unslothai#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. With `AMD_SERIALIZE_KERNEL=3` the first failure is `hipErrorInvalidValue` from `F.scaled_dot_product_attention` in `_sdpa_packed_segments`. 2026.9.7 trains on the same machine. The reporters bisected it to unslothai#12740 and unslothai#14158. ## Root cause `unsloth/__init__.py:29` sets `TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1` (since unslothai#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 with `enable_gqa=True`, and only math accepts that combination. - **unslothai#12740** (`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. - **unslothai#14158** (`e6c95c292b`, 2026.10.7) expands K/V whenever `enable_gqa` would leave only math (`_sdpa_gqa_state_now`, `attention_dispatch.py:907`, used by the dense path at `:2133` and by the segment runs). On ROCm that sends masked calls to the AOTriton memory-efficient kernel. This is why `UNSLOTH_SDPA_PACKED_SEGMENTS=0` stopped 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](pytorch/pytorch#201476) (gfx1201 memory-efficient SDPA wrong in fp32), [ROCm/TheRock#10001](ROCm/TheRock#10001) (gfx120X memory-efficient grads fail tolerance), and [ROCm/TheRock#10054](ROCm/TheRock#10054) (gfx1201 FLASH and EFFICIENT fail with `hipErrorInvalidImage`). ## Fix The new `unsloth/utils/rocm_sdpa_check.py` checks each AOTriton backend once per GPU: - **Isolation.** The check runs in a child process with `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. - **Shapes.** The child sends the GQA shapes Unsloth uses: per-segment strided views, expanded K/V, `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. - **Comparison.** Forward and backward are checked against an fp32 reference, with the same tolerance as the unslothai#18313 varlen self-check. - **Failure.** A backend fails if it errors, faults, hangs or disagrees with the reference. A failed backend is left out of every SDPA call in `attention_dispatch` on that GPU: packed segments, the dense path, decode, and the GQA probe that picks between `enable_gqa` and expanded K/V. The remaining backends run, down to math, which is what 2026.9.7 used. - **Output.** When a backend fails, a one-line message names the arch and the failing case. Scope: - CDNA (gfx9xx) is AOTriton's release target and skips the check. - CUDA builds are unchanged: the guard is a module constant that is False there. - If a caller has enabled only refused kernels (`sdpa_kernel([FLASH])`), its own policy is kept. - `UNSLOTH_ROCM_SDPA_CHECK=0` skips the check and trusts torch, which is the current behaviour. - `rocm_sdpa_verdict(device_index)` is exported from `attention_dispatch` so users can see what the check decided. ## Evidence **Flip test.** `tests/utils/test_rocm_sdpa_check.py` fakes ROCm on CPU tensors. | tree | result | |---|---| | main (55ef8bd) | 6 failed: packed segments x3, dense masked, decode, GQA probe all still run with the refused kernels enabled | | this branch | 14 passed | **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: - Scaling the kernel output by 1.05 fails every case, at 2.5x the bound. - A child that exits without a result refuses both backends. **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. - **main:** trains, with or without `AMD_SERIALIZE_KERNEL=3`. - **this branch:** the check passes both backends, so routing and losses are identical to main (AOTriton flash, same six losses). - **this branch, check forced to fail:** every attention call goes to math. Logits match a math-only forward and training stays finite. 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 - On import plus the first attention call, look for the line `Unsloth: ROCm gfx1200 0: AOTriton ... attention failed a self-check`. - Check `from unsloth.utils.attention_dispatch import rocm_sdpa_verdict; print(rocm_sdpa_verdict(0))` after loading a model. - If the check passes and training still faults, please report the verdict. It means the failure needs a shape the check does not cover. ## Not covered - **gfx1200 itself.** No such card is reachable here. - **The HF attention path.** Models that do not go through `attention_dispatch` (`hf_packed_attention`, transformers' own sdpa integration) keep the current behaviour. - **Memory.** When both AOTriton backends are refused, attention runs on math. That costs (H, L, L) scores per segment, which is less than the dense (T, T) mask 2026.9.7 used, but more than the fused kernels.
Problem
Without flash-attn or xformers (the usual Colab / Kaggle install today: torch 2.11, no xformers wheel), every padding-free or packed SFT batch goes through the SDPA branch of
run_attention, which builds a dense(T, T)block-diagonal mask (build_sdpa_packed_attention_mask) and calls SDPA with it. A mask rules out the flash kernel, and together withenable_gqait also rules out the memory-efficient kernel, so the math kernel runs and keeps every(T, T)score. SFT turns padding-free on by default, so this is the default path for those users.Qwen3-0.6B,
per_device_train_batch_size = 2, 2048 tokens (one packed row of 4096 tokens, 16 query / 8 KV heads): a memory trace at the step peak shows 1 GiB blocks fromrun_attentionplus 3.1 GiB of their gradients in the checkpoint backward, against 8 MiB for the cross-entropy loss. The int32-overflow fallback (huge packed batches rerouted from flash / xformers to SDPA) lands on the same path.Fix
is_causal(or bidirectional) and no mask, so the flash or memory-efficient kernel runs and memory stays linear in tokens. Consecutive equal-length segments share one batched call. The TRL pad tail keeps its own segment, as in the dense mask.enable_gqaonly where the flash kernel can take it (CUDA sm80+, fp16 / bf16, head_dim <= 256 and a multiple of 8); elsewhere (T4, fp32, ROCm) K / V are expanded so the memory-efficient kernel stays available.packed_block_mask, shared with the dense builder so both paths mask identically).UNSLOTH_SDPA_PACKED_SEGMENTS=0restores the dense-mask path. Rows whose lengths do not tile the row, batched rows, and rows with a padding mask keep the existing path.Results
B200, xformers hidden
Qwen3-0.6B LoRA,
per_device_train_batch_size = 2,gradient_accumulation_steps = 3, 2048-token rows, 15 steps, B200, flash-attn / xformers hidden for the SDPA rows:The xformers rows are unchanged code (that path is untouched); their spread is run-to-run noise on a shared GPU. Graph breaks 0 and recompiles 0 in every run.
Colab (real install without flash-attn / xformers: torch 2.11, transformers 5.17, TRL 1.13)
Same install, dense-mask path (
UNSLOTH_SDPA_PACKED_SEGMENTS=0) vs this PR, LoRA r=16,per_device_train_batch_size = 2,gradient_accumulation_steps = 3, 2048-token rows, median step over steps 12-61:Graph breaks 0 and recompiles 0 in every run. The T4 row runs the expanded K/V path (no flash kernel on sm75).
Tests
tests/utils/test_sdpa_packed_segments.py: per-segment output and Q / K / V gradients match the dense-mask path on CPU fp32 and CUDA bf16 / fp16, for MHA and GQA, causal and bidirectional, sliding windows shorter and longer than a segment, equal-length runs, single segments and a pad tail; the per-segment path never builds the dense mask; peak memory for 2 x 2048 tokens with 16 / 8 heads stays under 256 MiB (the dense path needs over 1 GiB).tests/utils/test_packing.py::test_packing_sdpanow checks the SDPA packed path receives the packed segment lengths;tests/utils/test_attention_masks.py::test_run_attention_sdpa_passes_sliding_windowpins the dense path with the switch off.test_segments_never_build_the_dense_mask,test_peak_memory_is_linear_in_tokens,test_packing_sdpa).tests/utils/test_attention_masks.py,test_attention_dispatch_bidirectional.py,test_attention_dispatch_dora_dtype.py,test_packing.py, new file: 129 passed, 1 skipped.