Skip to content

SDPA: attend packed rows per segment instead of under a dense mask (2.9x less memory, 2.5x faster without flash-attn / xformers) - #12740

Merged
danielhanchen merged 3 commits into
mainfrom
packed-sdpa-per-segment
Oct 5, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
packed-sdpa-per-segment

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

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 with enable_gqa it 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 from run_attention plus 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

  • The SDPA branch now runs packed rows one segment at a time: each segment gets its own SDPA call with 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.
  • GQA uses enable_gqa only 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.
  • A segment longer than the sliding window gets a window mask of its own length only (packed_block_mask, shared with the dense builder so both paths mask identically).
  • UNSLOTH_SDPA_PACKED_SEGMENTS=0 restores 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:

Attention Peak VRAM Step Train tok/s Loss steps 1, 2, 3, 14, 15 max abs loss diff vs xformers
SDPA, main 5.50 GB 1751 ms 7005 1.5090, 1.5112, 1.6419, 1.4329, 1.3750 0.0015
SDPA, this PR 1.92 GB 697 ms 17530 1.5086, 1.5097, 1.6416, 1.4333, 1.3756 0.0007
xformers, main 1.92 GB 817 ms 14481 1.5086, 1.5097, 1.6414, 1.4340, 1.3751 0
xformers, this PR 1.92 GB 883 ms 13181 1.5086, 1.5097, 1.6419, 1.4334, 1.3756 0.0006

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:

GPU Model Dense mask This PR Speedup Peak VRAM Loss steps 1, 2, 3 (dense / PR)
T4 Qwen3-0.6B 24289 ms 4421 ms 5.5x 5.45 -> 1.87 GB 1.5395, 1.4875, 1.6083 / 1.5396, 1.4874, 1.6084
L4 Qwen3-0.6B 15395 ms 1840 ms 8.4x 5.45 -> 1.87 GB 1.5406, 1.4876, 1.6189 / 1.5402, 1.4885, 1.6184
A100 40GB Qwen3-0.6B 4873 ms 927 ms 5.3x 5.45 -> 1.87 GB 1.5404, 1.4874, 1.6192 / 1.5406, 1.4874, 1.6187
RTX PRO 6000 (G4) Qwen3-0.6B 2561 ms 343 ms 7.5x 5.45 -> 1.87 GB 1.5404, 1.4880, 1.6188 / 1.5404, 1.4878, 1.6184
RTX PRO 6000 (G4) Llama-3.2-1B 2677 ms 387 ms 6.9x 10.70 -> 3.05 GB 1.3373, 1.2388, 1.3205 / 1.3378, 1.2390, 1.3203
RTX PRO 6000 (G4) Qwen3-8B (bnb 4-bit) 7698 ms 2065 ms 3.7x 16.01 -> 8.31 GB 1.2161, 1.1742, 1.2652 / 1.2164, 1.1753, 1.2650

Graph breaks 0 and recompiles 0 in every run. The T4 row runs the expanded K/V path (no flash kernel on sm75).

Tests

  • New 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_sdpa now checks the SDPA packed path receives the packed segment lengths; tests/utils/test_attention_masks.py::test_run_attention_sdpa_passes_sliding_window pins the dense path with the switch off.
  • Reverting only the dispatch change fails 3 tests (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.

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

chatgpt-codex-connector Bot commented Oct 5, 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-05T13:39:36.566516Z 616ba0c New commits
ℹ️ 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.

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

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 1d56a419a3

ℹ️ 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 self-assigned this Oct 5, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 5, 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. More of your lovely PRs please.

Reviewed commit: 0dc4151f30

ℹ️ 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 5babb22 into main Oct 5, 2026
@danielhanchen
danielhanchen deleted the packed-sdpa-per-segment branch October 5, 2026 15:14
danielhanchen added a commit that referenced this pull request Oct 5, 2026
…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.
danielhanchen added a commit that referenced this pull request Oct 11, 2026
…#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...
@LeoBorcherding

Copy link
Copy Markdown
Collaborator

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 CUDA error: invalid argument, and UNSLOTH_SDPA_PACKED_SEGMENTS=0 brings training back.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants