Skip to content

[rl] SGLang generator: MTP speculative decoding for Qwen3.5 - #6414

Draft
felipemello1 wants to merge 4 commits into
mainfrom
felipemello1/sgl203/s5-mtp
Draft

felipemello1 wants to merge 4 commits into
mainfrom
felipemello1/sgl203/s5-mtp

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: SGLangEngine.Config(num_speculative_tokens=3) turns the checkpoint's MTP head into a draft model for Qwen3.5 (GDN) generators. On Qwen3.5-27B (one GB300), it gives 1.45x the output tokens/s of no drafts on a multi-turn agent load. On the same load it is 1.05x the vLLM engine with MTP-3 (the open vLLM MTP stack at its top, one run per arm), though by each engine's own count vLLM holds 1.77x the KV tokens. Both engines give KV and GDN states about the same memory (see Results). The output follows the model's distribution (rejection sampling), and the logprobs are the model's.

With MTP drafts, each SGLang decode step checks 3 drafted tokens and emits 1 to 4; on Qwen3.5-27B and one GB300 an agent load gets 1,929 output tokens/s instead of 1,327.

SGLangEngine.Config(num_speculative_tokens=3)
  -> SGLang ServerArgs: NEXTN draft, 3 steps, topk 1, rejection sampling, FlashInfer draft attention,
     ReplaySSM GDN verify, unified memory off
  -> SGLang builds its Qwen3.5 MTP model from the checkpoint's mtp.* weights;
     its embedding and LM head are TorchTitan's tensors (get_embed_and_head)
  -> each decode step: the draft proposes 3 tokens -> the model checks 4 rows -> 1 to 4 tokens
     verify rows: TorchTitan's varlen attention (causal) + SGLang's GDN verify kernels on TorchTitan's state pool

Problem

  1. Qwen3.5 checkpoints ship an MTP head (mtp.* weights), and SGLang can run it as a draft model for its own Qwen3.5 class.
  2. TorchTitan's SGLang generator runs TorchTitan's model instead, which SGLang's draft path does not expect: the draft's config parse, the draft runner's GDN backend, the GDN verify rows, and SGLang's ReplaySSM gate all assume SGLang's classes.
  3. So the SGLang generator decodes one token per request per step.
  4. On the 27B agent load below, decode steps take 80% of the step time without drafts.

Solution

  1. One field, SGLangEngine.Config.num_speculative_tokens (the vLLM engine's name). With k > 0 the engine sets SGLang's draft server args; extra_server_args cannot set any speculative_* key.
  2. TorchTitanGDNAttnBackend._forward_target_verify runs the verify rows of GDN layers with SGLang's two kernels: the conv update, then the ReplaySSM recurrence. ReplaySSM keeps, per request, a ring of the accepted tokens' records over the state slot, and SGLang's commit folds it. This needs no per-draft state copies.
  3. Wiring: SGLangModelWrapper.get_embed_and_head shares the embedding and LM head with the draft, so model state dict loads reach it. registry.py routes the draft's config parse to SGLang's HF parser and patches two SGLang internals: the draft runner gets TorchTitan's GDN backend, and SGLang's ReplaySSM gate accepts TorchTitanGDNConfig.
  4. Guards: the generator's RoPE caches get CONTEXT_LENGTH_MARGIN (6) more rows, for every k, because verify rows near max_context_length run positions past it. After the build, the engine raises if SGLang built no ReplaySSM rings, or keeps fewer running requests than max_num_seqs.
  5. Unchanged: k = 0, the default, is main's path: unified memory on, no new server args. Its RoPE caches gain 6 rows, and the existing rows keep their values. The parser and backend patches act only on a draft; the gate patch, on CUDA, only with the ReplaySSM flag.

Results

Numerics: Qwen3.5-0.8B, test_sglang_mtp.py (16 prompts of 1,024 tokens of TorchTitan's RL docs, one GB300). The reference is the TorchTitan trainer on [prompt + completion].

check                                            measured               bar          without drafts
temperature 1, 16 x 512 tokens
  tokens per verify step                         2.48                   > 2.0        -
  mean of log p(x) + H(p) (0 for exact sampling) +0.013 (SE 0.023)      < 3 SE       +0.048 (SE 0.023)
  logprob |delta| mean / max                     0.014 / 0.22           0.03 / ln 5  0.015 / 0.19
greedy, 16 x 512 tokens
  trainer max logprob - token logprob, max       0.078                  <= 0.25      0.135
  logprob |delta| mean                           0.0021                 0.01         0.0024
greedy gap max / |delta| mean:
  second turn, 8 x 128 (cached prefix)           0.183 / 0.0020         same bars    0.039 / 0.0021
  after a x1.01 weight load, 8 x 128             0.072 / 0.0081         same bars    0.031 / 0.0075
  2 loads mid-decode, 8 x 128 (each request      0.000 / 0.0019         same bars    0.000 / 0.0018
    retracted, then resumed on fresh rings)
same seed twice                                  same tokens
prompt of max_context_length - 2 tokens          2 tokens, with a verify step whose drafts sit past the limit

A sampler that favors the draft's tokens fails the log p + H check: greedy outputs score +0.25, 39 standard errors.

Speed (measured on main at bb79a81): Qwen3.5-27B, one GB300, TP 1, bf16. Agent load: 54 sessions in groups of 9 on a 27,000-token shared prompt, 100-1,500 output tokens per turn, 200-1,100-token tool replies after a ~1 s wait, sessions end at 30K-60K tokens, temperature 1, text from a 3.1M-token corpus of TorchTitan files. max_num_seqs 64, gpu_memory_limit 0.85, 150 s window after 90 s warmup. One run per arm.

arm                       output tok/s   vs own no-draft   tokens per verify step   KV tokens    build s
SGLang, no drafts         1,326.8        -                 -                        1,562,225    94.7
SGLang, MTP-3 (this PR)   1,929.3        1.45x             3.09                     1,520,560    151.5
vLLM, no drafts           1,431.0        -                 -                        2,880,640    85.2
vLLM, MTP-3               1,838.1        1.28x             2.70 (vLLM's log)        2,686,208    97.6
  • The vLLM arms run the open vLLM MTP stack at its top, dc7d9c3: "MTP speculative decoding in the vLLM generator", then "MTP verify steps: verify rows on FA4's decode kernel, piecewise graphs for steps with prefill", "MTP: replay the verify CUDA graph only when every row verifies" and "MTP on GDN models: FULL CUDA graphs for steps with prefill" (with its fp8 KV parent; KV stays bf16 here). vLLM runs cuda_graph.mode="FULL" with its session KV holder; SGLang runs cuda_graph="breakable".

  • KV tokens are each engine's own count, and they count different things. Without drafts, both engines give KV and GDN states about the same memory: SGLang's pool is 180.80 GiB, vLLM's 175.85 GiB.

    • SGLang: max_total_num_tokens. Without drafts, KV and GDN states share one pool (unified memory). This count is the KV share that mamba_full_memory_ratio (0.9) gives on paper; at run time the two share the bytes, and the pool holds 2,962,229 tokens if all of it holds KV. With drafts, the count is a KV-only pool, and the states sit in a separate pool.
    • vLLM: num_gpu_blocks x block_size, the whole block pool counted as KV. Its GDN states take blocks from the same pool.
    • Drafts cost SGLang 3% of its KV tokens and vLLM 7%.
  • Build with drafts: +56.8 s on SGLang (151.5 vs 94.7 s; not split by phase: the draft's model load, FlashInfer's kernels and the draft's CUDA graphs all add to it), +12.4 s on vLLM (97.6 vs 85.2 s).

  • The load is closed loop: a session sends its next turn only after its tool wait. So the faster arm holds fewer requests per step (23.2 rows per verify step vs 41.2 per decode step without drafts; 20 vs 36 sessions alive at the end). 1.45x is this load's speedup, not one at full batch.

  • The verify rules differ: SGLang's draft samples its tokens; vLLM's proposes its argmax. That shows in acceptance (3.09 vs 2.70).

  • SGLang's verify step: 27.5 ms (70% of the time), prefill steps 141.6 ms (30%).

Decode only (no prefill in the timed round): one 27,000-token cached prompt, 1,024 output tokens per request, temperature 1, max_num_seqs 32, gpu_memory_limit 0.8. One run per arm.

requests   no drafts tok/s   MTP-3 (this PR) tok/s   speedup   tokens per verify step
1          82.3              173.4                   2.11x     2.77
8          589               1,157                   1.96x     2.72
32         1,656             2,957                   1.79x     2.69

Memory: Qwen3.5-27B, one GB300, gpu_memory_limit 0.8, 256 running requests asked.

                                          running requests kept   KV tokens    per-request verify memory
no drafts (unified memory)                110                     1,443,671    -
MTP-3, SGLang's default verify            59                      1,321,057    576 MiB (4 fp32 GDN states)
MTP-3, ReplaySSM (this PR, classic pool)  98                      1,403,013    ~23 MiB (12 MiB rings + 11 MiB conv windows, computed)

Without drafts, the KV count is unified memory's KV share on paper: KV can also use the memory that no state uses. SGLang caps running requests at (state slots) / 5, with or without drafts, and only warns. With drafts this PR raises instead, so a run asks for fewer.

You may ask:

  • Why SGLang's Qwen3.5 MTP model as the draft, not a TorchTitan module? TorchTitan has no Qwen3.5 MTP module: MTPDecoder (models/common/mtp.py) trains DeepSeek V3's MTP layers. A TorchTitan draft would drop most of the draft wiring in registry.py. Its own layer would still keep the checkpoint's weights unless the trainer trains an MTP loss; the shared embedding and LM head already follow the policy. The vLLM MTP stack makes the same choice. A TODO in engine.py marks it. Open question for review: land this draft now, and a TorchTitan draft later?
  • Why rejection sampling? SGLang's default verify keeps the draft's argmax with probability p, which accepts less at temperature 1: 1.70 vs 2.37 tokens per verify step on 0.8B (both on main at bb79a81).
  • Why ReplaySSM, and only ReplaySSM? SGLang's default verify keeps 4 fp32 GDN states per request (576 MiB on 27B): 59 of 256 requests fit. ReplaySSM fits 98, and was 12% faster at 32 requests.
  • Why unified memory off with drafts? At this SGLang pin, the unified pool has no ReplaySSM rings. SGLang main has them.
  • Why FlashInfer for the draft's attention? It was 7-29% faster than Triton in the decode-only runs; the agent load's verify step went from 41.9 to 28.3 ms.
  • Why not Attention Gym's kernels for the verify rows? It has no verify kernel; k + 1 one-token decodes would read and write the state k + 1 times.
  • Why only topk 1 (a chain of drafts, no tree)? TorchTitan's varlen attention runs causal rows only.
  • Why raise on fewer running requests only with drafts? Raising for every k changes main's k = 0 behavior (a warning). Open question for review: raise for every k, here or in a follow-up?

NOTE:

  • Raises when the Config is made: k > 5, enable_mixed_chunk (its mixed steps would decode running requests from stale GDN states), and speculative_* keys in extra_server_args. Raises at engine build with drafts: TP > 1, DP > 1, SGLang's hierarchical cache, MoE or KDA layers, a model without GDN layers, batch-invariant mode, and a checkpoint without mtp.* weights or of another architecture than SGLang's Qwen3.5 MTP draft takes. None of these has run with drafts.
  • Not bitwise: with drafts, GDN decode tokens run SGLang's kernels, not the trainer's. The numbers above bound the gap.
  • New metric generator/tokens_per_verify_step: the draft's own layers stay frozen while the policy trains, so acceptance can fall. It leaves out the tokens that prefills sample: the first, and one after each preemption. Its field, RequestMetricsInputs.num_verify_steps, is the one the vLLM MTP stack's TODO asks for ("Needs new RequestMetricsInputs fields"), so vLLM can fill it too.
  • fp8 KV cache with drafts: whichever of this PR and "[rl] SGLang generator: fp8 KV cache through FA4's fp8 forward" lands second carries TestSGLangMTPFp8KVCache (this test with kv_cache_dtype="fp8", about 40 lines, no production code). The two compose with no code change.
  • KV admission control for the SGLang generator (a separate open PR) counts the unified pool. Drafts turn unified memory off, so the two can't run together on GDN models at this SGLang pin. Whichever lands second makes admission count the classic pool, or raise.
  • Open PRs that edit the same files; whichever lands second rebases:
    • "[rl] SGLang generator: use SGLang's public extra_buffer hooks for GDN and KDA": gdn.py, linear_attention.py;
    • "[rl] SGLang generator: full prefill CUDA graphs for linear attention (GDN, KDA) models": engine.py, linear_attention.py. It lifts the raise that makes GDN models use cuda_graph="breakable". No run has used full prefill graphs with drafts, so the rebase onto it adds cuda_graph="full" to the drafts' untested list;
    • "[rl] SGLang generator: use SGLang's public attention-layer and FA kernel hooks": engine.py, registry.py, model_wrapper.py;
    • "[rl] SGLang generator: top-k logprobs for score centering" and "[rl] generator: receive SGLang scheduler outputs through output_sink": engine.py;
    • "[rl] SGLang generator: log the CUDA graph padding share and HiCache-loaded prompt tokens": RequestMetricsInputs and the dispatcher;
    • "[rl] SGLang generator: decode CUDA graphs up to max_num_seqs": engine.py. With drafts, SGLang captures the verify graphs on the same decode runner at k + 1 tokens per request, so the largest verify graph holds 4 x max_num_seqs tokens at k = 3. The second to land checks capture memory and build time, or caps the graph batch size with drafts;
    • "[rl] SGLang generator: abort a request whose logprob turns NaN or -inf": engine.py and the parity test;
    • "[rl] SGLang generator: run GDN prefill inside breakable prefill CUDA graphs": gdn.py, linear_attention.py.
  • Not run here: the SGLang parity classes on 2 or 4 GPUs (this box has one). The RoPE change reaches them at k = 0. On their generator configs, _replace_sglang_layer_configs only makes the RoPE caches longer (2,048 to 2,054 rows; Kimi K3's MLA layers have none). A cache 6 rows longer keeps its first rows bitwise, on CPU and CUDA. The B200 job runs those classes.
  • CI: the B200 job now downloads Qwen3.5-0.8B and runs test_sglang_mtp.py. FlashInfer and SGLang's verify sampler compile their kernels at engine build. The job's image, nvidia/cuda:13.0.3-cudnn-devel, has nvcc and the CUDA headers. The job runs only on pytorch/torchtitan, so the first signal comes from this PR's ciflow/b200 run upstream. If FlashInfer fails there, the fallback is the Triton draft attention: 1,672.4 tok/s on the agent load (a prototype of this PR) vs 1,929.3.
  • Three workarounds of SGLang internals in registry.py (the draft runner's GDN backend, the ReplaySSM gate, the draft's config parse keyed on decrypted_draft_config_file). Each has a TODO that says what to drop and what SGLang change it waits for. The SGLang issues are drafted, not filed; their links go into the TODOs once filed.

Test plan

# GPU, one GB300 (7 passed in 148 s)
TORCHTITAN_QWEN3_5_0_8B_HF_PATH=<Qwen3.5-0.8B> torchrun --nproc-per-node=1 -m pytest \
    tests/rl/unit_tests/gpu/test_sglang_mtp.py -v -s
# GPU, the KDA class: it shares the linear attention backend this PR edits, and its MLA layers have no RoPE (6 passed)
torchrun --nproc-per-node=1 -m pytest \
    "tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py::TestSGLangBitwiseParityKDA" -v
# CPU: 774 passed, 8 skipped (dist_moe or verifiers not installed, and one test main marks TODO).
# 2 failed, as on main: test_kv_offload_coordination.py::test_terminal_cleanup_preserves_block_identity
# [FINISHED_ABORTED-True] and [FINISHED_ERROR-True] ("'KVOffloadScheduler' object has no attribute 'skipped_waiting'").
pytest tests/rl/unit_tests/cpu -q

SGLangEngine.Config.num_speculative_tokens turns the checkpoint's MTP head into
an SGLang draft model (NEXTN, topk 1, rejection sampling, FlashInfer draft
attention). GDN verify rows run SGLang's conv update and ReplaySSM recurrence on
TorchTitan's state pool; the draft shares the model's embedding and LM head.

- registry.py: the draft's config parse goes to SGLang's HF parser; patches for
  the draft runner's GDN backend and SGLang's ReplaySSM gate, each with a TODO.
- engine.py: raises for untested setups (MoE, KDA, no GDN layers, another
  checkpoint architecture), enable_mixed_chunk and k > 5; RoPE caches
  CONTEXT_LENGTH_MARGIN rows longer with drafts; after the build, raises if
  SGLang built no ReplaySSM rings or keeps fewer running requests than asked.
- generator/tokens_per_verify_step metric.
- tests/rl/unit_tests/gpu/test_sglang_mtp.py, run in the B200 SGLang CI step.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

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

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: the maintainers need to decide whether the draft should be SGLang's own frozen MTP class or TorchTitan's MTP module; the other items are mechanical. 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 SGLang's own frozen Qwen3.5 MTP class wired in through three patches of SGLang internals, not TorchTitan's MTP module. Maintainers need to make that call for both engines (this PR and the vLLM stack, #6287). The other items are mechanical.

What this PR does. It adds SGLangEngine.Config.num_speculative_tokens. With k > 0, SGLang builds its Qwen3.5 MTP model from the checkpoint's mtp.* weights as an EAGLE-chain draft, sharing TorchTitan's embedding and LM head. TorchTitan's model checks the drafts with rejection sampling. GDN verify rows run SGLang's conv-update and ReplaySSM kernels on TorchTitan's state pool. Unified memory is off with drafts, and many unsupported setups raise.

Example.

SGLangEngine.Config(num_speculative_tokens=3, cuda_graph="breakable")
before: 1 token per request per decode step
after:  the draft proposes 3 tokens -> 4 verify rows -> 1-4 tokens per step
        (27B agent load: 1,327 -> 1,929 tok/s, one run per arm)
        GDN decode now runs SGLang's kernels, not Attention Gym's (not bitwise vs the trainer)
        the draft's own mtp.* layer keeps the checkpoint weights while the policy trains

Must fix

  1. Draft design (gate, maintainer call). Training and inference are supposed to share modules (rules/models.md), and models/common/mtp.py already exists for DeepSeek. Here the draft is an SGLang-only model whose weights never follow the policy, so generator/tokens_per_verify_step exists to watch acceptance decay. A TorchTitan-native draft (Qwen3.5 MTP built on models/common/mtp.py, served by SGLangModelWrapper) would delete:

    • the draft config-parse branch (registry.py:358) and the reserved decrypted_*_config_file keys;
    • _MTP_DRAFT_ARCHITECTURES and the config.json architecture check;
    • the aliasing of SGLang's draft embedding and LM head onto TorchTitan's (get_embed_and_head), and probably _patch_draft_gdn_attention_backend;
    • the FlashInfer/nvcc build-time dependency.

    The draft would also stay in sync with the policy after each weight load. It has real costs: SGLang's draft-worker API, and Qwen3.5 has no MTP in TorchTitan today. So please add a paragraph to the PR on why that can't work or is deferred, and the maintainers decide. The vLLM stack (#6287) makes the same choice, so whatever they decide applies to both engines.

  2. engine.py:402-425 -- patches the finished model config in the constructor. Fold it into _replace_sglang_layer_configs and apply it for every k, which leaves numerics unchanged (inline).

  3. gdn.py:238 -- the Attention Gym verify-kernel gap needs a TODO with an upstream link (inline).

  4. registry.py:196,228,361 -- the SGLang TODOs need the filed issue links (inline).

  5. gdn.py:256 -- B and J are missing from the file's shape legend (inline).

  6. test_sglang_mtp.py:62 -- the test imports another module's private _load_trainer_weights (inline).

Should consider

  • dispatcher.py:416 -- tokens from a retracted request's second prefill may be counted as verify tokens (unverified, inline).

Questions

  • engine.py:695 (your open question): raising when SGLang keeps fewer running requests than max_num_seqs follows "errors over warnings" for every k. But at k = 0 that turns a working setup that only warns into a raise, so it's a maintainer call. I'd do it in its own PR.
  • Second-turn greedy argmax gap: 0.183 with drafts vs 0.039 without, while the mean |delta| stays the same. When a request finishes after verify steps, does the radix cache store the state with the ReplaySSM ring folded in (cache_finished_req)? The unchanged mean suggests it does. Please confirm.
Details
  • Overlap search: MTP, SGLang generator. Found the vLLM MTP stack (#6287, #6364, #6402, #6403, #6365, #6366) and the SGLang PRs that edit the same files (#6318, #6200, #6021, #6379, #6018, #6413). All are already listed in the description; whichever PR lands second rebases.
  • linear_attention.py:189: removing the verify NotImplementedError is safe. The only way into verify is num_speculative_tokens, since extra_server_args rejects every speculative_* key, and KDA layers raise at engine build.
  • RoPE: max_context_length feeds only torch.arange(...) in every RoPE variant, and the caches are persistent=False (rope.py:198). So extending them never changes existing rows or checkpoints.
  • Build-time validation in __init__ (parallelism, model layers, debug, checkpoint) is fine where it can't be in __post_init__: those are build arguments, not fields of SGLangEngine.Config.

Not verified: SGLang internals (hybrid_gdn_config uses being gated on the ReplaySSM flag, select_verify_intermediate_state_indices semantics, spec_verify_ct on retraction). The SGLang source was not available here, and the GPU tests were not run.

Before merge: fill in the human-written summary.

Comment on lines +402 to +425
# A verify step runs each request's drafts after its last token, so a request
# near max_context_length runs positions past it (SGLang's context is
# CONTEXT_LENGTH_MARGIN tokens longer). Their tokens are cut, but their RoPE
# lookups must stay inside the caches.
layers = []
for layer in model.layers:
attention = layer.attention
# Softmax attention layers with RoPE: GDN layers (LinearAttention) have
# none.
if (
isinstance(attention, Attention.Config)
and not isinstance(attention, LinearAttention.Config)
and attention.rope is not None
):
rope = dataclasses.replace(
attention.rope,
max_context_length=attention.rope.max_context_length
+ CONTEXT_LENGTH_MARGIN,
)
layer = dataclasses.replace(
layer, attention=dataclasses.replace(attention, rope=rope)
)
layers.append(layer)
model = dataclasses.replace(model, layers=layers)

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 patches the finished generator model config in the engine constructor, which rules/config.md rules out ("Don't patch a finished config tree at runtime"). It also walks the layers a second time, after the walk that _replace_sglang_layer_configs (model_wrapper.py:60) already does to swap each layer's inner attention.

Smaller fix: in the softmax-attention branch of _replace_sglang_layer_configs (model_wrapper.py:168-182), also replace attention_cfg.rope with max_context_length + CONTEXT_LENGTH_MARGIN when it is not None, and do it for every k. That doesn't change numerics. RoPE caches read max_context_length only as the arange length (rope.py:312,474,524,614), and the cache is a non-persistent buffer. It also matches SGLang's context, which is already max_context_length + CONTEXT_LENGTH_MARGIN for every k (registry.py:83, engine.py:579). registry.py imports model_wrapper only lazily, so model_wrapper can import the constant at top level. This deletes this 20-line k > 0 branch.

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: Done in ef2eef3. _replace_sglang_layer_configs now gives every softmax layer's RoPE cache CONTEXT_LENGTH_MARGIN more rows, for every k. The engine no longer patches the built config. Configs without a rope field (Kimi K3's MLA) are left alone.

The existing rows keep their values: on Qwen3.5-0.8B's generator config, a cache built 6 rows longer matches the old one bitwise on its first 4,096 rows, on CPU and CUDA. test_sglang_mtp.py prints the same numbers as before (7 passed).

commit: ring [t1 t2 x d1]; conv history <- the window after d1

Each row's conv window goes to the request's scratch row, which the commit
reads. Attention Gym has no verify kernels, so these are SGLang's.

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 is a workaround for a gap in a PyTorch library (Attention Gym is meta-pytorch), and it is the reason trainer and generator GDN decode numerics now differ with drafts. Principle 3 asks for a TODO with an upstream issue link here, e.g. TODO(<attention-gym issue>): run verify rows on Attention Gym's GDN kernels once it has a multi-token verify kernel, so trainer and generator share them.

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: Added in ef2eef3, at the top of _forward_target_verify. No Attention Gym issue exists yet, so the TODO has no link. The link goes in once one is filed.

# ======== Convolution ========
# SGLang's kernel takes [C, W - 1] conv histories with contiguous channels:
# transposed views of the pool's [W - 1, C].
convolved_BCJ = causal_conv1d_update(

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.

The file legend (line 9) defines T, C, H, V and W only. B and J aren't defined, and the shape-suffix rule needs one legend per file. Add them to the legend at the top, e.g. B = requests of a verify step, J = tokens per request (k + 1).

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: Done in ef2eef3. The legend now ends: "in an MTP verify step, B = requests and J = tokens per request (drafts + 1)."

if "_configuration_file" in kwargs:
# Only an MTP draft's parse carries a config file (SGLangEngine sets
# decrypted_draft_config_file): the draft is SGLang's own model class.
# TODO: drop this branch once SGLang can give a draft its own config

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 TODO and the two at lines 196 and 228 wait on SGLang changes but have no issue links. The description says the issues are drafted, not filed. File them and put the links in the three TODOs, as the other SGLang workarounds in this package do (e.g. TODO(https://github.com/sgl-project/sglang/issues/48474)). This branch also probes SGLang's kwargs (_configuration_file) to find out which parse it is in, so the issue link is what tells a reader when the probe can go.

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: The three SGLang issues are written, each with a repro at the pinned SGLang and a check of SGLang main. They are in review before filing. Their links go into these three TODOs once filed.

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: The three SGLang issues are now drafted on Felipe's SGLang fork, for his review:

  • registry.py:196 (no linear attention backend for an MTP draft): felipemello1/sglang issue 4.
  • registry.py:228 (ReplaySSM gate for registered models): felipemello1/sglang issue 5.
  • registry.py:361 (a draft's own config parser): felipemello1/sglang issue 3.

The code keeps plain TODOs for now. When Felipe files them on SGLang's tracker, each TODO gets that upstream issue's link.

from torchtitan_recipes.rl.model_configs import build_rl_model_configs

from tests.rl.unit_tests.gpu.test_bitwise_parity import build_trainer_model
from tests.rl.unit_tests.gpu.test_sglang_bitwise_parity import _load_trainer_weights

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 imports another module's _private name, which CLAUDE.md (Naming) rules out. Now that a second module uses it, rename it to load_trainer_weights in test_sglang_bitwise_parity.py and import that.

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: Done in ef2eef3. load_trainer_weights is now public in test_sglang_bitwise_parity.py, and both test files call it by that name.

"generator/inter_token_latency_ms"
] = first_to_last_token_ms / (inputs.num_generation_tokens - 1)

if inputs.num_verify_steps > 0:

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.

Should consider (unverified): a retracted request prefills again and samples one more token in that prefill. If SGLang's spec_verify_ct survives the retraction, this counts those tokens as verify tokens. In RL with reset_kv_cache_on_model_state_dict_load, every weight load retracts every running request. (num_generation_tokens - 1 - num_preemptions) / num_verify_steps would remove the bias, if SGLang works the way I think. Please check Req.reset_for_retract at the pinned SGLang.

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: Confirmed at the pinned SGLang, and fixed in ef2eef3.

So each retraction adds one prefill token. The metric is now (num_generation_tokens - 1 - num_preemptions) / num_verify_steps, where num_preemptions is SGLang's retraction_count. test_tokens_per_verify_step gains a case: 9 tokens, 2 preemptions, 4 verify steps -> 1.5.

…ps re-prefill tokens

- model_wrapper: _replace_sglang_layer_configs gives softmax layers' RoPE caches
  CONTEXT_LENGTH_MARGIN more rows, for every k; MLA configs without RoPE (Kimi K3) are
  left alone. The engine no longer patches the built config.
- engine: TODO for a TorchTitan Qwen3.5 MTP draft.
- dispatcher: tokens_per_verify_step drops one prefill token per preemption.
- gdn: B and J in the legend; TODO for an Attention Gym verify kernel.
- tests: load_trainer_weights is public; a preemption case for the metric.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: The fixes for the review are in ef2eef3. Answers to the two questions:

  1. Raise at k = 0 when SGLang keeps fewer running requests than max_num_seqs: agreed, that goes in its own PR.

  2. Second-turn argmax gap: yes, the radix cache stores the state with the ring folded in. At the pinned SGLang:

    • For GDN, the verify commit takes the compact-replay branch (spec_utils.py:1243-1320). With our fp32 checkpoint state, it folds a ring only when the ring is full (fold_every_commit is False).
    • Its commit_gdn_replayssm_circular gets the track slots: "track rows snapshot the exact crossing state without disturbing the active circular history" (spec_utils.py:1285-1303).
    • When a request finishes, the cache stores that track slot, at mamba_last_track_seqlen (mamba.py:748-806).
    • So turn 2 resumes from an exact state at the last track boundary, and prefills the rest.

    The max gap is one near tie in 1,024 tokens. On turn 1 the order flips: 0.078 with drafts vs 0.135 without, over 8,192 tokens.

Draft design: the body now has a "Why SGLang's Qwen3.5 MTP model as the draft" item, and engine.py has a TODO at the draft's server args.

@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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


Needs discussion: the maintainers still need to decide on the draft design (SGLang's own frozen MTP class or TorchTitan's MTP module); the other earlier items are resolved except the missing upstream issue links. 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 maintainers still have to decide whether the draft can be SGLang's own frozen Qwen3.5 MTP class, wired in through patches of SGLang internals, or must be a TorchTitan module. That decision covers the vLLM stack (#6287) too. The rest is mechanical or resolved.

What this PR does. It adds SGLangEngine.Config.num_speculative_tokens. With k > 0, SGLang builds its Qwen3.5 MTP draft from the checkpoint's mtp.* weights, using TorchTitan's embedding and LM head. TorchTitan's model checks the drafts with rejection sampling, and GDN verify rows run SGLang's conv-update and ReplaySSM kernels on TorchTitan's state pool. Since the last review, the RoPE margin moved into _replace_sglang_layer_configs for every k, and the verify-step metric no longer counts the extra prefill token after a preemption.

Example.

SGLangEngine.Config(num_speculative_tokens=3, cuda_graph="breakable")
before: 1 token per request per decode step
after:  3 drafts -> 4 verify rows -> 1-4 tokens per step
        RoPE caches: max_context_length + 6 rows for every k (existing rows unchanged, non-persistent)
        generator/tokens_per_verify_step = (tokens - 1 - preemptions) / verify steps
          e.g. 9 tokens, 2 preemptions, 4 verify steps -> 1.5

Earlier must-fix items

  • Resolved: the RoPE config patch in the engine (now in model_wrapper.py:169-181), the B/J shape legend, the private _load_trainer_weights import, and the preemption bias in the verify-step metric (dispatcher.py:416).
  • Still open: draft design (maintainer call). The new "Why SGLang's Qwen3.5 MTP model" paragraph and the TODO at engine.py:980 state the trade-off. Only a maintainer can make the call.
  • Still open: the upstream TODOs at gdn.py:662 (Attention Gym) and registry.py:1120,1152,1198 (SGLang) still have no issue links. This is mechanical once the issues are filed.

Should consider

  • #6417 ("decode CUDA graphs up to max_num_seqs", opened after this PR's description was written) sets cuda_graph_config["decode"]["max_bs"] = max_num_seqs in engine.py. With drafts, SGLang captures the verify graphs on that same decode runner at k + 1 tokens per request, so the largest verify graph would grow to 4 x max_num_seqs tokens. Whichever PR lands second should check that capture memory and build time still fit, or cap max_bs when drafts are on. #6419 adds RequestMetricsInputs fields and dispatcher metrics next to num_verify_steps, so it needs a rebase too.
Details
  • Re-review scope: c84ca4d (test comments only) and ef2eef3 (the fixes). I re-read the full diff at ef2eef3.
  • RoPE margin for every k: max_context_length only sets the arange length in every RoPE variant (rope.py:312,474,524,614). The cache is persistent=False (rope.py:198). Scaling is a separate field, and the vision RoPE __post_init__s don't read the length. So k = 0 numerics and checkpoints don't change. getattr(attention_cfg, "rope", None) is needed: rope sits on GQAttention.Config and the per-model subclasses, not on Attention.Config, and KimiMLAAttention.Config (kimi_k3/attention.py:51) has none. Nothing else in torchtitan/rl reads rope.max_context_length.
  • model_wrapper.py now imports CONTEXT_LENGTH_MARGIN from registry.py at module level. registry.py has no top-level import of model_wrapper, so there is no cycle.
  • Overlap search: MTP, SGLang generator. Found the vLLM MTP stack (#6287, #6364, #6365, #6366, #6402, #6403), the PRs already listed in the description (#6018, #6021, #6200, #6318, #6379, #6413, #6415), and #6417, #6418, #6419 (all opened 2026-11-27, after the description). #6418 edits engine.py and the parity test.

Not verified: SGLang internals (reset_for_retract keeping spec_verify_ct, the ReplaySSM gate's uses); the SGLang source isn't available here. GPU tests were not run.

Before merge: fill in the human-written summary.

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.

1 participant