Skip to content

[rl] MTP speculative decoding in the vLLM generator - #6476

Draft
liangel-02 wants to merge 3 commits into
liangel-02/gdn-layer-draftsfrom
liangel-02/vllm-mtp-spec-decode
Draft

liangel-02 wants to merge 3 commits into
liangel-02/gdn-layer-draftsfrom
liangel-02/vllm-mtp-spec-decode

Conversation

@liangel-02

Copy link
Copy Markdown
Contributor

Supersedes #6287 (originally by felipemello1).

Summary (human-written)

Agent details

Needs retesting on H100: every number below is from one GB300 (SM103). The GDN draft path and the draft's attention backend were not run on H100.

Stack, bottom to top:

  1. "[rl] GDN builder: stage steps with drafts in fixed buffers"
  2. "[rl] MTP: replay the verify CUDA graph only when every row verifies"
  3. "[rl] GDN layer: run steps with drafts from TorchTitan's builder"
  4. this PR
  5. "[rl] MTP verify steps: run verify rows on FA4's decode kernel"
  6. "[rl] MTP on GDN models: FULL CUDA graphs for steps with prefill"
  7. "[rl] vLLM generator: fp8 KV cache through FA4's fp8 forward, MTP verify steps included"

The stack lands after the vLLM 0.33 PRs ("[rl] generator: vLLM 0.33 API fixes and TP padding in the model wrapper", "[rl] Install vLLM 0.33.0 on the torch nightly"). "[rl] generator: run on vLLM's model runner V2 (vLLM 0.34)" rebases on it.

TLDR: VLLMEngine.Config.num_speculative_tokens = 3 turns on vLLM's MTP drafting for Qwen3.5-architecture checkpoints that ship an MTP head (tested: Qwen3.8-27B). The draft guesses 3 tokens and the TorchTitan model checks them in one step. vLLM's rejection sampler keeps a draft token with probability min(1, p_target / p_draft) and resamples on a reject, so the output follows the TorchTitan model's distribution and the logprobs are its own. On one GB300 with Qwen3.8-27B, one request decodes 1.66x faster at a 27k-token context and 2.14x at 77k (144.7 vs 87.3 and 179.3 vs 84.0 tok/s), and the trainer agrees with MTP-3's logprobs as closely as with MTP off's (k3 2.61e-4 vs 2.65e-4).

With this PR, vLLM's MTP draft guesses 3 tokens and one TorchTitan model step checks them, so a step emits 2.35 tokens on average instead of 1 and one request at a 27k-token context decodes at 144.7 tok/s instead of 87.3 on one GB300, and the runner waits for each step's accepted-token count before rows move.

