Skip to content

Packed sequences attention: one path for encoders and packed text (SDPA varlen, flex block masks) - #51224

Draft
IlyasMoutawwakil wants to merge 4 commits into
mainfrom
sdpa-varlen-attention
Draft

IlyasMoutawwakil wants to merge 4 commits into
mainfrom
sdpa-varlen-attention

Conversation

@IlyasMoutawwakil

@IlyasMoutawwakil IlyasMoutawwakil commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

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 × T block-causal mask for text.

Piece Contract
packed inputs cu_seqlens, plus max_seqlen, packed_block_mask and sequence_lengths, built once per forward (get_packed_sequences_inputs), each precomputable in kwargs
host reads only outside tracing; sizes depending on values (text's document count) too
attention flash, SDPA (varlen kernel) and flex (block mask): one call over all the sequences. Eager and SDPA's fallback: one call per sequence
encoders towers build the inputs, attentions call packed_sequences_attention_forward
text create_causal_mask hands SDPA the 1D cu_seqlens instead of the dense mask; flash and flex unchanged
flowchart 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"]
Loading
Where Change
integrations/sdpa_attention.py packed sequences run torch's varlen kernel (varlen_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 before
integrations/flex_attention.py packed sequences get a block mask letting each attend to itself only (create_packed_block_mask): cross-sequence blocks are skipped, never a dense mask
vision_utils.py packed_sequences_attention_forward replaces the per-model branch; get_packed_sequences_inputs builds flash's max length and flex's block mask once per forward, not per layer
models the 13 packed attentions call it; their towers build the inputs once (window towers per layer type)
masking_utils.py packed text rows (batch 1, plain causal, no cache, not tracing): SDPA gets their cumulative lengths instead of the dense mask; varlen gains causal and GQA (enable_gqa or repeat_kv)
flex support declared on the Qwen2-VL family and its inheritors, MiniCPM-V 4.6, RADIO, Qwen3.5(-MoE), Qwen3-ASR (flex tests pass). GLM-4V family and ERNIE 4.5-VL opt out explicitly: inductor can't lower their flex attention, also on 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]
Loading
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]
Loading

Encoder · Qwen2-VL-2B-Instruct vision tower

Images (patches) SDPA main → PR SDPA peak main → PR Eager main → PR Flex (PR)
16 × 224² (4,096) 81.3 → 57.8 ms 🟢 1.41× 173 → 173 MiB ⚪ 146.5 → 127.9 ms 🟢 1.15× 60.6 ms
4 × 448² (4,096) 65.7 → 59.5 ms 🟢 1.10× 173 → 173 MiB ⚪ 113.6 → 110.1 ms ⚪ 1.03× 67.1 ms
mixed 224²–896² (5,888) 101.5 → 94.1 ms 🟢 1.08× 249 → 250 MiB ⚪ 256.4 → 248.9 ms ⚪ 1.03× 114.3 ms
2 × 1344² (18,432) 445.6 → 439.8 ms ⚪ 778 → 778 MiB ⚪ 2125.6 → 2120.4 ms ⚪ 684.1 ms

Mean 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 main on 4 × 448² and 2 × 1344², and within main's own eager / SDPA spread elsewhere.

Encoder compiled · torch.compile (inductor, default mode)

Images (patches) SDPA main → PR Graphs main → PR SDPA peak main → PR Flex (PR)
16 × 224² (4,096) 65.1 → 40.6 ms 🟢 1.61× 11 → 5 🟢 92.6 → 90.3 MiB 🟢 43.1 ms
4 × 448² (4,096) 50.0 → 44.3 ms 🟢 1.13× 11 → 5 🟢 92.6 → 90.3 MiB 🟢 51.4 ms
mixed 224²–896² (5,888) 77.3 → 73.5 ms 🟢 1.05× 11 → 5 🟢 133.9 → 131.6 MiB 🟢 91.7 ms

Without 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 memory per forward, 🟢 best in column

Variant 4 × 1024 mixed 256–4096 4 × 4096 2 × 16384
per-sequence loop (main) 25.2 ms · 24 MiB 64.9 ms · 44 MiB 75.7 ms · 96 MiB 481.7 ms · 192 MiB
SDPA varlen (PR) 7.0 ms · 🟢 16 MiB 26.2 ms · 🟢 30 MiB 61.9 ms · 🟢 65 MiB 478.3 ms · 🟢 130 MiB
↳ precomputed max 🟢 5.9 ms 🟢 24.4 ms 60.8 ms 478.0 ms
↳ .item() max per layer 10.6 ms 28.8 ms 64.2 ms 479.9 ms
SDPA dense batch (equal only) 5.8 ms · 24 MiB — 🟢 61.1 ms · 96 MiB 🟢 467.4 ms · 192 MiB
Flex, mask once (PR) 8.0 ms · 25 MiB 27.1 ms · 45 MiB 65.4 ms · 98 MiB 497.6 ms · 197 MiB
↳ mask per layer 38.5 ms 41.8 ms 72.8 ms 516.5 ms
Decision Why
🟢 SDPA: varlen over the loop up to 3.6× faster, a third less memory
🟢 launch bounded by the total length no host sync, faster than .item() per layer
⚪ varlen also for equal lengths a dense batch is ≤ 2.5% faster but peaks ~50% higher
🟢 flex mask built once per forward built per layer, it is slower than the loop on small images

Text · Qwen3-0.6B, one packed training row (forward + backward)

Packed row main PR
causal LM, 8 × 1024 (8k) 1268.1 ms · 33.7 GiB 413.0 ms · 29.3 GiB 🟢 3.07×
causal LM, 4 × 4096 (16k) out of memory (80 GB) 919.5 ms · 58.7 GiB 🟢 runs
decoder, 8 × 4096 (32k) out of memory 1512.5 ms · 62.3 GiB 🟢 runs
decoder, 4 × 8192 (32k) out of memory 1847.0 ms · 62.3 GiB 🟢 runs

Same loss on both (13.5950 vs 13.5945 at 8k). Per layer, attention only (16 heads, head dim 64):

Packed row SDPA dense mask (main) SDPA causal varlen (PR)
8 × 1024 (8k) 7.0 ms · 208 MiB 0.30 ms · 16 MiB 🟢 23×
8 × 4096 (32k) 88.5 ms · 3.1 GiB 2.5 ms · 66 MiB 🟢 35×
4 × 8192 (32k) 88.8 ms · 3.1 GiB 4.8 ms · 66 MiB 🟢 18×

Text models kept on the dense mask

Models Why How they could migrate
sparse-attention indexers (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-VL their indexers select keys on the dense 4D mask select keys within cu_seqlens instead of overlaying the mask
MLA (DeepSeek-V3, MiniCPM3, Youtu, Kimi K2.5, …) migrated, but value heads differ from query heads, which the varlen kernel doesn't take they run SDPA once per document: varlen once torch supports different value head sizes
any model on eager each model's own eager_attention_forward reads the dense mask eager would split per document like encoders, 4–8× faster with 16–61× less memory (measured), once text models pass the packed inputs like encoders do
compiled / exported forwards the document count depends on position_ids' values stay on the dense mask by design

Host syncs

Implementation main PR
SDPA .tolist() every layer 🟢 one per forward (the lengths)
Eager .tolist() every layer 🟢 one per forward
Flex attention not supported 🟢 one per forward
Flash attention one per forward (max length) ⚪ one per forward

The lengths are read once per forward, outside of tracing only: under torch.compile or 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 their window_ variants) can be precomputed and passed in kwargs: with #50887's get_data_dependent_inputs computing them, the forward is sync-free for flash, SDPA and flex.

Related PRs

PR Relation
#45153 · native torch flash attention on the same varlen API complementary: it adds an implementation, this makes the default sdpa use the kernel and gives the packed models one path it would plug into
#48418 · packed split sizes once per Qwen3-VL forward superseded for SDPA, flash and flex, which no longer split
#47210 · varlen for packed text rows covered here: SDPA varlen for packed text rows, through create_causal_mask

Tests

Check Result
touched models' suites vs main, same conditions 🟢 no failure only on this branch (flaky static-cache / assisted-decoding and an env-dependent kernel test fail on both)
SDPA (varlen, fallback) and flex vs eager, Qwen2-VL and Qwen2.5-VL (window) towers, mixed and equal sizes 🟢 fp32 ≤ 4e-7, bf16 within one or two rounding steps
eager attention weights and memory 🟢 identical to main
test_sdpa_padding_matches_padding_free_with_position_ids, all models 🟢 no failure only on this branch (BERT-family tolerance flakes fail on both)
packed Llama row (GQA), SDPA vs documents run apart 🟢 exact on CUDA bf16 (varlen), 2e-7 on CPU fp32 (per document)

Future work

What How
cu_seqlens / max_seqlen in **kwargs typed like FlashAttentionKwargs: packed layers shrink to (hidden_states, position_embeddings, **kwargs)
sync-free forward get_data_dependent_inputs (#50887) precomputes max_seqlen and the block mask
ColQwen2 its processor pads Qwen2-VL's packed pixel_values for DDP, and the model unpads them back

🤖 Generated with Claude Code

… 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>
@HuggingFaceDocBuilderDev

Copy link
Copy Markdown

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.

IlyasMoutawwakil and others added 2 commits November 25, 2026 11:00
`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 IlyasMoutawwakil changed the title Packed sequences attention: SDPA varlen, flex block masks, one shared path Packed sequences attention: one path for encoders and packed text (SDPA varlen, flex block masks) Nov 25, 2026
@IlyasMoutawwakil
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>
@github-actions

Copy link
Copy Markdown
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

No deployments
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