Skip to content

[rl] generator: SGLang generation engine - #5812

Merged
tianyu-l merged 3 commits into
sglang-1-paged-attn-flashfrom
sglang-2-engine
Nov 10, 2026
Merged

tianyu-l merged 3 commits into
sglang-1-paged-attn-flashfrom
sglang-2-engine

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #6001 (the generator's paged attention runs FlashAttention, not cuDNN).

Summary (human-written)

experimental alternative generation engine support

Why

The RL generator runs only on vLLM today. SGLang's scheduler (radix prefix
cache, overlap scheduling, breakable prefill CUDA graphs, session-referenced
KV, host KV offload) is a strong fit for RL rollouts, especially multi-turn
agentic ones. This PR adds an SGLangEngine behind the existing
GenerationEngine interface. As with VLLMEngine, SGLang runs the trainer's
TorchTitan model and attention kernel; it owns only KV cache management and
scheduling.

Maintainer decision (@tianyu-l): torchtitan keeps SGLang as an alternative
generation backend next to vLLM, not only as an experiment. Its tests run in
the B200 RL job (integration_test_rl_b200.yaml), added here.

Example.

# before: vLLM only
generator=Generator.Config(..., engine=VLLMEngine.Config())
# after: pick the engine by config type
generator=Generator.Config(..., engine=SGLangEngine.Config())
SGLangEngine (every rank, in-process; no tokenizer/detokenizer processes)
  add_requests ----> Scheduler.process_input_requests
  step ------------> one iteration of Scheduler.event_loop_overlap
                       TorchTitan Decoder, attention -> RadixAttention ->
                       trainer's varlen FlashAttention on SGLang's paged KV
  load_model_state_dict -> ModelStateDictLoader (in place, CUDA graphs stay valid)