num_speculative_tokens = 3
  -> EngineArgs.speculative_config = {"method": "mtp", "num_speculative_tokens": 3, "attention_backend": <target's>}
  -> vLLM builds its own MTP draft (Qwen3_5MTP) from the checkpoint's mtp.* weights;
     its embed_tokens and lm_head point at TorchTitan's tok_embeddings and lm_head storage
  -> each decode step: the draft proposes 3 tokens, the target verifies 4 tokens per row, 1-4 tokens are emitted
     GDN layers: verify rows run vLLM's verify kernels (PRs 1-3); prefill rows stay on Attention Gym

Problem

  1. Decode at long context is slow: one request at a 27k-77k-token context decodes at ~85 tok/s on a GB300.
  2. Qwen3.8 checkpoints (Qwen3.5 architecture) ship a one-layer MTP head that vLLM can use as a draft model at no training cost.
  3. The vLLM generator refuses speculative decoding: every GDN layer raises in __init__.
  4. vLLM also can't build the draft next to a TorchTitan target. It parses the draft's HF config with the target's config_format ("torchtitan"), and it looks up the target's embedding and lm_head by HF attribute names.

Solution

  1. One config field, num_speculative_tokens, maps to vLLM's speculative_config with method "mtp". speculative_config becomes a TorchTitan-owned engine arg, so extra_engine_args can't set it. The draft's attention layer uses the target's backend: vLLM's own pick (FlashInfer) has no block size in common with CUSTOM's 128-token pages (FA4 on SM100).
  2. TorchTitanConfigParser sends the draft's config parse to vLLM's HF parser (registry.py).
  3. TorchTitanEagleProposer (worker.py) accepts only Qwen3.5-architecture drafts, gives the draft its own model config, and points its embed_tokens and lm_head at the target's storage. It raises if shapes or dtypes differ. The CUDA worker installs it the way it already installs TorchTitanGPUModelRunner.
  4. GDN: the layer's refusal of speculative decoding goes. PRs 1-3 stage and run the draft rows.
  5. Decode CUDA graphs cover max_num_seqs * (1 + k) tokens (config.py).
  6. The OTel stat logger exports vLLM's counters vllm.spec_decode_num_drafts, vllm.spec_decode_num_draft_tokens and vllm.spec_decode_num_accepted_tokens. The metrics README gives the acceptance-rate query.
  7. Refused, each with a ValueError that says why: k < 0, cuda_graph.mode="FULL" (PR 6 lifts it), session_kv_holder (main's refusal stays), debug.batch_invariant, generator DP > 1, models with a vision encoder, non-CUDA devices. add_requests rejects a prompt under 2 tokens: vLLM pads it with placeholder drafts, which GDN's verify kernels can't run. Only that request fails; the GDN builder's check (PR 1) is the backstop.
  8. Accepted-token counts under async scheduling (worker.py). vLLM's V1 runner moves rows before it waits for the last step's count copy, then gathers each row's count by its last-step position. So a new request right after the last one ended, or a decode row that the decode/prefill reorder moved, can start from another request's count, and from the wrong GDN state. TorchTitanGPUModelRunner._update_states waits for the copy before any row moves and keeps the counts by request. _prepare_inputs puts them back, with 1 for a row that has no last-step count or that vLLM removed and added again (a forced preemption). vLLM main has no V1 runner ("[Core] Remove Model Runner V1"), so this goes with the move to V2 (TODO).
  9. Unchanged: with num_speculative_tokens = 0 (the default), the engine takes main's path. vLLM builds a drafter only when speculative_config is set, and the 3 counters add only when vLLM reports drafts.

Results

Qwen3.8-27B, 1 GB300, FULL_DECODE_ONLY graphs, temperature 1, natural stop (<|im_end|>), at most 2,048 tokens.
Cells: C1 = 16 requests one at a time; C8 = 4 batches of 8; C32 = 1 batch of 32.

numerics: the generator's logprobs vs the trainer's on the same tokens (every generated token is kept)
           tokens   mean|d|   max|d|   k3        outside [0.2, 5]
MTP off     7,990   0.0095    0.35     2.65e-4   0      (8 requests per cell)
MTP-3      57,530   0.0095    0.70     2.61e-4   0      (every request; max|d| grows with the tokens scored)

per-request decode tok/s (median)
context  C    MTP off   MTP-3   speedup   tokens per verify step
27k      1     87.3     144.7    1.66x     2.35
27k      8     80.2     136.2    1.70x     2.62
27k     32     61.4      90.6    1.47x     2.50
77k      1     84.0     179.3    2.14x     2.92
77k      8     71.9     139.3    1.94x     2.60
77k     32     47.9      72.9    1.52x     3.05
draft acceptance 0.51 (34,818 of 68,316 draft tokens)

accepted-token counts (Solution 8)
27k C1, before the fix   5 of 16 requests: the first token differs from MTP off (its id, or its logprob by more
                         than 0.2); max|d| 29.9 on 8 scored requests
27k C1, with the fix     0 of 16; token-identical to the same cell with async scheduling off
agent load (Qwen3.5-27B weights, MTP-3): 54 multi-turn sessions in groups of 9. A group shares a 27k-token
                         first prompt. Each turn adds 100-1,500 output tokens, a tool wait (1 s mean) and 200-1,100
                         tool tokens, until the session reaches 30k-60k tokens.
                         Rows whose count vLLM's gather got wrong, all corrected: 44 of 123,002 checked, 3,021 steps

You may ask:

  • Why vLLM's drafter and not a TorchTitan-native one? This stack keeps vLLM's tested drafter (Qwen3_5MTP). A native drafter can follow: it would remove the parser routing, the draft model-config swap, the two private-method overrides and the .data alias, and a trained head would sync like any other weight. It takes three pieces: a Qwen3.5 MTP block on main's shared MTPDecoder (torchtitan/models/common/mtp.py, as DeepSeek-V3 and V4 use), a drafter wrapper that runs it in vLLM's draft loop with paged-KV attention, and training it (TODO in load_model_state_dict).
  • Why not train the MTP head now? It needs the native MTP block above. A frozen head keeps acceptance near 0.5 at temperature 1 in the runs below.
  • Which recipe turns it on? None in-tree yet. In a recipe: engine=VLLMEngine.Config(num_speculative_tokens=3, cuda_graph=VLLMCudaGraphConfig(mode="FULL_DECODE_ONLY")), on a Qwen3.5-architecture checkpoint that ships mtp.* weights. At this PR, it pays when requests mostly decode. PRs 5-7 make it pay on agent loads.
  • Why a module-level class swap? vLLM's runner builds its drafter inside GPUModelRunner.__init__ with no factory. vLLM's method="custom_class" builds a proposer from vllm_config alone, and it is not an EAGLE-style method (use_eagle()), so the runner would not hand it the target's hidden states. The worker already swaps the runner class the same way.
  • Why share the tensors and not the modules? vLLM's logits path needs its own layer types, so the draft keeps its modules and points their weights at the target's storage.

NOTE:

  • Tested on qwen3_5's text-only 27B flavor with Qwen3.8-27B weights, and Qwen3.5-27B for the agent load. The qwen3_6 and qwen3_8 27B flavors build the vision encoder, and MTP refuses models with a vision encoder.
  • Dense 27B only. The MoE draft (Qwen3_5MoeMTP) is accepted but untested. Tested at TP1 only: at TP > 1, if the draft's vocabulary shard and the target's local shard differ in shape, the engine raises at start-up.
  • Not run inside an RL job: parity was measured offline (generator vs trainer on the same tokens), and weight sync through VLLMEngine.load_model_state_dict.
  • CUDA graphs: drafts need FULL_DECODE_ONLY here. Steps with a prefill chunk and the drafter's 3 passes run eagerly; PR 6 graphs both.
  • KV memory: the draft's attention layer makes each KV block larger, so the pool has 5.5% fewer blocks (3,521 -> 3,329 on Qwen3.8-27B at gpu_memory_limit 0.9). vLLM also gives each running request one more GDN state block per draft token in each GDN group: +9 blocks per running request on Qwen3.8-27B (3 GDN groups).
  • session_kv_holder still refuses drafts. "[rl] Evict an ended rollout's KV from vLLM's prefix cache" replaces the holder with an evictor that runs with drafts (TODO at the refusal).
  • Without stat_logger (the default), acceptance shows only in vLLM's console log ("SpecDecoding metrics").
  • fp8 KV cache: PR 7.
  • The count fix (Solution 8) moves vLLM's own wait earlier. Measured lost overlap: 0.74 ms mean per step (p90 1.51), about 1% of a 73 ms step.
  • Agent-load throughput, one run each with a race counter on: two runs with the fix, -2.9% and -4.0% (the second adds one dict lookup per row and a heavier counter), vs one run without the wait. Noise and counter cost not separated.
  • The agent load's outputs were not trainer-scored: its harness keeps no logprobs.
  • MTP off ran at this PR before the count fix, which runs only with drafts.

Follow up / TODO (each has a # TODO in the code)

  • vLLM V2 runner: subclass MTPSpeculator and register it with register_speculative_method.
  • Train the MTP head and load it into the draft on weight sync.
  • Drafts with batch-invariant mode, at generator DP > 1, and with models that have a vision encoder.
  • Upstream vLLM hooks, so this PR's workarounds go away: a draft config_format, and a target hook for the draft's embedding and lm_head (as SGLang's get_embed_and_head). Both feature requests are drafted; the TODOs link them.
  • A GPU test that the draft's embedding and lm_head still alias the target's after a model state dict load (Qwen3.5-0.8B has an MTP head).
  • Drop the accepted-token count fix with the move to vLLM's V2 runner, which keeps the counts on the GPU.

Test plan

pytest tests/rl/unit_tests/cpu
pytest tests/rl/unit_tests/gpu/test_gdn_graph_metadata.py   # 1 GPU (GB300)
pre-commit run --files <changed files>
RL CPU suite   788 passed, 0 failed, 8 skipped on the pinned vLLM (1.0.0.dev20261107, vLLM 9f03b510c), main merged in.
GPU            test_gdn_graph_metadata.py: 38 passed (63 s). The speed and numerics runs above (engine with MTP-3 and
               FULL_DECODE_ONLY graphs), and the agent load with the count checks
pre-commit     all hooks pass (pyrefly and lychee skipped)

New tests: test_a_row_copies_its_gdn_state_from_its_own_last_steps_offset (4 cases), test_a_row_moved_by_the_reorder_keeps_its_accepted_count (3 cases), test_speculative_draft_parse_is_told_apart_from_the_target_parse, test_cuda_graph_config_with_draft_tokens, test_eagle_proposer_hooks_match_vllm, test_admission_rejects_one_token_prompts_with_drafts. test_cuda_only_features_rejected_off_cuda gets a case for drafts off CUDA. The stat logger tests cover the speculative-decoding counters.

VLLMEngine.Config.num_speculative_tokens turns on vLLM's MTP drafter for Qwen3.5-architecture
checkpoints. The draft shares the target's embedding and lm_head storage, so weight syncs
reach it. The stat logger exports vLLM's acceptance counters. speculative_config is now
TorchTitan's key (extra_engine_args can't set it), so the GDN layer's refusal of
speculative decoding goes.

Refused: cuda_graph.mode="FULL" (FULL_DECODE_ONLY and NONE work), session_kv_holder,
debug.batch_invariant, generator DP > 1, vision encoders, non-CUDA devices, and 1-token
prompts (rejected per request).

Under async scheduling, vLLM moves rows while the last step's accepted-count copy may still land, then
gathers counts by last-step row: a new request or a reordered decode row could read another request's count.
The runner waits for the copy before rows move and puts each row's count back by request; a request vLLM
removes and adds again (a forced preemption) gets 1.
…ecode

# Conflicts:
#	torchtitan/rl/generator/vllm/attention/gdn.py
#	torchtitan/rl/generator/vllm/worker.py
… read-back test

The draft config_format and embedding/lm_head TODOs link their vLLM feature requests.
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Dec 1, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Dec 1, 2026

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

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