Repository navigation
[rl] generator: SGLang generation engine - #5812
Conversation
|
@claude review |
There was a problem hiding this comment.
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 + continueMust fix
-
PR description -- "Summary (human-written)" is empty. The author needs to fill it in.
-
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:569copies the body ofevent_loop_overlapand calls private members (_apply_war_barrier,_sched_idled).engine.py:327sets_war_barrier_enabled.engine.py:231-234replacesoutput_streamer.send_to_detokenizerandipc_channels.send_to_tokenizer.engine.py:227clearshf_eos_token_id.engine.py:193monkeypatchesModelRunner.maybe_enable_batch_invariant_modefor the whole process wheneverdebug.seedis set.attention.py:62overrides_init_flash_attention_functions.registry.py:127writes toModelRegistry.modelsdirectly.batch_invariance.py:73patchesSampler.forward.model_wrapper.py:136adds an unregisteredattnalias.
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.
-
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-- withhas_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_holdertakes 6.22 s. The large wins (decode 1.65x, prefill 1.3x) are from generator-only microbenchmarks. Which in-repo workload, e.g. long-decodedapo_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_timeexists 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.mdand the vLLM precedent.extra_server_argsmatches vLLM'sextra_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_logitsis shared correctly. Inside the vLLM method body,compute_logitsresolves to the module-level import, not the method.replace_sglang_layer_configsuses a stricttype(...) is VarlenInnerAttention.Configcheck. 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_sessionsreleases sessions in sorted order, and the releases arrive through the broadcast decision, so all TP ranks agree.- The
GenerationEnginethreading 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, |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
| 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(), | ||
| ) |
There was a problem hiding this comment.
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 configThat 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.
fe2a838 to
7938547
Compare
|
@claude review again |
There was a problem hiding this comment.
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.pynow importsmake_prompt_tokens, which this PR renames intest_bitwise_parity.pyand its two other callers.- SGLang requests now report
has_stats=True, with queue, TTFT, prefill, decode and preemption metrics taken fromReq.time_statsandretraction_count(engine.py:596). The README lists them as supported. rl_grpo_qwen3_0_6b_varlen_sglangnow derives fromrl_grpo_qwen3_0_6b_varlenand changes only the engine (alphabet_sort.py:189). The helper is gone.
Must fix
-
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.
-
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:605readsReq.time_statsandReq.retraction_countdirectly because SGLang only exports them withenable_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_timenow feeds only the TTFT metric, not scheduling. Does SGLang's priority policy break ties by insertion order only? engine.py:405-407registers only the requests found inwaiting_queueright afterprocess_input_requests.engine.py:574then doesself._admitted.pop(request_id)with no default for every non-abort finish. Does SGLang ever place an admitted request somewhere other thanwaiting_queue, for example with session radix cache or HiCache? If it does, the engine loop dies with aKeyError.
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.
5e1d410 to
9e493d8
Compare
|
@claude review again |
There was a problem hiding this comment.
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
- PR description. "Summary (human-written)" is still the template placeholder, and the author needs to fill it in.
engine.py:617-- the_metrics_inputsTODO is the only private SGLang touchpoint left without an issue (it readsReq.time_statsandReq.retraction_countdirectly). 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 ifadd_requestsfinds them inwaiting_queue. On every non-abort finish,_receive_tokensthen callsself._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 bareKeyError. To fail where the invariant is set up, assert inadd_requeststhat every admitted, non-rejected rid was found inwaiting_queueand registered withadmit().
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.
9e493d8 to
c83a38a
Compare
|
@claude review again |
There was a problem hiding this comment.
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_inputsTODO now links sgl-project/sglang#48482, and the description lists that issue. Every SGLang workaround TODO undersglang/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
- 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_requestscallsadmit()only for admitted requests it finds inwaiting_queue._receive_tokensthen callsself._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 bareKeyError. To catch that where it happens, assert inadd_requeststhat every admitted rid that wasn't rejected went throughadmit().
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.
c83a38a to
49f8172
Compare
|
@claude review again |
There was a problem hiding this comment.
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_requestsnow asserts that every admitted rid that wasn't rejected was found in SGLang's waiting queue and registered withadmit(). If SGLang ever routes an admitted request somewhere else,add_requestsnow fails with the rids involved, instead of the engine loop hitting a bareKeyErroratengine.py:589later.
Must fix
- 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.
49f8172 to
ca5642b
Compare
|
@claude review again |
|
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 |
There was a problem hiding this comment.
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 VMMThe 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'sregistered=Falseoverride. No run after this change used CUDA graphs withexpandable_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) |
There was a problem hiding this comment.
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.
5a88cf4 to
baf9e7f
Compare
| TORCHTITAN_VARLEN_ATTENTION_BACKEND = "torchtitan_varlen" | ||
|
|
||
|
|
||
| class TorchTitanVarlenAttnBackend(FlashAttentionBackend): |
There was a problem hiding this comment.
shall we inherit from _FA4PageSize here similar to vllm? otherwise codex telling me the default page size is 1.
There was a problem hiding this comment.
[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
fa4attention 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'sno_bufferstate 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}") |
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def force_trainer_logprobs_for_batch_invariance() -> None: |
There was a problem hiding this comment.
also change vllm's naming to align
| 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 |
There was a problem hiding this comment.
only under enable_deterministic_inference = False case
There was a problem hiding this comment.
[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( |
There was a problem hiding this comment.
from codex:
1.
extra_server_argsshould be an allowlist, not a denylist (sglang/engine.py:69-94,130-136)
There was a problem hiding this comment.
[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_graphis rejected: SGLang applies its per-phase graph keys (e.g.cuda_graph_backend_decode) overdisable_cuda_graph, so they could turn on graphs that the engine's checks assume are off; page_sizeis set and owned by the engine;max_queued_requestsis 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 ofextra_server_argsis HiCache, and an allowlist would need updating for every SGLang option a user wants.
felipemello1
left a comment
There was a problem hiding this comment.
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'))") |
There was a problem hiding this comment.
is that what we do for vllm tests as well? Should we use one of the dummy models?
There was a problem hiding this comment.
[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.
| # 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 |
There was a problem hiding this comment.
this doesnt look right. Should we do something like vllm, install latest stable --no-deps and torch nightlies?
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
we dont have this for vllm, do we? maybe we could do something like
install_rl.sh --generator sg_lang
There was a problem hiding this comment.
[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.
| 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. |
There was a problem hiding this comment.
is this a TODO? if not, should we delete this?
| if fa_impl not in ("FA3", "FA4"): | ||
| raise ValueError( | ||
| f"{TORCHTITAN_VARLEN_ATTENTION_BACKEND} needs FA3 or FA4 (SM90+), " | ||
| f"got {fa_impl}" | ||
| ) |
There was a problem hiding this comment.
does this work on A10G in our tests?
There was a problem hiding this comment.
[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.
| # 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. |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
[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.Enginesubprocess; none steps an in-processSchedulerwith a foreign model, which is where these come from.
The exception was the sampler TODO: SGLang does haveregister_sampler_backend, and the engine now uses it instead of patchingSampler.forward(see the reply on batch_invariance.py:74).
| @property | ||
| def data_parallel_size(self) -> int: | ||
| return 1 | ||
|
|
||
| @property | ||
| def data_parallel_rank(self) -> int: | ||
| return 0 |
There was a problem hiding this comment.
i understand that we dont support dp>1, but should we use the given value anyway instead of hardocde?
There was a problem hiding this comment.
[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).
| cache_salt = ( | ||
| None | ||
| if self._reset_kv_cache_on_model_state_dict_load | ||
| else str(request.min_policy_version) | ||
| ) |
There was a problem hiding this comment.
this sounds wrong. You are reseting the salt on every new request if _reset_kv_cache_on_model_state_dict_load is true.
There was a problem hiding this comment.
[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.
| class _OutputCollector: | ||
| """Stands in for the scheduler's sockets to the tokenizer and detokenizer processes. |
There was a problem hiding this comment.
not sure whats going on here. If we do token in token out, then what tokeniation/detokenization is going on?
There was a problem hiding this comment.
[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: |
There was a problem hiding this comment.
could use a docstring
|
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 |
There was a problem hiding this comment.
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:
- 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).
- No CI test runs the reset path that every batch-invariant recipe uses (test:116).
- 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).
extra_server_argscan 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'sScheduler.event_loop_overlap. - SGLang main (1be97a0a63) is 271 commits after the pinned SGLang commit.
- Since the pinned commit, its
scheduler.pyhas 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, |
There was a problem hiding this comment.
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):
pause_generation(retract): stop the running requests and take them back.flush_cache: drop the KV cache.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
- 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. - Turn it on for one existing class.
- In that class, load the same weights while a generation is in flight.
- Assert the tokens and logprobs equal a run without the load.
That is the check the PR body's local script ran.
There was a problem hiding this comment.
[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.
| # 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 |
There was a problem hiding this comment.
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
- Write a
TorchTitanSampler(Sampler)with today's forward body. Keep the logits copy at line 55. - Register it under both "pytorch" and "flashinfer". This works because
create_samplerchecks 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
Samplerstays unpatched. - And the
_trainer_logprobsflag 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.
There was a problem hiding this comment.
| _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", | ||
| } | ||
| ) |
There was a problem hiding this comment.
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:
- Set
cuda_graph="none", and pass{"cuda_graph_backend_decode": "full"}inextra_server_args. - SGLang captures full decode graphs.
- 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 passesconfig.cuda_graphto model.py:316, 347). - So the checks let the all-to-all dispatcher through.
- 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_buffercache 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
_FA4PageSizedocstring. 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_configafterServerArgsis built, before theScheduler.
| if self._reset_kv_cache_on_model_state_dict_load | ||
| else str(request.min_policy_version) | ||
| ) | ||
| sglang_request = TokenizedGenerateReqInput( |
There was a problem hiding this comment.
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.
- 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.
- 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).
- The embedding is plain
- 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.
| 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( |
| scheduler = self._scheduler | ||
| with scheduler.device_module.StreamContext(scheduler.schedule_stream): | ||
| _overlap_event_loop_iteration(scheduler) |
There was a problem hiding this comment.
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 undertorch.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_reducetakes its fast path only whennot 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.
| 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) |
| ), | ||
| ) | ||
| logger.info("Building the SGLang scheduler...") | ||
| self._scheduler = Scheduler(server_args, PortArgs.init_new(server_args)) |
There was a problem hiding this comment.
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
Schedulerstarts SGLang's hard watchdog (scheduler.py:1551-1555). - Rule: if no forward runs for
watchdog_timeout(default 300 s) whilecur_batch_for_debugis 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'sScheduler.event_loop_overlap. - The copied loop sets
cur_batch_for_debugevery step (line 684). - In reset mode,
pause_generationclears it. - In a load without reset, nothing clears it.
Example (unverified on GPU)
- Reset is off, and the load uses
gpu_fetch. - A batch is in flight.
- The fetch takes over 300 s.
- The watchdog signals whatever launched the generator.
- The log points at SGLang instead of the slow fetch.
Smallest fix
Handle the load explicitly:
- After line 494, wait on the host for the in-flight forward (
scheduler.forward_stream.synchronize()). - Then clear
cur_batch_for_debugfor 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.
| # 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. |
There was a problem hiding this comment.
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
- A request's last token is computed under policy 7.
- The token still sits in
result_queuewhen the load installs policy 8. - What happens next depends on the reset mode:
- Reset off: the next
step()processes and returns it. - Reset on:
pause_generationprocesses it intoself._finished, and the nextstep()returns it.
- Reset off: the next
- Either way, the engine loop reports it after bumping
policy_versionto 8 (engine_loop.py:392-395, 564). - 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.
There was a problem hiding this comment.
[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).
483d869 to
5c1767d
Compare
|
[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.
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 |
5c1767d to
19e4b88
Compare
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.
19e4b88 to
59d1deb
Compare
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.
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).
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.
…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.
…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.
…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.

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
SGLangEnginebehind the existingGenerationEngineinterface. As withVLLMEngine, SGLang runs the trainer'sTorchTitan 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.
What changed
torchtitan/rl/generator/sglang/(new):engine.py:SGLangEngine. It builds SGLang'sSchedulerin-process perTP rank and steps one overlap-loop iteration per
step(). It also does:continue);
cache_salt;context_len - 6tokens or more, so the engine sets SGLang's context length tomax_context_length + 6(registry.CONTEXT_LENGTH_MARGIN) and caps eachrequest's output at
max_context_lengthtokens in total. Prompts of up tomax_context_length - 1tokens run, as in vLLM; without the margin, prompts of65,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-backendsubclass that calls the shared
paged_varlen_attention_out.registry.py: model class, config parser and attention backendregistration.
batch_invariance.py: the trainer'scompute_logprobsfor returnedlogprobs.
README.md.inference_model.compute_logits: the lm_head plus TP gather, now shared bythe 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, theSGLang 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=Falseoverride now also applies to a rebuilt engine's communicator, and the docstring's
reason for routing
spmd.redistributedirectly is corrected (its all-reducereaches 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 reciperl_grpo_qwen3_0_6b_varlen_sglang:rl_grpo_qwen3_0_6b_varlen(generator TP 4plus trainer TP 2, 6 GPUs) with the SGLang engine.
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.pylists theSGLang recipe as needing an optional package.
generator.pyandtorchtitan/rl/README.mdmention the new engine.scripts/install_rl_env.sh --sglang(new flag): installs SGLang at the pinnedcommit with a git-URL install, keeping the environment's PyTorch (uv overrides)
and dropping torchaudio, which the engine never imports.
integration_test_rl_b200.yaml) gains a last step. Itinstalls SGLang with
scripts/install_rl_env.sh --sglangon top of the job's RLenvironment and runs
test_sglang_bitwise_parity.pyon 2 GPUs. The README'senvironment 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 undertorch.no_grad(), as SGLang's own loops and the vLLM enginedo, so the model's TP all-reduces take their fast path in eager steps.
add_requestsrejects empty prompts and token ids outside the vocab (SGLangchecks only the length; at TP > 1 a bad id would embed as zeros silently).
extra_server_argscannot setpage_size(the engine sets 1, with the reason)or any key containing
cuda_graph: SGLang applies its per-phase graph keys overdisable_cuda_graph, so they could turn on graphs the engine's checks assumeare off.
register_sampler_backendinstead of patchingSampler.forward.salt,
page_size.Workarounds of SGLang APIs, each with a TODO in code:
event_loop_overlap);User-facing changes
Generator.Config.engine:VLLMEngine.ConfigonlySGLangEngine.Config(cuda_graph=..., extra_server_args=...)rl_grpo_qwen3_0_6b_varlen_sglangscripts/install_rl_env.sh --sglang: also installs SGLang into the RL environmentforce_logprobs_fn_for_batch_invariance(vLLM)force_trainer_logprobs_for_batch_invariance, the SGLang helper's nameNumerics
Batch-invariant mode matches the trainer bitwise.
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 weights851642aderl_grpo_qwen3_0_6b_varlen_batch_invariantwith SGLang (1 generator TP 2 + trainer TP 2), 10 stepslogprob_diff/max= 0 every stepOutside batch-invariant mode,
logprob_diff/maxon 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
GenerationEnginecalls; temperature1; fixed-length outputs.
session_kv_holdergpu_memory_limit=0.8End to end,
alphabet_sortwith generator TP 2 + trainer TP 2 (4x GB300, 10steps): 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 1763trainer 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):
Most of the decode gap to vLLM is not SGLang's scheduling. The vLLM engine's
default
FULLCUDA graphs capture one graph per size for mixed prefill/decodebatches, 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:
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'sgc.collect()after each load take 1.2 s.Testing
test_sglang_bitwise_parity.pyat 19e4b88: 5 passed on 2x GB300, includingthe new
test_sglang_decode_across_model_state_dict_load(a load of the sameweights 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 theRL environment's torch: installs SGLang at the pin, torch unchanged, no
torchaudio.
environment): 3 passed. On B200: run 42015554306,
3 passed on both ranks; the step took 2 minutes, SGLang install included.
reset_kv_cache_on_model_state_dict_loadoff and on:pytest tests/rl/unit_tests/cpu: 546 passed (581 at the top of the stack afterthe review fixes).
TestBitwiseParityVarlen: 3 passed (it covers the sharedcompute_logits).test_context_length_limits(new, inTestSGLangBitwiseParityVarlen): a prompt ofmax_context_length - 1tokens runs and stops atmax_context_lengthtokens intotal, and a prompt of
max_context_lengthtokens is rejected. Without the marginit fails (the first prompt is rejected). With it, all 4 tests of the class pass on
2x GB300.
Known issues / follow-ups
implementation). Where SGLang falls back to its legacy custom all-reduce, CUDA
graph capture on
expandable_segmentsmemory is unverified.runners of the other RL GPU jobs.
Schedulersgl-project/sglang#48472;config's EOS ids: Decouple per-request sampling seeds from
enable_deterministic_inference's kernel overrides; allow ignoring the generation config's EOS ids sgl-project/sglang#48474;attention kernels, sampler logprobs): Feature request: extension points for externally defined models (registration of runtime classes, attention lookup, attention kernels, sampler logprobs) sgl-project/sglang#48475;
enable_metrics: Feature request: per-request time stats in scheduler outputs without enable_metrics sgl-project/sglang#48482.costs about 6 s of stalls once per run.
reported at the new policy version (TODO in
load_model_state_dict).(their next turn recomputes the prefix).
it needs evaluation on larger models.
tokens), SGLang's median request latency is 3.0 s against vLLM's 0.9 s. Each
step that admits a prompt is an extend step of about 17 ms whatever the prompt
length (vLLM: 7-9 ms), a fixed per-step cost. SGLang also does not mix decode rows
into a prefill batch when requests return logprobs (TODO in its scheduler);
allowing it in a local SGLang patch moved p90 latency from 4.7 to 2.8 s, the
median only from 2.9 to 2.5 s. Follow-up.
FULLCUDA graphs run decode attention with prefill-sizedparameters (see Performance); follow-up on the vLLM path.