Skip to content

[rl] generator: DeepEP and HybridEP token dispatchers on SGLang; shared dispatcher checks - #5959

Merged
tianyu-l merged 3 commits into
sglang-9-stagger-shared-promptsfrom
sglang-10-deepep
Nov 10, 2026
Merged

tianyu-l merged 3 commits into
sglang-9-stagger-shared-promptsfrom
sglang-10-deepep

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

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

Summary (human-written)

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.

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 [rl] generator: SGLang generation engine #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

@tianyu-l
tianyu-l requested a review from fegin as a code owner November 8, 2026 22:45
@tianyu-l tianyu-l added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 8, 2026
@tianyu-l tianyu-l added ciflow/rl ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 8, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 8, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 8, 2026 22:45
@tianyu-l
tianyu-l force-pushed the sglang-10-deepep branch 2 times, most recently from a2c654b to d3a5165 Compare November 8, 2026 22:58
@tianyu-l
tianyu-l added this pull request to stack #5813 November 8, 2026 22:58
@tianyu-l tianyu-l changed the title [rl] generator: SGLang DeepEP and HybridEP token dispatchers [rl] generator: DeepEP and HybridEP token dispatchers on SGLang; shared dispatcher checks Nov 8, 2026
@tianyu-l

tianyu-l commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, with two small items to address before merging -- review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The shared checks replace SGLang's blanket rejection of DeepEP and HybridEP. They also replace vLLM's lack of any check with build-time ValueErrors, and the RL recipes that use EP still pass. A maintainer still needs to review.

What this PR does. generator/model.py gets two engine-agnostic checks:

  • validate_ep_token_dispatchers runs at engine build. Under CUDA graphs it rejects dispatchers that read split sizes on the host, and DeepEP in deterministic mode. It also rejects HybridEP when the EP degree is not divisible by 4.
  • validate_ep_token_dispatcher_capacity runs in the model wrappers. It rejects a DeepEP/HybridEP num_max_tokens_per_rank below the per-EP-rank token bound of one engine step.

SGLang's all-to-all-only loop is deleted in favor of the first check, so SGLang now runs DeepEP and HybridEP.

Example. search_r1's generator (vLLM, TP 4 / EP 4, max_num_batched_tokens=2048, DeepEP cuda_graph_compatible=True, num_max_tokens_per_rank=2048 // 4 = 512):

bound = ceil(2048 / 4) * 4 // 4 = 512   -> passes (512 >= 512)
num_max_tokens_per_rank=256             -> before: assert at the first 2048-token step
                                           after:  ValueError while the vLLM model wrapper builds
same config on SGLang                   -> before: ValueError "supports the all-to-all ... only"
                                           after:  runs under CUDA graphs

Must fix

  1. PR description: the "Summary (human-written)" section is empty. The author needs to fill it in.
  2. torchtitan/rl/generator/model.py:313: the DeepEP determinism TODO has no upstream issue link (inline).

Should consider

  • torchtitan/rl/generator/sglang/README.md "Environment" section: neither scripts/install_rl_env.sh nor scripts/install_sglang.sh installs DeepEP or HybridEP. The PR body also notes that the SGLang venv's own DeepEP wheel fails an NCCL version assert against torch. One line pointing SGLang users to .github/scripts/install_deepep_v2.sh / .ci/docker/common/install_deepep.sh would save the next user the debugging. Without it, the newly "supported" path can't be reproduced from the docs.

Questions

  • torchtitan/rl/generator/model.py:323: should the generator ban a HybridEP non_blocking_capacity_factor below 1.0? Below 1.0, tokens are dropped silently (inline).
Details
  • Placement: both checks are engine-agnostic and sit next to build_dist_moe_runtime in rl/generator/model.py. Core and models/common/ are untouched, which is the right layer, since only the generator has variable per-step token counts plus CUDA graphs.
  • Dist-MoE: DistMoeRoutedExperts configs are not BaseEPTokenDispatcher.Configs, so the traversal skips them, and Dist-MoE under CUDA graphs keeps working on both engines. This is the same traversal SGLang already used.
  • Capacity bounds: SGLang's bound reuses the padded chunked_prefill_size + max_running_requests that already sizes Dist-MoE. vLLM's padded max_num_batched_tokens is an upper bound on every step, because capture sizes are capped at it and filtered to TP multiples (vllm/config.py). With DP > 1, replicas pad to the largest count across replicas, which is still within the bound.
  • Determinism: Generator._set_determinism sets torch.use_deterministic_algorithms in-process, and the SGLang scheduler runs in-process. So DebugConfig.deterministic is exactly what makes DeepEPTokenDispatcher.init_buffer build a deterministic buffer, and the check matches the runtime condition. Activation remat doesn't run in the generator.
  • The HybridEP comment talks about "the ranks in its node", but the check uses the EP degree. The two agree when EP sits within one node, or spans nodes whose GPU count is a multiple of 4, which covers every current recipe.
  • No new unit test: the checks fail loudly at build, so there's no silent invariant to guard.

