Skip to content

[rl] vLLM generator: run a mixed step's single-token rows as their own FA4 call - #5941

Merged
tianyu-l merged 1 commit into
mainfrom
vllm-mixed-attn-split
Nov 8, 2026
Merged

tianyu-l merged 1 commit into
mainfrom
vllm-mixed-attn-split

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Upstream FA4 seems not optimized for mixed prefill-decode setup. This PR is a bandaid, which when getting mixed prefill-decode request, seperately calls one prefill kernel, and one decode kernel.

Why

With chunked prefill, vLLM puts prefill chunks into the same step as running decodes. Our vLLM attention backend runs such a mixed step as one FA4 varlen call, and FA4 picks one kernel configuration per call from max_seqlen_q. The multi-token rows set max_seqlen_q, so the step's single-token decode rows lose the configuration a decode-only step gives them. For example, at head dim 256, when the GQA ratio does not divide 128, FA4 turns PackGQA off for every sequence once max_seqlen_q > 128 (default_pack_gqa in flash_attn/cute/config.py): each decode row then takes its own query tile per query head and reads its KV once per query head. Head-dim-128 GQA models slow down too (table below).

Example. Qwen3.5-27B (24 query heads over 4 KV heads, head dim 256), GB300, FA4 4.0.0b38, 128-token KV pages (what our backend uses with FA4 on SM100), ~9,000 KV tokens per sequence:

one FA4 call                                     time per call
100 decode rows (max_seqlen_q = 1)               1.70 ms
the same rows, max_seqlen_q = 129                6.30 ms
100 decode rows + one 650-token prefill row      6.59 ms   <- every mixed step, per attention layer
the same, as two calls (decode rows, prefill)    1.92 ms   <- this PR

In an RL generator under load (Qwen3.5-27B, one engine, 100 concurrent multi-turn requests), the mixed steps took ~3x as long as decode-only steps and set the inter-token latency (numbers below).