What changed

  • torchtitan/rl/generator/sglang/ (new):
    • engine.py: SGLangEngine. It builds SGLang's Scheduler in-process per
      TP rank and steps one overlap-loop iteration per step(). It also does:
      • request admission and rejection;
      • incremental output collection;
      • model state dict loads, with and without a KV reset (retract, flush,
        continue);
      • policy-version cache_salt;
      • session references;
      • seeded sampling.
      • prompt-length limits matching vLLM's: SGLang rejects prompts of
        context_len - 6 tokens or more, so the engine sets SGLang's context length to
        max_context_length + 6 (registry.CONTEXT_LENGTH_MARGIN) and caps each
        request's output at max_context_length tokens in total. Prompts of up to
        max_context_length - 1 tokens run, as in vLLM; without the margin, prompts of
        65,530-65,535 tokens at a 64K context were rejected.
    • model_wrapper.py: the TorchTitan model as an SGLang model class, with
      _DecoderBody, the module SGLang's prefill CUDA graphs capture.
    • attention.py: SGLangInnerAttention, plus a FlashAttention-backend
      subclass that calls the shared paged_varlen_attention_out.
    • registry.py: model class, config parser and attention backend
      registration.
    • batch_invariance.py: the trainer's compute_logprobs for returned
      logprobs.
    • README.md.
  • inference_model.compute_logits: the lm_head plus TP gather, now shared by
    the vLLM and SGLang wrappers. For vLLM this is mechanical (the same code,
    moved).
  • inference_model.route_tp_all_reduce: the routing half of the vLLM wrapper's
    _patch_vllm_all_reduce, moved and shared. Outside batch-invariant mode, the
    SGLang wrapper routes the model's TP sum all-reduces through SGLang's
    tensor_model_parallel_all_reduce (SGLang's custom all-reduce) instead of NCCL.
    For vLLM this is mechanical, with two differences: the registered=False
    override now also applies to a rebuilt engine's communicator, and the docstring's
    reason for routing spmd.redistribute directly is corrected (its all-reduce
    reaches the op swap through funcol; the direct route is about 2-3% faster for
    vLLM decode at TP 2).
  • torchtitan_recipes/rl/alphabet_sort.py: new recipe
    rl_grpo_qwen3_0_6b_varlen_sglang: rl_grpo_qwen3_0_6b_varlen (generator TP 4
    plus trainer TP 2, 6 GPUs) with the SGLang engine.
  • Per-request metrics (queue time, time to first token, prefill and decode times,
    preemptions) come from the timestamps SGLang's scheduler stamps on each request,
    as the vLLM engine reports them. The queue time starts at admission, since SGLang
    restamps its wait-queue entry time when it retracts a request.
  • test_sglang_bitwise_parity.py (new). test_model_defaults.py lists the
    SGLang recipe as needing an optional package.
  • Docs: generator.py and torchtitan/rl/README.md mention the new engine.
  • scripts/install_rl_env.sh --sglang (new flag): installs SGLang at the pinned
    commit with a git-URL install, keeping the environment's PyTorch (uv overrides)
    and dropping torchaudio, which the engine never imports.
  • CI: the B200 RL job (integration_test_rl_b200.yaml) gains a last step. It
    installs SGLang with scripts/install_rl_env.sh --sglang on top of the job's RL
    environment and runs test_sglang_bitwise_parity.py on 2 GPUs. The README's
    environment steps use the same flag, so the SGLang commit is pinned in one
    place. The step runs after the job's other tests, so installing SGLang cannot
    affect them, and it adds about 2 minutes to a job that takes 16-26.

Supported: dense softmax attention with the varlen backend (Qwen3, Llama 3),
any TP, decode plus breakable prefill CUDA graphs, batch-invariant mode,
session KV, and CPU KV offload (SGLang HiCache, through extra_server_args).
These raise at build: DP > 1, EP / Dist-MoE, SP, flex attention, sliding window,
sinks, MLA and GDN.

Review fixes (19e4b88):

  • step() runs under torch.no_grad(), as SGLang's own loops and the vLLM engine
    do, so the model's TP all-reduces take their fast path in eager steps.
  • add_requests rejects empty prompts and token ids outside the vocab (SGLang
    checks only the length; at TP > 1 a bad id would embed as zeros silently).
  • extra_server_args cannot set page_size (the engine sets 1, with the reason)
    or any key containing cuda_graph: SGLang applies its per-phase graph keys over
    disable_cuda_graph, so they could turn on graphs the engine's checks assume
    are off.
  • The trainer-logprobs sampler is registered with SGLang's
    register_sampler_backend instead of patching Sampler.forward.
  • A load without a KV reset clears SGLang's watchdog batch before the fetch.
  • Docstrings and comments: the output collector (no tokenization runs), the cache
    salt, page_size.

Workarounds of SGLang APIs, each with a TODO in code:

  • single-iteration loop (mirrors event_loop_overlap);
  • an in-process output sink replacing the detokenizer and tokenizer sockets;
  • a hook to plug a kernel into SGLang's FA metadata;
  • skipping SGLang's own aten batch-invariant overrides in deterministic mode;
  • registering the trainer-logprobs sampler for every built-in sampling backend;
  • registering a model class built at runtime;
  • the layer attribute path its prefill graphs use to find attention.

User-facing changes

Before After
Generator.Config.engine: VLLMEngine.Config only also SGLangEngine.Config(cuda_graph=..., extra_server_args=...)
- recipe rl_grpo_qwen3_0_6b_varlen_sglang
- scripts/install_rl_env.sh --sglang: also installs SGLang into the RL environment
force_logprobs_fn_for_batch_invariance (vLLM) renamed force_trainer_logprobs_for_batch_invariance, the SGLang helper's name

Numerics

Batch-invariant mode matches the trainer bitwise.

Check Hardware Result
test_sglang_bitwise_parity.py: trainer prefill vs SGLang decode; decode bsz 1 vs 5 with the prompt cached; trainer vs SGLang after an in-place model state dict load of perturbed weights 2x GB300, SGLang 851642ade 3 passed, max delta 0 (a no-op load fails it: delta 19.5)
E2E rl_grpo_qwen3_0_6b_varlen_batch_invariant with SGLang (1 generator TP 2 + trainer TP 2), 10 steps 4x GB300 logprob_diff/max = 0 every step
Multi-turn workload (192 sessions x 4 turns), batch-invariant, HiCache on vs off 2x GB300 identical tokens for every session
Outside batch-invariant mode, Qwen3-0.6B TP 2, 32 greedy requests x 64 tokens, SGLang's vs NCCL's all-reduce 2x GB300 identical tokens and logprobs

Outside batch-invariant mode, logprob_diff/max on the default recipe
(10 steps) is in vLLM's range: SGLang 0.4-18.5, vLLM 0.4-12.4. Across
other runs it varies: SGLang reached 4.9, 7.4 and 11.1; vLLM reached 9.8.

Performance

Qwen3-0.6B, generator TP 2, 2x GB300. Same GenerationEngine calls; temperature
1; fixed-length outputs.

Workload vLLM SGLang
Decode: 512 requests, 256 in / 1024 out 18.0 s (29.1k out tok/s) 10.9 s (48.0k out tok/s)
Prefill: 512 requests, 1536 in / 128 out 4.1-4.6 s 3.1 s
Shared prefix: 512 requests, 1536 in (1280 shared) / 256 out 4.9 s 3.7 s
Multi-turn: 192 sessions x 4 turns (1024 + 4 x (256 obs + 128 gen)), KV pool 300K tokens 6.96 s, 21% prefix hits; 6.22 s, 30% with session_kv_holder 6.24 s, 37%
Multi-turn, KV pool 450K tokens (fits) 5.8-6.2 s 5.5 s
Peak GPU memory at gpu_memory_limit=0.8 81.2% 81.1%

End to end, alphabet_sort with generator TP 2 + trainer TP 2 (4x GB300, 10
steps): trainer tokens/s over steps 3-9 is 1682 and 1693 for vLLM (two runs), and
1632 and 1758 for SGLang (two runs). The shipped recipe uses generator TP 4 (6
GPUs, as the vLLM recipe); it was not run, since this host has 4 GPUs.

The table and these E2E runs were measured before the TP all-reduce routing. With
the routing, one more SGLang run of the same E2E (RL environment, so
expandable_segments; decode and breakable prefill CUDA graphs) reached 1763
trainer tokens/s over steps 3-9. SGLang's custom all-reduce registered the graph
buffers through FABRIC handles, so capture works on that memory. With a separate
local benchmark (perf mode, temperature 1, decode and breakable prefill CUDA graphs,
the RL environment defaults including expandable_segments, median of 2 runs;
Qwen3-0.6B TP 2, 2x GB300):

Workload SGLang, NCCL all-reduce SGLang, SGLang all-reduce vLLM
Decode 64 requests x 512 tokens, ms/step 2.85 2.12 3.57
Decode 256 requests x 512 tokens, ms/step 4.30 3.56 7.9
GRPO 16 prompts x 8 samples (1024 in, 256 out), s 1.25 1.04 1.46

Most of the decode gap to vLLM is not SGLang's scheduling. The vLLM engine's
default FULL CUDA graphs capture one graph per size for mixed prefill/decode
batches, with prefill-sized attention parameters, so decode steps run FlashAttention
4's non-persistent varlen scheduler: 1.99 ms of decode attention per step at 256
requests, against 0.75 ms in SGLang and 0.70 ms in vLLM with FULL_DECODE_ONLY.
vLLM's decode step is also mostly host time.

Three engine fixes were needed to get there:

  • Breakable prefill CUDA graphs: eager prefill was CPU-bound, at 114 ms of host
    time against 16 ms of GPU time per 16K-token chunk.
  • gc.freeze() after the build: SGLang's ~1.5M objects made the engine loop's
    gc.collect() after each load take 1.2 s.
  • KV-pool bookkeeping on SGLang's schedule stream.

Testing

  • test_sglang_bitwise_parity.py at 19e4b88: 5 passed on 2x GB300, including
    the new test_sglang_decode_across_model_state_dict_load (a load of the same
    weights at step 10, mid-decode, leaves tokens and logprobs identical). Earlier
    revisions: 3 passed in a fresh environment built the way the CI step builds it.
  • scripts/install_rl_env.sh --sglang's SGLang install, in a fresh venv with the
    RL environment's torch: installs SGLang at the pin, torch unchanged, no
    torchaudio.
  • The new CI step, run locally the way CI runs it (the step's own commands, in the fresh
    environment): 3 passed. On B200: run 42015554306,
    3 passed on both ranks; the step took 2 minutes, SGLang install included.
  • Engine checks (local script) at TP 1 and TP 2, each with
    reset_kv_cache_on_model_state_dict_load off and on:
    • a too-long prompt is rejected;
    • a mid-generation reload of the same weights leaves outputs identical;
    • reset mode passes 6 of 6 repeats at TP 2.
  • pytest tests/rl/unit_tests/cpu: 546 passed (581 at the top of the stack after
    the review fixes).
  • vLLM TestBitwiseParityVarlen: 3 passed (it covers the shared
    compute_logits).
  • E2E runs as above.
  • test_context_length_limits (new, in TestSGLangBitwiseParityVarlen): a prompt of
    max_context_length - 1 tokens runs and stops at max_context_length tokens in
    total, and a prompt of max_context_length tokens is rejected. Without the margin
    it fails (the first prompt is rejected). With it, all 4 tests of the class pass on
    2x GB300.

Known issues / follow-ups

@tianyu-l
tianyu-l added this pull request to stack #5813 November 4, 2026 15:56
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 4, 2026
@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

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

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 5m 56s —— View job


Needs discussion: the engine is careful, but it means maintaining ~10 private SGLang touchpoints, pinned to one commit, with no CI, and end-to-end throughput on the in-repo recipe is at parity with vLLM. 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 engine is careful and fits the GenerationEngine interface. But adding a second inference engine means maintaining about 10 private SGLang touchpoints, pinned to one SGLang commit, with no CI. The PR's own end-to-end numbers on the in-repo recipe are at parity with vLLM, not ahead. Maintainers need to decide whether that cost is worth taking on now.

What this PR does. It adds SGLangEngine, a second GenerationEngine. On every TP rank it builds SGLang's Scheduler in-process and runs one iteration of SGLang's overlap event loop per step(). The TorchTitan Decoder is plugged in as an SGLang model class, and attention goes through RadixAttention into a FlashAttention-backend subclass that calls the trainer's varlen kernel. The lm_head plus TP gather moves into inference_model.compute_logits, which both engines now share. It also adds a 4-GPU recipe and a bitwise-parity test that doesn't run in CI.

Example.

# before: one engine
Generator.Config(..., engine=VLLMEngine.Config())
# after: pick the engine by config type
Generator.Config(..., engine=SGLangEngine.Config())
#   add_requests -> Scheduler.process_input_requests (no tokenizer/detokenizer procs)
#   step         -> _overlap_event_loop_iteration(scheduler)   # copy of the pinned event_loop_overlap body
#   load         -> ModelStateDictLoader in place; reset mode = pause(retract) + flush_cache + continue

Must fix

  1. PR description -- "Summary (human-written)" is empty. The author needs to fill it in.

  2. Upstream workarounds have no issue links (CLAUDE.md principle 3). Each workaround has a TODO, but none links an issue; the PR says the issues aren't filed yet. With a commit pin (851642ade) and no CI, an SGLang bump will break these silently, so they need tracking upstream. Touchpoints:

    • engine.py:569 copies the body of event_loop_overlap and calls private members (_apply_war_barrier, _sched_idled). engine.py:327 sets _war_barrier_enabled.
    • engine.py:231-234 replaces output_streamer.send_to_detokenizer and ipc_channels.send_to_tokenizer. engine.py:227 clears hf_eos_token_id.
    • engine.py:193 monkeypatches ModelRunner.maybe_enable_batch_invariant_mode for the whole process whenever debug.seed is set.
    • attention.py:62 overrides _init_flash_attention_functions.
    • registry.py:127 writes to ModelRegistry.models directly.
    • batch_invariance.py:73 patches Sampler.forward.
    • model_wrapper.py:136 adds an unregistered attn alias.

    File the issues (at minimum one for a public single-iteration step API and one for an in-process output sink, which together cover most of these) and link them in the TODOs.

  3. tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:52 -- imports the private _make_prompt_tokens (inline).

Should consider

  • torchtitan/rl/generator/sglang/engine.py:558 -- with has_stats=False, SGLang runs drop the queue, TTFT, prefill and preemption metric keys (inline).
  • torchtitan_recipes/rl/alphabet_sort.py:126 -- generator TP 2 instead of 4 is the only reason the base recipe had to be restructured into a helper (inline).

Questions

  • Value end to end. The alphabet_sort trainer tokens/s is 1682/1693 for vLLM and 1632/1758 for SGLang, which is noise. On the multi-turn benchmark, SGLang takes 6.24 s and vLLM with session_kv_holder takes 6.22 s. The large wins (decode 1.65x, prefill 1.3x) are from generator-only microbenchmarks. Which in-repo workload, e.g. long-decode dapo_math, shows an end-to-end gain that justifies a second engine?
  • CI and ownership. Who owns the SGLang environment, and when does the SGLang CI job land? Until it does, ~1.8K lines and the only parity test are unguarded.
  • Priority tie-breaks across TP ranks. EngineRequest.arrival_time exists so that TP ranks with different clocks break priority ties the same way. The SGLang engine never passes it. Does SGLang's priority policy break ties by insertion order only, or does it use rank-local timestamps (e.g. wait-time thresholds) that could make TP ranks schedule differently?
Details

Gate.

  • Problem: the generator only supports vLLM. The PR measures what SGLang's scheduler adds.
  • Layer: SGLang lives in its own subpackage, behind the existing interface, selected by config type. Imports are lazy in the recipe, and core never imports SGLang. That matches direction.md and the vLLM precedent. extra_server_args matches vLLM's extra_engine_args, including the owned-key check.
  • One-sided design: not applicable; this is an engine alternative, not a generator-only optimization.
  • The open questions are value and maintenance cost, which is why the verdict is Needs discussion rather than Request changes.

Checked and fine.

  • compute_logits is shared correctly. Inside the vLLM method body, compute_logits resolves to the module-level import, not the method.
  • replace_sglang_layer_configs uses a strict type(...) is VarlenInnerAttention.Config check. That rejects sliding-window varlen, flex, MLA, GDN/KDA and linear attention at engine build. GPT-OSS's sinks are never reached because its layer 0 is sliding-window.
  • release_sessions releases sessions in sorted order, and the releases arrive through the broadcast decision, so all TP ranks agree.
  • The GenerationEngine threading and TP-collective contract holds: every rank gets the same calls.

Size. About 1.3K lines of logic plus a 148-line README. The compute_logits move and the recipe helper are mechanical.

Not verified: behaviour inside SGLang (whether flush_cache succeeds with retracted requests in the waiting queue, whether is_fully_idle is affected by held session references, SGLang's priority tie-break), and all GPU parity and perf numbers. SGLang isn't installed in this environment.

finish_reason=reason["type"],
metrics_inputs=RequestMetricsInputs(
num_cached_tokens=None if stats is None else stats.cached_tokens,
has_stats=False,

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.

has_stats=False on every finished request means dispatcher.py:400 skips all the per-request timing metrics with SGLang: queue_time_ms, num_preemptions, time_to_first_token_ms, prefill_time_ms, and the decode metrics after them. Only num_cached_tokens survives. So switching Generator.Config.engine silently drops metric keys that vLLM runs report, and dashboards built on them go blank. Neither the PR description nor the README mentions this.

Smallest fix: fill queued_ts / scheduled_ts / first_token_ts / last_token_ts / num_preemptions from SGLang's per-request stats (you already read output.request_stats[i].cached_tokens here) and set has_stats=True. If SGLang doesn't expose them, list the missing metrics under "Known issues" and in the README's Supported table.

)

from tests.rl.unit_tests.gpu.test_bitwise_parity import (
_make_prompt_tokens,

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 a module-private name (_make_prompt_tokens) from test_bitwise_parity. CLAUDE.md says not to import another module's _private names. The helper now has two consumers, so rename it to make_prompt_tokens in test_bitwise_parity.py and update its callers there. That's a mechanical rename.

Comment thread torchtitan_recipes/rl/alphabet_sort.py Outdated
Comment on lines +126 to +138
def rl_grpo_qwen3_0_6b_varlen_sglang(*, seq_len: int = 2048) -> Controller.Config:
"""GRPO training config for Qwen3-0.6B with the SGLang engine (4 GPUs: 2 gen + 2 train)."""
# Imported here so the other recipes do not depend on SGLang.
from torchtitan.rl.generator.sglang.engine import SGLangEngine

return _qwen3_0_6b_varlen_config(
seq_len=seq_len,
generator_parallelism=InferenceParallelismConfig(
data_parallel_degree=1,
tensor_parallel_degree=2,
),
engine=SGLangEngine.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.

Why does the SGLang recipe use generator TP 2 when the vLLM recipe uses TP 4? Qwen3-0.6B (16 query / 8 KV heads) divides by 4, and SGLangEngine supports any TP.

The TP change is the only reason for the new _qwen3_0_6b_varlen_config helper and the restructuring of rl_grpo_qwen3_0_6b_varlen: the generator model's sharding is built from generator_parallelism. With TP 4, the recipe could derive from the base recipe, as rl_grpo_qwen3_0_6b_varlen_no_compile already does:

def rl_grpo_qwen3_0_6b_varlen_sglang(*, seq_len: int = 2048) -> Controller.Config:
    """... with the SGLang engine (6 GPUs: 4 gen + 2 train)."""
    from torchtitan.rl.generator.sglang.engine import SGLangEngine

    config = rl_grpo_qwen3_0_6b_varlen(seq_len=seq_len)
    config.generator.engine = SGLangEngine.Config()
    return config

That drops the helper (about 25 fewer lines) and makes the two recipes differ only by engine. If TP 2 is intentional (e.g. a 4-GPU CI budget), say so in the docstring.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 15s —— View job


Needs discussion: three earlier findings are resolved (private import, metric keys, recipe); the description is stale and empty, the upstream issue links are still missing, and the value/CI questions are still open. 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 force-push resolves the private import, the dropped metric keys and the recipe restructuring. The maintainer questions from the last review are still open: end-to-end value over vLLM, CI ownership, and the untracked private SGLang touchpoints.

Re-review of 7938547 against the review of 2026-11-04 16:23.

Resolved

  • test_sglang_bitwise_parity.py now imports make_prompt_tokens, which this PR renames in test_bitwise_parity.py and its two other callers.
  • SGLang requests now report has_stats=True, with queue, TTFT, prefill, decode and preemption metrics taken from Req.time_stats and retraction_count (engine.py:596). The README lists them as supported.
  • rl_grpo_qwen3_0_6b_varlen_sglang now derives from rl_grpo_qwen3_0_6b_varlen and changes only the engine (alphabet_sort.py:189). The helper is gone.

Must fix

  1. PR description. "Summary (human-written)" is still empty. The description is also stale after the recipe change:

    • It still says the recipe runs "generator TP 2 plus trainer TP 2".
    • It still says rl_grpo_qwen3_0_6b_varlen "now builds through a shared helper".
    • The E2E throughput and logprob numbers were measured at 2+2 on 4 GPUs. The in-repo recipe now runs 4+2 on 6 GPUs.

    Update these lines, or re-measure on the recipe as it is now.

  2. Still open: upstream workarounds have no issue links. No TODO under sglang/ links an SGLang issue. The new metrics code adds another private touchpoint: engine.py:605 reads Req.time_stats and Req.retraction_count directly because SGLang only exports them with enable_metrics. Add that to the issues to file, alongside the single-iteration step API and the in-process output sink.

Questions

  • Still open: which in-repo workload shows an end-to-end gain that justifies a second engine? Who owns the SGLang CI job, and when does it land?
  • Still open: priority tie-breaks across TP ranks. arrival_time now feeds only the TTFT metric, not scheduling. Does SGLang's priority policy break ties by insertion order only?
  • engine.py:405-407 registers only the requests found in waiting_queue right after process_input_requests. engine.py:574 then does self._admitted.pop(request_id) with no default for every non-abort finish. Does SGLang ever place an admitted request somewhere other than waiting_queue, for example with session radix cache or HiCache? If it does, the engine loop dies with a KeyError.

Not verified (SGLang isn't installed here): what SGLang's forward_entry_time and prefill_finished_time mean under chunked prefill and retraction, compared with vLLM's scheduled_ts and first_token_ts. The two engines' prefill_time_ms and queue_time_ms may not measure the same intervals.

@tianyu-l
tianyu-l force-pushed the sglang-2-engine branch 2 times, most recently from 5e1d410 to 9e493d8 Compare November 4, 2026 23:45
@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 13s —— View job


Needs discussion: the upstream issue links and the stale description are fixed. The human-written summary is still empty and one TODO has no issue link. The value and CI-ownership questions are still for maintainers. 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 upstream workarounds are now tracked and the description is accurate. The value and CI-ownership questions are still open, and only maintainers can decide them.

Re-review of 9e493d8 against the review of 2026-11-04 22:55.

Resolved

  • Upstream issue links. Every SGLang workaround TODO now links an issue: sgl-project/sglang#48472 (step API, engine.py:317, :643), #48473 (output sink, engine.py:232), #48474 (deterministic mode and EOS ids, engine.py:192, :228), #48475 (out-of-tree models: registry.py:124, attention.py:63, batch_invariance.py:72, model_wrapper.py:132) and #48476 (DP, engine.py:158).
  • Stale description. It now gives the recipe as generator TP 4 plus trainer TP 2, and drops the shared-helper line. It also says the E2E numbers were measured at 2+2 and that the shipped 4+2 recipe was not run.

Must fix

  1. PR description. "Summary (human-written)" is still the template placeholder, and the author needs to fill it in.
  2. engine.py:617 -- the _metrics_inputs TODO is the only private SGLang touchpoint left without an issue (it reads Req.time_stats and Req.retraction_count directly). The description says so itself. Fold it into #48473 or file a new issue, then link it.

Should consider

  • engine.py:409-411 / engine.py:584 -- this is the question from the last review, still unanswered. Requests get stats registered only if add_requests finds them in waiting_queue. On every non-abort finish, _receive_tokens then calls self._admitted.pop(request_id) with no default. If SGLang ever routes an admitted request elsewhere (for example a session or HiCache prefetch path), the engine loop dies later with a bare KeyError. To fail where the invariant is set up, assert in add_requests that every admitted, non-rejected rid was found in waiting_queue and registered with admit().

Questions (still open, for maintainers)

  • End-to-end value. Which in-repo workload shows an end-to-end gain that justifies a second engine? The only E2E number, alphabet_sort at 2+2, shows no measurable difference from vLLM. The large wins are generator-only microbenchmarks.
  • CI and ownership. Who owns the SGLang environment, and when does the SGLang CI job land? Until then, the ~1.8K lines and the only parity test run in no CI job.
  • TP tie-breaks. Does SGLang's priority policy break ties by insertion order only, so that every TP rank schedules the same way?

Not verified (SGLang isn't installed here): whether SGLang restamps forward_entry_time and prefill_finished_time on retraction, which decides whether prefill_time_ms means the same thing as vLLM's.

@tianyu-l

tianyu-l commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 53s —— View job


Needs discussion: the last SGLang workaround TODO now links an upstream issue. The human-written summary is still empty, and the value and CI-ownership questions are still for maintainers. 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 last private SGLang touchpoint now links an issue. The human-written summary is still empty, and only maintainers can answer the value and CI-ownership questions.

Re-review of c83a38a against the review of 2026-11-04 23:48.

Resolved

  • engine.py:617: the _metrics_inputs TODO now links sgl-project/sglang#48482, and the description lists that issue. Every SGLang workaround TODO under sglang/ now has an issue link. The two TODOs without links (engine.py:461, model_wrapper.py:61) are limitations on the torchtitan side, not upstream gaps.

Must fix

  1. Still open: PR description. "Summary (human-written)" is still the template placeholder. The author needs to write it.

Should consider

  • Still open: engine.py:409-411 / engine.py:584. add_requests calls admit() only for admitted requests it finds in waiting_queue. _receive_tokens then calls self._admitted.pop(request_id) with no default on every finish that isn't an abort. If SGLang ever puts an admitted request somewhere else, the engine loop dies later with a bare KeyError. To catch that where it happens, assert in add_requests that every admitted rid that wasn't rejected went through admit().

Questions (still open, for maintainers)

  • End-to-end value. Which in-repo workload shows an end-to-end gain big enough to justify a second engine? The only E2E number is alphabet_sort at generator TP 2 + trainer TP 2, and it shows no measurable difference from vLLM. The large wins come from generator-only microbenchmarks.
  • CI and ownership. Who owns the SGLang environment, and when does the SGLang CI job land? Until it does, no CI job runs the ~1.8K lines or test_sglang_bitwise_parity.py.
  • TP tie-breaks. Does SGLang's priority policy break ties only by insertion order, so that every TP rank schedules the same way?

Not verified: I couldn't fetch the previously reviewed commit, so I checked the earlier findings at HEAD rather than through an incremental diff. SGLang isn't installed here.

@tianyu-l

tianyu-l commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 53s —— View job


Needs discussion: the admission-invariant assert is in, so no code findings remain. The human-written summary is still empty, and the value and CI-ownership questions are still for maintainers. 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 admission invariant now fails where it is set up, so no code findings remain. The human-written summary is still empty, and only maintainers can answer the value and CI-ownership questions.

Re-review of 49f8172 against the review of 2026-11-05 00:25.

Resolved

  • engine.py:422-424: add_requests now asserts that every admitted rid that wasn't rejected was found in SGLang's waiting queue and registered with admit(). If SGLang ever routes an admitted request somewhere else, add_requests now fails with the rids involved, instead of the engine loop hitting a bare KeyError at engine.py:589 later.

Must fix

  1. Still open: PR description. "Summary (human-written)" is still the template placeholder. The author needs to write it.

Questions (still open, for maintainers)

  • End-to-end value. Which in-repo workload shows an end-to-end gain big enough to justify a second engine? The only E2E number is alphabet_sort at generator TP 2 + trainer TP 2, and it shows no measurable difference from vLLM. The large wins come from generator-only microbenchmarks.
  • CI and ownership. Who owns the SGLang environment, and when does the SGLang CI job land? Until it does, no CI job runs the ~1.8K lines or test_sglang_bitwise_parity.py.
  • TP tie-breaks. Does SGLang's priority policy break ties only by insertion order, so that every TP rank schedules the same way?

Not verified: the previously reviewed commit c83a38a can't be fetched here, so I checked the earlier findings at HEAD instead of through an incremental diff. SGLang isn't installed here.

@tianyu-l

tianyu-l commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 6s —— View job


Needs discussion: the human-written summary is now filled in. The new TP all-reduce routing has no evidence of a run under the RL env's CUDA graphs plus expandable_segments, and the value and CI-ownership questions are still for maintainers. 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 human-written summary is now filled in. The new TP all-reduce routing has no evidence that it works under the RL environment's CUDA graphs plus expandable_segments, and the value and CI-ownership questions are still for maintainers.

Re-review of ca5642b against the review of 2026-11-05 00:33.

Resolved

  • PR description. "Summary (human-written)" now has the author's text ("experimental alternative generation engine support").

New since the last review

route_tp_all_reduce moves the routing half of vLLM's _patch_vllm_all_reduce into inference_model.py. The SGLang wrapper now uses it to send the model's TP sum all-reduces through SGLang's custom all-reduce whenever batch-invariant mode is off.

Example.

# SGLangModelWrapper.__init__, TP > 1, batch_invariant off
route_tp_all_reduce(tensor_model_parallel_all_reduce)
# every _c10d_functional.all_reduce(x, "sum", g) and no-grad spmd.redistribute(P -> R/I)
#   -> SGLang's TP all-reduce (custom AR when the message fits, else NCCL)
# vLLM: same swap, plus ca_comm forced to registered=False for CUDA graphs over VMM

The vLLM refactor is mechanical, except for the two differences the description lists. Both are fine: the ca override now runs on every call, so a rebuilt engine's communicator also gets it, and the swap still installs once.

Should consider

  • torchtitan/rl/generator/sglang/model_wrapper.py:200 -- the SGLang custom all-reduce is passed without vLLM's registered=False override. No run after this change used CUDA graphs with expandable_segments, which is the configuration the shipped recipe uses (inline).

Questions (still open, for maintainers)

  • End-to-end value. Which in-repo workload shows an end-to-end gain big enough to justify a second engine? The only E2E number (alphabet_sort at 2+2, measured before the all-reduce routing) shows no measurable difference from vLLM.
  • CI and ownership. Who owns the SGLang environment, and when does the SGLang CI job land? Until it does, no CI job runs the ~1.8K lines or test_sglang_bitwise_parity.py.
  • TP tie-breaks. Does SGLang's priority policy break ties only by insertion order, so that every TP rank schedules the same way?

Not verified: SGLang's custom all-reduce capture path and its in-place fallback (SGLang isn't installed here). I couldn't fetch 49f8172, so I reviewed the new routing at HEAD rather than through an incremental diff.

# SGLang's TP all-reduce picks its algorithm by message size, which breaks
# batch invariance.
if self.parallelism_context.tp_enabled and not is_in_batch_invariant_mode():
route_tp_all_reduce(tensor_model_parallel_all_reduce)

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.

route_tp_all_reduce's docstring says all_reduce "must be capturable in CUDA graphs over the expandable_segments (VMM) memory the RL stack enables" (torchtitan/rl/_env.py:20). The vLLM side meets that requirement only through its registered=False override: registered=True calls cudaIpcGetMemHandle on graph buffers, which fails for VMM memory. The SGLang side passes tensor_model_parallel_all_reduce with no matching override. SGLang's custom all-reduce comes from vLLM's and records graph buffers in its capture() path (unverified, SGLang isn't installed here).

The description doesn't show that this path ran under the RL environment either. The E2E table was "measured before the TP all-reduce routing". The parity check of SGLang's all-reduce against NCCL's and the local perf benchmark don't say whether expandable_segments was on. If capture fails, the shipped rl_grpo_qwen3_0_6b_varlen_sglang recipe breaks when the generator is built: it runs at TP 4 with CUDA graphs on and batch invariance off, which is exactly this path.

Please run the recipe (or alphabet_sort at 2+2) with the routing on, through the RL env, and note it in the PR. If capture fails, apply the same registered=False override to SGLang's ca_comm.

Smaller point, also unverified: when a message is too large for the custom AR, SGLang's GroupCoordinator.all_reduce falls back to an in-place NCCL all-reduce and returns its input. That breaks the out-of-place contract of the _c10d_functional.all_reduce op it replaces. vLLM's fallback is out-of-place. It's harmless today because the partial input is dead after the reduce, but the route_tp_all_reduce docstring should state whether all_reduce may mutate its input.

Base automatically changed from sglang-1-inference-model to main November 9, 2026 07:21
TORCHTITAN_VARLEN_ATTENTION_BACKEND = "torchtitan_varlen"


class TorchTitanVarlenAttnBackend(FlashAttentionBackend):

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.

shall we inherit from _FA4PageSize here similar to vllm? otherwise codex telling me the default page size is 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.

[From Claude (AI agent), on behalf of @tianyu-l] Page 1 is on purpose, and 5c1767d now sets it explicitly (page_size=1) with a comment, and extra_server_args can no longer override it.

  • SGLang's 128-token FA4 pages apply only to its own fa4 attention backend; ours is the TorchTitan varlen backend, so SGLang already defaults to 1.
  • 128-token pages would put batch-invariant decode on FA4's SwapAB kernel, which does not match prefill bitwise (the reason for vLLM's _FA4PageSize). GDN/KDA's no_buffer state cache ([rl] generator: SGLang GDN linear attention #5817, [rl] generator: SGLang KDA linear attention #5819) also accepts only page 1.
  • Outside batch-invariant mode, 128 might be faster for softmax-only models; not measured.

name for name, value in kwargs.items() if value is not None
)
if unsupported:
raise ValueError(f"SGLangInnerAttention does not support {unsupported}")

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.

NotImplementedError?

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.

[From Claude (AI agent), on behalf of @tianyu-l] Yes, done in 5c1767d: unsupported kwargs raise NotImplementedError, as _paged_attention in the same file does.

logger = logging.getLogger(__name__)


def force_trainer_logprobs_for_batch_invariance() -> None:

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.

also change vllm's naming to align

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.

[From Claude (AI agent), on behalf of @tianyu-l] Done in 5c1767d: vLLM's force_logprobs_fn_for_batch_invariance is renamed to force_trainer_logprobs_for_batch_invariance, the SGLang name, at all callers (engine, tests, BITWISE_PARITY.md).

def force_trainer_logprobs_for_batch_invariance() -> None:
"""Compute the sampled tokens' logprobs with the trainer's ``compute_logprobs``.

SGLang's sampler fuses temperature and softmax into one kernel and returns

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.

only under enable_deterministic_inference = False case

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.

[From Claude (AI agent), on behalf of @tianyu-l] Right: in its deterministic mode (on with DebugConfig.seed), SGLang returns log_softmax(logits / T) with its own ops, not log(probs). The docstring now describes both modes (5c1767d). The sampler still recomputes with the trainer's compute_logprobs in both, so there is one code path; the batch-invariant recipes set no seed, so the fused path is the one they run.

logger = logging.getLogger(__name__)

# The ServerArgs SGLangEngine sets itself, which extra_server_args cannot set.
_TORCHTITAN_SERVER_ARGS = frozenset(

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.

from codex:

1. extra_server_args should be an allowlist, not a denylist (sglang/engine.py:69-94, 130-136)

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.

[From Claude (AI agent), on behalf of @tianyu-l] Kept a denylist, to match the vLLM engine's extra_engine_args, but closed the holes it had (5c1767d):

  • every key containing cuda_graph is rejected: SGLang applies its per-phase graph keys (e.g. cuda_graph_backend_decode) over disable_cuda_graph, so they could turn on graphs that the engine's checks assume are off;
  • page_size is set and owned by the engine;
  • max_queued_requests is rejected from [rl] generator: SGLang reuses a rollout group's prompt KV #5918 on (held requests are outside SGLang's waiting queue).
    The only documented use of extra_server_args is HiCache, and an allowlist would need updating for every SGLang option a user wants.

@felipemello1

Copy link
Copy Markdown
Contributor

from claude to felipe: a TLDR image of this PR, drawn from its diff at baf9e7f85.

SGLang becomes a second RL generation engine beside vLLM: SGLangEngine runs one SGLang Scheduler per TP rank in-process, SGLang owns scheduling and the KV cache, and the TorchTitan model, its attention kernel and the code moved out of vllm/ are shared by both engines.

@felipemello1 felipemello1 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.

Stamping to unblock.

Found one or two things that may be bugs.
I am skeptical of some of the TODOs and i think that claude can probably find a way to use the apis better.

The installation looks hacky.

Overall it looks good. I disliked a bit how the engine.py is. I didn't find it too pleasing to the human eye. It could use more structure, better comments, utilities, cleaning up, etc. But those are nits.

It scares me a bit the idea of maintaining both. Now we also have to test both and make sure that all features work for both.

export PYTHONPATH="$PWD:${PYTHONPATH:-}"

bash scripts/install_sglang.sh "$RUNNER_TEMP/sglang"
MODEL_PATH=$(python -c "from huggingface_hub import snapshot_download; print(snapshot_download('Qwen/Qwen3-0.6B'))")

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.

is that what we do for vllm tests as well? Should we use one of the dummy models?

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.

[From Claude (AI agent), on behalf of @tianyu-l] Yes, the same as vLLM: unit_test_gpu_rl.yaml downloads Qwen3-0.6B for TestBitwiseParityVarlen. Only TestSGLangBitwiseParityVarlen loads HF weights; the classes later in the stack (MoE EP, Dist-MoE, sliding window, GDN, MLA, KDA) use debug models with the trainer's random weights. Keeping one real checkpoint also covers HF checkpoint loading through the SGLang wrapper.

Comment thread scripts/install_sglang.sh Outdated
Comment on lines +26 to +31
# The engine uses private SGLang APIs and is verified only at this commit.
sglang_commit="851642ade"

if [ ! -d "$src" ]; then
git clone https://github.com/sgl-project/sglang "$src"
fi

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 doesnt look right. Should we do something like vllm, install latest stable --no-deps and torch nightlies?

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.

[From Claude (AI agent), on behalf of @tianyu-l] vLLM is not installed as the latest stable release: install_rl_env.sh pins a vLLM nightly wheel from the PyTorch index, built against the torch nightly. SGLang has no such wheel, and its latest release (v0.5.23) predates the commit the engine needs (it lacks private APIs the engine uses, e.g. allocate_distinct_stream, should_process_last_batch_early). --no-deps would also drop sglang-kernel, flashinfer and the rest; the script keeps PyTorch with uv overrides instead.
Simplified in 5c1767d: no clone or editable install any more, see the reply on line 1.

Comment thread scripts/install_sglang.sh Outdated

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.

we dont have this for vllm, do we? maybe we could do something like

install_rl.sh --generator sg_lang

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.

[From Claude (AI agent), on behalf of @tianyu-l] Done in 5c1767d: scripts/install_sglang.sh is gone, and scripts/install_rl_env.sh --sglang installs SGLang at the pinned commit with a git-URL install (sglang @ git+https://github.com/sgl-project/sglang.git@<commit>#subdirectory=python), keeping the environment's torch. Checked in a fresh venv: it installs SGLang at the pin with torch 2.16.0.dev20261030 unchanged and no torchaudio. CI and the README use the flag.

Comment on lines +61 to +63
The prebuilt `sglang-kernel` wheel loads under the PyTorch nightly. The engine
does not use SGLang's Rust extensions (`SGLANG_BUILD_RUST_EXTS=none`): the radix
tree falls back to its Python implementation.

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.

is this a TODO? if not, should we delete this?

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.

[From Claude (AI agent), on behalf of @tianyu-l] Not a TODO; it repeated the install script's comments. Deleted in 5c1767d.

Comment on lines +52 to +56
if fa_impl not in ("FA3", "FA4"):
raise ValueError(
f"{TORCHTITAN_VARLEN_ATTENTION_BACKEND} needs FA3 or FA4 (SM90+), "
f"got {fa_impl}"
)

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.

does this work on A10G in our tests?

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.

[From Claude (AI agent), on behalf of @tianyu-l] No: A10G is SM86, which runs FA2, and the backend raises (it needs FA3/FA4; SGLang's FA metadata is built for FA3/FA4). The SGLang tests run only in the B200 job.

Comment on lines +229 to +235
# TODO(https://github.com/sgl-project/sglang/issues/48474): SGLang has no option
# to drop the checkpoint generation config's EOS ids it adds to every request's
# stops; the renderer's stop tokens (EOS included) are the only stops.
self._scheduler.model_config.hf_eos_token_id = set()
# TODO(https://github.com/sgl-project/sglang/issues/48473): SGLang has no
# in-process output sink; stand in for the sockets to its detokenizer and
# tokenizer processes, so results and aborts come here.

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.

i am a bit skeptical of the many todos here. Maybe they are true limitations, but hundreds of libraries use sglang. Perhaps the agents were a bit lazy to find a way to make it work?

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.

[From Claude (AI agent), on behalf of @tianyu-l] I re-checked each TODO in engine.py against SGLang at the pinned commit. Each is a real gap with an open SGLang issue:

  • DP replicas in one world (Support data-parallel attention/replicas inside one existing torch distributed world (in-process scheduler) sgl-project/sglang#48476), EOS from the generation config (#48474), the in-process output sink (#48473), stepping the event loop one iteration (#48472), per-request time stats without Prometheus (#48482): no public API at the pin.
  • Other frameworks (verl, slime, AReaL) run SGLang as a server or an sglang.Engine subprocess; none steps an in-process Scheduler with a foreign model, which is where these come from.
    The exception was the sampler TODO: SGLang does have register_sampler_backend, and the engine now uses it instead of patching Sampler.forward (see the reply on batch_invariance.py:74).

Comment on lines +338 to +344
@property
def data_parallel_size(self) -> int:
return 1

@property
def data_parallel_rank(self) -> int:
return 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.

i understand that we dont support dp>1, but should we use the given value anyway instead of hardocde?

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.

[From Claude (AI agent), on behalf of @tianyu-l] __init__ raises unless data_parallel_degree == 1, so size 1 and rank 0 are exact here. Returning the configured size would also need a real rank, which only comes with DP support (sgl-project/sglang#48476).

Comment on lines +373 to +377
cache_salt = (
None
if self._reset_kv_cache_on_model_state_dict_load
else str(request.min_policy_version)
)

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 sounds wrong. You are reseting the salt on every new request if _reset_kv_cache_on_model_state_dict_load is true.

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.

[From Claude (AI agent), on behalf of @tianyu-l] The code is right, but the comment was unclear; reworded in 5c1767d. With a reset on model state dict load, every load retracts the running requests and flushes the cache, so the cache only ever holds KV of the current weights and every request can share it: no salt is needed. Without a reset, the salt is the request's pinned version, so a request reuses only KV computed under that version. The vLLM engine does the same.

Comment on lines +527 to +528
class _OutputCollector:
"""Stands in for the scheduler's sockets to the tokenizer and detokenizer processes.

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.

not sure whats going on here. If we do token in token out, then what tokeniation/detokenization is going on?

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.

[From Claude (AI agent), on behalf of @tianyu-l] None runs: the engine sets skip_tokenizer_init. SGLang's scheduler still sends its token ids (BatchTokenIDOutput) and aborts to the detokenizer and tokenizer processes' sockets, and this object replaces those sockets. The docstring now says so (5c1767d).

finished, self._finished = self._finished, []
return finished

def _receive_tokens(self, output: BatchTokenIDOutput) -> None:

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.

could use a docstring

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.

[From Claude (AI agent), on behalf of @tianyu-l] Added docstrings to _OutputCollector's methods in 5c1767d.

@felipemello1

Copy link
Copy Markdown
Contributor

I would also consider moving this to some /experimental folder, so the burden of maintenance is reduced for now, rather than keeping it at the same level of expectation as vllm

@felipemello1 felipemello1 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.

Automated review by claude. Do NOT put high weight on this comment.

Four gaps: wrong policy version after a weight load, untested reset path, unchecked prompt ids, and graph and page-size settings that extra_server_args can override.

Review on paper. No GPU runs.

A load = a model state dict load. The reset path = retract the running requests, flush the cache, then continue.

The points that matter most, each in an inline comment:

  1. A request whose last token is still queued at a load is reported with the new policy version, in both reset modes (engine.py:481-483).
  2. No CI test runs the reset path that every batch-invariant recipe uses (test:116).
  3. Prompt token ids are never checked. An out-of-range id or an empty prompt gives a wrong sample or can stop the engine (engine.py:378).
  4. extra_server_args can still change the graph mode, the capture sizes and the page size (engine.py:70-94).

About unchanged code

  • The copied loop = _overlap_event_loop_iteration, a hand copy of one iteration of SGLang's Scheduler.event_loop_overlap.
  • SGLang main (1be97a0a63) is 271 commits after the pinned SGLang commit.
  • Since the pinned commit, its scheduler.py has 884 changed lines.
  • It changed retract-on-pause (sgl-project/sglang#49253).
  • So the next SGLang bump needs the copied loop and the reset path re-checked.

dist_moe_runtime=None,
# SGLang samples with the requests' seeds only with DebugConfig.seed.
debug=dataclasses.replace(config.generator.debug, seed=0),
reset_kv_cache_on_model_state_dict_load=False,

@felipemello1 felipemello1 Nov 10, 2026 •

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.

Automated review by claude. Do NOT put high weight on this comment.

No CI test runs the reset path.

Reset = reset_kv_cache_on_model_state_dict_load. The reset path is what the engine does when weights load with reset on (engine.py:488-503):

  1. pause_generation(retract): stop the running requests and take them back.
  2. flush_cache: drop the KV cache.
  3. continue_generation: run the requests again.

Every batch-invariant recipe uses it. The generator requires reset when batch invariance is on (generator.py:195-202), and the recipe turns it on (alphabet_sort.py:773).

Why the tests miss it

  • This class runs with reset off. That is right here, because test 3 checks the salt path: after the load, requests move to the next policy version's cache salt.
  • Every later class in the stack copies this setting.
  • Test 3 loads weights while the engine is idle, so no request is ever taken back.

Why it matters
This is the path most likely to break on an SGLang bump. SGLang main already changed retract-on-pause (sgl-project/sglang#49253).

Smallest fix

  1. Make the flag a class attribute next to cuda_graph. The base class comes in [rl] generator: SGLang MoE with expert parallelism and Dist-MoE #5815.
  2. Turn it on for one existing class.
  3. In that class, load the same weights while a generation is in flight.
  4. Assert the tokens and logprobs equal a run without the load.

That is the check the PR body's local script ran.

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.

[From Claude (AI agent), on behalf of @tianyu-l] Done:

  • 5c1767d adds test_sglang_decode_across_model_state_dict_load: it loads the same weights at step 10, while requests decode, and checks tokens and logprobs equal a run without the load. The reset flag is a class attribute.
  • 1ddcd6c turns reset on in the GDN class, so CI runs the reset path (retract, flush, continue) with SGLang's normal event loop; the other classes keep it off and cover the cache salt.

Comment on lines +72 to +74
# TODO(https://github.com/sgl-project/sglang/issues/48475): SGLang has no hook for
# the logprobs its sampler returns; patch its forward.
Sampler.forward = forward

@felipemello1 felipemello1 Nov 10, 2026 •

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.

Automated review by claude. Do NOT put high weight on this comment.

SGLang already has the sampler hook this TODO asks for.

The TODO is outdated at the pinned SGLang commit:

  • register_sampler_backend(name, factory) is that hook (srt/layers/sampler.py:750).
  • The model runner builds its sampler with create_sampler() (model_runner.py:748).

What can replace the class patch

  1. Write a TorchTitanSampler(Sampler) with today's forward body. Keep the logits copy at line 55.
  2. Register it under both "pytorch" and "flashinfer". This works because create_sampler checks registered factories before built-in names (sampler.py:770).

Why both names

  • The batch-invariant recipe sets no seed. So SGLang's deterministic mode stays off, and the backend defaults to "flashinfer" (overrides.py:1019-1025).
  • With a seed, the backend is forced to "pytorch" (overrides.py:1030-1035).

Compared with today's patch

  • The registry is process-wide, like today's patch.
  • But Sampler stays unpatched.
  • And the _trainer_logprobs flag goes away.

Not a substitute: SGLang's own rl_on_policy_target path
It runs log_softmax on bf16 logits / T (sampler.py:243-256). That is not the trainer's compute_logprobs.

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.

[From Claude (AI agent), on behalf of @tianyu-l] Done in 5c1767d: the engine registers a Sampler subclass with register_sampler_backend for every built-in sampling backend, instead of patching Sampler.forward. The _trainer_logprobs flag and the TODO are gone.

Comment on lines +70 to +94
_TORCHTITAN_SERVER_ARGS = frozenset(
{
"model_path",
"model_config_parser",
"skip_tokenizer_init",
"dtype",
"tp_size",
"mem_fraction_static",
"max_running_requests",
"context_length",
"attention_backend",
"enable_priority_scheduling",
"schedule_low_priority_values_first",
"enable_session_radix_cache",
"disable_cuda_graph",
"disable_prefill_cuda_graph",
"cuda_graph_backend_prefill",
"skip_server_warmup",
"log_level",
"chunked_prefill_size",
"random_seed",
"enable_deterministic_inference",
"disable_custom_all_reduce",
}
)

@felipemello1 felipemello1 Nov 10, 2026 •

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.

Automated review by claude. Do NOT put high weight on this comment.

extra_server_args can still change the graph mode, the capture sizes and the page size.

This is the concrete list for acisseJZhong's allowlist thread above. Each key below changes behavior the engine relies on, and extra_server_args still accepts it.

1. Graph mode

Keys: cuda_graph_backend_decode, disable_decode_cuda_graph, and cuda_graph_config (until #5853 owns it).

SGLang applies them after disable_cuda_graph, so they override it (cuda_graph_hook.py:54-94 at the pinned SGLang commit).

Example:

  1. Set cuda_graph="none", and pass {"cuda_graph_backend_decode": "full"} in extra_server_args.
  2. SGLang captures full decode graphs.
  3. The EP (expert parallel) checks read config.cuda_graph, which still says "none". These checks are in [rl] generator: SGLang MoE with expert parallelism and Dist-MoE #5815 (engine.py:183) and [rl] generator: DeepEP and HybridEP token dispatchers on SGLang; shared dispatcher checks #5959 (engine.py:196, which passes config.cuda_graph to model.py:316, 347).
  4. So the checks let the all-to-all dispatcher through.
  5. Capture then fails (unverified).

2. Capture sizes

Keys: cuda_graph_bs_*, cuda_graph_max_bs_*, cuda_graph_max_seq_len_prefill, cuda_graph_prefill_max_context.

  • By default, prefill capture stops at chunked_prefill_size (memory_hook.py:235-238).
  • The Dist-MoE and DeepEP buffers assume that limit.
  • An explicit list is kept as given (memory_hook.py:267). It can overflow those buffers at capture.

This answers claude[bot]'s open question on #5815.

3. page_size

Set it to 1 on purpose. Two reasons:

  • GDN/KDA's no_buffer cache accepts only 1 (mamba_hook.py:160-161).
  • In batch-invariant mode, 128 would put decode on FA4's SwapAB kernel. Decode on that kernel no longer matches prefill. Source: vLLM's _FA4PageSize docstring. Unverified on SGLang.

This also answers acisseJZhong's page-size question. For softmax-only models outside batch-invariant mode, vLLM's 128 on SM100 is a speed option. It is unmeasured here.

Smallest fix, one of:

  • Add these keys to _TORCHTITAN_SERVER_ARGS.
  • Or check the resolved cuda_graph_config after ServerArgs is built, before the Scheduler.

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.

[From Claude (AI agent), on behalf of @tianyu-l] Done in 5c1767d: every key containing cuda_graph (graph modes and capture sizes, including cuda_graph_config from #5853) and page_size are rejected. A comment says why page_size is 1.

if self._reset_kv_cache_on_model_state_dict_load
else str(request.min_policy_version)
)
sglang_request = TokenizedGenerateReqInput(

@felipemello1 felipemello1 Nov 10, 2026 •

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.

Automated review by claude. Do NOT put high weight on this comment.

Nothing checks the prompt token ids on this path. A bad id or an empty prompt gives a wrong sample or can stop the engine.

The docstring says "SGLang validates the rest". But nothing checks the prompt token ids on this path. vLLM's renderer does (vllm/engine.py:381-392).

What goes wrong

An out-of-range id = below 0, or at least the vocab size.

  1. Out-of-range id at TP 2:
    • The vocab-parallel embedding masks it to zeros on every rank (embedding.py:54,72).
    • So the request samples from a wrong prompt, with no error.
  2. Same id at TP 1:
    • The embedding is plain F.embedding (embedding.py:40-49).
    • That should hit a device-side assert and stop the engine for every request (unverified).
  3. Empty prompt:
    • SGLang's tokenized path admits it as a 0-token prefill.
    • Alone in a batch: out.view(0, -1, head_dim) (attention.py:227) raises.
    • Next to other requests: its logits row is another request's last token (unverified).

Smallest fix

Reject these per request, as for bad sampling parameters.

Suggested change
sglang_request = TokenizedGenerateReqInput(
prompt = request.prompt_token_ids
vocab_size = self._scheduler.model_config.vocab_size
if not prompt or min(prompt) < 0 or max(prompt) >= vocab_size:
message = (
f"prompt token ids must be non-empty and in [0, {vocab_size}); got "
f"{len(prompt)} ids, min {min(prompt, default=None)}, "
f"max {max(prompt, default=None)}"
)
rejected.append((request.request_id, ValueError(message)))
continue
sglang_request = TokenizedGenerateReqInput(

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.

[From Claude (AI agent), on behalf of @tianyu-l] Done in 5c1767d: add_requests rejects an empty prompt or ids outside [0, vocab_size) per request, like bad sampling parameters.

Comment on lines +469 to +471
scheduler = self._scheduler
with scheduler.device_module.StreamContext(scheduler.schedule_stream):
_overlap_event_loop_iteration(scheduler)

@felipemello1 felipemello1 Nov 10, 2026 •

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.

Automated review by claude. Do NOT put high weight on this comment.

step() runs the forward with grad mode on, so eager steps miss the route_tp_all_reduce fast path.

Problem

  • This step() runs the forward with grad mode on.
  • SGLang's own loops run under @DynamicGradMode() (scheduler.py:2104, 2140).
  • vLLM's step() runs under torch.no_grad() (vllm/engine.py:417).

Why it matters

  • The weights do not require grad, so no autograd graph is built.
  • But route_tp_all_reduce takes its fast path only when not torch.is_grad_enabled() (model.py:233).
  • So eager SGLang steps never take it.
  • The 2-3% in its docstring was measured on vLLM.

Fix
#5817 adds the normal-loop branch inside the same block. So this one change covers both the overlap loop and the normal loop.

Suggested change
scheduler = self._scheduler
with scheduler.device_module.StreamContext(scheduler.schedule_stream):
_overlap_event_loop_iteration(scheduler)
scheduler = self._scheduler
with torch.no_grad(), scheduler.device_module.StreamContext(
scheduler.schedule_stream
):
_overlap_event_loop_iteration(scheduler)

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.

[From Claude (AI agent), on behalf of @tianyu-l] Done in 5c1767d: step() runs under torch.no_grad(); #5817's normal-loop branch is inside the same block.

),
)
logger.info("Building the SGLang scheduler...")
self._scheduler = Scheduler(server_args, PortArgs.init_new(server_args))

@felipemello1 felipemello1 Nov 10, 2026 •

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.

Automated review by claude. Do NOT put high weight on this comment.

SGLang's watchdog can send SIGQUIT to the generator's parent during a slow load without reset.

A load = a model state dict load. Reset = reset_kv_cache_on_model_state_dict_load.

How the watchdog works

  • This Scheduler starts SGLang's hard watchdog (scheduler.py:1551-1555).
  • Rule: if no forward runs for watchdog_timeout (default 300 s) while cur_batch_for_debug is set, it sends SIGQUIT to the parent process (watchdog.py:133-163).

Why a load can trigger it

  • The copied loop = _overlap_event_loop_iteration, a hand copy of one iteration of SGLang's Scheduler.event_loop_overlap.
  • The copied loop sets cur_batch_for_debug every step (line 684).
  • In reset mode, pause_generation clears it.
  • In a load without reset, nothing clears it.

Example (unverified on GPU)

  1. Reset is off, and the load uses gpu_fetch.
  2. A batch is in flight.
  3. The fetch takes over 300 s.
  4. The watchdog signals whatever launched the generator.
  5. The log points at SGLang instead of the slow fetch.

Smallest fix
Handle the load explicitly:

  1. After line 494, wait on the host for the in-flight forward (scheduler.forward_stream.synchronize()).
  2. Then clear cur_batch_for_debug for the fetch.

Why this is safe:

  • The host wait keeps the watchdog on while that forward could still hang.
  • No new forward is launched during the fetch.

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.

[From Claude (AI agent), on behalf of @tianyu-l] Done in 5c1767d: the load clears cur_batch_for_debug before the fetch, as pause_generation does in the reset path.

Comment on lines +481 to +483
# TODO: the results of the batch in flight at a load are processed after it, so
# a request that finishes in that batch is reported at the new policy version
# though its last token came from the old weights.

@felipemello1 felipemello1 Nov 10, 2026 •

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.

Automated review by claude. Do NOT put high weight on this comment.

A request whose last token came from the old policy can be reported with the new policy version.

Reset = reset_kv_cache_on_model_state_dict_load. This TODO is a wrong-version bug, and it hits both reset modes.

Example

  1. A request's last token is computed under policy 7.
  2. The token still sits in result_queue when the load installs policy 8.
  3. What happens next depends on the reset mode:
    • Reset off: the next step() processes and returns it.
    • Reset on: pause_generation processes it into self._finished, and the next step() returns it.
  4. Either way, the engine loop reports it after bumping policy_version to 8 (engine_loop.py:392-395, 564).
  5. The dispatcher writes max_policy_version=8 (dispatcher.py:285).

Why it is wrong
That field means "Newest policy version among this turn's decode" (rollout/types.py:66-67). This turn has no policy-8 token.

Smallest fix
Report old results at the old version. Two ways:

  • Let the load drain the in-flight result and return the finished requests. Then have the engine loop report them before it bumps policy_version.
  • Or carry the producing version on FinishedRequest.

Not enough alone: SGLang's record_weight_version_change

  • A span = a range of output tokens and the policy version that produced them.
  • record_weight_version_change (scheduler.py:5996-6006) can add per-token spans after that fix, but not instead of it.
  • It counts len(req.output_ids) (weight_versions.py:39-51), which misses the queued token.

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.

[From Claude (AI agent), on behalf of @tianyu-l] Agreed it is real; the TODO above says so. Kept as a TODO: the version only feeds max_policy_version, which is used for metrics and records (the off-policy filter reads the min), and a fix changes the load interface for both engines (return the finished requests from the load, so the engine loop reports them before it bumps the version).

@tianyu-l

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] Replies on the review bodies (@felipemello1); the inline comments have their own replies. Fixes are in 5c1767d.

  • Install. It is now scripts/install_rl_env.sh --sglang: a git-URL install at the pinned commit, with no clone or editable install, and torch kept with uv overrides. I checked it in a fresh venv. vLLM is not a "latest stable + --no-deps" install either: it is a pinned nightly wheel built against the torch nightly. SGLang has no such wheel, and its latest release predates the APIs the engine uses.
  • TODOs. Each one in engine.py is a real gap with an open SGLang issue. Other frameworks run SGLang as a server or a subprocess, not as an in-process Scheduler stepped with a foreign model. The sampler TODO was the exception: it now uses SGLang's register_sampler_backend.
  • The four gaps from the automated review.
    • Prompt ids are validated.
    • extra_server_args can no longer set CUDA-graph keys or page_size.
    • The reset path is tested in CI (GDN class, [rl] generator: SGLang GDN linear attention #5817), as is a load mid-decode (every class).
    • The policy-version TODO stays: it affects only max_policy_version, a metric.
  • Maintaining two engines / experimental. @tianyu-l decided to keep SGLang as an alternative engine next to vLLM, not only as an experiment, and the README status now says so. Its tests run in the B200 RL job. The retract-on-pause change on SGLang main ([Fix] scheduler: Retract every KV holder on pause and order a few releases behind in-flight steps sgl-project/sglang#49253) is one reason the reset-path test now runs in CI.
  • engine.py readability. This round adds method docstrings to the output collector and rewrites the comments the review pointed at. Happy to restructure further if you point at the parts that read worst.

Tests at the stack top on GB300: every SGLang parity class passes (Varlen 7, GDN 6, sliding window 6, Dist-MoE 6, KDA 6, MoE EP 5 + 1 skipped, MLA 5 + 1 skipped), as do vLLM TestBitwiseParityVarlen and test_generator_dist_moe_mxfp8. At this PR's head, TestSGLangBitwiseParityVarlen passes 5 of 5.

@tianyu-l
tianyu-l removed this pull request from stack #5964 November 10, 2026 06:41
@tianyu-l
tianyu-l changed the base branch from main to sglang-1-paged-attn-flash November 10, 2026 06:41
@tianyu-l
tianyu-l added this pull request to stack #6002 November 10, 2026 06:41
Add SGLangEngine, a GenerationEngine that runs the generator's TorchTitan model
inside SGLang, as VLLMEngine does inside vLLM: SGLang provides KV cache
management (paged pool, radix prefix cache) and scheduling; the model and its
attention kernel are TorchTitan's. Each rank builds SGLang's Scheduler
in-process and steps one iteration of its overlap event loop per step().

Supports dense softmax attention with the varlen backend at any TP, decode and
breakable prefill CUDA graphs, model state dict loads (with and without a KV
reset), policy-version cache salting, multi-turn session KV references, CPU KV
offload through SGLang HiCache, and batch-invariant mode (bitwise parity with
the trainer). Unsupported configurations raise at build.
…okens, as vLLM does

SGLang caps a request at context_len - 1 tokens and rejects prompts of
context_len - 6 tokens or more, so with context_len = max_context_length it
rejected prompts of max_context_length - 6 to max_context_length - 1 tokens that
vLLM runs. Raise SGLang's context length by that margin and cap each request's
output so prompt and output take at most max_context_length tokens.
- step() runs under no_grad, as SGLang's loops and the vLLM engine do, so the
  model's TP all-reduces take their fast path in eager steps.
- add_requests rejects empty prompts and token ids outside the vocab; SGLang
  checks only the length.
- extra_server_args cannot set page_size or any CUDA-graph key: SGLang applies
  its per-phase graph keys over disable_cuda_graph.
- The trainer-logprobs sampler is registered with register_sampler_backend
  instead of patching Sampler.forward. vLLM's helper takes the same name,
  force_trainer_logprobs_for_batch_invariance.
- A load without a KV reset clears SGLang's watchdog batch, so a slow fetch is
  not reported as a hung forward.
- Test: a load of the same weights mid-decode leaves tokens and logprobs
  unchanged.
- SGLang installs with scripts/install_rl_env.sh --sglang (a git-URL install at
  the pinned commit); scripts/install_sglang.sh is removed.
- Docstrings and comments: the output collector, the cache salt, page_size.
@tianyu-l
tianyu-l merged commit 4f3be59 into main Nov 10, 2026
tianyu-l added a commit that referenced this pull request Nov 10, 2026
Stacked on #5812 (the SGLang engine).

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
`SGLangEngine` raises for MoE models with expert parallelism today, so
Qwen3 MoE,
DeepSeek V3 and Kimi K3 generators can only run on vLLM. This PR runs
them with EP
over the TP group, as the vLLM engine does, with either the all-to-all
token
dispatcher or Dist-MoE.

**Example.**
```python
# before: raises at engine build (EP / Dist-MoE not supported)
generator=Generator.Config(parallelism=InferenceParallelismConfig(
    tensor_parallel_degree=2, expert_parallel_degree=2), engine=SGLangEngine.Config())
# after: runs; with the all-to-all dispatcher, cuda_graph="none" is required
engine=SGLangEngine.Config(cuda_graph="none")
# with Dist-MoE (Generator.Config.dist_moe_runtime), CUDA graphs stay on
```
```
step of T tokens --pad to a multiple of TP--> MoE shards T/TP tokens per rank
attention / KV cache: only the T scheduled rows (padding skipped)
```

## What changed
- `sglang/model_wrapper.py`: `_DecoderBody` pads each step to a multiple
of the TP
degree (the MoE shards tokens over TP). With Dist-MoE, it masks the
padding rows out
of the dispatch: its own, plus the rows SGLang pads a batch with to a
CUDA graph's
size, which write their KV to SGLang's padding slot 0. It also sets
Dist-MoE's
  per-call token count, which is fixed per captured graph.
  The Dist-MoE runtime is sized from SGLang's `chunked_prefill_size +
  max_running_requests`.
- `sglang/attention.py`: attention runs on the scheduled rows only.
- `sglang/engine.py`: raises for the all-to-all dispatcher with CUDA
graphs (it
reads its split sizes on the host) and for the other EP dispatchers
(DeepEP,
HybridEP); Dist-MoE with EP 1 and TP > 1 already raises in `Decoder` (EP
below
  TP). It restores `triton.next_power_of_2`, which
importing SGLang replaces process-wide with a host-only function that
Dist-MoE's
  Triton kernels cannot call (TODO).
- `generator/model.py` `build_dist_moe_runtime`: moved from the vLLM
wrapper, shared by
  both engines. Mechanical, apart from the error message.
- Tests: two new parity classes (below). The shared tests move to a base
class;
`test_context_length_limits` (#5812) stays on
`TestSGLangBitwiseParityVarlen` only.
- CI: the B200 SGLang step (#5812) now launches each parity class on its
own and adds
the two new classes; only `TestSGLangBitwiseParityVarlen` gets the HF
checkpoint.
- Review fixes (71e8bf9): the engine's own Dist-MoE EP 1 / TP > 1
check is gone
(`Decoder` raises for it); a comment says Dist-MoE has no token
dispatcher, so the
dispatcher check sees only the stock ones; the vLLM wrapper builds its
real-token
  count buffer in an `if` block instead of an early return.

## User-facing changes
| Before | After |
| --- | --- |
| `SGLangEngine` raises for EP and Dist-MoE | supported; the all-to-all
dispatcher needs `cuda_graph="none"`; DeepEP / HybridEP raise |

## Numerics
| Check | Hardware | Result |
| --- | --- | --- |
| `TestSGLangBitwiseParityMoEEP` (Qwen3 MoE debug, TP 2 / EP 2,
all-to-all) | 2x GB300 | 3 passed, max delta 0 |
| `TestSGLangBitwiseParityDistMoE` (same, Dist-MoE, decode + prefill
CUDA graphs) | 2x GB300 | 3 passed, max delta 0 |

## Testing
- The two classes above (trainer vs SGLang decode, decode batch
invariance, and
  after an in-place model state dict load).
- vLLM `test_generator_dist_moe_mxfp8` passes (covers the moved
  `build_dist_moe_runtime`).
- `pytest tests/rl/unit_tests/cpu`: 546 passed.

## Known issues / follow-ups
- Next in the stack: sliding window, GDN, MLA, KDA.
tianyu-l added a commit that referenced this pull request Nov 10, 2026
Stacked on #5816 (SGLang sliding window).

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
`SGLangEngine` raises for GDN linear attention (Qwen3.5). GDN layers
keep a
per-request conv and recurrent state instead of KV. SGLang already
manages such
states for its own hybrid models (a state pool whose slots its radix
cache
snapshots), and its linear attention model registry accepts external
models. This
PR runs TorchTitan's GDN on SGLang's state slots with the trainer's
Attention Gym
kernels. A session's next turn resumes from its cached prefix, as with
KV.

**Example.**
```
turn 1: prompt (150) + completion (50) -> radix cache: KV of full-attention layers
                                          + GDN conv/recurrent state at token 200
turn 2: turn 1 + 8 new tokens          -> prefill 8 tokens from the cached state
```

## What changed
- `sglang/attention/gdn.py` (new):
- `TorchTitanGDNConfig`: the HF-shaped config SGLang reads to size state
slots.
It uses Attention Gym's `[W - 1, C]` conv layout and a float32 recurrent
state.
- `TorchTitanGDNAttnBackend`: runs Attention Gym's conv and GDN kernels
on
    SGLang's slots.
  - `SGLangInnerGDN`.

Breakable prefill CUDA graphs call the backend eagerly at replay, using
the layer
attributes from the last capture. So the adapter hands over parameter
storage,
  and the backend derives the tensors the kernels take.
- `sglang/engine.py`: SGLang's mamba radix cache runs without overlap
scheduling,
so `step()` runs one iteration of whichever event loop SGLang uses.
Models without
  linear attention still require overlap scheduling.
- `sglang/registry.py`: registers the backend through SGLang's linear
attention
model registry, and builds and validates the GDN config at registration.
- `generator/attention/gdn.py` (new): the GDN recurrence over a paged
state pool, moved from the
vLLM adapter and shared by both engines. This is mechanical. The vLLM
GDN unit
  tests patch the moved names.
- Tests:
  - a Qwen3.5 parity class;
- a new test in the base class: parity for a session's next turn. It
also covers
    session KV for softmax attention (#5812), which had no test.
- CI: the B200 SGLang step also runs `TestSGLangBitwiseParityGDN`.
- Review fixes (29cce70): the GDN parity class turns on
`reset_kv_cache_on_model_state_dict_load`, so CI covers the reset path
(retract,
flush, continue) with SGLang's normal event loop, including a load
mid-decode;
the `extra_buffer` TODO names both costs of its absence (no overlap
scheduling,
no reuse of a prefix shared mid-request) and the kernel change it needs.
The overlap
check moved to `SGLangEngine.__init__` (raise unless SGLang kept overlap
or the
model has linear attention); the TODO links
meta-pytorch/attention-gym#735.

## User-facing changes
| Before | After |
| --- | --- |
| GDN layers raise | supported; SGLang runs these models without overlap
scheduling |

## Numerics
| Check | Hardware | Result |
| --- | --- | --- |
| `TestSGLangBitwiseParityGDN` (Qwen3.5 debug, TP 2), incl. the
next-turn test | 2x GB300 | 4 passed, max delta 0; with the cached state
ignored (`has_initial_state` False), it fails |
| Next-turn test on every class (Qwen3, MoE EP, Dist-MoE, sliding
window) | 2x GB300 | passed, max delta 0 |
| vLLM `TestBitwiseParityQwen35DebugVarlen` (covers the moved paged GDN)
| 2x GB300 | 5 passed |
| HiCache (`write_through`, small GPU pools): cached turn whose prefix
was evicted to host memory and loaded back (local script; Qwen3.5 debug,
TP 2) | 2x GB300 | max delta 0; 199 of 208 prompt tokens served from the
cache (0 without HiCache) |

## Testing
- As above. vLLM GDN unit tests: 21 passed, 2 skipped (need a
Qwen3.5-0.8B model).
- `pytest tests/rl/unit_tests/cpu`: 546 passed.
- The GDN parity class depends on #5963: it failed intermittently on
attn-gym 0.0.18,
whose recurrent GDN scan rounds differently per launch config. #5963
pins attn-gym with the
batch-invariant scan (meta-pytorch/attention-gym#704) and opts in; with
it, the class passed
  3 of 3 runs, where 0.0.18 failed 3 of 3.

## Known issues / follow-ups
- SGLang snapshots a request's state when it caches the request, not at
intermediate positions: a prefix shared at another position recomputes.
- No overlap scheduling for these models (SGLang's mamba radix cache).
tianyu-l added a commit that referenced this pull request Nov 10, 2026
Stacked on #5819 (SGLang KDA).

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
`SGLangEngine` captures prefill batches as SGLang's breakable CUDA
graphs: the model runs in graph segments, and attention runs eagerly
between them. Each eager attention call costs about 0.27 ms of CPU time
(FlashAttention 4's host-side dispatch plus the varlen wrapper), so
every prefill step pays about 7-8 ms of CPU time for Qwen3-0.6B's 28
layers, however few tokens it has. When requests arrive while others
decode (multi-turn and agentic rollouts), most steps are small prefills,
and this CPU time dominates them.

**Example.** Qwen3-0.6B, TP 1, one request (300 prompt tokens) admitted
every step while earlier ones decode (stream workload below), per-step
profile:
```
breakable prefill graphs: prefill step 14.7 ms (p50)
  aten::_flash_attention_forward   214 us CPU per call, one per layer
  torch_attn::_varlen_attn_out      51 us CPU per call
full prefill graphs:      prefill step  4.3 ms (p50)
```

SGLang's full prefill CUDA graphs capture the whole forward, attention
included, one graph per token-count bucket with a fixed number of
request slots. By default SGLang sizes the slots to
`chunked_prefill_size // 512` (32 at the default 16K); a prefill batch
with more requests runs eagerly, which made many-short-prompt prefill
slower than breakable graphs (0.51 s vs 0.39 s for 256 prompts of 100
tokens).

## What changed
- `sglang/engine.py`: a new `cuda_graph="full"` mode, now the default,
captures prefill batches as SGLang's full CUDA graphs, with
`max_num_seqs` request slots, so no prefill batch has too many requests
for them. `"breakable"` (the old default) stays for models with linear
attention (GDN, KDA): SGLang's hybrid linear attention backend fails to
capture full prefill graphs (TODO in code), so `"full"` raises for them
at engine build instead of falling back. `cuda_graph_config` joins the
server args `extra_server_args` cannot set.
- Tests: the parity base class runs `"full"`; the GDN and KDA classes
set `"breakable"`.
- `sglang/README.md`: the CUDA graphs section and the support table.
- Review fixes (fb2c483): `test_prefill_replays_cuda_graphs` counts
the prefill
graph backend's replays for classes with breakable or full prefill
graphs and
asserts at least one, since every other test would also pass with eager
prefill;
  the README names the graph modes Dist-MoE runs under.

## User-facing changes
| Before | After |
| --- | --- |
| default `cuda_graph="breakable"`: breakable prefill graphs | default
`cuda_graph="full"`: full prefill graphs |
| GDN/KDA models with the default | raise `ValueError`: set
`cuda_graph="breakable"` |
| `extra_server_args` may set `cuda_graph_config` | raises `ValueError`
(TorchTitan sets it) |

## Numerics
Batch-invariant mode stays bitwise identical to the trainer.

| Check | Hardware | Result |
| --- | --- | --- |
| All 7 `test_sglang_bitwise_parity.py` classes. Varlen, sliding window,
MLA and Dist-MoE capture full prefill graphs; GDN and KDA run
`"breakable"`; MoE EP and MLA at EP 2 run without graphs | 4x GB300 |
passed, max delta 0 |
| Batch-invariant Qwen3-0.6B TP 1, 32 greedy requests (64-281 prompt
tokens, 64 output tokens), one admitted every 3 steps: full vs breakable
prefill graphs | 1x GB300 | identical tokens, bitwise-identical logprobs
|

## Performance
Qwen3-0.6B, generator TP 2, 2x GB300, perf mode, temperature 1,
fixed-length outputs. Local benchmark through the same
`GenerationEngine` calls; one process per configuration, run one after
another on the same GPUs; three repeats each (ranges).

| Workload | Breakable prefill graphs | Full prefill graphs | vLLM |
| --- | --- | --- | --- |
| Stream: one request (300 in / 150 out) admitted every step, 256
requests: wall | 5.09-5.35 s | 1.98-2.02 s | 2.10-2.20 s |
| Stream: request latency p50 / p90 | 2.86-2.97 / 4.62-4.85 s |
1.30-1.34 / 1.84-1.88 s | 0.90-0.93 / 1.00-1.01 s |
| Prefill: 512 requests, 1536 in / 128 out | 2.68-3.08 s | 2.51-2.53 s |
|
| Prefill: 256 requests, 100 in / 64 out | 0.40-0.41 s | 0.37-0.39 s | |
| GRPO 16 prompts x 8 samples (1024 in, 256 out) | 1.03-1.22 s |
1.01-1.13 s | |
| GRPO 64 prompts x 8 samples (128 in, 256 out) | 2.13-2.17 s |
2.06-2.19 s | |
| GRPO 16 x 8, siblings admitted after the head's prefill (cached
prefix) | 0.97-1.04 s | 0.96-0.99 s | |
| Decode: 256 requests, 128 in / 512 out | 2.03-2.05 s (first repeat:
6.38 s) | 2.01-2.05 s | |

Prefill graph memory: 0.77 GB (full, 256 slots) vs 1.02 GB (breakable).
Prefill graph capture: 28 s vs 31 s. At max_num_seqs=512 (the
controller's cap): 0.94 GB and 36 s, with the stream workload at
2.14-2.17 s. The first decode repeat with breakable graphs includes
attention kernel compilation, which the full-graph run did not show.

End to end, `alphabet_sort` with generator TP 2 + trainer TP 2 (4x
GB300, 10 steps, RL environment): trainer
tokens/s over steps 3-9 is 1684 with full prefill graphs and 1651 for
vLLM (one run each, same session). Earlier
SGLang runs with breakable graphs gave 1632, 1758 and 1763, so this
workload does not separate the engines.

## Testing
- `test_sglang_bitwise_parity.py`, all 7 classes, and the
batch-invariant check above.
- CI: the B200 SGLang step (#5812), [run
42015552173](https://github.com/pytorch/torchtitan/actions/runs/42015552173),
before the split into `"breakable"` and `"full"`: all 7 classes passed
(4 tests each, every rank); the step took 9 minutes. The split changes
which mode each class selects, not what a mode captures; the B200 job
reruns them at the current head.
- Benchmarks and E2E runs as above.
- No new test: the parity classes cover both prefill graph modes
(`"full"` in the base class, `"breakable"` in the GDN and KDA classes).

## Known issues / follow-ups
- Mixing a prefill chunk into the running decodes (SGLang's
`enable_mixed_chunk`) is gated off in SGLang when requests return
logprobs. With a local SGLang patch that lifts the gate, mixed steps
take 7.6 ms (p50), about a prefill step plus a decode step. On the
stream workload that brings latency p50 / p90 to 1.04-1.14 / 1.19-1.25
s, but wall time rises to 2.35-2.54 s.
- After several workloads in one engine, the stream workload's decode
steps slow from 3.4 ms to 8.4 ms with either prefill graph backend; not
investigated yet.
tianyu-l added a commit that referenced this pull request Nov 10, 2026
…ed dispatcher checks (#5959)

Stacked on #5918. Addresses the DeepEP / HybridEP question on #5815.

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

Integrate sglang with deepep and hybrided

## Why
`SGLangEngine` accepts only the all-to-all token dispatcher and
Dist-MoE, so an MoE
generator configured with DeepEP or HybridEP (as `search_r1`'s vLLM
generator uses
DeepEP) cannot run on SGLang. `VLLMEngine` accepts them, but checks
nothing: a
dispatcher config the engine cannot run fails mid-capture or
mid-generation with a
low-level error.

**Example.**
```python
generator = Generator.Config(
    parallelism=InferenceParallelismConfig(tensor_parallel_degree=2, expert_parallel_degree=2),
    engine=SGLangEngine.Config(),  # default cuda_graph="full"
)
# model's dispatcher: DeepEPTokenDispatcher(cuda_graph_compatible=True, num_max_tokens_per_rank=N)
# before: ValueError "the SGLang engine supports the all-to-all token dispatcher and Dist-MoE only"
# after: runs, under CUDA graphs

# Either engine, num_max_tokens_per_rank=4096 for an 8195-token-per-rank step bound:
# before: AssertionError mid-generation "DeepEP current token count 5120 exceeds the preallocated capacity of 4096"
# after: ValueError at build "num_max_tokens_per_rank=4096 is below the 8195 tokens an EP rank can get in one engine step"
```

## What changed
- `generator/model.py` (engine-agnostic): two checks both engines call.
  - `validate_ep_token_dispatchers`, at engine build:
- a dispatcher that reads its split sizes on the host (all-to-all,
DeepEP
without `cuda_graph_compatible`, HybridEP without
`non_blocking_capacity_factor`)
      raises under CUDA graphs;
- DeepEP's deterministic dispatch (`DebugConfig.deterministic`) raises
under CUDA
graphs: DeepEP sorts the received tokens with data-dependent shapes
      (`ElasticBuffer.deterministic_sort`);
- HybridEP needs an EP degree divisible by 4: a step can have any token
count,
and HybridEP's TMA loads need a rank's tokens times the ranks in its
node, in
4-byte words, to fill 16-byte rows (EP 2 with 3 tokens per rank raised
      "TMA 16B alignment error" while SGLang captured a decode graph);
- a HybridEP `non_blocking_capacity_factor` below 1.0 raises: HybridEP
drops the
tokens past its capacity without an error, which changes the sampled
tokens.
- `validate_ep_token_dispatcher_capacity`, in the model wrappers: a
DeepEP/HybridEP
`num_max_tokens_per_rank` below a step's tokens per EP rank raises.
SGLang's bound
is `chunked_prefill_size + max_running_requests`, vLLM's
`max_num_batched_tokens`,
    each padded to a multiple of TP and split over TP.
- `sglang/engine.py`: its dispatcher loop is replaced by the shared
check, so it
  accepts DeepEP and HybridEP.
- `vllm/engine.py`, `vllm/model_wrapper.py`: call the shared checks.
- `sglang/README.md`: the MoE section, including where to get DeepEP and
HybridEP
builds (the install scripts in `.github/scripts/` and
`.ci/docker/common/`).

| Generator dispatcher | SGLang before | vLLM before | Both after |
| --- | --- | --- | --- |
| DeepEP `cuda_graph_compatible` / HybridEP
`non_blocking_capacity_factor`, CUDA graphs | ValueError | runs | runs |
| Host-synced dispatcher, CUDA graphs | ValueError | fails at capture
("Cannot copy between CPU and CUDA tensors during CUDA graph capture") |
ValueError at build |
| DeepEP + `DebugConfig.deterministic` + CUDA graphs | ValueError |
fails at capture (same DeepEP code; not run on vLLM) | ValueError at
build |
| HybridEP, EP degree not divisible by 4 | ValueError | TMA alignment
error on small steps (expected; not run on vLLM) | ValueError at build |
| HybridEP `non_blocking_capacity_factor` < 1.0 | ValueError | drops
tokens silently | ValueError at build |
| `num_max_tokens_per_rank` too small | ValueError (DeepEP/HybridEP
unsupported) | assert at the first large step | ValueError at build |

Every existing RL recipe whose generator uses EP passes the new checks
(built on CPU
and checked: the `alphabet_sort`, `dapo_math`, `search_r1` and test
`alphabet_sort`
recipes; `verifiers_terminal_bench` already turns generator CUDA graphs
off).
- Review fixes (19d9f98): the shared validator notes that Dist-MoE
experts have
no token dispatcher; the CUDA-graph server-args comment names the DeepEP
/
HybridEP capacity check, which assumes SGLang's default capture sizes.
Explicit
capture sizes and graph-mode keys in `extra_server_args` are rejected
since #5812.

## Numerics
No change for configurations that ran before. DeepEP and HybridEP
results on SGLang
match the trainer bitwise when the trainer uses the same dispatcher
(below).

## Testing
Locally on GB300, Qwen3 MoE debug model
(`TestSGLangBitwiseParityMoEEP`'s config with
the dispatcher swapped). DeepEP v2 at the pin in
`.github/scripts/install_deepep_v2.sh`
and HybridEP at the pin in `.ci/docker/common/install_deepep.sh`, built
against
torch's NCCL 2.32.3:

| Run | Result |
| --- | --- |
| DeepEP on trainer and generator, TP 2 / EP 2, batch-invariant,
`cuda_graph="none"` | all 4 parity tests pass bitwise on both ranks |
| DeepEP, `cuda_graph="full"`, `DebugConfig.deterministic=False` |
graphs capture, generation runs, decode batch invariance passes |
| HybridEP on trainer and generator, TP 4 / EP 4, `cuda_graph="full"` |
decode batch invariance and 2 trainer-vs-SGLang tests pass bitwise on
all 4 ranks; the 4th test fails in the test's own trainer forward
(HybridEP on a 150-token sequence, outside the generator) |
| Generator-only DeepEP or HybridEP (trainer all-to-all) | decode batch
invariance passes; trainer vs SGLang differs (max ~6e-3): the
dispatchers combine expert outputs in different orders |
| DeepEP deterministic + `cuda_graph="full"`;
`num_max_tokens_per_rank=4096`; HybridEP with EP 2; HybridEP factor 0.5
| each raises the new ValueError at build |

- `pytest tests/rl/unit_tests/cpu`: 568 passed, 7 skipped.
- No new CI test: the RL B200 job installs neither DeepEP nor HybridEP,
and the SGLang
venv's own DeepEP wheel asserts on an NCCL version mismatch with torch.

## Known issues / follow-ups
- DeepEP's deterministic dispatch cannot run in CUDA graphs (DeepEP
limitation, deepseek-ai/DeepEP#820).
- The trainer's HybridEP dispatch raises TMA alignment errors for token
counts per
rank that miss the alignment (small test sequences); training
microbatches are
  packed to aligned sizes.
- A CI job for DeepEP / HybridEP generators needs DeepEP builds in the
RL and SGLang
  environments.
acisseJZhong pushed a commit that referenced this pull request Nov 11, 2026
…r argument (#6024)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

#5824 changed the generation engine interface for image prompts, and the
SGLang engine (#5812), which landed on main while #5824 was in review,
kept the old one:

- `EngineRequest.prompt_token_ids: list[int]` became
`EngineRequest.prompt: Prompt` (tokens plus images).
`SGLangEngine.add_requests` still reads `request.prompt_token_ids` (3
places).
- `Generator` passes `vision_processor=` to every engine's `build`.
`SGLangEngine.__init__` has no such parameter.

**Example.** On main, any generator with `engine=SGLangEngine.Config()`:

```
Generator setup -> config.engine.build(..., vision_processor=None, ...)
  TypeError: SGLangEngine.__init__() got an unexpected keyword argument 'vision_processor'
```

and, past that, every request: `AttributeError: 'EngineRequest' object
has no attribute 'prompt_token_ids'`.

## What changed

- `SGLangEngine` takes `vision_processor: VisionProcessor.Config | None`
(as `VLLMEngine` does) and raises a `ValueError` unless it is None:
SGLang serves text prompts only, and image prompts need `VLLMEngine`.
- `add_requests` reads `request.prompt.token_ids` once and uses it for
the range check, the sampling params and SGLang's `input_ids`.
- `test_sglang_bitwise_parity.py` builds requests with
`Prompt(token_ids=...)` and passes `vision_processor=None` to the
engine's `build`.

## Testing

- No local environment has SGLang, so I could not run its tests here. A
static check (AST of the sources) of the keyword arguments `Generator`
passes to `engine.build` against `SGLangEngine.__init__`'s parameters:
on main, `vision_processor` is missing; with this PR, nothing is.
- `pre-commit` on the two files passes.
- CI: the RL B200 workflow runs `test_sglang_bitwise_parity.py` (SGLang
installed); it needs the `ciflow/rl` label.
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests 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.

3 participants