Repository navigation
Attention: GQA never forces SDPA math, cuDNN-over-varlen on sm100 only, native before xformers - #14158
Conversation
…y, native before xformers - enable_gqa is passed only when SDPA's chosen kernel takes it. The memory-efficient kernel does not, so fp32 (DoRA), pre-sm80 GPUs and masked calls flash cannot run fell to the math kernel: 3x slower and 4.3x the memory on a T4 (10.7 vs 2.5 GB). K/V are expanded there instead, decided by asking torch._fused_sdp_choice (ROCm included). The packed-segment windowed runs get the same rule. - The cuDNN-per-segment preference over torch varlen for long documents was measured on B200; on H100 it is 2.2x to 2.6x slower at mean lengths 1024 to 2048. Keep it on sm100-family only. - Without FlashAttention, select torch's kernels over xformers on all-sm80+ CUDA hosts once torch has varlen (2.12+): 1.00x to 1.06x xformers on A100, L4, RTX PRO 6000 and H100. T4, mixed hosts, ROCm and torch 2.10 / 2.11 keep xformers.
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. |
…ers for packed opt-out and sentence unpadding - A GQA call no enabled SDPA backend takes raises in torch._fused_sdp_choice; the expanded K/V probe now still runs, and K/V are expanded when it has a backend. - With UNSLOTH_SDPA_PACKED_SEGMENTS off, packed SDPA builds a dense (T, T) mask, so packed calls keep xformers instead of preferring torch's kernels. - Sentence-transformer unpadding only runs on FlashAttention or xformers: when training prefers torch's kernels it still takes xformers if installed.
…probe carries grad and dropout - Dense calls keep xformers before SDPA when FlashAttention is absent: xformers alone consumes a caller's block-diagonal causal_mask, and SDPA would expand an fp32 GQA KV cache on decode. The packed / varlen route still prefers torch's kernels on sm80+ with torch varlen and UNSLOTH_SDPA_PACKED_SEGMENTS on. - The _fused_sdp_choice probe uses the real call's requires_grad and dropout_p (both change which backends qualify) and caches on them.
…ith dropout keep xformers
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
…rue) (unslothai#14779) The SDPA GQA routing added in unslothai#14158 asks torch which kernel a call would get. That probe, `_sdpa_gqa_state` (and `_sdpa_backend_state` for the varlen choice), runs through `torch.compiler.assume_constant_result`, and dynamo can only pass such a function Python constants. unslothai#14398 handled the boolean arguments. Under `torch.compile(fullgraph=True, dynamic=True)` the head dim and head counts are still SymInts, so compilation fails before the forward: ``` torch._dynamo.exc.Unsupported: assume_constant_result argument conversion failed Cannot convert argument of type SymNodeVariable to a Python constant ``` Repro: `run_attention` plus backward, noncausal GQA on CUDA, Q (2, 8, 32, 64), K/V (2, 2, 32, 64), no mask, SDPA backend. Before unslothai#14158 both static and dynamic fullgraph passed. Fix: a small `_constant_probe` wrapper replaces the two bare `assume_constant_result` wraps. It passes integer arguments through `operator.index` before the call. Under dynamo that specialises the head sizes, which are fixed per model. Batch and sequence length stay dynamic. Plain ints pass through unchanged, so eager and static-shape routing is identical. `functools.wraps` is avoided on purpose: `assume_constant_result` marks the wrapped function in place, and copying its `__dict__` would mark the wrapper too. Tests (`tests/test_attention_dispatch_compiled_block.py`): - CPU: `_sdpa_gqa_state` and `_torch_varlen_beats_segments` traced fullgraph, static and `dynamic=True`, match eager with 0 graph breaks and one graph across batch / length changes. - CUDA: real `run_attention` forward plus backward in bf16 GQA, compiled fullgraph static and dynamic with Inductor. Outputs and gradients match eager, with 0 graph breaks and one graph under `dynamic=True`. Results on B200, torch 2.13.0 and 2.14.1: | | main | this PR | |---|---|---| | fullgraph, static | pass | pass | | fullgraph, dynamic=True | fails before forward | pass, 0 graph breaks | | attention dispatch tests (GPU) | 4 failed, 69 passed | 1 failed, 72 passed | The remaining failure, `test_plain_causal_attention_traces_with_a_dynamic_length[xformers]`, is already on main and fails only on a GPU host: the xformers fp32 downcast gate looks at the host GPU, not at the tensor device. It is left for a separate change.
|
Second regression behind the RX 9060 XT (gfx1200, Linux) QLoRA crash in #18403: 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.
Three fixes to Unsloth's attention routing when the FlashAttention wheel is not installed, from a FA2 wheel vs PyTorch native vs xformers benchmark (Qwen3-0.6B and Llama-3.1-8B 4-bit LoRA, torch 2.10 to 2.14, T4 / L4 / A100 / RTX PRO 6000 / H100, packed, padding-free and padded).
Why
enable_gqa=Truefor every GQA model, but only flash and cuDNN take it. Where flash cannot run (sm75, fp32 / DoRA, masked calls), SDPA silently fell to math. On a T4 with torch 2.10 to 2.13 that made padded training 3x slower with 4.3x the memory of xformers (10.7 vs 2.5 GB)._torch_varlen_beats_segmentsprefers per-segment cuDNN SDPA above a mean segment length of 1024, a threshold measured on B200. On H100 that choice is 2.2x to 2.6x slower than torch varlen at mean lengths 1024 to 2048.select_attention_backendprefers xformers, but xformers 0.0.35 has no kernel of its own on sm80+ and torch's varlen path matched or beat it on torch 2.12+.Changes
enable_gqais passed only when SDPA's chosen kernel takes it, decided by askingtorch._fused_sdp_choicefor both the GQA and the expanded-K/V call (cached per shape class, constant undertorch.compile, so ROCm's backend set is answered by torch too). Otherwise K/V are expanded. The packed segment runs use the same rule.UNSLOTH_TORCH_VARLEN=0still disables varlen.Tests
tests/utils/test_attention_native_routing.py(24 new tests, 20 fail on main).test_sdpa_packed_segments.py: the peak memory test asserted the old math path's footprint and now asserts linear memory. Existing attention suites: 504 passed (two order-dependenttest_tiny_mistral_packed_row_matches_the_masked_pathfailures also happen on main and pass in isolation). No new graph breaks undertorch.compile; compiled output matches eager.Base vs head
Colab, fresh venv per torch, Qwen3-0.6B LoRA, 3 interleaved repeats, tokens/s median [spread]. Identical inputs across arms; losses of steps 1 to 10 agree within 1.8e-3 relative.
Not run: ROCm (the GQA decision is torch's own answer there), B200 (cuDNN rule unchanged by design), Windows, torch 2.10 / 2.11 dense GQA on sm80+.