Repository navigation
[rl] fp8 KV + MTP: verify rows take the fp8 descales, one FA4 call with query_len_in_heads - #6366
felipemello1 wants to merge 55 commits into
Conversation
`VLLMEngine.Config.num_speculative_tokens = k` drafts k tokens per decode step with the
checkpoint's MTP head, run as vLLM's own draft model (Qwen3_5MTP). The TorchTitan target
verifies them with vLLM's rejection sampler, so the output follows the target's distribution
and the logprobs are the target's.
- engine: the field maps to speculative_config {"method": "mtp"}, with the target's attention
backend for the draft's attention layer. The config refuses k < 0 and session_kv_holder;
the engine refuses batch-invariant mode and image prompts before building anything.
- registry: the draft's config parse goes to vLLM's HF parser.
- worker: TorchTitanEagleProposer accepts only Qwen3.5-architecture drafts, gives the draft
its own model config, and points its embed_tokens / lm_head at the target's storage, so
they follow model state dict loads.
- GDN: with drafts, the layer uses vLLM's GDN metadata and a port of vLLM's _forward_core;
the prefill recurrence stays on Attention Gym.
- config: decode CUDA graphs cover max_num_seqs * (1 + k) tokens.
- generate.py refuses num_speculative_tokens > 0 for now.
- TODOs at the follow-up sites (V2 runner, eager draft passes, FULL graphs for mixed batches,
session KV holder, trained MTP head, vLLM hooks, acceptance metrics, KDA, SGLang).
…at logger vllm.spec_decode_num_drafts, vllm.spec_decode_num_draft_tokens and vllm.spec_decode_num_accepted_tokens (vLLM's own names), from SchedulerStats.spec_decoding_stats. Acceptance rate and mean acceptance length come from their rates (README).
…s with drafts - GPU tests: verify rows with j of 1 + k tokens accepted match j single-token decodes without drafts, and each row of a step with drafts (decode, verify, prefill) matches the same request in a step without drafts. - VLLMEngine.Config raises for num_speculative_tokens > 0 with cuda_graph.mode="FULL": vLLM's GDN metadata builder supports CUDA graphs for decode steps only. - The vision check names its condition: models with a vision encoder. - Drop the roadmap TODOs in kda.py and the SGLang linear attention backend.
With MTP drafts, vLLM drops the last block of every prefix hit (its EAGLE block drop) and caches the prompt-end GDN state one block earlier. A held session's next turn then also needs the attention block past the held ones. Once churn evicts that block, the hit falls to a boundary with no GDN state, and the turn recomputes its whole history. - engine: with session_kv_holder, speculative_config also gets disable_eagle_block_drop=True, and num_speculative_tokens no longer refuses the holder. Engines without the holder pass no new key. vLLM main removes the drop and this key; a TODO says what to delete and re-check at that pin, and why to keep it until then. - holder: with drafts, refuses a scheduler whose use_eagle_block_drop is on (the bit vLLM's scheduler hands its KV cache manager). Without drafts it reads nothing new. - test: the held-prefix churn test also runs with 3 draft tokens (3 more GDN state blocks per request, a speculative config, block drop off); the refusal test sets the bit. GPU check (Qwen3.8-27B, MTP-3, FULL_DECODE_ONLY, one GB300): after other prompts push 1.3x the KV cache through it, a held session's next turn hits 26,880 cached tokens. With vLLM's default drop forced on, it hits 0.
… vLLM generator One conflict, in torchtitan/rl/generator/vllm/worker.py: the PR adds TorchTitanEagleProposer and _alias_draft_weight after TorchTitanGPUWorker; main (#5402) adds the XPU worker block at the same spot. Both kept: the drafter classes first, then main's `if device_type == "xpu":` block.
Only TorchTitanGPUWorker installs TorchTitanEagleProposer. On XPU, a flex model without GDN layers passed every platform check, then reached vLLM's stock drafter, which looks up `model.embed_tokens` on the target and fails. - _validate_platform raises for num_speculative_tokens > 0 off CUDA; the field docstring lists non-CUDA devices; one test case covers it. - The XPU worker's comment says it swaps the runner only. - The load_model_state_dict TODO points at the shared MTPDecoder (torchtitan/models/common/mtp.py), which DeepSeek-V3 and V4 inherit.
FA4 runs its SwapAB decode kernel only for one query token per row, so 4-token verify rows took the prefill kernel: 23.9 of a 46.4 ms verify step (Qwen3.8-27B, 26 rows, GB300). Each row's tokens now become extra query heads of one decode row over the keys they all see; the last k keys are added in fp32 and merged by logsumexp. The decode path runs only where SwapAB admits the rows: SM100/SM103, query heads per KV head x (1 + k) <= 32, K head dims 64/96/128/256. The GPU test compares verify and mixed batches with causal attention at max_seq_len 131072 and 262144, and runs in the B200 job.
…refill and for the drafter FULL with drafts becomes vLLM's FULL_AND_PIECEWISE on breakable CUDA graphs: uniform verify steps replay FULL graphs; steps with prefill and the MTP drafter replay piecewise graphs with attention and GDN run eagerly between pieces. VLLMEngine sets VLLM_USE_BREAKABLE_CUDAGRAPH=1 and raises unless vLLM's attention op is then a graph break. The GDN eager-break wrapper is built on first use (k > 0 layers only). TODOs name the remaining MTP step costs. Qwen3.8-27B, one GB300, 26 sessions: 1,106 output tok/s vs 1,008 with FULL_DECODE_ONLY (no MTP: 892).
VLLMEngine.Config.kv_cache_dtype = "fp8" stores K/V in e4m3 (vLLM's reshape_and_cache_flash, scale 1), quantizes the query in vLLM's Attention layer, and runs FA4's fp8 forward (_flash_attn_fwd with TensorwiseScales) for decode and prefill rows. "auto" (bf16) stays the default and keeps the trainer's kernel. - fp8 with debug.batch_invariant raises: generator logprobs can't match the bf16 trainer bitwise. - fp8 with MTP drafts raises: the verify-row decode path doesn't pass the fp8 descales yet. - TorchTitanVarlenInnerAttentionBackend.supports_combination hides fp8 from FlashAttentionBackend's check (about vLLM's own kernel) and returns a reason off SM100. TODOs with drop conditions mark the three workarounds. - test_paged_attention_fp8.py runs in the B200 RL workflow. FA4 floor >=4.0.0b39, the first release with TensorwiseScales. Qwen3.8-27B on one GB300, fp8 vs bf16: 5.6M vs 2.8M KV tokens; 1,043 vs 902 output tok/s at 32 sessions with 27k-135k contexts; 857 vs 892 at 26 sessions sharing prompts (FA4's SwapAB decode kernel takes only bf16/fp16, so fp8 decode runs FA4's standard kernel). Trainer-vs-generator logprob mean abs diff at temperature 1: 0.0217 vs 0.0096.
…en FA4 takes query_len_in_heads - _verify_rows_as_decode passes the (q, k, v) descales to the decode call and dequantizes the fp32 tail; its decode-call output is bf16 like the caller's. - An FA4 whose SwapAB kernel takes query_len_in_heads hides key L-4+i from the tokens before token i, so fp8 verify rows run as one decode call over all keys: no fp32 tail or merge (~0.11 ms per layer at 26-32 rows, GB300). Only when V's head dim equals K's: SwapAB refuses some DiffKV head dims. bf16 rows keep the tail path: torch's varlen API can't pass the knob. - VLLMEngine with fp8 KV and drafts raises at init when FA4 lacks query_len_in_heads (the tail path was never measured with drafts in an engine), and logs which flash_attn.cute it loaded. The verify GPU test also runs an fp8 cache (vLLM's uint8 storage, e4m3 query, non-unit scales): rel L2 < 0.05 per row; dropping the descales of either part gives 0.45-0.6. The CPU test fakes flash_attn.cute, so it runs without FA4.
- vllm/attention/attention.py: the SwapAB TODO names SwapABPolicy.rejection instead of a line number in FA4's config.py; blank lines around the verify-step dispatch. - vllm/attention/gdn.py: a blank line before the speculative branch of _forward.
- attention/attention.py, vllm/engine.py: the FA4 TODOs name Dao-AILab/flash-attention#3217, which adds fp8 SwapAB and query_len_in_heads. - vllm/attention/attention.py: _verify_rows_as_decode gets its own banner for the one-call path; the "keys every token sees" banner moves to the decode + tail path it labels.
- The verify-step TODO names the real blockers: FA4's query_len_in_heads (open FA4 PR) and torch's varlen API, which can't pass it yet. - A TODO on the breakable-CUDA-graph variable: drop it once vLLM takes it as a config field. - GDN's speculative call uses kwargs; the verify gate's comment is 3 lines; no effort estimate in the GDN TODO.
- The two fp8 TODOs are 3 lines each: torch's varlen API can't take fp8 descales (no torch issue filed yet), and the FA4 floor rises with the first release that has fp8 SwapAB (the open FA4 PR), with its GB300 numbers. - The fp8 call's num_splits drops the batch-invariant branch: the engine refuses fp8 in batch-invariant mode. - kv_cache_dtype's docstring drops a mask the repo doesn't have. - The fp8 + drafts error says how to fix it.
Conflicts: the fp8 TODOs in generator/attention/attention.py take the lower branch's final form; vllm/engine.py keeps this branch's FA4 check, which replaces the lower branch's fp8 + drafts refusal.
… message) - `_verify_rows_as_decode`'s fp8 paths are two picture rows instead of prose. - `query_len_in_heads`'s arg doc names the argument instead of an undefined n. - The startup error for fp8 + drafts without query_len_in_heads says how to fix it.
… call The fp32 tail of `_verify_rows_as_decode` adds 53-71 us per layer at 1-4 rows (Qwen3.5 attention, head dim 256, GB300), and SwapAB only saves time when 8+ rows share long prompts. Steps with fewer rows keep FA4's varlen call; the row count is fixed per FULL graph. The verify test gets 8 rows and a few-rows case.
… block table) - `_verify_rows_as_decode`'s docstring counts the fp32 tail's 1.2 ms next to the 14.9 ms. - The verify test's block table is max_seq_len / page_size wide, as vLLM sizes it, so FA4 runs its per-sequence splits. - Single backticks in the new docstrings.
…ne refusal test) - `test_forward_matches_causal_attention` runs fp8 for the steps without verify rows (vLLM's uint8 cache, e4m3 query, non-unit scales), so `forward`'s fp8 branch has a test. - kv_cache_dtype's docstring says the block sizes are Qwen3.8-27B's, and how the ratios were measured in one line. - The two fp8 refusal tests are one parametrized test; the fp8 TODO comment has a verb.
# Conflicts: # tests/rl/unit_tests/gpu/test_vllm_verify_attention.py
…ng windows refused, one fp8 GPU test) - fp8 with MTP drafts reads only config fields, so `VLLMEngine.Config.__post_init__` refuses it. - fp8 with sliding-window attention (gpt-oss, which also adds sinks; Muse Spark) is untested: refuse it. - Drop test_paged_attention_fp8.py: the verify test's fp8 cases cover the decode and the varlen call with non-unit scales, now that its mixed case starts with a 1-token row.
…nvariant, one bf16 TODO, no flash_attn.cute import in the FA4 check)
…LLM's flex backend refuses fp8)
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 1m 17s —— View job Approve -- the code fixes from the last review are in. Before merge, the human-written summary still needs filling in and one description claim needs fixing: the verify gate has no head-dim check. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The code-level items from the last review are fixed at d4b5325. What's left is in the PR description, plus one docstring nit. A maintainer still needs to review.
Re-review of the earlier items
attention/attention.py,ValueError->assert: fixed.- Duplicate bf16 TODO: fixed. The forward's TODO now covers bf16 rows only, and the one-call TODO keeps only the copy cost.
- Extra
flash_attn.cuteimport in the engine check: fixed. The CPU test now patches onlyfa4_takes_query_len_in_heads. - Empty "Summary (human-written)": still open.
Example. One fp8 verify step, 3 rows, k = 3, seq_lens [130, 30000, 257]:
before: VLLMEngine.Config(kv_cache_dtype="fp8", num_speculative_tokens=3) -> ValueError
after: one _flash_attn_fwd: q (3, K*4*G, D), cu_seqlens_q [0,1,2,3], seqused_k [130, 30000, 257],
query_len_in_heads=4 -> one copy back to token-major; no fp32 tail, no 8-row cutoff
FA4 without the knob: RuntimeError at VLLMEngine init
bf16: unchanged
Must fix
- PR description: "Summary (human-written)" is still empty, and only the author can fill it in. One claim also doesn't match the code. The text block says "layers the verify gate skips, e.g. a head dim SwapAB doesn't take". The gate at
vllm/attention/attention.py:386-395has no head-dim condition. It skips only non-FA4, sliding windows,out_transform, and batch-invariant mode. Either drop the head-dim example or say what happens to such a layer (see Questions).
Should consider
vllm/attention/attention.py:473-- the docstring hardcodesL-4+ifor k = 3; write it in terms ofn(inline).
Questions
- Say a layer's head dim isn't one SwapAB takes, and FA4 picks another fp8 kernel for a
max_seqlen_q=1call withquery_len_in_heads=4. Does that FA4 build raise, or does it ignore the knob? If it ignores it, earlier tokens would see later keys without any error. One line in the description (or a sentence at L494) saying FA4 raises would settle this.
Not verified: FA4's query_len_in_heads semantics and packing order (token-major within each KV head), and the GB300 timings. These rest on the author's GPU runs. The fp8 one-call cases of test_vllm_verify_attention.py skip on FA4 4.0.0b40.
|
Reply from claude: Round 2 is in 1f27085 (the docstring nit). The other two items need no code change. The head-dim claim. The gate does check head dim, through self.verify_query_len = None
if speculative_config is not None:
verify_query_len = 1 + speculative_config.num_speculative_tokens
if (
torch.cuda.get_device_capability() in ((10, 0), (10, 3))
and self.head_size in (64, 96, 128, 256)
and self.num_queries_per_kv * verify_query_len <= 32
):
self.verify_query_len = verify_query_lenThe body now says this. Q: off SwapAB, does FA4 raise or ignore the knob? It raises. In the FA4 PR ( |
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 59s —— View job Approve -- the docstring fix is in, and I withdraw last round's head-dim finding: the gate checks head dim through |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The only commit since the last review (1f27085) fixes the docstring nit. Only the PR description is still open. A maintainer still needs to review.
Re-review of the earlier items
- Docstring
L-4+i->L-n+i(vllm/attention/attention.py:473-474): fixed. - Head-dim claim: I was wrong last round. The gate does check head dim, indirectly.
__init__(L238-246) setsverify_query_lenonly for SM100/SM103, head dim in {64, 96, 128, 256}, andnum_queries_per_kv * n <= 32. Otherwise it staysNone, sois_uniform_verify(L380-383) is never true and the layer takes the fp8 varlen call. The description now says this. - FA4 raises or ignores the knob off SwapAB: the author says the FA4 PR raises
ValueErrorthere (and with a local window,score_modormask_mod). This answers the question. - Empty "Summary (human-written)": still open.
Example. One fp8 verify step, 3 rows, k = 3, seq_lens [130, 30000, 257], head dim 256:
before: VLLMEngine.Config(kv_cache_dtype="fp8", num_speculative_tokens=3) -> ValueError
after: one _flash_attn_fwd with q (3, K*4*G, D), seqused_k [130, 30000, 257], query_len_in_heads=4,
then one copy back to token-major; no fp32 tail, no 8-row cutoff
head dim 192 (no SwapAB): verify_query_len=None -> the parent PR's fp8 varlen call
FA4 without the knob: RuntimeError at VLLMEngine init
Must fix
- PR description: "Summary (human-written)" is empty. Only the author can fill it in.
Not verified: FA4's query_len_in_heads semantics, its packing order, and its raising off SwapAB (these are in the FA4 PR, not this repo). The GB300 timings are also unverified. The fp8 one-call cases of test_vllm_verify_attention.py skip on FA4 4.0.0b40.
# Conflicts: # tests/rl/unit_tests/cpu/test_generator.py
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 55s —— View job Approve -- the only new commit merges the parent's fp8 tensor-parallel refusal and adds no new problems. Before merge, the author still needs to fill in the human-written summary. See the review. |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The one change since the last review (1f27085) is ad1774b, which merges the parent's fp8 tensor-parallel refusal. It adds no new problems. Only the PR description is still open. A maintainer still needs to review.
Re-review
- New since 1f27085:
engine.pygets the parent'stensor_parallel_degree > 1refusal, andtest_fp8_kv_cache_refusalsgets itsparallelismcolumn andtensor_parallelcase. Against the base branch, this PR's diff only addsconfig_kwargs/errorto that test and thedrafts_without_query_len_in_headscase. The TP check runs before the FA4 check, and the TP case passes no drafts, so thefa4_takes_query_len_in_headsmonkeypatch doesn't change what that case tests. - Every earlier code item is still fixed at HEAD: the assert, the single bf16 TODO, the check with no extra import, and
L-n+iin the docstring. - Empty "Summary (human-written)": still open.
Example. One fp8 verify step, 3 rows, k = 3, seq_lens [130, 30000, 257], head dim 256:
before: VLLMEngine.Config(kv_cache_dtype="fp8", num_speculative_tokens=3) -> ValueError
after: one _flash_attn_fwd with q (3, K*4*G, D), seqused_k [130, 30000, 257], query_len_in_heads=4,
then one copy back to token-major; no fp32 tail, no 8-row cutoff
fp8 + tensor_parallel_degree=2: ValueError at VLLMEngine init (parent PR's check, runs first)
FA4 without the knob: RuntimeError at VLLMEngine init
Must fix
- PR description: "Summary (human-written)" is empty. Only the author can fill it in.
Not verified: FA4's query_len_in_heads semantics and packing order, which live in the FA4 PR, not in this repo. The GB300 timings are also unverified. The fp8 one-call cases of test_vllm_verify_attention.py skip on FA4 4.0.0b40.
0e7ce67 to
4bf200c
Compare
…pytorch#6366 on pytorch#6365's head) Port of pytorch#6366 (ad1774b; its own delta e5678e9..ad1774b) onto pytorch#6365's head 6348be1, which dropped the descales: fp8 is now told by the cache dtype. As r8 (597ebff) ran it: - paged_varlen_attention_out takes query_len_in_heads on the fp8 path; fa4_takes_query_len_in_heads(). - Uniform fp8 verify steps go to _verify_rows_as_decode at any row count, which makes one decode call over every key; FA4 hides each token's later keys. V head dims unlike K's keep the varlen call. - The engine refuses fp8 with drafts on an FA4 without query_len_in_heads. Needs an FA4 with query_len_in_heads (Dao-AILab/flash-attention#3217); the r11 run puts r8's copy fa4_b40_fp8swapab first on PYTHONPATH. Per layer on the r11 venv (runshared:46): verify 1.436 -> 0.973 ms, decode 1.433 -> 0.953 ms.
|
Reply from claude: closing. #6365 now runs fp8 MTP verify steps as one FA4 varlen call ( |
Summary (human-written)
Agent details
Needs retesting on B200 (SM100): every number below is from one GB300 (SM103). The kernels' split heuristics are tuned per GPU, so B200 timings can differ.
Stack: MTP speculative decoding -> MTP verify steps -> fp8 KV cache -> this PR.
TLDR: This PR needs FA4's open PR that adds
query_len_in_heads. On FA4 4.0.0b40, the newest release, fp8 KV + MTP drafts still raises at engine start. With that FA4, an fp8 KV cache and MTP drafts run together: each fp8 verify row is one call to SwapAB (FA4's decode kernel for one query token per row), and FA4 hides each token's later keys. fp8 verify rows never take the fp32 tail. Qwen3.8-27B, one GB300, 32 sessions: fp8 + MTP-3 gives 1,634 output tok/s, vs 1,170 for fp8 without MTP and 902 for bf16. Stock vLLM with fp8 + MTP-3 also gives 1,634.Problem
VLLMEngine.Config:_verify_rows_as_decode(the MTP verify steps PR) passes no descales.Solution
_verify_rows_as_decode(descales=...): an fp8 verify row runs as one FA4 call over all its keys, withquery_len_in_headsso FA4 hides each token's later keys. This holds at any row count: the MTP verify steps PR's 8-row cutoff exists because of the fp32 tail's cost, and one call has no tail. Under 8 rows, one call takes 0.47-0.92x the time of FA4's fp8 varlen call (table below).VLLMEngine.Configno longer refuses fp8 with drafts. Instead,VLLMEngineraises at init when FA4's_flash_attn_fwdlacksquery_len_in_heads(fa4_takes_query_len_in_heads, a cached signature check). So no fp8 verify row needs the decode call + fp32 tail, and this PR adds no fp8 tail. Layers whose V head dim differs from K's, which SwapAB may refuse, come only from MLA in batch-invariant mode, and fp8 refuses that mode at engine start.Results
Hot swap with fp8 KV, MTP-3 and the CPU offload: a weight update under load gave no error, in 2 runs. After it, greedy outputs equal a fresh engine with the same target and drafter weights, bit for bit (8/8 streams).
NOTE: the engine and drift numbers ran on a development branch that also carries generator changes not in this stack (e.g. the CPU KV offload connector). The per-layer table ran an earlier commit of that branch. There, the two attention files differ from this PR's head only in comments, docstrings, a
num_splitsterm for batch-invariant mode (which fp8 refuses), an fp8 decode + fp32 tail path that this head drops (those runs never took it: every fp8 verify row ran the one call), and the bf16 8-row cutoff. The unique-context rows ran a later commit of that branch, whose attention files differ from this PR's head the same way; every decode step there had 8+ rows. One run per arm.NOTE: MTP pays only while the KV cache has room; the 46-session rows above show both sides.
NOTE: two open PRs edit files this PR edits, so the one that lands second rebases. The vLLM V2 model runner PR:
vllm/attention/attention.py,engine.py,test_generator.py. The ROCm paged-KV gather PR:vllm/attention/attention.py.NOTE: CI's
lint (3.11)fails on pyrefly'sCould not import quadratic_attention_flops_per_tokenattorchtitan/models/kimi_k3/dsa.py:297, a file this stack doesn't touch. CI lints this PR merged onto the MTP speculative decoding PR's merge commit, which sits on main 519624e. main has that error since 74a2c8e and fixed it in c561820. The MTP speculative decoding PR's own lint fails the same way: https://github.com/pytorch/torchtitan/actions/runs/45483313210/job/138761942077You may ask: why raise instead of falling back to the decode + fp32 tail when FA4 lacks the knob? That fallback would keep a second fp8 verify path, with its own test, that no engine run has measured with drafts. Raising keeps one fp8 verify path. TODO at the check: drop it once a released FA4 takes
query_len_in_heads.Follow up / TODO (each has a
# TODOat its site)query_len_in_heads.query_len_in_heads, and raise the FA4 floor.Test plan (TorchTitan ad1774b. The GPU runs used 59c7949: later commits change docstrings and merge the parent's tensor-parallel check, which runs at engine start and no GPU test reaches)
pytest tests/rl/unit_tests/gpu -m "not multi_gpu": 38 passed, 3 skipped (the parent 3be3ff0: 37 passed, 4 skipped).test_vllm_verify_attention.pyruns the fp8 "verify" and "few_rows" cases as one call and checks that a call gotquery_len_in_heads=4; they skip on an FA4 without it.test_vllm_verify_attention.pyon FA4 4.0.0b40, at 1f27085: 4 passed, 2 skipped (the fp8 one-call cases).pytest tests/rl/unit_tests/cpu: 830 passed, 6 skipped (the parent: 830 passed, 6 skipped).test_fp8_kv_cache_refusals[drafts_without_query_len_in_heads]replaces the parent's config-time drafts test; it patchesfa4_takes_query_len_in_heads, so it runs without FA4.torchtitan/rl/): all hooks passed.