Repository navigation
[rl] vLLM generator: run a mixed step's single-token rows as their own FA4 call - #5941
Conversation
|
@claude review |
There was a problem hiding this comment.
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 withmax_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_qcame 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 insidetorchtitan/rl/generator/vllm/attention/; no core, config, or test changes. - Hidden syncs: none.
max_seqlen_qis a host int from vLLM metadata, and the split math stays on device. - Excluding
out_transformis necessary, not just a simplification: each call would return its ownlse, 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 = 1as a class attribute matchesTorchTitanLinearAttentionMetadataBuilder(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.
40a252e to
4af4cd7
Compare
|
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
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. 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. |
|
@claude review again |
There was a problem hiding this comment.
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(lengthnum_reqs) lines up withseqused_k(lengthnum_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_lens0) 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:87uses 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.whereops 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).
## 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.
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 setmax_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 oncemax_seqlen_q > 128(default_pack_gqainflash_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:
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 clampingcu_seqlens_qat the number of leading single-token rows, so it is CUDA-graph safe (no host sync, no data-dependent shapes):Each call gets the other call's rows with zero KV length (
seqused_k): atmax_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
pack_gqa=Trueper call:torch.nn.attention.varlen.varlen_attn_outdoes not expose it, and the long rows prefer 2CTA (~8% slower with PackGQA).max_num_batched_tokensonly makes mixed steps rarer (see the table).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):
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.
TestBitwiseParityVarlenpasses, includingtest_vllm_decode_vs_prefill, whose generation runs mixed steps.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_tokensDecode-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 failstest_vllm_decode_vs_prefill, so the existing test covers a wrong split; no new test.seqused_kzeroing applies: 64 of 64 tokens match, with the same max logprob difference (0.027) as without this PR.