Repository navigation
Packed SDPA rows: one torch varlen_attn call instead of one SDPA call per segment - #13221
Conversation
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. |
…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+.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if hasattr(torch.compiler, "assume_constant_result"): | ||
| _sdpa_backend_state = torch.compiler.assume_constant_result(_sdpa_backend_state) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
|
On a B200 (torch 2.14.1, no flash-attn or xformers), packed rows on 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 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. |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
…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).
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.
|
@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". |
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_attninstead: one kernel over the whole row viacu_seqlens, causal throughwindow_size = (-1, 0), GQA throughenable_gqawith 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:
varlen_attnwithwindow_sizeandenable_gqa(torch 2.12+); 2.10 / 2.11 havevarlen_attnbut not both, so they are unchangedtorch.backends.cuda.is_flash_attention_available())scale(left, right)spelling matchespacked_block_mask)torch.are_deterministic_algorithms_enabled()is False (the varlen backward is not deterministic)enable_flash_sdp(False)or ansdpa_kernel(...)context without FLASH_ATTENTION keeps the per-segment path), sincevarlen_attncalls the flash op directlytorch._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. undersdpa_kernel([MATH, FLASH_ATTENTION], set_priority=True), keeps the per-segment pathdq_accumbound already applied to flash-attn 2 varlenThe backend reads go through
torch.compiler.assume_constant_result, so compilingrun_attentionadds no graph break, and the cached probe makes the routing check about 0.3 us per packed call (B200).UNSLOTH_TORCH_VARLEN=0turns it off.Semantics match the per-segment path: sliding window
(window - 1, 0)ispacked_block_mask'sk >= q - (window - 1), the collator's pad tail gets its own segment throughcover_padded_cu_seqlens, andscaleis forwarded.cu_seqlensis moved to the query device, since callers may buildseq_infoon 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.offis this branch withUNSLOTH_TORCH_VARLEN=0.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_attentionalone on a packed row also gives 0 graph breaks on 2.12 and 2.14, with compiled output equal to eager.varlen_attnis 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):
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:1doc_4096and2docs_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
test_padded_tail_segment_counts_toward_the_bound[xformers|flash_varlen], fail on base too), GPU job green.Tests
New
tests/utils/test_torch_varlen_packed.py:window_size(or did not, for a single run of equal lengths)torch._fused_sdp_choicepinned to cuDNN, flash, math or efficient, plus a realsdpa_kernel([MATH, FLASH_ATTENTION], set_priority=True)contextscaleis forwardedvarlen_attnwithoutwindow_size/enable_gqa, and forUNSLOTH_TORCH_VARLEN=0Run 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: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) andtest_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