Skip to content

Packed SDPA rows: one torch varlen_attn call instead of one SDPA call per segment - #13221

Merged
danielhanchen merged 10 commits into
mainfrom
torch-varlen-packed-sdpa
Oct 11, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
torch-varlen-packed-sdpa

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 10, 2026 •

Copy link
Copy Markdown
Member

When neither flash-attn 2 nor xformers is installed, packed (padding-free) rows fall back to SDPA, which runs one call per run of equal-length documents, per layer, in the forward, the checkpoint recompute and the backward. A packed 8k row of a chat dataset holds around 40 documents, so that is dozens of small kernels per layer.

This routes those rows through torch.nn.attention.varlen.varlen_attn instead: one kernel over the whole row via cu_seqlens, causal through window_size = (-1, 0), GQA through enable_gqa with no K / V expansion. Everything the per-segment path cannot hand over unchanged keeps the per-segment path.

When it applies

All of these must hold, otherwise the existing per-segment SDPA path runs exactly as before:

  • torch exposes varlen_attn with window_size and enable_gqa (torch 2.12+); 2.10 / 2.11 have varlen_attn but not both, so they are unchanged
  • the torch build has flash attention (torch.backends.cuda.is_flash_attention_available())
  • CUDA, not ROCm, compute capability 8.0+, fp16 / bf16 Q / K / V, head_dim <= 256 and a multiple of 8
  • no dropout and no extra SDPA kwargs beyond scale
  • no bidirectional sliding window (no (left, right) spelling matches packed_block_mask)
  • not a bidirectional call with equal query / KV heads: torch 2.14 sends that to cuDNN's ragged kernel on sm90 / sm100, which has no head_dim 256 plan and also re-selects cuDNN in the backward
  • torch.are_deterministic_algorithms_enabled() is False (the varlen backward is not deterministic)
  • flash SDPA is enabled (enable_flash_sdp(False) or an sdpa_kernel(...) context without FLASH_ATTENTION keeps the per-segment path), since varlen_attn calls the flash op directly
  • the row has more than one run of equal lengths; a single run is already one batched SDPA call
  • SDPA's own backend choice for these shapes (asked through torch._fused_sdp_choice, cached per shape and backend flags / priority order) is FLASH_ATTENTION, or CUDNN_ATTENTION with a mean segment length of at most 1024 (e.g. B200: past that cuDNN per segment is faster per token than torch's varlen flash kernel). A MATH or EFFICIENT_ATTENTION choice, e.g. under sdpa_kernel([MATH, FLASH_ATTENTION], set_priority=True), keeps the per-segment path
  • the segment lengths cover exactly the row; malformed lengths keep the per-segment path and its shape error instead of indexing past the tensor
  • the row passes the same int32 dq_accum bound already applied to flash-attn 2 varlen

The backend reads go through torch.compiler.assume_constant_result, so compiling run_attention adds no graph break, and the cached probe makes the routing check about 0.3 us per packed call (B200).

UNSLOTH_TORCH_VARLEN=0 turns it off.

Semantics match the per-segment path: sliding window (window - 1, 0) is packed_block_mask's k >= q - (window - 1), the collator's pad tail gets its own segment through cover_padded_cu_seqlens, and scale is forwarded. cu_seqlens is moved to the query device, since callers may build seq_info on the CPU (the per-segment path only reads lengths on the host).

Results

Packed SFT on B200 (SDPA picks cuDNN here), torch 2.14.1, transformers 4.56.2, no flash-attn / xformers (banner FA2 = False, Xformers = None), yahma/alpaca-cleaned, packing=True, max_seq_length 8192, bs 1, LoRA r16, 30 steps (first 5 not timed), one exclusive GPU, fresh process per run, order base, head, off, off, head, base. off is this branch with UNSLOTH_TORCH_VARLEN=0.

model arm s/step (2 runs) vs base peak GB varlen calls per-segment calls
Qwen3-4B base 2.515 / 2.448 1.00x 4.84 0 2160
Qwen3-4B this PR 0.298 / 0.290 8.44x 5.01 2160 0
Qwen3-4B off 2.371 / 2.384 1.04x 4.84 0 2160
Llama-3.1-8B base 2.363 / 2.444 1.00x 7.67 0 1920
Llama-3.1-8B this PR 0.402 / 0.404 5.96x 7.60 1920 0
Llama-3.1-8B off 2.299 / 2.297 1.05x 7.67 0 1920

Re-run on the final commit (same setup, base / head / head / base): Qwen3-4B 3.50 / 0.33 / 0.35 / 3.13 s/step, Llama-3.1-8B 3.06 / 0.42 / 0.41 / 3.01 s/step, varlen calls 2160 and 1920 per head run, 0 on base.

Loss: the step-1 loss on identical weights differs only by bf16 rounding (Qwen3-4B 1.7142 vs 1.7168, Llama 1.4042 vs 1.4039). Against an fp32 reference on a fixed packed row (about 7.9k tokens, 43 documents), the per-token NLL error is the same size on both paths (Qwen3-4B 0.0278 per-segment vs 0.0281 varlen, Llama 0.0186 vs 0.0187). Over 30 steps the mean absolute loss difference vs base is 0.0008 to 0.0041, the same order as base vs base (0.0007 to 0.0009).

torch.compile: 0 graph breaks and 1 unique graph on both base and this branch in the packed SFT run; compiling run_attention alone on a packed row also gives 0 graph breaks on 2.12 and 2.14, with compiled output equal to eager. varlen_attn is a registered custom op with fake and autograd implementations on 2.12, 2.13 and 2.14.

Kernel level, B200, forward + backward, varlen vs per-segment (cuDNN), rows of 8192 / 16384 tokens, Llama-8B heads (32 / 8 / 128):

documents mean length speedup
random lengths ~130 13.3x / 27.5x
random lengths ~260 5.7x / 12.9x
random lengths ~550 3.4x / 5.3x
random lengths ~950 1.8x / 2.4x
random lengths ~1500 to 2048 0.81x / 1.31x
random lengths ~2700 to 4096 0.57x / 0.49x
all equal (one run) any 0.26x to 0.9x

That is where the one-run rule and the 1024 mean-length limit on cuDNN come from; Qwen3 (32 / 4 / 128) and head_dim 64 shapes follow the same pattern.

Colab, torch 2.14.1 installed in the runtime (stock Colab torch 2.11 has no GQA varlen_attn, so this PR is a no-op there), forward + backward speedup vs per-segment SDPA, Llama-8B / Qwen3 / head_dim 64 shapes, median of 30, A/A spread under 0.5% for nearly all cells:

pack A100 (sm80) L4 (sm89) RTX PRO 6000 (sm120)
8docs_8192 2.43x / 2.29x / 2.70x 2.36x / 2.22x / 2.64x 2.19x / 2.10x / 2.93x
16docs_4096 5.36x / 5.45x / 6.46x 4.86x / 4.75x / 5.35x 4.59x / 4.33x / 7.52x
2docs_2048 1.03x / 1.02x / 1.16x 0.98x / 0.99x / 1.16x 1.26x / 1.22x / 1.22x
1doc_4096 0.98x / 0.98x / 0.76x 1.03x / 1.02x / 0.91x 1.02x / 0.99x / 0.94x
win1024_4096 4.82x / 4.75x / 2.83x 5.08x / 5.12x / 4.47x 9.12x / 9.28x / 5.32x

1doc_4096 and 2docs_2048 ([1100, 948]) are the cases this PR now leaves on per-segment SDPA (one run) or where it is roughly even. On T4 (sm75) the path never engages and timings match per-segment within 1%. Outputs match per-segment within 0.0078 max abs on every cell.

Other platforms

  • AMD gfx1151 (Linux, ROCm): the path is gated off on ROCm. Base vs head on the attention dispatch tests: NO_REGRESSION (the only failures, test_padded_tail_segment_counts_toward_the_bound[xformers|flash_varlen], fail on base too), GPU job green.
  • Transformers 5.17 (torch 2.13): packed SFT on Qwen3-4B reaches the path, 432 varlen calls, 2.82 to 0.91 s/step, same peak memory and loss.
  • CPU-only Linux, macOS and Windows staging legs: green (the path never loads a kernel there).

Tests

New tests/utils/test_torch_varlen_packed.py:

  • outputs and dQ / dK / dV match the per-segment path for MHA and GQA, the pad tail, causal and bidirectional rows, sliding windows (3, 4, 128), head_dim 64 / 128 / 256, bf16 and fp16, and that the varlen call actually happened with the expected window_size (or did not, for a single run of equal lengths)
  • the cuDNN mean-length rule and the one-run rule, with torch._fused_sdp_choice pinned to cuDNN, flash, math or efficient, plus a real sdpa_kernel([MATH, FLASH_ATTENTION], set_priority=True) context
  • lengths overrunning the row keep the per-segment path
  • scale is forwarded
  • fp32, dropout, extra SDPA kwargs, bidirectional window, bidirectional MHA, deterministic mode, disabled flash SDPA and the int32 bound all keep the per-segment path
  • the tests need sm80+ and skip elsewhere
  • the loader returns None for a varlen_attn without window_size / enable_gqa, and for UNSLOTH_TORCH_VARLEN=0

Run with the existing attention dispatch tests (test_sdpa_packed_segments.py, test_varlen_int32_overflow_guard.py, test_attention_dispatch_bidirectional.py, test_attention_masks.py) on B200:

torch varlen path passed skipped failed
2.14.1 active 152 2 3
2.12.1 active 152 2 3
2.10.0 inactive 80 74 3

The 3 failures are the same IDs on main on this host and are not touched here: test_peak_memory_is_linear_in_tokens (the dense arm on B200 stays at about 190 MB, under its 4x assertion) and test_padded_tail_segment_counts_toward_the_bound[xformers|flash_varlen] (the per-segment path makes two SDPA calls for that row, one per distinct length).

Not covered

  • Hopper was not run (no Hopper GPU available). B200 locally, A100 / L4 / RTX PRO 6000 / T4 on Colab were. Whether SDPA picks cuDNN on Hopper or sm120 is read at runtime, so the mean-length limit applies there only if it does.
  • No sliding-window model and no sentence-transformer model end to end; both are covered at the kernel level by the parity tests.
  • ROCm and pre-sm80 are gated off; ROCm was run (gfx1151 Linux) to show nothing moved. Windows with an AMD or NVIDIA GPU was not run: the Windows gfx1151 runners have no torch, and there is no Windows NVIDIA runner.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 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 ✅ Completed 2026-10-11T05:52:07.381234Z 1c10424 Manual request
ℹ️ 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 10, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ong cuDNN segments on per-segment SDPA

- Skip varlen when flash SDPA is disabled (enable_flash_sdp(False) or an sdpa_kernel context without it).
- Skip it when the row is one run of equal lengths: per-segment SDPA is then a single batched call.
- Where SDPA picks cuDNN (B200), use varlen only up to a mean segment length of 1024, past which
  cuDNN per segment is faster than torch's varlen flash kernel.
- Read both through torch.compiler.assume_constant_result so the compiled graph does not break.
- Varlen tests need sm80+.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9656864233

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

Comment on lines +161 to +162
if hasattr(torch.compiler, "assume_constant_result"):
_sdpa_backend_state = torch.compiler.assume_constant_result(_sdpa_backend_state)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not freeze the Flash-backend setting in compiled graphs

When a model is first run through torch.compile while Flash SDPA is enabled, assume_constant_result bakes (flash, cudnn) into that graph; PyTorch explicitly states that it does not validate whether this constant assumption remains true. Executing the cached graph later under sdpa_kernel(SDPBackend.MATH) or after enable_flash_sdp(False) therefore still sees flash=True and invokes the Flash-only varlen operator directly, bypassing the caller's restriction. The fresh evidence beyond the prior eager-path fix is this decorator, which also means the new eager-only disabled-backend test cannot detect the compiled regression.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This matches how compiled SDPA already behaves, so it is not a new bypass. torch picks the SDPA backend while tracing and does not guard on the backend flags: with torch 2.14.1 on B200, a torch.compiled F.scaled_dot_product_attention(q, q, q, is_causal=True) first run with defaults, then run again under sdpa_kernel(SDPBackend.MATH), and again after enable_flash_sdp(False), enable_cudnn_sdp(False) and enable_mem_efficient_sdp(False), launches cudnn_generated_fort_native_sdpa_sm100_flash_fprop all three times with no recompile (profiled kernel names, one unique graph). The per-segment path this replaces is exactly that call, so a compiled model on main already keeps its traced backend when the flags change afterwards.

Reading flash_sdp_enabled() live instead would put a graph break in every compiled attention layer (torch.* op returned non-Tensor, measured: 3 breaks per run_attention call), which is the cost assume_constant_result avoids. In eager the flag is read on every call, and changing backends before compiling (or under a fresh torch.compile) is honoured.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 9656864233

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

@Etherll

Etherll commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

On a B200 (torch 2.14.1, no flash-attn or xformers), packed rows on 396eda29f now make one varlen_attn call per attention layer pass, where before there was one SDPA call per run of equal lengths. A short packed SFT (Qwen3-0.6B, LoRA r16, 8k packed alpaca-cleaned rows, 25 steps) went from 2.70 to 0.17 s/step. Per-step loss differed from base by 0.0008 on average, against 0.0003 between two base runs, and peak memory was the same at 1.99 GB. With UNSLOTH_TORCH_VARLEN=0 it ran at 2.68 s/step, on the old path.

At the kernel level (Llama-8B head layout, forward plus backward), short documents (mean 282 tokens) went from 8.25 to 1.53 ms and mid-length ones (mean 745) from 3.71 to 1.76 ms. Long documents (mean 1820), where SDPA picks cuDNN, stay on the per-segment path at the same speed, as intended.

The existing attention tests fail the same 3 tests on base and on this head, under torch 2.11 and 2.14. The new test file passes on torch 2.12 and 2.14; on 2.11 its varlen cases skip because the loader returns None. Compiling run_attention gives 0 graph breaks and matches eager. On the open thread about compiled graphs and backend flags: a compiled run_attention keeps the kernel it was traced with when sdpa_kernel([SDPBackend.MATH]) or enable_flash_sdp(False) is applied afterwards, on base (cuDNN) and on this head (flash varlen). Nothing errors.

No changes were pushed. Fork CI is still running at Etherll#227. The red upstream checks are the TRL-latest ORPO/CPO tokenizer tests, an embeddings proxy timeout, and a chunked-mask test that main has since fixed; none touch this diff. Hopper, Ampere/Ada, and ROCm were not run.

@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 793228d66c

ℹ️ 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 added a commit that referenced this pull request Oct 11, 2026
…eached (#13272)

test_non_streaming_proxy_disconnect_returns_499[openai_embeddings] timed out in Backend CI (l-r) on #13221 and #13240 waiting 0.2 s for the route to reach HangingCancelableClient. The route gets there in milliseconds, but the first embeddings call on a loaded, cold xdist worker can take longer. The 0.5 s bound after the disconnect is five polls of the 0.1 s watcher, equally tight. Both are upper bounds only, so raise them to 10 s and 5 s through named constants used by all seven waits in the file; a route that never reaches the client or never notices the disconnect still fails.
…N backend choice

Malformed packed lengths (sum larger than the row) raised a clean shape error on the per-segment path but
sent cu_seqlens past the tensor into varlen_attn (illegal memory access). The SDPA backend probe is now
cached per shape and backend flags: the routing check drops from about 9 us to 0.3 us per packed call (B200).
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Inside sdpa_kernel([MATH, FLASH_ATTENTION], set_priority=True) flash stays enabled but SDPA picks math,
and treating every non-cuDNN choice as flash bypassed that order. Varlen now runs only when SDPA would pick
flash, or cuDNN within the mean-length limit; math, efficient or an unknown choice keep per-segment SDPA.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@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: 1c10424c98

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

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