Not verified: the DeepEP deterministic_sort capture failure and the HybridEP TMA-alignment rule (both need GPUs and the DeepEP/HybridEP builds).

Comment thread torchtitan/rl/generator/model.py Outdated
Comment on lines +313 to +315
# TODO: DeepEP's deterministic dispatch sorts the received tokens with
# data-dependent shapes (ElasticBuffer's deterministic_sort), which CUDA
# graphs cannot capture.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This TODO waits on an upstream DeepEP gap (the deterministic sort's data-dependent shapes), but it has no issue link. Without one, nobody can tell when the ban can be lifted. Please file or link a DeepEP issue here, e.g. # TODO(<deepep issue URL>): ..., as CLAUDE.md asks for upstream workarounds.

"the engine's CUDA graphs"
)
elif isinstance(dispatcher, HybridEPTokenDispatcher.Config):
syncs_host = dispatcher.non_blocking_capacity_factor 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.

Question: per HybridEPTokenDispatcher.Config's docstring, a non_blocking_capacity_factor below 1.0 drops tokens past the fused-permute capacity silently, and only a GPU overflow_flag records it. In training, forced load balancing keeps this rare. The generator's routing has no aux loss pushing it toward balance, though, and a drop silently changes the sampled tokens and the trainer-vs-generator logprob match. Should the generator require non_blocking_capacity_factor == 1.0 here, or is a lossy generator an intended setting? Not verified on GPU.

@tianyu-l

tianyu-l commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] @claude review again. New in a7bf976: HybridEP non_blocking_capacity_factor < 1.0 now raises in the generator (answering your question: below 1.0 HybridEP drops tokens silently), and the SGLang README points to the DeepEP/HybridEP install scripts.

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve, but two items from the last review are still open: the empty human-written summary and the DeepEP TODO with no issue link. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. a7bf976 answers the HybridEP question and the README item from the last review. Both earlier must-fix items are still open, and the new commit adds no new problems. A maintainer still needs to review.

What changed since the last review.

  • validate_ep_token_dispatchers (torchtitan/rl/generator/model.py:322-335) now raises when HybridEP's non_blocking_capacity_factor is below 1.0. This matches _num_permuted_tokens_for_non_blocking in torchtitan/distributed/deepep/hybridep.py: 1.0 sizes the permute buffer for the worst case (num_tokens * ep_size * min(num_local_experts, top_k)), and anything smaller can drop tokens without an error.
  • sglang/README.md now says that neither install script installs DeepEP or HybridEP, and points to .github/scripts/install_deepep_v2.sh and .ci/docker/common/install_deepep.sh. Both scripts exist at HEAD.

Example.

HybridEPTokenDispatcher.Config(non_blocking_capacity_factor=0.5), EP 4, any engine
  before a7bf976e4: runs, and skewed routing drops tokens silently (sampled tokens change)
  after:            ValueError at engine build "... below 1.0 drops tokens in the generator"
non_blocking_capacity_factor=1.0 -> passes (worst-case buffer, no drops)

Resolved since the last review

  • Question: HybridEP non_blocking_capacity_factor < 1.0 in the generator. It now raises.
  • Should consider: the SGLang README now points to the DeepEP/HybridEP install scripts.

Must fix (still open)

  1. PR description: the "Summary (human-written)" section is still the empty template. The author needs to write it.
  2. torchtitan/rl/generator/model.py:313: the DeepEP deterministic-dispatch TODO still has no upstream issue link (see the earlier inline comment).

Not verified: the HybridEP drop behavior below 1.0 on GPU. The reasoning above comes from the buffer-sizing code only.

@tianyu-l

