Skip to content

Attention: GQA never forces SDPA math, cuDNN-over-varlen on sm100 only, native before xformers - #14158

Merged
danielhanchen merged 8 commits into
mainfrom
attn-native-fixes
Oct 19, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
attn-native-fixes

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

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

  • GQA forced SDPA's math kernel. The dense path passes enable_gqa=True for 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).
  • cuDNN over varlen hurt H100. _torch_varlen_beats_segments prefers 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.
  • xformers was picked over faster native kernels. Without FA2, select_attention_backend prefers 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

  1. enable_gqa is passed only when SDPA's chosen kernel takes it, decided by asking torch._fused_sdp_choice for both the GQA and the expanded-K/V call (cached per shape class, constant under torch.compile, so ROCm's backend set is answered by torch too). Otherwise K/V are expanded. The packed segment runs use the same rule.
  2. The cuDNN-over-varlen preference applies only on sm100-family GPUs; elsewhere torch varlen wins. UNSLOTH_TORCH_VARLEN=0 still disables varlen.
  3. Without FA2, packed batches use PyTorch's varlen path over xformers when every visible CUDA GPU is sm80+, the host is not ROCm, torch has varlen (2.12+) and the packed segment path is enabled. Dense and decode calls keep xformers first (explicit block masks, grouped FP32 KV layout); sentence unpadding keeps xformers. T4, mixed hosts and torch 2.10 / 2.11 are unchanged. Nothing changes when FA2 is installed.
  4. The GQA probe uses the real call's grad state and dropout, and probes the GQA and expanded calls independently.

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-dependent test_tiny_mistral_packed_row_matches_the_masked_path failures also happen on main and pass in isolation). No new graph breaks under torch.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.

Cell Base Head Reference
T4, torch 2.12, padded, native 477 [4], peak 10.66 GB 1388 [6], peak 2.46 GB xformers 1416 [4], 2.46 GB
A100, torch 2.13, packed, xformers installed 11793 [130] (xformers) 12308 [72] (native)
A100, torch 2.13, packed, native (control) 12428 [211] 12393 [204]
H100, torch 2.14, packed, native 18226 [5925] 20227 [1694] FA2 22131 [892]
H100, torch 2.14, padding-free, native 20243 [1662] 20076 [1512] FA2 22317 [802]

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+.

…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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-19T07:39:50.788508Z ee2097d New commits
🔒 Security Review ⚠️ Failed 2026-10-18T21:07:11.164979Z 445e809 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 18, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: eb771ea79b

ℹ️ 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".

@danielhanchen
danielhanchen merged commit e6c95c2 into main Oct 19, 2026
@danielhanchen
danielhanchen deleted the attn-native-fixes branch October 19, 2026 11:32
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 22, 2026
…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.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator

Second regression behind the RX 9060 XT (gfx1200, Linux) QLoRA crash in #18403: with UNSLOTH_SDPA_PACKED_SEGMENTS=0 set, the parent commit trains and this one fails at the first step with CUDA error: invalid argument. No env var gets current releases training on that card again. The PR body lists ROCm as not run.

u064241 pushed a commit to u064241/unsloth that referenced this pull request Nov 19, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants