Skip to content

[rl] generator: SGLang MoE with expert parallelism and Dist-MoE - #5815

Merged
tianyu-l merged 2 commits into
sglang-2-enginefrom
sglang-3-moe
Nov 10, 2026
Merged

tianyu-l merged 2 commits into
sglang-2-enginefrom
sglang-3-moe

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Stacked on #5812 (the SGLang engine).

Summary (human-written)

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.

# 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 ([rl] generator: SGLang generation engine #5812) stays on TestSGLangBitwiseParityVarlen only.
  • CI: the B200 SGLang step ([rl] generator: SGLang generation engine #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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 4, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 4, 2026
@tianyu-l
tianyu-l added this pull request to stack #5813 November 4, 2026 19:49
@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging: review (see the Reviews tab of #5815).

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The design matches the vLLM engine (EP over the TP group, with a shared build_dist_moe_runtime), and both new parity classes are bitwise exact. The remaining items are small, local edits.

What this PR does. Lets SGLangEngine run MoE models with EP. _DecoderBody pads each step to a multiple of TP, because the EP MoE shards tokens over TP. SGLangInnerAttention runs only on the rows SGLang scheduled and zero-fills the padding rows. The all-to-all dispatcher is allowed only with cuda_graph="none". Dist-MoE gets a runtime sized from chunked_prefill_size + max_running_requests, and its per-call row count is fixed when each graph is captured.

Example. TP 2 / EP 2, a decode step with 5 running requests:

SGLang input_ids: 5 rows -> body pads to 6, padding_mask = [0,0,0,0,0,1]
attention: q[:5] (out_cache_loc has 5 slots) -> out padded back to 6 rows
MoE: 3 rows per TP rank; Dist-MoE routes row 5 to no expert,
     all-to-all dispatches it like a real token
body returns hidden_states[:5]

Before this PR, the same config raised "SGLangEngine does not support MoE expert parallelism yet".

Must fix

  1. The PR description leaves "Summary (human-written)" empty, and the author needs to fill it in. The description also says the body "masks the padding out of the MoE dispatch". That holds only for Dist-MoE: the stock dispatchers ignore padding_mask_T (moe/moe.py:119-125). The same wording appears in the code comment (inline).
  2. sglang/engine.py:208 -- the triton.next_power_of_2 monkeypatch needs an SGLang issue link in its TODO (inline).

Should consider

  • sglang/model_wrapper.py:187 -- with Dist-MoE and EP 1, TP > 1, the token count is floored instead of failing loudly; vLLM asserts in the same place (inline).

Questions

  • Rows SGLang adds to pad a batch to a CUDA graph's size are not masked under Dist-MoE, as the TODO says. They likely carry identical inputs (unverified), so they would route to the same top-k experts and pile load onto one EP rank. Both test classes use scratch_capacity_factor=2.0, which is the worst case at EP 2, so the tests can't show what happens at a smaller factor or a larger EP. With VMM off, what does Dist-MoE do when routing exceeds the scratch capacity? If it fails, or drops real rows, then "real rows are unaffected" depends on the user over-provisioning the factor, and the README should say so.
Details
  • Gate: the problem is real (the engine raised for EP on the base branch), and SGLang's own adapter is the right layer for the fix. build_dist_moe_runtime moves into shared inference_model.py with two consumers, which is a mechanical move apart from the error message. The trainer and core code are untouched.
  • CUDA graphs: the pad length, padding_mask, hidden_states[:num_tokens], and the Dist-MoE per-call count all depend only on a graph's capture size, so they are static per graph. With breakable prefill graphs, attention slices q by out_cache_loc at run time.
  • Dispatcher check: TorchAOTokenDispatcher subclasses AllToAllTokenDispatcher, so MXFP8 all-to-all passes the check. DeepEP and HybridEP raise.
  • Size bound: max_num_tokens_per_step assumes chunked prefill is on, which holds because chunked_prefill_size is in _TORCHTITAN_SERVER_ARGS and can't be overridden. Whether SGLang's prefill CUDA graph capture sizes ever exceed chunked_prefill_size (which would raise in set_num_local_input_tokens_per_call at capture) is unverified. The default config passes per the PR's test runs.

Not verified: GPU runs. In particular, triton.constexpr_function availability in the pinned Triton, and how Dist-MoE behaves when scratch overflows.

Comment on lines +208 to +211
# TODO: importing SGLang replaces triton.next_power_of_2 with a host-only
# function, process-wide, which Triton kernels cannot call (e.g. Dist-MoE's
# routing kernels); make it callable in kernels again.
triton.next_power_of_2 = triton.constexpr_function(next_power_of_2)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This patches a third-party module process-wide to work around an SGLang bug: SGLang replaces triton.next_power_of_2 on import. Per CLAUDE.md principle 3, a workaround for an upstream gap needs a TODO with a link to the upstream issue. As written, nobody can tell when it is safe to remove. Please file (or link) the SGLang issue in the TODO.

The patch also runs for every SGLang engine, with or without Dist-MoE, and it rewraps SGLang's own replacement function. Whether SGLang's host-side callers still behave the same with a constexpr_function wrapper is unverified (I couldn't run it). One sentence in the comment saying so would help.

if num_padding:
input_ids = F.pad(input_ids, (0, num_padding))
positions = F.pad(positions, (0, num_padding))
# Keeps the padding rows out of the MoE's dispatch.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This comment is only true for Dist-MoE. With the all-to-all dispatcher (and the other stock dispatchers), the mask is ignored and the padding rows are dispatched and computed like real tokens (moe/moe.py:119-125, del padding_mask_T). The router only drops them from the load-balancing statistics. The PR description ("masks the padding out of the MoE dispatch") has the same inaccuracy.

Suggested change
# Keeps the padding rows out of the MoE's dispatch.
# Dist-MoE routes padding rows to no expert; the stock token dispatchers
# dispatch them like real tokens.

Comment on lines +187 to +189
self._dist_moe_runtime.set_num_local_input_tokens_per_call(
input_ids.shape[0] // self._parallelism_context.tp
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This floor division assumes the step was padded to a multiple of TP. But token_multiple is expert_sequence_parallel_size, which is 1 when expert_parallel_degree == 1 (parallelism.py). Meanwhile Dist-MoE always splits tokens over cp * tp (dist_moe/runtime.py:311). So with Dist-MoE, EP 1 and TP 2:

  • a 5-token step sets 2 local rows instead of 2.5 (impossible), and
  • a 1-token decode step sets 0, which raises in set_num_local_input_tokens_per_call.

max_num_tokens_per_step also isn't rounded in that case, so the runtime build can raise "must divide evenly". vLLM asserts here (_dist_moe_num_local_input_tokens). Either raise at engine build when Dist-MoE runs with EP 1 and TP > 1, or keep the floor but assert input_ids.shape[0] % tp == 0 so the bad config fails loudly. (Unverified whether that config is otherwise reachable.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Is this addressed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Reply from Claude (AI agent), on behalf of the PR author]

(Re: "Is this addressed?") Partly before (a runtime assert that TP divides the step); now fully: the engine raises at build for Dist-MoE with TP > 1 and EP 1 ("set expert_parallel_degree > 1 or tensor_parallel_degree = 1"). Dist-MoE shards a step's tokens over TP, and the engine pads steps to a multiple of TP only with EP, so that combination would fail at the first odd-sized step. The README's MoE section says so. The vLLM engine has the same gap (it pads only with EP too); not changed here.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging (PR description, SGLang issue link in the triton TODO): review (see the Reviews tab of #5815).

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The amended commit fixes the inaccurate padding comment. It also answers the earlier question about CUDA-graph padding rows, since Dist-MoE now masks those rows too. What remains is the PR description and one TODO link.

What changed since the last review (9ab4463 -> 845d5ce). Under Dist-MoE, _DecoderBody now builds padding_mask from forward_batch.out_cache_loc == 0. It then pads that mask with True for the TP-multiple padding rows. The mask now covers both the rows the body adds and the rows SGLang adds to fill a CUDA graph's batch size, because both write their KV to padding slot 0. With the stock dispatchers, padding_mask is now None.

Example. Decode, TP 2 / EP 2, 5 running requests, replayed in the 8-row graph:

out_cache_loc = [s0..s4, 0, 0, 0]       # SGLang pads to the graph size with slot 0
before: padding_mask = [0]*8            # rows 5-7 routed to experts
after:  padding_mask = [0]*5 + [1]*3    # Dist-MoE routes rows 5-7 to no expert

Earlier items

  • Resolved: the model_wrapper.py comment now says that only Dist-MoE masks padding rows.
  • Resolved: the question about unmasked CUDA-graph padding rows piling onto one EP rank. Under Dist-MoE those rows are now masked.
  • Still open: sglang/engine.py:208. The triton.next_power_of_2 monkeypatch TODO still has no SGLang issue link (CLAUDE.md principle 3).
  • Still open (should consider): sglang/model_wrapper.py:614. With Dist-MoE, EP 1 and TP > 1, token_multiple is 1, but Dist-MoE splits tokens over cp * tp (dist_moe/runtime.py:311). The floor division can then give a wrong count, and the unrounded max_num_tokens_per_step can raise "must divide evenly". Raising at engine build for that combination would make it fail clearly.

Must fix

  1. PR description. "Summary (human-written)" is still empty, and the author needs to fill it in. Two other parts are stale or inaccurate at HEAD:
    • "What changed" says the body "masks the padding out of the MoE dispatch". At HEAD, that is true only for Dist-MoE.
    • "Known issues" says the rows SGLang pads a CUDA-graph batch with run through the experts, with a TODO. The code now masks them under Dist-MoE, and that TODO is gone. The issue remains only for the all-to-all dispatcher, which runs without CUDA graphs anyway, so the entry can be deleted.
  2. sglang/engine.py:208: link the SGLang issue in the TODO (still open, see above).
Details
  • The new mask relies on two SGLang behaviors. First, KV slot 0 is reserved for padding, so a real row never gets it. Second, the CUDA graph runner zero-fills out_cache_loc for padded rows. The mask is built on the device from a tensor SGLang updates before each replay, so it stays correct across graph replays with no host sync.
  • F.pad(out_cache_loc == 0, (0, num_padding)) assumes out_cache_loc has as many rows as input_ids before padding. The attention change (q_THK[:out_cache_loc.shape[0]]) assumes the same thing. Under breakable prefill graphs, a mismatch would be a shape error, not a silent bug. The Dist-MoE class runs decode_and_prefill and passes per the PR.
  • The stock-dispatcher path drops padding_mask. The generator never reads the router's load-balancing statistics, so this changes nothing.

Not verified (no SGLang or GPU here): that slot 0 is reserved and out_cache_loc is zero-filled in the pinned SGLang, and that out_cache_loc has as many rows as input_ids under prefill graphs.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items before merging (human-written summary in the PR description, and an SGLang issue link in the triton TODO): review (see the Reviews tab of #5815). Correction: the review gives two wrong line numbers. The triton TODO is at sglang/engine.py:208, not :520, and the new assert is at sglang/model_wrapper.py:191, not :617.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The new commit makes the Dist-MoE token-count path fail loudly, and the description now matches the code. Two items are still open: the human-written summary and the upstream link in the triton TODO.

What changed since the last review (845d5ce -> 545f725). _DecoderBody.forward now asserts that input_ids.shape[0] % tp == 0 before it calls set_num_local_input_tokens_per_call. The padding-mask comment now names the two SGLang internals the mask relies on: KV slot 0 is never allocated, and graph buffers zero-fill out_cache_loc. The PR description's "What changed" and "Known issues" sections are updated.

Example. Dist-MoE with EP 1 and TP 2, which was the earlier should-consider case:

token_multiple = expert_sequence_parallel_size = 1   # no padding to a multiple of TP
1-token decode step:
  before: set_num_local_input_tokens_per_call(1 // 2 = 0) -> obscure error inside the runtime
  after:  AssertionError "TP=2 does not divide 1 tokens"  (at capture or in the first step)

If chunked_prefill_size + max_running_requests is odd, the runtime build fails even earlier, with "must divide evenly". Either way the config fails clearly.

Earlier items

  • Resolved: Dist-MoE with EP 1 and TP > 1 no longer floors the per-call count silently (sglang/model_wrapper.py:617).
  • Resolved: the description's padding-mask wording, and the stale "Known issues" entry about CUDA-graph padding rows.
  • Still open: sglang/engine.py:520. The triton.next_power_of_2 monkeypatch TODO still has no SGLang issue link (CLAUDE.md principle 3).

Must fix

  1. PR description: the author still needs to fill in "Summary (human-written)".
  2. sglang/engine.py:520: link the SGLang issue in the TODO (still open, see above).

No new problems in this commit.

Not verified (no SGLang or GPU here): the assert and the runtime-build error for the EP 1 / TP 2 Dist-MoE case.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the item before merging (write the "Summary (human-written)" section of the PR description; the SGLang issue link in the triton TODO is now resolved): review (see the Reviews tab of #5815).

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. The new commit adds the SGLang issue link to the triton TODO. The only open item is the human-written summary.

What changed since the last review (545f725 -> 943f378). The triton.next_power_of_2 TODO in sglang/engine.py:520 now links sgl-project/sglang#48460. The rest of the diff is the same as before.

Example. Since the code didn't change, this is the reviewed path again. Decode, TP 2 / EP 2, Dist-MoE, 5 running requests replayed in the 8-row graph:

out_cache_loc = [s0..s4, 0, 0, 0]       # SGLang pads to the graph size with slot 0
padding_mask  = [0]*5 + [1]*3           # rows 5-7 routed to no expert
set_num_local_input_tokens_per_call(8 // 2 = 4)
body returns hidden_states[:5]

Earlier items

  • Resolved: sglang/engine.py:520. The monkeypatch TODO now links the upstream SGLang issue (CLAUDE.md principle 3).
  • Resolved earlier: the padding-mask comment and description wording, the stale "Known issues" entry, and the Dist-MoE EP 1 / TP > 1 assert (sglang/model_wrapper.py:618).

Must fix

  1. PR description: "Summary (human-written)" still holds only the template placeholder. The author needs to write it, not an agent.

No new problems in this commit.

Not verified: GPU runs (no SGLang or GPU here).

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the item before merging (write the "Summary (human-written)" section of the PR description; the code is unchanged since the last review and has no new problems): review (see the Reviews tab of #5815).

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. The code at HEAD is unchanged from what I approved last time, and I found no new problems. The only open item is still the human-written summary.

What changed since the last review (943f378 -> 84ffd91). This was a force-push. I couldn't fetch 943f378 to diff the two commits directly, so I re-read the full diff at HEAD instead. Every part reviewed earlier is still in place:

  • the TP-multiple padding and the out_cache_loc == 0 padding mask in _DecoderBody
  • the assert before set_num_local_input_tokens_per_call (sglang/model_wrapper.py:618)
  • attention running only on the scheduled rows
  • the dispatcher and CUDA-graph checks
  • the linked triton TODO (sglang/engine.py:520)
  • the shared build_dist_moe_runtime

Example. Same path as before. Decode, TP 2 / EP 2, Dist-MoE, 5 running requests replayed in the 8-row graph:

out_cache_loc = [s0..s4, 0, 0, 0]       # SGLang pads to the graph size with slot 0
padding_mask  = [0]*5 + [1]*3           # rows 5-7 routed to no expert
set_num_local_input_tokens_per_call(8 // 2 = 4)
body returns hidden_states[:5]

Earlier items

  • Resolved earlier: the triton TODO's upstream link, the padding-mask comment and description wording, and the assert for Dist-MoE with EP 1 / TP > 1.

Must fix

  1. PR description: "Summary (human-written)" still holds only the template placeholder. The author needs to write it, not an agent.

Not verified: GPU runs (no SGLang or GPU here).

@tianyu-l

tianyu-l commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] @claude review again. The description is updated for your must-fix items (file paths and design now match the code); the stack is also rebased onto latest main.

@claude

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the item before merging (write the "Summary (human-written)" section; the description fixes resolve both earlier stale items, and the code is unchanged in substance after the rebase): review (see the Reviews tab of #5815).

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the item below before merging. The description fixes resolve both stale items from the last review. The code at HEAD matches what I approved before. The only item left is the human-written summary.

What changed since the last review (16514f2 -> 06d386e). This was a rebase onto latest main. I couldn't fetch 16514f2 to diff the two commits, so I re-read the full diff at HEAD instead. The logic is the same as the version I approved:

  • the TP-multiple padding and the out_cache_loc == 0 padding mask in _DecoderBody
  • the assert before set_num_local_input_tokens_per_call
  • attention runs on the scheduled rows only
  • the dispatcher and CUDA-graph checks
  • the build-time raise for Dist-MoE with EP 1 and TP > 1 (sglang/engine.py:569-578)
  • the linked triton TODO (sglang/engine.py:586)
  • the shared build_dist_moe_runtime in torchtitan/rl/generator/model.py

registry.py only passes dist_moe_runtime through to SGLangModelWrapper.

Example. Same path as before. Decode, TP 2 / EP 2, Dist-MoE, 5 running requests replayed in the 8-row graph:

out_cache_loc = [s0..s4, 0, 0, 0]       # SGLang pads to the graph size with slot 0
padding_mask  = [0]*5 + [1]*3           # rows 5-7 routed to no expert
set_num_local_input_tokens_per_call(8 // 2 = 4)
body returns hidden_states[:5]

Earlier items

  • Resolved: the description's "What changed" now places build_dist_moe_runtime in generator/model.py.
  • Resolved: the description now lists the Dist-MoE EP 1 / TP > 1 raise, both in "What changed" and in the user-facing table.
  • Still open: "Summary (human-written)".

Must fix

  1. PR description: "Summary (human-written)" still holds only the template placeholder. The author has to write it, not an agent.

Should consider

  • Commit message: the body still says inference_model.build_dist_moe_runtime. The function is now in torchtitan/rl/generator/model.py. If the commit message becomes the merge message, update it.

No new problems at HEAD.

Not verified: GPU runs after the rebase (no SGLang or GPU here).

@tianyu-l
tianyu-l force-pushed the sglang-3-moe branch 2 times, most recently from 7b5877a to 741aec6 Compare November 9, 2026 07:22
@felipemello1

Copy link
Copy Markdown
Contributor

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

One decode step of 5 requests at TP 2 / EP 2: the model wrapper pads 5 rows to 6 so the MoE splits them 3 + 3 over the TP ranks and attention skips the padding row; with Dist-MoE under CUDA graphs, SGLang's graph padding rows are masked out of the experts.

Comment on lines +177 to +182
if not isinstance(dispatcher, AllToAllTokenDispatcher.Config):
raise ValueError(
f"{fqn}: the SGLang engine supports the all-to-all token "
f"dispatcher and Dist-MoE only, got "
f"{type(dispatcher).__qualname__}"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

the check here seems to be for all-to-all only. Is this also checking distmoe?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[From Claude (AI agent), on behalf of @tianyu-l] Dist-MoE passes on purpose: its routed experts have no token dispatcher config, so this loop sees only the stock dispatchers, and Dist-MoE runs under CUDA graphs. Added a comment saying so (350bcb8); #5959 moves the loop into the shared validate_ep_token_dispatchers with the same comment.

Comment on lines +185 to +187
padding_mask = F.pad(
forward_batch.out_cache_loc == 0, (0, num_padding), value=True
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

noob question: does this make the last rank severely unbalanced. I wonder if theres a mitigation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[From Claude (AI agent), on behalf of @tianyu-l] No. The step padding is at most TP - 1 rows, and every rank passes the same row count (T / TP). With Dist-MoE, the padding rows (and the rows SGLang adds to reach a CUDA graph's size) are masked and routed to no expert, so they cost no dispatch or expert work. Expert compute follows the routing, not which rank a token came from.

Comment on lines +249 to +251
max_num_tokens_per_step = (
schedule.chunked_prefill_size + schedule.max_running_requests
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this should be ~16k. At least this works well with vllm. See #5952

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[From Claude (AI agent), on behalf of @tianyu-l] It already is on GB300/B200: the engine sets chunked_prefill_size only when max_num_batched_tokens is given, and otherwise SGLang picks it by GPU memory, 16384 on GPUs with at least 160 GB (8192 on H100/H200; _handle_gpu_memory_settings). That is the table #5952 copies from vllm serve, so the buffer here is 16384 + max_running_requests.

@felipemello1 felipemello1 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

User server args can pass this PR's all-to-all check and go past its Dist-MoE buffer.

No inline comments on this PR. Two points from the #5812 comment on engine.py:70-94 apply here.

A graph-mode alias = a key in extra_server_args that changes the graph mode, such as cuda_graph_backend_decode.

  1. The all-to-all check reads config.cuda_graph (engine.py:183). A graph-mode alias in extra_server_args passes it.
  2. The Dist-MoE buffer is sized for chunked_prefill_size + max_running_requests (model_wrapper.py:249-250).
    • That covers live steps and SGLang's default capture sizes.
    • An explicit cuda_graph_bs_prefill list can go past it at capture.
    • This answers claude[bot]'s open question here from 2026-11-04.

Comment on lines +189 to +198
if (
parallelism.expert_parallel_degree == 1
and parallelism.tensor_parallel_degree > 1
and next(model.traverse(DistMoeRoutedExperts.Config), None) is not None
):
raise ValueError(
"Dist-MoE splits each step's tokens over the TP ranks, and SGLangEngine "
"pads steps to a multiple of TP only with expert parallelism: set "
"expert_parallel_degree > 1 or tensor_parallel_degree = 1"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this check seems unnecessary as decode init already checks

  if moe_configs and ep < tp:
      raise ValueError(
          f"MoE models require expert parallel degree ({ep}) to be "
          f"greater than or equal to tensor parallel degree ({tp})."
      )

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[From Claude (AI agent), on behalf of @tianyu-l] Agreed. Decoder raises for any MoE model with EP below TP, and that covers Dist-MoE. Removed the engine's check in 350bcb8.

# The attention layers read forward_batch from SGLang's context variable too.
num_tokens = input_ids.shape[0]
num_padding = -num_tokens % self._token_multiple
if num_padding:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can we do the padding outside similar to vllm

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[From Claude (AI agent), on behalf of @tianyu-l] SGLang has no hook for this, unlike vLLM: the vLLM engine pads in TorchTitanGPUModelRunner._pad_for_sequence_parallelism, a vLLM model-runner method. SGLang pads a step to the TP size only in its DP-attention path (ForwardBatch.prepare_mlp_sync_batch), which this engine does not use. Padding outside would mean overriding more private SGLang model-runner code. Padding in the wrapper also keeps attention and the KV writes on the scheduled rows only.

pp_schedule=None,
max_num_tokens_per_step=max_num_batched_tokens,
)
if self._dist_moe_runtime is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

is this necessary?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[From Claude (AI agent), on behalf of @tianyu-l] It keeps _num_valid_tokens None for models without Dist-MoE, which set_num_valid_tokens and forward check. That matches main's early return. It now reads as an if block instead of a return (350bcb8).

@tianyu-l

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] On the automated review body:

  1. A graph-mode key in extra_server_args getting past the all-to-all check: fixed in [rl] generator: SGLang generation engine #5812 (5c1767d). Every key containing cuda_graph is rejected.
  2. An explicit cuda_graph_bs_prefill past the Dist-MoE buffer: rejected by the same rule. SGLang's default capture sizes stay within chunked_prefill_size + max_running_requests, which the buffer is sized for. Before the rule, an overflow raised at capture from set_num_local_input_tokens_per_call, not silently.
    Jessica's EP 1 / TP > 1 point is in 350bcb8: the engine's own check is gone, because Decoder raises for it.

@tianyu-l
tianyu-l removed this pull request from stack #5964 November 10, 2026 06:41
@tianyu-l
tianyu-l added this pull request to stack #6002 November 10, 2026 06:41
MoE models run in the SGLang engine with EP over the TP group, with the
all-to-all token dispatcher (cuda_graph="none" only: it reads its split
sizes on the host; the engine raises otherwise) or Dist-MoE (under decode
and breakable prefill CUDA graphs). Other EP token dispatchers raise.

- model_wrapper.py: _DecoderBody pads each step to a multiple of the TP
  degree, as the MoE shards tokens over TP. With Dist-MoE, it masks the
  padding rows (its own, and those padding a batch to a CUDA graph's
  size, which write to SGLang's padding KV slot 0) out of the dispatch,
  and sets the per-call token count. Dist-MoE is
  sized from SGLang's chunked_prefill_size + max_running_requests.
- attention.py: attention skips the padding rows.
- engine.py: restores triton.next_power_of_2, which importing SGLang
  replaces 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 and
  shared by both engines (mechanical, apart from the error message naming
  Generator.Config.dist_moe_runtime).
- test_sglang_bitwise_parity.py: Qwen3 MoE debug at TP 2 / EP 2, with the
  all-to-all dispatcher and with Dist-MoE.
- Drop the engine's Dist-MoE check for EP 1 with TP > 1: Decoder already
  raises for any MoE model whose EP degree is below its TP degree.
- Comment that Dist-MoE experts have no token dispatcher, so the dispatcher
  check sees only the stock ones.
- vLLM wrapper: build the real-token-count buffer in an if block instead of
  an early return.
@tianyu-l
tianyu-l merged commit 41856d9 into main Nov 10, 2026
tianyu-l added a commit that referenced this pull request Nov 10, 2026
Stacked on #5815 (SGLang MoE).

## 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` accepts full attention only, so models with
sliding-window layers
(Muse Glimmer) can't use it. SGLang's `RadixAttention` already takes a
window and
its FlashAttention backend passes it to the kernel, so the adapter only
needs to
translate the window convention.

**Example.**
```
TorchTitan window W = 128 (keys in [q - 127, q])  ->  FlashAttention window_size=(127, 0)
SGLang RadixAttention(sliding_window_size=127)     ->  the same (127, 0)
W = 1: SGLang reads 0 as "no window"               ->  raises at config time
```

## What changed
- `sglang/attention/attention.py`:
`SGLangInnerAttention.Config.sliding_window_size`, passed
  to `RadixAttention` as `W - 1`; `W == 1` raises in `__post_init__`.
- `sglang/model_wrapper.py`: accepts
`SlidingWindowVarlenInnerAttention`; raises
  for GPT-OSS attention, whose sinks the engine doesn't apply (TODO).
- Test: a generic debug-model config helper and a Muse Glimmer parity
class.
- CI: the B200 SGLang step also runs
`TestSGLangBitwiseParitySlidingWindow`.
- Review fix (a5b3b24): the sliding-window KV pool TODO names the two
HF config
keys (`sliding_window`, a mixed `layer_types`) that turn SGLang's pool
on.

## User-facing changes
| Before | After |
| --- | --- |
| sliding-window layers raise | supported (KV of every token stays
cached: SGLang's sliding-window KV pool is not used) |
| GPT-OSS: raised as non-varlen inner attention | raises naming
attention sinks |

## Numerics
| Check | Hardware | Result |
| --- | --- | --- |
| `TestSGLangBitwiseParitySlidingWindow` (Muse Glimmer debug, TP 2,
128-token windows, prompts of 60-150 tokens + 50 generated) | 2x GB300 |
3 passed, max delta 0; with the window off by one, delta 2.72 |

## Testing
- The class above.
- `pytest tests/rl/unit_tests/cpu`: 546 passed.

## Known issues / follow-ups
- SGLang's sliding-window KV pool (which frees KV outside the window) is
not used.
tianyu-l added a commit that referenced this pull request Nov 10, 2026
…ed dispatcher checks (#5959)

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

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

Integrate sglang with deepep and hybrided

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

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

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

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

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

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

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

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

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

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

## Known issues / follow-ups
- DeepEP's deterministic dispatch cannot run in CUDA graphs (DeepEP
limitation, deepseek-ai/DeepEP#820).
- The trainer's HybridEP dispatch raises TMA alignment errors for token
counts per
rank that miss the alignment (small test sequences); training
microbatches are
  packed to aligned sizes.
- A CI job for DeepEP / HybridEP generators needs DeepEP builds in the
RL and SGLang
  environments.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants