Repository navigation
Packed sequences attention: one path for encoders and packed text (SDPA varlen, flex block masks) - #51224
Draft
IlyasMoutawwakil wants to merge 4 commits into
Draft
Packed sequences attention: one path for encoders and packed text (SDPA varlen, flex block masks)#51224IlyasMoutawwakil wants to merge 4 commits into
IlyasMoutawwakil wants to merge 4 commits into
Conversation
… path Packed vision and audio encoders attend within each of the sequences packed along one length, delimited by `cu_seqlens`. Only flash attention did it in one call: SDPA split the sequences on the host and looped in every layer, through 13 copies of the same branch. - SDPA runs torch's varlen kernel on packed sequences when it supports them, bounded by the total length so it needs no host sync, and falls back to one call per sequence otherwise. - Flex attention gets a block mask letting each sequence attend to itself only, built once per forward. - `packed_sequences_attention_forward` replaces the per-model branch, and `get_packed_sequences_inputs` builds what the implementation needs once per forward, precomputable through `kwargs`. - Flex support is declared on the packed models whose flex tests pass; GLM-4V and ERNIE 4.5-VL-MoE opt out. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
`get_packed_sequences_inputs` reads the sequence lengths once per forward outside of tracing: flash attention takes its max length from them, and eager and SDPA's fallback split the sequences with them instead of reading them in every layer. They ride in the layers' `kwargs` like the block mask, so no signature changes; under `torch.compile` or export nothing is read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…se mask For packed text rows (batch size 1, plain causal, no cache, not tracing), `create_causal_mask` hands SDPA the rows' cumulative lengths instead of the dense block-causal mask, and SDPA attends with its varlen kernel (now causal, and GQA through `enable_gqa` or `repeat_kv`), or once per document when the kernel can't run. Sparse-attention indexers (`index_topk`) keep the dense mask they select keys on, and varlen requires equal value and query head sizes (not MLA's). A 1D mask passed back into the mask creation is returned as is, like a prepared 4D one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
IlyasMoutawwakil
marked this pull request as draft
November 25, 2026 10:33
- SDPA varlen takes the layer's sliding window and packed rows of any batch size (one call over the flattened batch); it needs torch 2.11 (`scale` and `window_size`), and 2.12 for GQA without repeating the keys - Eager attends over each sequence of packed rows separately, wired once in `AttentionInterface.get_interface`; the SDPA fallback shares its per-sequence loop - Padded rows, and callers asking for a materialized mask (`allow_is_causal_skip=False`), keep the dense mask; GPT-Neo and GPT-NeoX-Japanese, which apply the mask themselves, now ask for it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
|
[For maintainers] Suggested jobs to run (before merge) run-slow: cohere_compass, cosmos3_edge, cosmos3_omni, dots3_note, ernie4_5_vl_moe, exaone4_5, glm46v, glm4v, glm4v_moe, glm5_next, glm_image, glm_ocr, gpt_neo, gpt_neox_japanese, hunyuan_vl, hy_v4_vl |
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What does this PR do?
One way for every model to attend within sequences packed along one length: vision and audio encoders (all their images in one sequence) and packed text rows (several documents in one row). Until now only flash attention did it efficiently: SDPA, the default, looped over images in every layer for encoders, and used a dense
T × Tblock-causal mask for text.cu_seqlens, plusmax_seqlen,packed_block_maskandsequence_lengths, built once per forward (get_packed_sequences_inputs), each precomputable inkwargspacked_sequences_attention_forwardcreate_causal_maskhands SDPA the 1Dcu_seqlensinstead of the dense mask; flash and flex unchangedflowchart TD E["<b>Encoder tower</b><br/>images packed in one sequence"] --> P["<b>get_packed_sequences_inputs</b><br/>once per forward: max_seqlen · block mask · lengths"] P --> F["<b>packed_sequences_attention_forward</b>"] F -->|flash| FL["flash varlen kernel"] F -->|sdpa| S F -->|flex| X["flex + packed block mask"] F -->|eager| L["one call per sequence"] T["<b>Text model</b><br/>documents packed in one row"] --> M{"<b>create_causal_mask</b><br/>SDPA, not tracing?"} M -->|yes| C["1D cu_seqlens"] --> S M -->|no| D["dense block-causal mask (as on main)"] S{"<b>SDPA</b><br/>CUDA · fp16/bf16 · supported heads?"} -->|yes| V["torch varlen_attn<br/>no host sync"] S -->|no| L2["one call per sequence"]integrations/sdpa_attention.pyvarlen_attn, torch ≥ 2.10) when it supports them (CUDA, fp16 / bf16, bidirectional, no dropout, MHA, head size a multiple of 8 ≤ 256), launch bounded by the total length so no host sync. Per-sequence SDPA otherwise, as beforeintegrations/flex_attention.pycreate_packed_block_mask): cross-sequence blocks are skipped, never a dense maskvision_utils.pypacked_sequences_attention_forwardreplaces the per-model branch;get_packed_sequences_inputsbuilds flash's max length and flex's block mask once per forward, not per layermasking_utils.pyenable_gqaorrepeat_kv)main−796 lines. Eager keeps its loop, attention weights and peak memory, and reads the lengths once per forward instead of in every layer.
Numbers
bf16 · one A100-SXM4-80GB · one process per row · 🟢 faster than
main⚪ same (±2%)xychart-beta title "Qwen2-VL-2B vision tower, SDPA: speedup over main (×)" x-axis ["16 × 224²", "4 × 448²", "mixed", "16 × 224² compiled", "4 × 448² compiled", "mixed compiled"] y-axis "× faster than main" 0 --> 2 bar [1.41, 1.10, 1.08, 1.61, 1.13, 1.05]xychart-beta title "Packed text attention per layer, SDPA: speedup over main's dense mask (×)" x-axis ["8 × 1024 (8k)", "8 × 4096 (32k)", "4 × 8192 (32k)"] y-axis "× faster than main" 0 --> 40 bar [23, 35, 18]Encoder · Qwen2-VL-2B-Instruct vision tower
main→ PRmain→ PRmain→ PRMean of 20 forwards. Eager's peak is unchanged too (240 MiB at 4 × 448², 13.3 GB at 2 × 1344²), and flex peaks like SDPA. On the full tower the MLP activations set the peak, not the attention: the attention-only saving is below. SDPA outputs are bit-identical to
mainon 4 × 448² and 2 × 1344², and withinmain's own eager / SDPA spread elsewhere.Encoder compiled ·
torch.compile(inductor, default mode)main→ PRmain→ PRmain→ PRWithout the per-layer
.tolist(), the attention no longer breaks the graph: the remaining breaks are elsewhere in the tower.Attention only · 32 packed layers, 16 heads, head dim 64
time · peak memoryper forward, 🟢 best in columnmain).item()max per layer.item()per layerText · Qwen3-0.6B, one packed training row (forward + backward)
mainSame loss on both (13.5950 vs 13.5945 at 8k). Per layer, attention only (16 heads, head dim 64):
main)Text models kept on the dense mask
index_topk): Kolibri 1.1, DeepSeek-V3.2 / V4, GLM-DSA, GLM-5-Next, Mistral Large 4, Step3p7, HY-V4(-VL), AXK2, Dots3, MiniMax-M3-VLcu_seqlensinstead of overlaying the maskeager_attention_forwardreads the dense maskposition_ids' valuesHost syncs
main.tolist()every layer.tolist()every layerThe lengths are read once per forward, outside of tracing only: under
torch.compileor export nothing is read, and SDPA's varlen launch is bounded by the total length instead.max_seqlen, the block mask and the lengths (and theirwindow_variants) can be precomputed and passed inkwargs: with #50887'sget_data_dependent_inputscomputing them, the forward is sync-free for flash, SDPA and flex.Related PRs
sdpause the kernel and gives the packed models one path it would plug intocreate_causal_maskTests
main, same conditionsmaintest_sdpa_padding_matches_padding_free_with_position_ids, all modelsFuture work
cu_seqlens/max_seqlenin**kwargsFlashAttentionKwargs: packed layers shrink to(hidden_states, position_embeddings, **kwargs)get_data_dependent_inputs(#50887) precomputesmax_seqlenand the block maskpixel_valuesfor DDP, and the model unpads them back🤖 Generated with Claude Code