Skip to content

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

Closed
felipemello1 wants to merge 3 commits into
felipemello1/gdn-layer-draftsfrom
felipemello1/vllm-mtp-spec-decode
Closed

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

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 20, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 4m 7s —— View job


Needs discussion -- review posted: should the draft be a TorchTitan-native MTP module instead of vLLM's Qwen3_5MTP with private-API overrides, and should this wait for #5956's V2 runner? A maintainer still needs to 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: Needs discussion -- The draft is vLLM's Qwen3_5MTP attached to a TorchTitan target through private-API overrides. A TorchTitan-native drafter would remove that machinery, and the maintainers need to decide whether to build it, especially with #5956 about to replace the V1 runner hooks this PR extends.

What this PR does. VLLMEngine.Config.num_speculative_tokens = k turns on vLLM's MTP speculative decoding. vLLM builds its own Qwen3.5 MTP draft from the checkpoint's mtp.* weights. The draft's embedding and lm_head are re-pointed with .data at TorchTitan's storage. GDN layers switch to vLLM's metadata builder and a port of vLLM's verify/conv kernels. CUDA graph sizes scale by 1 + k, and the stat logger exports acceptance counters.

Example.

VLLMEngine.Config(num_speculative_tokens=3), Qwen3.8-27B with mtp.* weights, TP1
before: GDN __init__ raises "Attention Gym GDN does not support speculative decoding."
after:  draft proposes 3 tokens/step, target verifies 4 rows, emits 1-4 tokens
        agent load: 648 -> 838 tok/s; draft's mtp.* stays frozen through weight syncs

Must fix

  1. The "Summary (human-written)" section is empty. Only the author can fill it in.
  2. One-sided design (gate). The PR itself lists what a native drafter (Qwen3.5 MTP module, run by the generator like the target) would delete: the parser routing on SpeculativeConfig._apply_composed_hf_override, the _create_draft_vllm_config swap, the _maybe_share_* private overrides, the .data alias, and the module-level EagleProposer swap. It would also make the head trainable and synced like any other weight. Today the head is frozen while the policy drifts, so acceptance during a real RL run is unmeasured (all numbers are offline, on the base checkpoint). The "You may ask" section says why this PR doesn't build the native drafter, but not why that design can't work. Please either build it or explain in the PR why it can't.
  3. Direction: #5956 replaces the runner this PR builds on. The TODO at worker.py already says to subclass MTPSpeculator with register_speculative_method there. That is a real registration hook, and it removes the class swap. Landing V1-only machinery that #5956 will rewrite needs a maintainer decision. Otherwise, rebase onto #5956 and use the V2 hook.
  4. Numerics evidence isn't apples-to-apples. Every MTP-off row comes from "an earlier version of this patch at k = 0, on an older main". Greedy parity got worse: max |delta| 0.84 -> 6.08, and 0 -> 11 tokens outside [0.2, 5]. The verify and decode rows now run vLLM's FLA kernels while the trainer runs Attention Gym, so trainer/generator kernel parity no longer holds on the decode path. Please re-run MTP off at this PR's base, and state that this kernel divergence is intended.
  5. registry.py:392, worker.py:281 -- the private-API TODOs need vLLM issue links.
  6. gdn.py:350 -- nothing tests the speculative GDN port. A layer-level test with random weights is enough; no checkpoint needed.

Should consider

  • engine.py:157 -- FULL silently becomes FULL_DECODE_ONLY. Raise instead.
  • engine.py:215 -- the check fires on any vision model, but the message says "image prompts".
  • kda.py:91, sglang/attention/linear_attention.py:144 -- roadmap TODOs that don't belong in this PR.

Questions

  • The description says main's SM100 trainer defaults (cuDNN GDN + cuDNN attention) give logprob -11.5 where an fp32 reference gives -0.016. That looks like a trainer numerics bug on main, separate from this PR. Is there an issue for it?

Not verified: vLLM internals (GDN builder field semantics, FULL -> FULL_DECODE_ONLY capture behavior); vLLM isn't installed in this environment. No GPU runs.

# vLLM parses the MTP draft's config with the target's config_format. The
# draft is vLLM's own model (e.g. Qwen3_5MTP), so it needs the checkpoint's.
# TODO: drop once vLLM's SpeculativeConfig takes a draft config_format.
# No vLLM issue filed yet.

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.

Two workarounds depend on private vLLM APIs:

  • here, an identity check against SpeculativeConfig._apply_composed_hf_override;
  • worker.py:281, overrides of _maybe_share_embeddings and _maybe_share_lm_head.

CLAUDE.md principle 3 asks for a TODO with an upstream issue link for each one. "No vLLM issue filed yet" doesn't meet that. Please file the two vLLM issues (a draft config_format, and a target hook for the draft's embedding and lm_head) and link them in both TODOs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Not filed yet. Filing vLLM issues is the author's call, so this stays open for him. Each TODO names the hook an issue would ask for: a draft config_format, and a target hook for the draft's embedding and lm_head.

Comment thread torchtitan/rl/generator/vllm/engine.py Resolved
Comment thread torchtitan/rl/generator/vllm/engine.py Resolved
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: e274140 addresses the code items (see the threads). On the rest:

Numerics (must-fix 4). MTP off now ran at this PR's head (k = 0), with the same requests and seeds. All 164 requests are bitwise equal to the earlier rows, so every row is now "this PR". Each row has 18,432 tokens, compared with the trainer running fused GDN and Flash:

row mean abs delta max abs delta tokens past ln 5
temperature 1, MTP off 0.0095 3.81 3
temperature 1, MTP-3 0.0078 1.47 0
greedy, MTP off 0.0036 0.84 0
greedy, MTP-3 0.0050 6.08 11

The kernels diverge on purpose. With drafts, verify and decode rows run vLLM's kernels, while MTP off and the trainer run Attention Gym's. The description says so now. All 11 greedy outliers sit at near ties: the generator emits its token at -0.4 to -0.8.

Native drafter (must-fix 2). It can work, and the description now says what it takes:

  • a Qwen3.5 MTP module with weight loading;
  • a drafter wrapper that runs it in vLLM's draft loop with paged-KV attention;
  • the trainer side, to train it.

This PR reuses vLLM's tested drafter instead. Which way to go is the maintainers' call.

V2 runner (must-fix 3). Whichever PR lands second rebases. If the V2-runner PR lands first, this PR moves to MTPSpeculator + register_speculative_method, as the worker.py TODO says.

Question: SM100 trainer numerics. No upstream issue yet. It is separate from this PR, and the author decides on the issue.

@claude please review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 28s —— View job


Needs discussion -- review posted. The code items are fixed. Four items are still open: the human-written summary, the native-drafter design gate, the landing order with the V2-runner PR, and vLLM issue links in the TODOs. A maintainer still needs to 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: Needs discussion -- e274140 fixes the code items. What's left are decisions only maintainers can make: whether the draft should be TorchTitan-native, and how this lands relative to the V2-runner PR. There's also one numerics trade-off for them to accept or reject.

What this PR does. VLLMEngine.Config.num_speculative_tokens = k turns on vLLM's MTP drafting. vLLM's Qwen3_5MTP is the draft. Its embedding and lm_head share storage with TorchTitan's. With drafts on, GDN layers run a port of vLLM's verify and conv kernels.

Example.

VLLMEngine.Config(num_speculative_tokens=3, cuda_graph=VLLMCudaGraphConfig(mode="FULL_DECODE_ONLY"))
before: GDN __init__ raises "Attention Gym GDN does not support speculative decoding."
after:  the target verifies 4 rows per step and emits 1-4 tokens; agent load 648 -> 838 tok/s
        with the default mode="FULL": ValueError at config time (new in e2741408e)

Resolved since the last review

  • Numerics evidence: MTP off was re-run at this PR's head with the same requests and seeds. The run is bitwise equal to the earlier rows, and the description now says the kernel divergence is intended.
  • gdn.py:350: the speculative port is now tested. test_verify_rows_match_single_token_decodes and test_speculative_step_matches_step_without_drafts cover accepted-state selection, conv rows and mixed decode/verify/prefill ordering against the no-draft path, with metadata from vLLM's real builder.
  • engine.py: FULL with drafts now raises in __post_init__.
  • engine.py: the vision check now says "models with a vision encoder".
  • The roadmap TODOs are gone from kda.py and the SGLang backend.

Still open

  1. The "Summary (human-written)" section is still empty. Only the author can fill it in.
  2. One-sided design (gate). The reply says a native Qwen3.5 MTP drafter "can work", and lists the three pieces it needs. A native drafter would delete the parser routing, the draft model-config swap, the two _maybe_share_* private overrides, the .data alias and the EagleProposer class swap. It would also let the head be trained and synced; today it stays frozen while the policy drifts. Since nothing says the native design can't work, maintainers need to decide whether vLLM's drafter is acceptable as an interim step.
  3. Landing order with the V2-runner PR. The worker extends the V1 runner swap, which V2 replaces with MTPSpeculator + register_speculative_method. "Whichever lands second rebases" is a plan, but maintainers still have to pick the order.
  4. registry.py:392 and worker.py:281: the TODOs on the private vLLM APIs still have no upstream issue link (CLAUDE.md principle 3).

For maintainers to weigh

  • Generator/trainer kernel parity on the decode path. With drafts on, the generator's decode and verify rows run vLLM/FLA GDN kernels, while the trainer runs Attention Gym's. .claude/rules/models.md asks to keep trainer and generator numerics consistent. The measured effect:

    • Temperature 1 does not get worse: max |delta| 3.81 -> 1.47, and 3 -> 0 tokens outside [0.2, 5].
    • Greedy does: max |delta| 0.84 -> 6.08, and 0 -> 11 tokens outside [0.2, 5], all at near ties.

    Whether that is acceptable for RL importance ratios is a policy call. The follow-up that removes it, speculative GDN kernels in Attention Gym, is already a TODO at gdn.py:147.

Not verified: vLLM internals and the new GPU tests (vLLM isn't installed here; no GPU run). I checked the test logic against the docstrings only.

@felipemello1

Copy link
Copy Markdown
Contributor Author

@claude please review. Also find opportunities, if any, to reduce the amount of lines or to break this pr further. If its not possible or unreasonable, it is ok.

@claude

claude Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 4m 17s —— View job


Needs discussion -- review posted: no new correctness problems. You could split out the session_kv_holder-with-drafts change (about 55 lines) and the OTel spec-decode counters (about 54 lines), and delete about 15 more lines. The GDN port can't be split off, but #6403 later in the stack replaces it. The design gate and the landing order are still open, and a maintainer still needs to 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: Needs discussion -- There are no new correctness problems. The design gate is still open, and the stack on top of this PR (#6364 -> #6402 -> #6365 -> #6403) rewrites the GDN code this PR adds.

What this PR does. VLLMEngine.Config.num_speculative_tokens = k turns on vLLM's MTP drafting with vLLM's Qwen3_5MTP as the draft. The draft's embedding and lm_head share storage with TorchTitan's. With drafts on, GDN layers run a port of vLLM's verify and conv kernels.

Example.

VLLMEngine.Config(num_speculative_tokens=3, cuda_graph=VLLMCudaGraphConfig(mode="FULL_DECODE_ONLY"))
main:    GDN __init__ raises; session_kv_holder refuses drafts
this PR: each step verifies 4 rows and emits 1-4 tokens; with the holder, vLLM gets disable_eagle_block_drop=True

Can it be smaller or split? (asked)

Net +869. About 500 lines are the GDN port (gdn.py +233) and its GPU tests (+269). They can't be split off: every accepted draft (Qwen3_5MTP) has GDN layers, and a GDN path that nothing can enable has no consumer. Three parts can be split off:

  1. Holder with drafts (3bb6333), about 55 lines, as its own PR. It touches session_kv_holder.py +15/-4, test_session_kv_holder.py +27/-8, the disable_eagle_block_drop block at engine.py:543-553, and its docstring bullet. This PR would keep main's "does not support speculative decoding" refusal. The split also moves the vLLM-version-dependent key and its pin TODO out of this PR, and that PR already has its own evidence table.
  2. OTel spec-decode counters, 54 lines, as a follow-up. stat_logger.py +26, its test +13, README +15. They are independent and only matter once drafts exist.
  3. Small deletions, about 15 lines (inline): test_alias_draft_weight_shares_storage_and_checks_shape and the roadmap TODO at engine.py:907. Also, _validate_platform adds three blank lines unrelated to drafts (before the cuda_graph, batch_invariant and draft checks).

Stack churn. #6403 deletes this PR's _forward_speculative port (gdn.py +122/-219), the GDNAttentionBackend switch and the FULL ban, and replaces them with one graph-safe forward on a GDNAttentionMetadataBuilder subclass. #6364 already changes this PR's FULL handling. Reviewers would spend time on about 250 lines whose replacement is already written. Maintainers should pick one:

  • (a) Land this PR as the interim base. The port mirrors upstream _forward_core and is tested against the path without drafts, so it is easier to review.
  • (b) Fold #6403's GDN design into this PR, so that design gets reviewed once.

I lean to (a) only if the stack lands soon after. Otherwise (b) avoids landing code with a known replacement.

Still open from the last review

  1. The "Summary (human-written)" section is empty.
  2. Design gate: should the drafter be TorchTitan-native instead of using private-API overrides? This is the maintainers' call.
  3. Landing order with #5956 (V2 runner, still open).
  4. registry.py:393 and worker.py:282: the TODOs on private vLLM APIs still have no upstream issue links.
Details

New since e274140: 3bb6333 (holder + drafts), 2fe076c (drafts refused off CUDA), f7c7105 (one __post_init__ after the merge).

  • f7c7105e1: main's SimpleCPU offload check and the draft checks now share one __post_init__. The added GenerationEngine.Config.__post_init__(self) calls a no-op base (configurable.py:48), so it is harmless.
  • 2fe076c11: the CUDA-only ban fits: the XPU worker doesn't install the proposer swap, so banning drafts beats an untested swap.
  • 3bb6333cf: the holder reads scheduler.use_eagle_block_drop only when a speculative config is set. Without drafts, it reads nothing new.
  • _forward_speculative makes three nearly identical fused_sigmoid_gating_delta_rule_update calls. A local helper would save about 20 lines, but only worth it under option (b).
  • The num_speculative_tokens=0 additions at 12 get_vllm_compilation_config call sites are mechanical. Leaving the parameter without a default follows CLAUDE.md's "no internal defaults that duplicate a config default".

Not verified: the vLLM scheduler attribute use_eagle_block_drop and the GPU tests. vLLM isn't importable here, and there was no GPU run.

Comment thread torchtitan/rl/generator/vllm/engine.py Resolved
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.
@felipemello1
felipemello1 removed this pull request from stack #6404 November 28, 2026 17:44
@felipemello1
felipemello1 force-pushed the felipemello1/vllm-mtp-spec-decode branch from f7c7105 to 9265203 Compare November 28, 2026 17:45
@felipemello1
felipemello1 changed the base branch from main to felipemello1/gdn-layer-drafts November 28, 2026 17:45
@felipemello1
felipemello1 added this pull request to stack #6434 November 28, 2026 17:50
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 3m 2s —— View job


Needs discussion -- review posted. Two maintainer calls are still open: the native drafter (#6414 repeats the same workarounds for SGLang) and the landing order with #5956. There's also one new question: does the accepted-count fix reach the GPU counts that the verify rows read?

@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: Needs discussion -- Two design calls are still for the maintainers: vLLM's drafter vs a TorchTitan-native MTP module, and landing order with #5956. Both now weigh more. #6414 repeats the same drafter workarounds for SGLang, and this PR adds new V1-only runner code that #5956 removes. There is also a new question on whether the accepted-count fix reaches the GPU.

What this PR does. VLLMEngine.Config.num_speculative_tokens = k turns on vLLM's MTP drafting, with vLLM's Qwen3_5MTP as the draft. The draft's embedding and lm_head share storage with TorchTitan's. The GDN port now sits lower in the stack (#6432/#6433). This PR adds a fix for the V1 runner under async scheduling: it keeps the last step's accepted-token counts by request before rows move, and writes them back after vLLM's gather.

Example.

last step rows [A, D], accepted 3 and 2; this step A ends, B (new prefill) takes row 0, the reorder moves D to row 0
vLLM V1 gather by last-step row: D <- 3 (A's count), B <- 2
this PR: D <- 2, B <- 1 (on input_batch.num_accepted_tokens_cpu; see the question at worker.py:239)

Resolved since the last review

  • The session_kv_holder-with-drafts change was split out. The refusal stays, with a TODO to #5919.
  • The roadmap TODO on per-request acceptance metrics is gone.

Still open

  1. Design gate. The native drafter is still open, and there is now new evidence. #6414 (SGLang MTP for Qwen3.5) adds its own draft config-parse workaround and its own embedding/head sharing (get_embed_and_head). So each generator builds the same Qwen3.5 MTP head with different glue. One Qwen3.5 MTP module on MTPDecoder would remove both sets of glue, and the trainer could train it (TODO at engine.py:830). A maintainer needs to decide.
  2. Landing order with #5956. The new count fix (worker.py:208-251, plus about 195 test lines) is V1-only, and its TODO says #5956 deletes it. Together with the EagleProposer swap, the V1-only code here keeps growing. A maintainer needs to decide.
  3. registry.py:393, worker.py:1146: the TODOs on private vLLM APIs still say "No vLLM issue filed yet".

Should consider

  • tests/rl/unit_tests/cpu/test_generator.py:1448 -- the reorder test checks the override against a re-implementation of vLLM's gather (inline).
  • Still open from the last review: test_alias_draft_weight_shares_storage_and_checks_shape (delete it), and splitting out the OTel spec-decode counters.

Questions

  • worker.py:239 -- does the corrected count reach self.num_accepted_tokens.gpu, which the GDN verify rows read? The numbers measured so far exercise only new prefill rows, where the builder forces the count to 1 (inline).
Details
  • Searched open PRs for "speculative", "MTP" and "worker.py vllm". Found the stack (#6432, #6433, #6402, #6364, #6365, #6366, #6403), #5956 (V2 runner, open), #5919 (session evictor, open) and #6414 (SGLang MTP, open; the same design on the other engine).
  • Count fix: the _update_states sync runs only when mamba_cache_mode == "align", async scheduling is on and num_accepted_tokens_event is set. With k = 0 it does nothing, which matches "Unchanged with k = 0" in the description. The cost per step is one dict over the rows plus the earlier wait (0.74 ms measured).
  • The new ValueErrors (k < 0, FULL with drafts, DP > 1, vision encoder, non-CUDA, prompts under 2 tokens) are checked at config time or per request, and their messages name the condition.

Not verified: vLLM V1 internals (where num_accepted_tokens is copied to the GPU, how prev_req_id_to_index is maintained). vLLM isn't importable here, and there was no GPU run.

Before merge: fill in the human-written summary.

Comment thread torchtitan/rl/generator/vllm/worker.py Resolved
…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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: Replies to the 11-28 review. Fixed in c8c6e08.

  • The count question: yes, the corrected counts reach num_accepted_tokens.gpu. The worker.py thread has the vLLM lines.
  • Private-API TODOs: registry.py:397 and worker.py:420 now link their vLLM feature requests: the draft's own config_format, and the target handing its embedding and lm_head to the drafter.
  • Alias test: deleted.
  • The gather test: kept. The reason is in its thread.
  • OTel spec-decode counters: kept here. This PR turns drafts on, and without the counters a run with drafts reports no acceptance rate in TorchTitan's metrics.
  • The design gate (vLLM's drafter or a TorchTitan-native one) and the landing order with the V2-runner PR are for the maintainers.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 1m 23s —— View job


Needs discussion: review posted. The code items are fixed, and the two open design calls (native drafter, landing order with #5956) are for the maintainers. New: the TODO links point to issues on a personal vLLM fork, not upstream vLLM.

@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: Needs discussion -- c8c6e08 resolves the code items from the last review. What's left is two maintainer decisions: vLLM's drafter vs a TorchTitan-native MTP module, and the landing order with #5956. The private-API TODOs now link to issues on a personal fork, which is not an upstream issue link.

What this PR does. VLLMEngine.Config.num_speculative_tokens = k turns on vLLM's MTP drafting, with vLLM's Qwen3_5MTP as the draft. The draft's embedding and lm_head share storage with TorchTitan's. Under async scheduling, the V1 runner now keeps the last step's accepted-token counts per request before rows move, then writes them back after vLLM's gather.

Example.

VLLMEngine.Config(num_speculative_tokens=3, cuda_graph=VLLMCudaGraphConfig(mode="FULL_DECODE_ONLY"))
main:    GDN __init__ raises "Attention Gym GDN does not support speculative decoding."
this PR: each step verifies 4 tokens per row and emits 1-4
         last step rows [A, D] accepted [3, 2]; A ends, B takes row 0, the reorder moves D to row 0
         vLLM V1 gather: D <- 3, B <- 2   this PR: D <- 2, B <- 1 (CPU counts, copied to the GPU in execute_model)

Resolved since the last review

  • worker.py:274, does the count fix reach the GPU: answered. execute_model copies input_batch.num_accepted_tokens_cpu into num_accepted_tokens after _prepare_inputs and preprocess_mamba, and before _build_attention_metadata. The comment now says so. I checked this against the author's cited lines only (vLLM isn't importable here).
  • test_alias_draft_weight_shares_storage_and_checks_shape: deleted.
  • The reorder test's copy of vLLM's gather: the reply (the gather sits inside a 320-line method that needs a full runner) is a fair reason to keep the 8-line copy. Dropped.
  • The OTel spec-decode counters: the reply (without them, a run with drafts reports no acceptance rate) is a fair reason to keep them in this PR. Dropped.

Still open

  1. Design gate. vLLM's Qwen3_5MTP with private-API overrides, or a TorchTitan-native Qwen3.5 MTP module on MTPDecoder. #6414 repeats the same glue for SGLang. This is a maintainer's call.
  2. Landing order with #5956. The EagleProposer swap and the count fix are V1-only, and #5956 removes them. This is a maintainer's call.

Must fix

  1. registry.py:397, worker.py:421: the TODOs link felipemello1/vllm/issues/4 and /5, which are issues on a personal fork, not upstream vLLM (inline).
Details
  • New since the 11-28 review: c8c6e08. It adds a comment on the GPU copy, links the TODOs to fork issues, and deletes the alias test.
  • I searched open PRs for "speculative". I found the same stack (#6432, #6433, #6402, #6364, #6365, #6366, #6403), #5956 (V2 runner), and #6414 (SGLang MTP). Nothing new overlaps.
  • _prepare_inputs write-back: _accepted_counts_by_request is keyed by the prev_req_id_to_index taken before super()._update_states. The write-back checks membership in prev_req_id_to_index again afterwards. If that map can only shrink in between, the lookup can't raise a KeyError. Unverified for vLLM's InputBatch.remove_request.

Not verified: vLLM V1 internals (the execute_model ordering, how prev_req_id_to_index changes on remove/re-add), because vLLM isn't importable here. I ran nothing on a GPU.

Before merge: fill in the human-written summary.

# vLLM parses the MTP draft's config with the target's config_format. The
# draft is vLLM's own model (e.g. Qwen3_5MTP), so it needs the checkpoint's.
# TODO: drop once vLLM's SpeculativeConfig takes a draft config_format.
# vLLM feature request: https://github.com/felipemello1/vllm/issues/4

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.

This link, and the one at worker.py:421 (felipemello1/vllm/issues/5), points at an issue on a personal fork, not on vllm-project/vllm. CLAUDE.md principle 3 asks for an upstream issue link. vLLM maintainers won't see a fork's issues, so the request that would let us delete the two private-API workarounds (SpeculativeConfig._apply_composed_hf_override, _maybe_share_embeddings / _maybe_share_lm_head) never reaches the people who could make the change. Also, the fork issue can disappear along with the fork.

Fix: file both requests on vllm-project/vllm and swap in the links here and at worker.py:421.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Reply from claude: Kept the fork links for now, on purpose. The PR's author files vLLM feature requests on his fork first and reviews them there. Then he files them on vllm-project/vllm. The two TODOs swap to the upstream issues once he does. Until then, the fork issues hold the full request text, with a repro.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: The write-back can't raise a KeyError: between the snapshot and the write-back, prev_req_id_to_index only loses entries. Checked at TorchTitan's pinned vLLM (9f03b510c).

  • execute_model calls _update_states (gpu_model_runner.py#L4226), then _prepare_inputs (#L4269). This PR takes the snapshot before super()._update_states and writes the counts back after super()._prepare_inputs.
  • In between, only InputBatch.remove_request changes the map, and it only pops entries (gpu_input_batch.py#L571-L572).
  • vLLM builds a new map only in sample_tokens, after the forward: in _bookkeeping_sync (#L3784-L3788, called at :4739), and in the pipeline-parallel receive (#L4880-L4896, called at :4574).

So every request the write-back looks up was in the snapshot. The fork links are explained in their thread. The design gate and the landing order with the V2-runner PR are still for the maintainers.

@liangel-02

Copy link
Copy Markdown
Contributor

Superseded by #6476

@liangel-02 liangel-02 closed this Dec 1, 2026
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