tianyu-l commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] @claude review again. cbcd584 links the DeepEP deterministic-dispatch TODO to deepseek-ai/DeepEP#820. The human-written summary is still pending from the author.

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve: both earlier must-fix items are resolved (the DeepEP TODO now links deepseek-ai/DeepEP#820, and the human-written summary is filled in). See the review.

@tianyu-l
tianyu-l force-pushed the sglang-10-deepep branch 2 times, most recently from d1e0f07 to 9ed452f Compare November 9, 2026 05:06
@tianyu-l
tianyu-l force-pushed the sglang-10-deepep branch 2 times, most recently from 5d7e568 to 3ec8f03 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 3ec8f03a6.

Bad EP token dispatcher configs used to fail at CUDA graph capture, mid-generation or silently on vLLM, and SGLang raised for any DeepEP or HybridEP use; now both engines raise ValueError at build, and DeepEP and HybridEP run on SGLang.

@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 get past the new capacity check and the shared validator.

No inline comments. Two gaps that the #5812 comment on engine.py:70-94 covers.

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

  1. Explicit capture sizes can exceed the bound the capacity check uses.
    • The new capacity check (model_wrapper.py:333-339) uses the live bound: chunked_prefill_size + max_running_requests.
    • SGLang's default capture sizes stay within it (memory_hook.py:235-238, cuda_graph_hook.py:529 at the pinned SGLang commit).
    • An explicit cuda_graph_bs_prefill or cuda_graph_max_bs_prefill is kept as given (memory_hook.py:267).
    • It can exceed the bound at capture, where DeepEP asserts (deepep.py:536 on main).
  2. A graph-mode alias passes the shared validator.
    • The shared validator reads config.cuda_graph (engine.py:196).
    • DeepEP's deterministic-mode guard (model.py:316) reads that same value.
    • A graph-mode alias in extra_server_args passes both.

@tianyu-l

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] On the automated review body: both gaps are closed by #5812 (5c1767d), which rejects every extra_server_args key containing cuda_graph. That covers explicit capture sizes such as cuda_graph_bs_prefill and cuda_graph_max_bs_prefill, and graph-mode keys such as cuda_graph_backend_decode. The capacity check and the shared validator therefore see SGLang's default capture sizes and the real graph mode. bef887c updates the comment and notes in the shared validator that Dist-MoE experts have no token dispatcher.

@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
Comment on lines +125 to +126
`.ci/docker/common/install_deepep.sh` (HybridEP) do. SGLang's own DeepEP wheel
fails its NCCL version check under the PyTorch nightly. Dist-MoE

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should we raise an issue? not p0 though

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[From Claude (AI agent), on behalf of @tianyu-l] I don't think an upstream issue would lead anywhere. SGLang's DeepEP wheel is built against the PyTorch (and NCCL) SGLang pins, and the check fails only because torchtitan runs the PyTorch nightly, which SGLang doesn't support. Building DeepEP against the environment's PyTorch, as CI does, is the fix on our side.

max_num_tokens_per_step = (
schedule.chunked_prefill_size + schedule.max_running_requests
num_tokens = schedule.chunked_prefill_size + schedule.max_running_requests
max_num_tokens_per_step = -(-num_tokens // token_multiple) * token_multiple

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why the minus?

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 was ceiling division: -(-a // b) rounds up. 761b7d7 uses torchtitan.tools.utils.round_up instead.

…ed dispatcher checks

SGLangEngine accepted only the all-to-all token dispatcher and Dist-MoE. It now
also accepts DeepEP and HybridEP, as VLLMEngine does. DeepEP with
cuda_graph_compatible and HybridEP with non_blocking_capacity_factor dispatch
without a host sync, so they run under CUDA graphs.

Both engines now run the same checks (generator/model.py), which VLLMEngine
lacked:
- validate_ep_token_dispatchers, at engine build: a host-synced dispatcher
  (all-to-all, DeepEP without cuda_graph_compatible, HybridEP without
  non_blocking_capacity_factor) under CUDA graphs raises, as does DeepEP's
  deterministic dispatch (DebugConfig.deterministic), whose receive sort has
  data-dependent shapes; HybridEP needs an EP degree divisible by 4, since 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.
- validate_ep_token_dispatcher_capacity, in the model wrappers: a DeepEP or
  HybridEP num_max_tokens_per_rank below a step's tokens per EP rank raises at
  build, instead of DeepEP asserting at the first large step.
- The shared dispatcher 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, as Dist-MoE does.
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.

2 participants