What changed

  • TorchTitanVarlenInnerAttentionImpl.forward: under FA4, a step with any multi-token row runs two varlen calls into the same output buffer: one over the single-token rows (max_seqlen_q = 1), one over the rest. The split happens on device by clamping cu_seqlens_q at the number of leading single-token rows, so it is CUDA-graph safe (no host sync, no data-dependent shapes):

    cu_seqlens_q            [0, 1, 2, 3, 653]   (3 decode rows, one 650-token row)
    decode call   min(., 3) [0, 1, 2, 3, 3]     max_seqlen_q 1    seqused_k [k0, k1, k2, 0]
    prefill call  max(., 3) [3, 3, 3, 3, 653]   max_seqlen_q 650  seqused_k [0, 0, 0, k3]
    

    Each call gets the other call's rows with zero KV length (seqused_k): at max_seqlen_q <= 128, FA4 still processes the KV of rows with no query tokens, so without this the prefill call over 100 empty decode rows and one 16-token row costs as much as the single call (8.9 ms in the setting above).

  • The backend's metadata builder sets reorder_batch_threshold = 1, so vLLM orders single-token rows first. Hybrid models (GDN, KDA) already got this order from their linear-attention builders; dense models now get it too.

  • Layers with an output transform (they need the logsumexp) keep one call. TODO in code: drop the split once FA4 decides PackGQA per sequence ([CuTe / SM100] varlen, head dim 256 with GQA: one query longer than 128 turns PackGQA off for every sequence, so decode rows in a mixed prefill/decode batch run ~4x slower Dao-AILab/flash-attention#3146).

Alternatives considered

Microbenchmark across attention shapes

FA4 4.0.0b38, GB300, 128-token KV pages, 100 decode rows plus one multi-token row, ~9,000 KV tokens per sequence, ms per step and attention layer (CUDA graph replay):

Query / KV heads, head dim Multi-token row One call This PR
24 / 4, 256 (Qwen3.5-27B) 16 8.90 2.24
128 17.47 2.28
650 6.59 1.92
2000 6.82 2.16
32 / 8, 128 16 2.83 1.06
650 2.02 0.87
16 / 8, 128 16 1.43 0.95
650 1.04 0.87
64 / 8, 128 16 5.51 1.02
650 3.95 0.96

The split is faster for every shape and row length measured (2 to 2000 tokens), so the condition does not depend on FA4's thresholds.

Numerics

The split changes which FA4 kernel computes a decode row inside a mixed step, to the one decode-only steps already use.

  • FA4 4.0.0b37: the split output is bitwise identical to the single call (microbenchmark, 100 decode rows + 2 prefill rows).
  • FA4 4.0.0b38: max abs difference 4.9e-4 (bf16) between the two kernels outside batch-invariant mode.
  • Batch-invariant mode: TestBitwiseParityVarlen passes, including test_vllm_decode_vs_prefill, whose generation runs mixed steps.
  • Qwen3.5-27B, real weights, greedy, a 5,000-token prompt prefilled and decoded beside 100 decoding requests and a stream of new prompts: 64 of 64 tokens match the request run alone, with the same max logprob difference (0.043) with and without this PR.

Performance

Qwen3.5-27B, one GB300 per engine, TP 1, FULL CUDA graphs, 100 concurrent multi-turn requests (~9,000-token contexts, ~900 new prompt tokens and 550 output tokens per turn), 240 s measured after a 300 s warmup:

max_num_batched_tokens ITL before ITL after Mixed step before -> after (synced)
2048 (vLLM's default) 45.6 ms 37.0 ms (-19%) 103 ms -> 66 ms
16384 39.6 ms 35.7 ms (-10%) 143 ms -> 106 ms

Decode-only steps are unchanged. In the mixed steps' profile, the attention call over the prefill rows takes 0.37 ms per layer, against 3.4 ms for the single call before.

Testing

  • TestBitwiseParityVarlen (2x GB300, FA4 4.0.0b38): all passed. A mutation that drops the decode rows from the first call fails test_vllm_decode_vs_prefill, so the existing test covers a wrong split; no new test.
  • The Qwen3.5 / Kimi K3 / GPT-OSS parity classes fail at setup in my environment with and without this PR (FSDP mesh mismatch); not run.
  • The greedy correctness check was repeated with 64-token new prompts, so that every multi-token row in the mixed steps is at most 128 tokens and the seqused_k zeroing applies: 64 of 64 tokens match, with the same max logprob difference (0.027) as without this PR.
  • The greedy correctness check and the benchmark above ran the same patch on an earlier main (f548851), with the packages of our RL cluster environment (FA4 4.0.0b37). The end-to-end benchmark was rerun on this revision with the same results (ITL 37.0 and 35.7 ms).

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 7, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 7, 2026
@tianyu-l

tianyu-l commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 17s —— View job


Approve: the stopgap is correct, measured, and safe under CUDA graphs. One question is open about the split running on models the stated cause doesn't affect. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- a measured, CUDA-graph-safe stopgap in torchtitan's own vLLM backend, with the upstream root cause filed and linked in a TODO. One question about scope is below.

What this PR does. Under FA4, a step that mixes decode and prefill rows now runs as two varlen_attn_out calls into the same output buffer. One call covers the leading single-token rows with max_seqlen_q = 1; the other covers the remaining rows with the step's max_seqlen_q. The split point is the length of the leading run of 1-token rows, computed on device (cumprod). Clamping cu_seqlens_q with min/max at that point empties the rows outside each call, so tensor shapes don't depend on the batch. reorder_batch_threshold = 1 makes vLLM put decode rows first for dense models too.

Example.

cu_seqlens_q = [0, 1, 2, 3, 653]       3 decodes + one 650-token chunk
before: 1 call, max_seqlen_q 650 -> FA4 turns PackGQA off for the 3 decode rows too
after : call 1 cu=[0,1,2,3,3]       max_seqlen_q 1    (decode kernel config)
        call 2 cu=[3,3,3,3,653]     max_seqlen_q 650  (rows 0-2 now have length 0)
unordered batch [0, 1, 651, 652, 653]: leading run = 1 -> rows 2-3 go to call 2;
        still correct, only less of the gain

Correctness doesn't depend on the reorder. Each token lands in exactly one call, because the clamp boundary equals cu_seqlens_q[k] for the leading run of k rows. Zero-length CUDA-graph padding rows end the run, so they are handled too.

Should consider

  • attention.py:292 -- the split runs on every FA4 mixed step, including head-dim-128 models and FULL-mode mixed graphs captured with max_query_len <= 128, where the stated PackGQA cause doesn't apply. It needs either a broader justification or one number showing no regression (inline).

Questions

  • In FULL mode, mixed steps above the largest capture size run eagerly, while smaller ones replay a graph whose max_seqlen_q came from the capture dummy. Did the measured mixed-step gain come entirely from eager steps, i.e. 650-token chunks above the capture size?
Details
  • Necessity: the problem is real and quantified, from a microbenchmark up to end-to-end ITL (-19% at vLLM's default max_num_batched_tokens). The root fix belongs in FA4 (Dao-AILab/flash-attention#3146), and the TODO links it. The change stays inside torchtitan/rl/generator/vllm/attention/; no core, config, or test changes.
  • Hidden syncs: none. max_seqlen_q is a host int from vLLM metadata, and the split math stays on device.
  • Excluding out_transform is necessary, not just a simplification: each call would return its own lse, valid only for its rows. In practice only gpt_oss (sinks) keeps the single call.
  • The split metadata is recomputed in each full-attention layer: about 7 tiny kernels, running eagerly in mixed steps that are not graph-captured. Computing it once per step in the builder would need persistent buffers for FULL replay, which is more code than it saves. Not worth changing, given that the measured ITL already includes this cost.
  • reorder_batch_threshold = 1 as a class attribute matches TorchTitanLinearAttentionMetadataBuilder (linear_attention.py:73).

Not verified: FA4's tile scheduler sizing its grid from total query tokens rather than max_seqlen_q, which the existing FULL mixed graphs already rely on; vLLM's handling of reorder_batch_threshold at the pinned commit.

@felipemello1 felipemello1 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

good finding!

@tianyu-l
tianyu-l force-pushed the vllm-mixed-attn-split branch from 40a252e to 4af4cd7 Compare November 7, 2026 23:10
@tianyu-l

tianyu-l commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. Both points are addressed in 4af4cd7.

Guard wider than the stated cause. Measuring head-dim-128 shapes found a real problem, but in the first revision, not in head dim 128. At the 128-token KV pages our backend uses with FA4 on SM100, FA4 still processes the KV of rows that have no query tokens when max_seqlen_q <= 128. So when every multi-token row in a step was at most 128 tokens, the second call over the empty decode rows cost as much as the single call, and the split was slower. Each call now gets the other call's rows with zero seqused_k. With that, the split is faster for every shape and row length measured (FA4 4.0.0b38, GB300, 100 decode rows at ~9,000 KV tokens plus one multi-token row, ms per layer):

Query / KV heads, head dim Multi-token row One call Split
24 / 4, 256 16 / 128 / 650 / 2000 8.90 / 17.47 / 6.59 / 6.82 2.24 / 2.28 / 1.92 / 2.16
32 / 8, 128 16 / 128 / 650 / 2000 2.83 / 5.51 / 2.02 / 2.08 1.06 / 1.05 / 0.87 / 0.95
16 / 8, 128 16 / 128 / 650 / 2000 1.43 / 2.83 / 1.04 / 1.10 0.95 / 1.06 / 0.87 / 0.88
64 / 8, 128 16 / 128 / 650 / 2000 5.51 / 10.99 / 3.95 / 4.13 1.02 / 1.11 / 0.96 / 1.11

The condition therefore stays free of FA4 thresholds, and the comment now gives the general reason: decode rows lose the configuration a decode-only step gives them, and PackGQA is one example. TestBitwiseParityVarlen passes. A greedy check with 64-token new prompts, so that the zeroing applies, matches 64 of 64 tokens, with the same logprob difference as without this PR.

Did the gain come from eager steps? No. In the 2048-token-budget run, vLLM captured FULL graphs up to 2048 tokens, so the ~750-token mixed steps replayed graphs. The slow kernel (3.5 ms per layer, grid 24624) ran inside those graphs, and after the split the prefill call took 0.40 ms.

@tianyu-l

tianyu-l commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 0s —— View job


Approve: both points from the last review are resolved, and the new seqused_k zeroing is correct and safe under CUDA graphs. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- both earlier points are resolved at 4af4cd7, and the new seqused_k zeroing is correct and safe under CUDA graphs.

What changed since the last review. Each of the two FA4 calls now also zeroes seqused_k for the rows that belong to the other call. Before, FA4 at max_seqlen_q <= 128 still read the KV of rows with no query tokens, so the split was slower when every multi-token row was short. The comment now gives the general cause (decode rows lose the configuration a decode-only step gives them) and keeps PackGQA as one example. It still copies no FA4 thresholds into the condition.

Example.

cu_seqlens_q = [0, 1, 2, 3, 19]     3 decodes + one 16-token chunk, seqused_k = [k0, k1, k2, k3]
r1 decode call : cu [0,1,2,3,3]    max_q 1   seqused_k [k0,k1,k2,k3]  <- row 3 KV still read
                 prefill call: cu [3,3,3,3,19] max_q 16 seqused_k [k0,k1,k2,k3]  <- rows 0-2 KV still read
HEAD decode call : seqused_k [k0,k1,k2,0]
     prefill call: seqused_k [0,0,0,k3]

Earlier items

  • attention.py:294, guard wider than the stated cause: resolved. The author measured head dim 128 (16/8, 32/8, 64/8 GQA) at 16 to 2000 tokens, and the split is faster in every case. The comment now states the general reason.
  • Question about whether the gain came only from eager steps: answered. The 2048-budget run replayed FULL graphs for the ~750-token mixed steps, and the slow kernel ran inside them.

No new problems.

Details
  • Zeroing correctness: is_leading_single_token (length num_reqs) lines up with seqused_k (length num_reqs). torch.where(cond, int32_tensor, 0) stays int32, because a Python scalar doesn't promote the dtype. A row with zero query tokens and zero KV is what FA4 already gets for FULL-graph padding rows, so neither call adds a new input pattern. Each row's query tokens and its KV length go to the same call, so no row loses KV it attends to.
  • Padding rows (query length 0, seq_lens 0) end the leading run and go to the prefill call with KV length 0. That is correct.
  • Correctness doesn't depend on the reorder, so other builders' thresholds (mla.py:87 uses 512; vLLM takes the minimum across groups) and speculative decoding can only move rows to the prefill call. They never drop a row.
  • The two extra torch.where ops add to the per-layer split metadata, which is already in the measured ITL.

Not verified: FA4 behavior for rows with seqused_k = 0 beyond what the existing FULL-graph padding path already exercises (GPU only).

@tianyu-l
tianyu-l merged commit 239a73f into main Nov 8, 2026
@tianyu-l
tianyu-l deleted the vllm-mixed-attn-split branch November 8, 2026 00:04
felipemello1 pushed a commit that referenced this pull request Nov 8, 2026
felipemello1 pushed a commit that referenced this pull request Nov 8, 2026
tianyu-l added a commit that referenced this pull request Nov 10, 2026
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
The generator's paged attention (`paged_varlen_attention_out`, called by
the vLLM and SGLang engines' attention backends) is documented as
running "PyTorch's FlashAttention, the kernel the trainer's
`VarlenInnerAttention` runs". Outside batch-invariant mode it runs cuDNN
instead:
- `torch.nn.attention.varlen` tries cuDNN first, before FlashAttention,
and with cuDNN >= 9.24 (the RL environment has 9.26) cuDNN accepts
paged-KV calls with power-of-two pages, including vLLM's 128-token FA4
pages and SGLang's 1-token pages.
- Batch-invariant mode is unaffected: it passes `num_splits=1`, which
cuDNN rejects, so those calls already run FlashAttention.

cuDNN is much slower on the generator's shapes.

**Example.** One mixed step, 100 decode rows plus one 650-token prefill
row, ~9,000 KV tokens each, 24 query / 4 KV heads, head dim 256
(Qwen3.5-27B's attention), 128-token pages, GB300. Profiling
`paged_varlen_attention_out`:
```
before: cudnn_generated_fort_native_sdpa_sm100_flash_fprop_...   6.64 ms
after:  flash_attncute...FlashAttentionForwardSm100...            2.97 ms
```

## What changed
- `torchtitan/rl/generator/attention/attention.py`:
`paged_varlen_attention_out` runs the varlen call under
`sdpa_kernel([SDPBackend.FLASH_ATTENTION])`. 5 lines plus a comment.

## User-facing changes
| Before | After |
| --- | --- |
| Generator paged attention outside batch-invariant mode: cuDNN on
SM90/SM100 | FlashAttention (FA3/FA4), as the docstring already says |

## Numerics
- Batch-invariant mode: unchanged (it already ran FlashAttention); the
vLLM bitwise parity tests pass.
- Outside batch-invariant mode, the generator's logprobs change in the
last bits (a different kernel); no bitwise contract applies there.

## Performance
Kernel time per call through torch's varlen API, CUDA-graph replay,
GB300, 128-token pages, ~9,000 KV tokens per sequence (`cuDNN` = before,
`FA4` = after; flash-attn-4 4.0.0b38):

| Shape (q / kv heads, head dim) | Batch | cuDNN | FA4 |
| --- | --- | --- | --- |
| 24 / 4, 256 | 100 decode rows | 1.70 ms | 0.51 ms |
| 24 / 4, 256 | one 650-token prefill | 0.17 ms | 0.09 ms |
| 24 / 4, 256 | 100 decode + 650 prefill, split as in #5941 | 1.93 ms |
0.72 ms |
| 32 / 8, 128 | 100 decode rows | 0.75 ms | 0.51 ms |
| 32 / 8, 128 | 100 decode + 650 prefill, split | 0.87 ms | 0.64 ms |

Not measured: end-to-end generation throughput.

## Testing
- Kernel profile above: the call runs FA4 after the change.
- vLLM tests on GB300, launched as CI launches them:
  - `TestBitwiseParityVarlen` (2 GPUs): 3 passed.
  - `TestBitwiseParityQwen35DebugVarlen` (2 GPUs): 5 passed.
  - `test_generator_uneven_decode.py` (4 GPUs): 1 passed.
- `test_generator_dp_cudagraph.py`, both tests the H100 job runs (2 GPUs
each): passed.
- No new test: the backend choice is a performance property, and a test
that greps the profiler for kernel names would be brittle.

## Known issues / follow-ups
- FA4's fix for mixed batches (Dao-AILab/flash-attention#3146) is on FA4
main but not in a wheel yet. With it, one FA4 call on a mixed batch
costs about the same as #5941's split; once a wheel ships, bump
`install_rl_env.sh`'s FA4 pin and consider removing the split.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants