Repository navigation
[MoE] Add routed-expert output postprocessing - #4623
Merged
Merged
Conversation
sanketpurandare
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
September 12, 2026 01:55
This was referenced Sep 12, 2026
This was referenced Sep 12, 2026
tianyu-l
reviewed
Sep 12, 2026
| topk_expert_ids_TK: torch.Tensor, | ||
| num_local_tokens_per_expert_E: torch.Tensor, | ||
| *, | ||
| expert_output_postprocess: Callable[[torch.Tensor], torch.Tensor] | None = None, |
Contributor
There was a problem hiding this comment.
maybe better to make this a configurable function https://github.com/pytorch/torchtitan/blob/main/torchtitan/config/function.py in RoutedExperts.Config
Contributor
Author
There was a problem hiding this comment.
Added expert_output_postprocess to RoutedExperts.Config as an owned Module.Config, rather than a function, because implementations such as RMSNorm may own learnable state. It runs after W2 and before combine; DistMoE accepts only modules that translate to an annex-native fused descriptor.
This was referenced Sep 13, 2026
anijain2305
added a commit
that referenced
this pull request
Sep 13, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0) (oldest at bottom): * #4543 * #4542 * #4541 * #4623 * #4559 * #4591 * #4592 * #4540 * #4539 * #4643 * #4526 * #4546 * __->__ #4535 Use one physical w13 Linear config and parameter for dense feed-forward gate and up projections. Compose their initialization before module construction, configure activation implementations directly, and translate external gate/up checkpoint keys in model state-dict adapters.
sanketpurandare
marked this pull request as draft
September 14, 2026 06:47
This was referenced Sep 14, 2026
sanketpurandare
marked this pull request as ready for review
September 14, 2026 17:52
tianyu-l
approved these changes
Sep 26, 2026
| w2: GroupedLinear.Config | ||
| token_dispatcher: LocalTokenDispatcher.Config | ||
| activation_fn: BinaryActivationFn.Config = field(default_factory=SwiGLU.Config) | ||
| expert_output_postprocess: Module.Config | None = None |
Contributor
There was a problem hiding this comment.
Suggested change
| expert_output_postprocess: Module.Config | None = None | |
| output_postprocess: Module.Config | None = None |
since it's not ambiguous?
sanketpurandare
added a commit
that referenced
this pull request
Sep 26, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0) (oldest at bottom): * #4543 * #4542 * #4541 * #4623 * #4559 * #4652 * #4591 * #4592 * __->__ #4540 Summary: Give eager pipeline stages complete static decoder-boundary metadata when the PP process group is fake. This avoids dynamic cross-rank metadata inference while preserving PyTorch's existing `PipelineStage` ownership and supports first, middle, and last decoder stages across context and tensor parallelism. TorchTitan also enables PyTorch's schedule-derived per-edge P2P groups whenever pipeline parallelism is active. Each directed physical edge receives a deterministic communicator FIFO that PyTorch initializes before execution and CUDA-graph capture, avoiding dependency on NCCL first-use ordering. Receive buffers use PyTorch's landed just-in-time allocation. A buffer is allocated immediately before `RECV_F` or `RECV_B`, transferred to the owning forward or backward computation, and released according to tensor lifetime. CUDA-graph capture records stable addresses, so replay does not repeat Python allocation. TorchTitan adds no receive-buffer policy or stage subclass. Test Plan: - `python -m pytest -q tests/unit_tests/cpu/test_no_new_cli_options.py tests/unit_tests/cpu/test_pipeline_parallel.py tests/unit_tests/cpu/test_config_manager.py` (79 passed) - Scoped pre-commit hooks passed for the changed files. - Targeted Pyrefly reported 0 errors for production files. - One-process pure-FakePG PP4 and four-process real-PP/fake-SPMD PP4 each completed 10 steps, captured at step 3, and replayed through step 10.
sanketpurandare
added a commit
that referenced
this pull request
Sep 26, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0) (oldest at bottom): * #4543 * #4542 * #4541 * #4623 * #4559 * #4652 * __->__ #4591 * #4592 Summary: Allow TorchTitan's whole-step CUDA-graph wrapper to capture every pipeline schedule, including Interleaved1F1B, InterleavedZeroBubble, ZBVZeroBubble, and custom runtime schedules loaded from CSV. The pipeline schedule is invoked as one captured callable. During capture, Python executes the complete schedule: `BACKWARD_INPUT` creates the per-microbatch weight-backward runner and `BACKWARD_WEIGHT` consumes it later in that same invocation. Replay launches the resulting CUDA graph directly; it does not re-enter the Python scheduler and therefore does not need to recreate or consume that Python state. The earlier split-backward rejection mistook state needed while constructing the captured graph for state needed during replay. The PyTorch pipeline dependencies already provide the other required runtime contracts. Receive buffers are allocated just in time and their captured addresses are stable on replay. Directed physical pipeline edges use preinitialized process groups, giving NCCL operations a stable communicator and FIFO order during eager warmup, capture, and replay. TorchTitan therefore does not need schedule-specific CUDA-graph policy or another user-facing configuration option. This change removes the InterleavedZeroBubble and ZBVZeroBubble validation gate, switches all three split-backward integration recipes (including the custom CSV schedule) to TorchTitan's existing varlen attention backend, and enables their real-PP integration entries. Varlen uses tensor metadata and therefore composes with split backward; the recipes do not exercise FlexAttention. The change does not alter pipeline actions, split-backward ownership, receive-buffer policy, or PyTorch schedule implementation. Numerical investigation: - A single distributed launch used the same initialized deterministic MLP on each rank, identical inputs, fixed parameters, and stable gradient buffers. For Interleaved1F1B, InterleavedZeroBubble, and ZBVZeroBubble, loss and every local parameter gradient were bitwise equal for all 10 comparisons: two eager warmups, capture at step 3, and seven replays. - The same-state Llama 3 varlen runs produced bitwise-equal loss for all 10 comparisons on all three schedules. Small raw-gradient differences also occurred during the eager warmups, with the Interleaved1F1B control, and in non-pipeline SDC replay. The largest observed differences were `3.8147e-06` for the PP4 runs and `7.62939e-06` for PP2 ZBV. This isolates the difference to varlen backward repeatability rather than random model initialization, split backward, or CUDA-graph replay. - FlexAttention is not used by these split-backward recipes. Compiled FlexAttention independently rejects split backward's `retain_graph=True`, while its uncompiled math path is not CUDA-graph capturable; neither issue is introduced or hidden by this change. Test Plan: - `python -m pytest -q tests/unit_tests/cpu/test_config_manager.py` (49 passed) - `python -m pytest -q tests/unit_tests/cpu/test_integration_test_definitions.py` (15 passed) - Four-GPU same-state Interleaved1F1B deterministic MLP: exact loss and every local gradient for 10/10 steps. - Four-GPU same-state InterleavedZeroBubble deterministic MLP: exact loss and every local gradient for 10/10 steps. - Two-GPU same-state ZBVZeroBubble deterministic MLP: exact loss and every local gradient for 10/10 steps. - Four-GPU Llama 3 varlen Interleaved1F1B and InterleavedZeroBubble, and two-GPU Llama 3 varlen ZBVZeroBubble: capture at step 3 and replay through step 10; loss was bitwise equal for 10/10 same-state comparisons. - Two-GPU Llama 3 varlen custom CSV split-backward schedule completed 10 steps, with capture at step 3 and replay through step 10. - Non-pipeline Llama 3 varlen SDC replay reproduced the raw-gradient nondeterminism at step 1; the existing deterministic FlexAttention SDC control completed successfully.
sanketpurandare
added a commit
that referenced
this pull request
Sep 26, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0) (oldest at bottom): * #4543 * #4542 * #4541 * #4623 * #4559 * __->__ #4652 * #4591 * #4592 Summary: Add two explicit debugging backends without pretending fake communication can replace a real distributed run. `comm.backend="fake"` uses one physical process and fake groups for every axis. `NGPU` defines the logical world, `FAKE_PP_RANK` selects the represented PP coordinate, and the logical SPMD coordinate is always zero. `comm.backend="real_pp_fake_spmd"` requires exactly one physical process per PP rank. Physical `RANK` selects the PP coordinate, a real NCCL PP group carries pipeline traffic, and DP, TP, CP, and EP remain fake at SPMD coordinate zero. `FAKE_PP_RANK` is rejected in this mode. Initialization returns a `DistributedTopology` containing the logical world size and an optional `real_pp_group_for_fake_spmd`. The explicit field name prevents this hybrid-only group from being mistaken for the ordinary PP group used by fully real distributed execution. `ParallelDims` replaces only the outermost PP mesh. The deliberately PP-specific contract keeps the implementation small while supporting local debugging of stage metadata, send/receive ownership, whole-step CUDA graphs, and rank-local memory for large logical configurations. Test Plan: - `python -m pytest -q tests/unit_tests/cpu/test_distributed_utils.py tests/unit_tests/cpu/test_parallel_dims.py tests/unit_tests/cpu/test_torchft_trainer.py tests/unit_tests/cpu/test_config_manager.py tests/unit_tests/cpu/test_no_new_cli_options.py tests/unit_tests/cpu/test_integration_test_definitions.py` (114 passed) - Scoped formatting, lint, codespell, and link checks passed. - Targeted Pyrefly reported 0 errors for production files; the broader TorchFT file retains an unrelated existing config-override error. - One-process pure fake and four-process real-PP/fake-SPMD each completed 10 PP4 steps with CUDA-graph replay. - After the topology-field rename, one-process pure fake and two-process real-PP/fake-SPMD PP2 smoke runs completed successfully.
sanketpurandare
added a commit
that referenced
this pull request
Sep 26, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0) (oldest at bottom): * #4543 * #4542 * #4541 * #4623 * __->__ #4559 * #4652 * #4591 * #4592 Summary: Implement eager FullAC through a selective-checkpoint context whose policy prefers recomputation for ordinary operations. PyTorch upgrades cacheable registered effects to `MUST_SAVE`, so effectful model operations execute once while pure tensor operations retain full-recomputation behavior. Non-selective FullAC has no per-operation preservation hook. Reusing PyTorch's selective-checkpoint machinery supplies that hook without duplicating its effect classification. GraphTrainer needs no change here: current TorchTitan already invokes `force_save_effectful_ops()` before graph rematerialization. Test Plan: - `python -m pytest -q tests/unit_tests/gpu/test_activation_checkpoint.py::TestApplyAC::test_full_ac_does_not_recompute_registered_effects` (1 passed) - `python -m pytest -q torchtitan/experiments/graph_trainer/tests/test_passes.py -k effectful_ops_are_saved_and_not_rematerialized` (1 passed) - Scoped pre-commit hooks passed for the changed files. - Targeted Pyrefly reported 0 errors for the production module.
Summary: Let `RoutedExperts.Config` own an optional `output_postprocess` `Module.Config` that transforms each expert output after W2 and before dispatcher combine. The name is unambiguous within `RoutedExperts`, while the module-based contract supports learned route-wise operations such as MS post-expert RMSNorm and keeps their parameters in the module state, checkpoint, optimizer, and FSDP ownership tree. The default remains `None`, so existing models retain the same execution path. Communication-owning expert backends can translate supported modules to their native fused descriptors and reject unsupported modules during conversion. Test Plan: - `python -m pytest -q tests/unit_tests/cpu/test_moe.py` - `pre-commit run --files torchtitan/models/common/moe.py tests/unit_tests/cpu/test_moe.py` ghstack-source-id: a96d6bf Pull Request resolved: #4623
sanketpurandare
force-pushed
the
gh/sanketpurandare/28/head
branch
from
September 26, 2026 18:40
e515bfe to
55b2a3e
Compare
sanketpurandare
changed the base branch from
gh/sanketpurandare/28/base
to
main
September 26, 2026 18:40
fegin
added a commit
that referenced
this pull request
Nov 11, 2026
## Summary (human-written) Muse Spark currently only supports AllToAll and Dist-MoE backends. The former is slow and the latter cannot be used on Hopper. This PR enables HybridEP. The main design decision is how to run `output_postprocess`, which Muse Spark uses to perform RMSNorm after the experts and before combine. With non-blocking HybridEP, the rows past the last expert offset are never written, so `output_postprocess` needs `torch.where` masks around it to keep those rows out of the forward and the gradients. The masks are slow in eager mode, so we use local_compile to fuse them into the RMSNorm kernels. See the performance section. TL;DR: with local_compile and CUDA graphs, we see about 60% higher TPS than AllToAll (note that the AllToAll performance is also improved after #placeholder). ## Why On Hopper, Dist-MoE is not available, so Muse Spark's only EP path is the AllToAll dispatcher. AllToAll syncs the CPU in every MoE layer, so it cannot use CUDA graphs. `MuseSparkMoE.Config` rejects HybridEP, which has no CPU sync in non-blocking mode and supports CUDA graphs. The check was added when the per-expert norm could only run after combine. `output_postprocess` (#4623) now runs it before combine, and HybridEP applies scores after it, so the operation order is right. Allowing HybridEP alone is not enough. Non-blocking HybridEP (`non_blocking_capacity_factor` set) sizes the routed rows to its capacity, not to the received token count. Rows past `offsets_E[-1]` are never written: in forward, the grouped GEMMs only write rows inside the expert offsets, and in backward, HybridEP's combine backward only writes grads for received tokens. So those rows hold stale memory in both directions. `output_postprocess` runs on every row, so its parameter grads sum over those rows. The result is a wrong grad, or NaN when the stale memory is not finite. Muse Spark is the only model that sets `output_postprocess`, so no other model hits this. **Example.** ```python config = muse_spark_debugmodel(seq_len) config = apply_transforms(config, [TokenDispatcherTransform( dispatcher=HybridEPTokenDispatcher, num_max_tokens_per_rank=tokens_per_microbatch // (cp * tp), kwargs={"non_blocking_capacity_factor": 1.0}, )]) # main: ValueError("Muse Spark MoE requires LocalTokenDispatcher or AllToAllTokenDispatcher, ...") # only the check removed: "Loss or gradient norm is not finite" at step 1 # this change: trains ``` The stale rows, at EP2, 64 tokens per rank, top-2, capacity factor 1.0, RMSNorm postprocess: ``` routed rows: 256, valid rows (offsets_E[-1]): 128 rows 128..255: stale inputs (abs max ~30) and nonzero incoming grads (abs max ~14) norm weight grad vs AllToAll: relative error 1.2 and 1.5 (all other grads bitwise equal) ``` ## What changed - Shared MoE (`models/common/moe/moe.py`, please review this first): with non-blocking HybridEP and an `output_postprocess`, `RoutedExperts.forward` calls `_masked_output_postprocess`. It masks rows past `offsets_E[-1]` with `torch.where` before the postprocess (finite forward) and after it (zero grad for those rows). `torch.where` instead of a multiply, so NaN rows are dropped too. The mask is built on the GPU from `offsets_E`, so there is no CPU sync and CUDA graph capture still works. The function is a `local_compile` region (`moe_masked_output_postprocess`), so Inductor fuses both masks into the postprocess kernels. Without the region it runs eagerly with the same math. In training, other dispatchers and blocking HybridEP never produce rows past the last offset, so they skip it. HybridEP `pad_multiple` padding rows are inside the offsets, and HybridEP writes zeros to them in both directions, so they need no mask. Dist-MoE does not use this forward. - Muse Spark enables the `moe_masked_output_postprocess` region in its default `local_compile.regions`. - `MuseSparkMoE.Config` accepts `HybridEPTokenDispatcher`. DeepEP stays rejected because it is untested with Muse Spark. - Add the `muse_spark_debugmodel_hybridep` test recipe with CUDA graphs on, like `deepseek_v3_debugmodel_hybridep`. Capacity factor 1.0 reserves the worst case, so no tokens are dropped. - Integration: add a Muse Spark FSDP2 + TP2 (SP) + EP2 run to the H100 HybridEP test, renamed from `deepseek_v3_fsdp+hybridep` to `fsdp+hybridep` because it covers both models. Mechanical: update the test name in `run_8xgpu_integration_tests.sh`, `validate_release_gpu.sh`, and `test_integration_test_definitions.py`. The last also checks every config of the test, not only the first. - README: list HybridEP as supported (verified with FSDP, TP+EP, and CUDA graphs; CP is not verified), say that on Hopper it is the EP path with CUDA graph support, give its memory cost (about 2x at capacity factor 1.0) and measured speedup, note its BF16 score rounding, and drop MinimalAsyncEP, which was deleted in #4627. ## Alternatives considered - Clean the rows inside HybridEP: only covers backward. The forward stale rows come from w2's grouped GEMM output. Masking in `RoutedExperts` handles both directions in one place. - Mask whenever `output_postprocess` is set: adds the mask cost to Muse Spark with AllToAll, which has no capacity rows. - A dispatcher property such as "may produce rows past the last offset": an interface with one implementer. The check follows the existing `DeepEPDispatchMetadata` branch in the same forward instead. - Reject non-blocking HybridEP with `output_postprocess`: blocking mode syncs the CPU in every MoE layer and cannot use CUDA graphs, which removes most of the reason to use HybridEP on Hopper. ## Numerics No change for other models or for Muse Spark with AllToAll: the mask only runs for non-blocking HybridEP with `output_postprocess`. Compiling the mask region does not change numerics: unfused masks vs the compiled region, `muse_spark_debugmodel_hybridep` on 4x H100, 20 steps, `scripts/loss_compare.py`: loss is bitwise identical at every step, and grad_norm matches. Muse Spark debug model, FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps, `scripts/loss_compare.py`, AllToAll (`muse_spark_debugmodel`) vs HybridEP (`muse_spark_debugmodel_hybridep`): | Step | AllToAll | HybridEP | Diff | | --- | --- | --- | --- | | 1 | 7.782996 | 7.783380 | +0.000383 | | 2 | 6.977194 | 6.979984 | +0.002790 | | 10 | 4.832992 | 4.837770 | +0.004778 | | 20 | 4.407280 | 4.412218 | +0.004938 | Average over 20 steps: 5.233406 vs 5.231284. The differences have no consistent sign. HybridEP rounds the routing scores to BF16 before the combine multiply, while AllToAll multiplies in FP32, and the two combine kernels sum in a different order. The README notes the BF16 rounding. ## Performance Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30. All runs include the fused SwiGLU recompile fix earlier in this stack; without it, AllToAll runs at 2,138 TPS. | Config | TPS | Memory | | --- | --- | --- | | AllToAll | 18,624 | 7.7 GiB | | HybridEP eager, masks unfused | 18,618 | 16.7 GiB | | HybridEP eager, masks compiled | 21,439 (+15%) | 16.7 GiB | | HybridEP CUDA graphs, masks unfused | 24,777 | 16.8 GiB | | HybridEP CUDA graphs, masks compiled | 30,287 (+63%) | 16.8 GiB | - Most of the gain comes from CUDA graphs, which AllToAll cannot use. - Unfused, the masks run over all capacity rows (8x the valid rows at EP8 and top-8), and remat runs them again. Compiling them into the postprocess region removes that cost: +15% eager, +22% with graphs. - The extra memory comes from capacity factor 1.0. A lower factor saves memory but can drop tokens. ## Testing - `test_matches_all_to_all_with_output_postprocess` (new, 2x H100): HybridEP (blocking and non-blocking) vs AllToAll with an RMSNorm postprocess. Compares loss, input grad, and router, W13, W2, and norm weight grads within 2 BF16 eps (normwise). Without the mask it fails with errors of 12.5 and 8.8 vs bounds below 0.87. This is the regression it catches. - The HybridEP activation-checkpointing tests also run with an RMSNorm postprocess, as the DeepEP tests do, so remat replay stays exact around the mask. They run the mask function eagerly; the loss comparison above covers the compiled region. - `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k HybridEP`: 4 passed. - Manual check: the parity test also passes with `pad_multiple=32`, with and without the postprocess. So the per-expert padding rows inside the offsets do not affect gradients. - `python -m tests.integration_tests.run_tests --test_suite h100 --execution_mode real_pg --ngpu 4 --test_name=fsdp+hybridep` (4x H100, HybridEP at the CI pin f725d29), CUDA graphs on: both configs pass and record a CUDA graph. The Muse Spark config (FSDP2 + TP2 + SP + EP2) keeps local compile on, so CI runs the compiled mask region. SPMD type checking would turn it off; Muse Spark TP+SP+EP type checking is covered by `muse_spark_mm_fsdp+tp+cp+ep+sp`. Muse Spark loss goes from about 7.7 to about 4.9-5.2 in 10 steps across three runs. - `pytest tests/unit_tests/cpu/test_integration_test_definitions.py tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py tests/unit_tests/cpu/config`: 263 passed, 3 xfailed. - `pytest tests/unit_tests/cpu -k "moe or expert or dispatcher or local_compile"`: 147 passed, 1 skipped. ## Known issues / follow-ups - CP + EP with HybridEP is not tested. - Multimodal training with CUDA graphs is not supported for Muse Spark with any dispatcher. - The score multiply in HybridEP's combine also runs over all capacity rows. Moving it into a compiled region would change HybridEP's combine, which DeepSeek-V3 also uses, so it is left for a follow-up. stack-info: PR: #6032, branch: fegin/stack/34
fegin
added a commit
that referenced
this pull request
Nov 11, 2026
## Summary (human-written) Muse Spark currently only supports AllToAll and Dist-MoE backends. The former is slow and the latter cannot be used on Hopper. This PR enables HybridEP. The main design decision is how to run `output_postprocess`, which Muse Spark uses to perform RMSNorm after the experts and before combine. With non-blocking HybridEP, the rows past the last expert offset are never written, so `output_postprocess` needs `torch.where` masks around it to keep those rows out of the forward and the gradients. The masks are slow in eager mode, so we use local_compile to fuse them into the RMSNorm kernels. See the performance section. TL;DR: with local_compile and CUDA graphs, we see about 60% higher TPS than AllToAll (note that the AllToAll performance is also improved after #6030). ## Why On Hopper, Dist-MoE is not available, so Muse Spark's only EP path is the AllToAll dispatcher. AllToAll syncs the CPU in every MoE layer, so it cannot use CUDA graphs. `MuseSparkMoE.Config` rejects HybridEP, which has no CPU sync in non-blocking mode and supports CUDA graphs. The check was added when the per-expert norm could only run after combine. `output_postprocess` (#4623) now runs it before combine, and HybridEP applies scores after it, so the operation order is right. Allowing HybridEP alone is not enough. Non-blocking HybridEP (`non_blocking_capacity_factor` set) sizes the routed rows to its capacity, not to the received token count. Rows past `offsets_E[-1]` are never written: in forward, the grouped GEMMs only write rows inside the expert offsets, and in backward, HybridEP's combine backward only writes grads for received tokens. So those rows hold stale memory in both directions. `output_postprocess` runs on every row, so its parameter grads sum over those rows. The result is a wrong grad, or NaN when the stale memory is not finite. Muse Spark is the only model that sets `output_postprocess`, so no other model hits this. **Example.** ```python config = muse_spark_debugmodel(seq_len) config = apply_transforms(config, [TokenDispatcherTransform( dispatcher=HybridEPTokenDispatcher, num_max_tokens_per_rank=tokens_per_microbatch // (cp * tp), kwargs={"non_blocking_capacity_factor": 1.0}, )]) # main: ValueError("Muse Spark MoE requires LocalTokenDispatcher or AllToAllTokenDispatcher, ...") # only the check removed: "Loss or gradient norm is not finite" at step 1 # this change: trains ``` The stale rows, at EP2, 64 tokens per rank, top-2, capacity factor 1.0, RMSNorm postprocess: ``` routed rows: 256, valid rows (offsets_E[-1]): 128 rows 128..255: stale inputs (abs max ~30) and nonzero incoming grads (abs max ~14) norm weight grad vs AllToAll: relative error 1.2 and 1.5 (all other grads bitwise equal) ``` ## What changed - Shared MoE (`models/common/moe/moe.py`, please review this first): with non-blocking HybridEP and an `output_postprocess`, `RoutedExperts.forward` calls `_masked_output_postprocess`. It masks rows past `offsets_E[-1]` with `torch.where` before the postprocess (finite forward) and after it (zero grad for those rows). `torch.where` instead of a multiply, so NaN rows are dropped too. The mask is built on the GPU from `offsets_E`, so there is no CPU sync and CUDA graph capture still works. The function is a `local_compile` region (`moe_masked_output_postprocess`), so Inductor fuses both masks into the postprocess kernels. Without the region it runs eagerly with the same math. In training, other dispatchers and blocking HybridEP never produce rows past the last offset, so they skip it. HybridEP `pad_multiple` padding rows are inside the offsets, and HybridEP writes zeros to them in both directions, so they need no mask. Dist-MoE does not use this forward. - Muse Spark enables the `moe_masked_output_postprocess` region in its default `local_compile.regions`. - `MuseSparkMoE.Config` accepts `HybridEPTokenDispatcher`. DeepEP stays rejected because it is untested with Muse Spark. - Add the `muse_spark_debugmodel_hybridep` test recipe with CUDA graphs on, like `deepseek_v3_debugmodel_hybridep`. Capacity factor 1.0 reserves the worst case, so no tokens are dropped. - Integration: add a Muse Spark FSDP2 + TP2 (SP) + EP2 run to the H100 HybridEP test, renamed from `deepseek_v3_fsdp+hybridep` to `fsdp+hybridep` because it covers both models. Mechanical: update the test name in `run_8xgpu_integration_tests.sh`, `validate_release_gpu.sh`, and `test_integration_test_definitions.py`. The last also checks every config of the test, not only the first. - README: list HybridEP as supported (verified with FSDP, TP+EP, and CUDA graphs; CP is not verified), say that on Hopper it is the EP path with CUDA graph support, give its memory cost (about 2x at capacity factor 1.0) and measured speedup, note its BF16 score rounding, and drop MinimalAsyncEP, which was deleted in #4627. ## Alternatives considered - Clean the rows inside HybridEP: only covers backward. The forward stale rows come from w2's grouped GEMM output. Masking in `RoutedExperts` handles both directions in one place. - Mask whenever `output_postprocess` is set: adds the mask cost to Muse Spark with AllToAll, which has no capacity rows. - A dispatcher property such as "may produce rows past the last offset": an interface with one implementer. The check follows the existing `DeepEPDispatchMetadata` branch in the same forward instead. - Reject non-blocking HybridEP with `output_postprocess`: blocking mode syncs the CPU in every MoE layer and cannot use CUDA graphs, which removes most of the reason to use HybridEP on Hopper. ## Numerics No change for other models or for Muse Spark with AllToAll: the mask only runs for non-blocking HybridEP with `output_postprocess`. Compiling the mask region does not change numerics: unfused masks vs the compiled region, `muse_spark_debugmodel_hybridep` on 4x H100, 20 steps, `scripts/loss_compare.py`: loss is bitwise identical at every step, and grad_norm matches. Muse Spark debug model, FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps, `scripts/loss_compare.py`, AllToAll (`muse_spark_debugmodel`) vs HybridEP (`muse_spark_debugmodel_hybridep`): | Step | AllToAll | HybridEP | Diff | | --- | --- | --- | --- | | 1 | 7.782996 | 7.783380 | +0.000383 | | 2 | 6.977194 | 6.979984 | +0.002790 | | 10 | 4.832992 | 4.837770 | +0.004778 | | 20 | 4.407280 | 4.412218 | +0.004938 | Average over 20 steps: 5.233406 vs 5.231284. The differences have no consistent sign. HybridEP rounds the routing scores to BF16 before the combine multiply, while AllToAll multiplies in FP32, and the two combine kernels sum in a different order. The README notes the BF16 rounding. ## Performance Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30. All runs include the fused SwiGLU recompile fix earlier in this stack; without it, AllToAll runs at 2,138 TPS. | Config | TPS | Memory | | --- | --- | --- | | AllToAll | 18,624 | 7.7 GiB | | HybridEP eager, masks unfused | 18,618 | 16.7 GiB | | HybridEP eager, masks compiled | 21,439 (+15%) | 16.7 GiB | | HybridEP CUDA graphs, masks unfused | 24,777 | 16.8 GiB | | HybridEP CUDA graphs, masks compiled | 30,287 (+63%) | 16.8 GiB | - Most of the gain comes from CUDA graphs, which AllToAll cannot use. - Unfused, the masks run over all capacity rows (8x the valid rows at EP8 and top-8), and remat runs them again. Compiling them into the postprocess region removes that cost: +15% eager, +22% with graphs. - The extra memory comes from capacity factor 1.0. A lower factor saves memory but can drop tokens. ## Testing - `test_matches_all_to_all_with_output_postprocess` (new, 2x H100): HybridEP (blocking and non-blocking) vs AllToAll with an RMSNorm postprocess. Compares loss, input grad, and router, W13, W2, and norm weight grads within 2 BF16 eps (normwise). Without the mask it fails with errors of 12.5 and 8.8 vs bounds below 0.87. This is the regression it catches. - The HybridEP activation-checkpointing tests also run with an RMSNorm postprocess, as the DeepEP tests do, so remat replay stays exact around the mask. They run the mask function eagerly; the loss comparison above covers the compiled region. - `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k HybridEP`: 4 passed. - Manual check: the parity test also passes with `pad_multiple=32`, with and without the postprocess. So the per-expert padding rows inside the offsets do not affect gradients. - `python -m tests.integration_tests.run_tests --test_suite h100 --execution_mode real_pg --ngpu 4 --test_name=fsdp+hybridep` (4x H100, HybridEP at the CI pin f725d29), CUDA graphs on: both configs pass and record a CUDA graph. The Muse Spark config (FSDP2 + TP2 + SP + EP2) keeps local compile on, so CI runs the compiled mask region. SPMD type checking would turn it off; Muse Spark TP+SP+EP type checking is covered by `muse_spark_mm_fsdp+tp+cp+ep+sp`. Muse Spark loss goes from about 7.7 to about 4.9-5.2 in 10 steps across three runs. - `pytest tests/unit_tests/cpu/test_integration_test_definitions.py tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py tests/unit_tests/cpu/config`: 263 passed, 3 xfailed. - `pytest tests/unit_tests/cpu -k "moe or expert or dispatcher or local_compile"`: 147 passed, 1 skipped. ## Known issues / follow-ups - CP + EP with HybridEP is not tested. - Multimodal training with CUDA graphs is not supported for Muse Spark with any dispatcher. - The score multiply in HybridEP's combine also runs over all capacity rows. Moving it into a compiled region would change HybridEP's combine, which DeepSeek-V3 also uses, so it is left for a follow-up. stack-info: PR: #6032, branch: fegin/stack/34
fegin
added a commit
that referenced
this pull request
Nov 11, 2026
## Summary (human-written) Muse Spark currently only supports AllToAll and Dist-MoE backends. The former is slow and the latter cannot be used on Hopper. This PR enables HybridEP. The main design decision is how to run `output_postprocess`, which Muse Spark uses to perform RMSNorm after the experts and before combine. With non-blocking HybridEP, the rows past the last expert offset are never written, so `output_postprocess` needs `torch.where` masks around it to keep those rows out of the forward and the gradients. The masks are slow in eager mode, so we use local_compile to fuse them into the RMSNorm kernels. See the performance section. TL;DR: with local_compile and CUDA graphs, we see about 60% higher TPS than AllToAll (note that the AllToAll performance is also improved after #6030). ## Why On Hopper, Dist-MoE is not available, so Muse Spark's only EP path is the AllToAll dispatcher. AllToAll syncs the CPU in every MoE layer, so it cannot use CUDA graphs. `MuseSparkMoE.Config` rejects HybridEP, which has no CPU sync in non-blocking mode and supports CUDA graphs. The check was added when the per-expert norm could only run after combine. `output_postprocess` (#4623) now runs it before combine, and HybridEP applies scores after it, so the operation order is right. Allowing HybridEP alone is not enough. Non-blocking HybridEP (`non_blocking_capacity_factor` set) sizes the routed rows to its capacity, not to the received token count. Rows past `offsets_E[-1]` are never written: in forward, the grouped GEMMs only write rows inside the expert offsets, and in backward, HybridEP's combine backward only writes grads for received tokens. So those rows hold stale memory in both directions. `output_postprocess` runs on every row, so its parameter grads sum over those rows. The result is a wrong grad, or NaN when the stale memory is not finite. Muse Spark is the only model that sets `output_postprocess`, so no other model hits this. **Example.** ```python config = muse_spark_debugmodel(seq_len) config = apply_transforms(config, [TokenDispatcherTransform( dispatcher=HybridEPTokenDispatcher, num_max_tokens_per_rank=tokens_per_microbatch // (cp * tp), kwargs={"non_blocking_capacity_factor": 1.0}, )]) # main: ValueError("Muse Spark MoE requires LocalTokenDispatcher or AllToAllTokenDispatcher, ...") # only the check removed: "Loss or gradient norm is not finite" at step 1 # this change: trains ``` The stale rows, at EP2, 64 tokens per rank, top-2, capacity factor 1.0, RMSNorm postprocess: ``` routed rows: 256, valid rows (offsets_E[-1]): 128 rows 128..255: stale inputs (abs max ~30) and nonzero incoming grads (abs max ~14) norm weight grad vs AllToAll: relative error 1.2 and 1.5 (all other grads bitwise equal) ``` ## What changed - Shared MoE (`models/common/moe/moe.py`, please review this first): with non-blocking HybridEP and an `output_postprocess`, `RoutedExperts.forward` calls `_masked_output_postprocess`. It masks rows past `offsets_E[-1]` with `torch.where` before the postprocess (finite forward) and after it (zero grad for those rows). `torch.where` instead of a multiply, so NaN rows are dropped too. The mask is built on the GPU from `offsets_E`, so there is no CPU sync and CUDA graph capture still works. The function is a `local_compile` region (`moe_masked_output_postprocess`), so Inductor fuses both masks into the postprocess kernels. Without the region it runs eagerly with the same math. In training, other dispatchers and blocking HybridEP never produce rows past the last offset, so they skip it. HybridEP `pad_multiple` padding rows are inside the offsets, and HybridEP writes zeros to them in both directions, so they need no mask. Dist-MoE does not use this forward. - Muse Spark enables the `moe_masked_output_postprocess` region in its default `local_compile.regions`. - `MuseSparkMoE.Config` accepts `HybridEPTokenDispatcher`. DeepEP stays rejected because it is untested with Muse Spark. - Add the `muse_spark_debugmodel_hybridep` test recipe with CUDA graphs on, like `deepseek_v3_debugmodel_hybridep`. Capacity factor 1.0 reserves the worst case, so no tokens are dropped. - Integration: add a Muse Spark FSDP2 + TP2 (SP) + EP2 run to the H100 HybridEP test, renamed from `deepseek_v3_fsdp+hybridep` to `fsdp+hybridep` because it covers both models. Mechanical: update the test name in `run_8xgpu_integration_tests.sh`, `validate_release_gpu.sh`, and `test_integration_test_definitions.py`. The last also checks every config of the test, not only the first. - README: list HybridEP as supported (verified with FSDP, TP+EP, and CUDA graphs; CP is not verified), say that on Hopper it is the EP path with CUDA graph support, give its memory cost (about 2x at capacity factor 1.0) and measured speedup, note its BF16 score rounding, and drop MinimalAsyncEP, which was deleted in #4627. ## Alternatives considered - Clean the rows inside HybridEP: only covers backward. The forward stale rows come from w2's grouped GEMM output. Masking in `RoutedExperts` handles both directions in one place. - Mask whenever `output_postprocess` is set: adds the mask cost to Muse Spark with AllToAll, which has no capacity rows. - A dispatcher property such as "may produce rows past the last offset": an interface with one implementer. The check follows the existing `DeepEPDispatchMetadata` branch in the same forward instead. - Reject non-blocking HybridEP with `output_postprocess`: blocking mode syncs the CPU in every MoE layer and cannot use CUDA graphs, which removes most of the reason to use HybridEP on Hopper. ## Numerics No change for other models or for Muse Spark with AllToAll: the mask only runs for non-blocking HybridEP with `output_postprocess`. Compiling the mask region does not change numerics: unfused masks vs the compiled region, `muse_spark_debugmodel_hybridep` on 4x H100, 20 steps, `scripts/loss_compare.py`: loss is bitwise identical at every step, and grad_norm matches. Muse Spark debug model, FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps, `scripts/loss_compare.py`, AllToAll (`muse_spark_debugmodel`) vs HybridEP (`muse_spark_debugmodel_hybridep`): | Step | AllToAll | HybridEP | Diff | | --- | --- | --- | --- | | 1 | 7.782996 | 7.783380 | +0.000383 | | 2 | 6.977194 | 6.979984 | +0.002790 | | 10 | 4.832992 | 4.837770 | +0.004778 | | 20 | 4.407280 | 4.412218 | +0.004938 | Average over 20 steps: 5.233406 vs 5.231284. The differences have no consistent sign. HybridEP rounds the routing scores to BF16 before the combine multiply, while AllToAll multiplies in FP32, and the two combine kernels sum in a different order. The README notes the BF16 rounding. ## Performance Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30. All runs include the fused SwiGLU recompile fix earlier in this stack; without it, AllToAll runs at 2,138 TPS. | Config | TPS | Memory | | --- | --- | --- | | AllToAll | 18,624 | 7.7 GiB | | HybridEP eager, masks unfused | 18,618 | 16.7 GiB | | HybridEP eager, masks compiled | 21,439 (+15%) | 16.7 GiB | | HybridEP CUDA graphs, masks unfused | 24,777 | 16.8 GiB | | HybridEP CUDA graphs, masks compiled | 30,287 (+63%) | 16.8 GiB | - Most of the gain comes from CUDA graphs, which AllToAll cannot use. - Unfused, the masks run over all capacity rows (8x the valid rows at EP8 and top-8), and remat runs them again. Compiling them into the postprocess region removes that cost: +15% eager, +22% with graphs. - The extra memory comes from capacity factor 1.0. A lower factor saves memory but can drop tokens. ## Testing - `test_matches_all_to_all_with_output_postprocess` (new, 2x H100): HybridEP (blocking and non-blocking) vs AllToAll with an RMSNorm postprocess. Compares loss, input grad, and router, W13, W2, and norm weight grads within 2 BF16 eps (normwise). Without the mask it fails with errors of 12.5 and 8.8 vs bounds below 0.87. This is the regression it catches. - The HybridEP activation-checkpointing tests also run with an RMSNorm postprocess, as the DeepEP tests do, so remat replay stays exact around the mask. They run the mask function eagerly; the loss comparison above covers the compiled region. - `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k HybridEP`: 4 passed. - Manual check: the parity test also passes with `pad_multiple=32`, with and without the postprocess. So the per-expert padding rows inside the offsets do not affect gradients. - `python -m tests.integration_tests.run_tests --test_suite h100 --execution_mode real_pg --ngpu 4 --test_name=fsdp+hybridep` (4x H100, HybridEP at the CI pin f725d29), CUDA graphs on: both configs pass and record a CUDA graph. The Muse Spark config (FSDP2 + TP2 + SP + EP2) keeps local compile on, so CI runs the compiled mask region. SPMD type checking would turn it off; Muse Spark TP+SP+EP type checking is covered by `muse_spark_mm_fsdp+tp+cp+ep+sp`. Muse Spark loss goes from about 7.7 to about 4.9-5.2 in 10 steps across three runs. - `pytest tests/unit_tests/cpu/test_integration_test_definitions.py tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py tests/unit_tests/cpu/config`: 263 passed, 3 xfailed. - `pytest tests/unit_tests/cpu -k "moe or expert or dispatcher or local_compile"`: 147 passed, 1 skipped. ## Known issues / follow-ups - CP + EP with HybridEP is not tested. - Multimodal training with CUDA graphs is not supported for Muse Spark with any dispatcher. - The score multiply in HybridEP's combine also runs over all capacity rows. Moving it into a compiled region would change HybridEP's combine, which DeepSeek-V3 also uses, so it is left for a follow-up. stack-info: PR: #6032, branch: fegin/stack/34
fegin
added a commit
that referenced
this pull request
Nov 12, 2026
## Summary (human-written) Muse Spark currently only supports AllToAll and Dist-MoE backends. The former is slow and the latter cannot be used on Hopper. This PR enables HybridEP. The main design decision is how to run `output_postprocess`, which Muse Spark uses to perform RMSNorm after the experts and before combine. With non-blocking HybridEP, the rows past the last expert offset are never written, so `output_postprocess` needs `torch.where` masks around it to keep those rows out of the forward and the gradients. The masks are slow in eager mode, so we use local_compile to fuse them into the RMSNorm kernels. See the performance section. TL;DR: with local_compile and CUDA graphs, we see about 60% higher TPS than AllToAll (note that the AllToAll performance is also improved after #6030). ## Why On Hopper, Dist-MoE is not available, so Muse Spark's only EP path is the AllToAll dispatcher. AllToAll syncs the CPU in every MoE layer, so it cannot use CUDA graphs. `MuseSparkMoE.Config` rejects HybridEP, which has no CPU sync in non-blocking mode and supports CUDA graphs. The check was added when the per-expert norm could only run after combine. `output_postprocess` (#4623) now runs it before combine, and HybridEP applies scores after it, so the operation order is right. Allowing HybridEP alone is not enough. Non-blocking HybridEP (`non_blocking_capacity_factor` set) sizes the routed rows to its capacity, not to the received token count. Rows past `offsets_E[-1]` are never written: in forward, the grouped GEMMs only write rows inside the expert offsets, and in backward, HybridEP's combine backward only writes grads for received tokens. So those rows hold stale memory in both directions. `output_postprocess` runs on every row, so its parameter grads sum over those rows. The result is a wrong grad, or NaN when the stale memory is not finite. Muse Spark is the only model that sets `output_postprocess`, so no other model hits this. **Example.** ```python config = muse_spark_debugmodel(seq_len) config = apply_transforms(config, [TokenDispatcherTransform( dispatcher=HybridEPTokenDispatcher, num_max_tokens_per_rank=tokens_per_microbatch // (cp * tp), kwargs={"non_blocking_capacity_factor": 1.0}, )]) # main: ValueError("Muse Spark MoE requires LocalTokenDispatcher or AllToAllTokenDispatcher, ...") # only the check removed: "Loss or gradient norm is not finite" at step 1 # this change: trains ``` The stale rows, at EP2, 64 tokens per rank, top-2, capacity factor 1.0, RMSNorm postprocess: ``` routed rows: 256, valid rows (offsets_E[-1]): 128 rows 128..255: stale inputs (abs max ~30) and nonzero incoming grads (abs max ~14) norm weight grad vs AllToAll: relative error 1.2 and 1.5 (all other grads bitwise equal) ``` ## What changed - Shared MoE (`models/common/moe/moe.py`, please review this first): with non-blocking HybridEP and an `output_postprocess`, `RoutedExperts.forward` calls `_masked_output_postprocess`. It masks rows past `offsets_E[-1]` with `torch.where` before the postprocess (finite forward) and after it (zero grad for those rows). `torch.where` instead of a multiply, so NaN rows are dropped too. The mask is built on the GPU from `offsets_E`, so there is no CPU sync and CUDA graph capture still works. The function is a `local_compile` region (`moe_masked_output_postprocess`), so Inductor fuses both masks into the postprocess kernels. Without the region it runs eagerly with the same math. In training, other dispatchers and blocking HybridEP never produce rows past the last offset, so they skip it. HybridEP `pad_multiple` padding rows are inside the offsets, and HybridEP writes zeros to them in both directions, so they need no mask. Dist-MoE does not use this forward. - Muse Spark enables the `moe_masked_output_postprocess` region in its default `local_compile.regions`. - `MuseSparkMoE.Config` accepts `HybridEPTokenDispatcher`. DeepEP stays rejected because it is untested with Muse Spark. - Add the `muse_spark_debugmodel_hybridep` test recipe with CUDA graphs on, like `deepseek_v3_debugmodel_hybridep`. Capacity factor 1.0 reserves the worst case, so no tokens are dropped. - Integration: add a Muse Spark FSDP2 + TP2 (SP) + EP2 run to the H100 HybridEP test, renamed from `deepseek_v3_fsdp+hybridep` to `fsdp+hybridep` because it covers both models. Mechanical: update the test name in `run_8xgpu_integration_tests.sh`, `validate_release_gpu.sh`, and `test_integration_test_definitions.py`. The last also checks every config of the test, not only the first. - README: list HybridEP as supported (verified with FSDP, TP+EP, and CUDA graphs; CP is not verified), say that on Hopper it is the EP path with CUDA graph support, give its memory cost (about 2x at capacity factor 1.0) and measured speedup, note its BF16 score rounding, and drop MinimalAsyncEP, which was deleted in #4627. ## Alternatives considered - Clean the rows inside HybridEP: only covers backward. The forward stale rows come from w2's grouped GEMM output. Masking in `RoutedExperts` handles both directions in one place. - Mask whenever `output_postprocess` is set: adds the mask cost to Muse Spark with AllToAll, which has no capacity rows. - A dispatcher property such as "may produce rows past the last offset": an interface with one implementer. The check follows the existing `DeepEPDispatchMetadata` branch in the same forward instead. - Reject non-blocking HybridEP with `output_postprocess`: blocking mode syncs the CPU in every MoE layer and cannot use CUDA graphs, which removes most of the reason to use HybridEP on Hopper. ## Numerics No change for other models or for Muse Spark with AllToAll: the mask only runs for non-blocking HybridEP with `output_postprocess`. Compiling the mask region does not change numerics: unfused masks vs the compiled region, `muse_spark_debugmodel_hybridep` on 4x H100, 20 steps, `scripts/loss_compare.py`: loss is bitwise identical at every step, and grad_norm matches. Muse Spark debug model, FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps, `scripts/loss_compare.py`, AllToAll (`muse_spark_debugmodel`) vs HybridEP (`muse_spark_debugmodel_hybridep`): | Step | AllToAll | HybridEP | Diff | | --- | --- | --- | --- | | 1 | 7.782996 | 7.783380 | +0.000383 | | 2 | 6.977194 | 6.979984 | +0.002790 | | 10 | 4.832992 | 4.837770 | +0.004778 | | 20 | 4.407280 | 4.412218 | +0.004938 | Average over 20 steps: 5.233406 vs 5.231284. The differences have no consistent sign. HybridEP rounds the routing scores to BF16 before the combine multiply, while AllToAll multiplies in FP32, and the two combine kernels sum in a different order. The README notes the BF16 rounding. ## Performance Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30. All runs include the fused SwiGLU recompile fix earlier in this stack; without it, AllToAll runs at 2,138 TPS. | Config | TPS | Memory | | --- | --- | --- | | AllToAll | 18,624 | 7.7 GiB | | HybridEP eager, masks unfused | 18,618 | 16.7 GiB | | HybridEP eager, masks compiled | 21,439 (+15%) | 16.7 GiB | | HybridEP CUDA graphs, masks unfused | 24,777 | 16.8 GiB | | HybridEP CUDA graphs, masks compiled | 30,287 (+63%) | 16.8 GiB | - Most of the gain comes from CUDA graphs, which AllToAll cannot use. - Unfused, the masks run over all capacity rows (8x the valid rows at EP8 and top-8), and remat runs them again. Compiling them into the postprocess region removes that cost: +15% eager, +22% with graphs. - The extra memory comes from capacity factor 1.0. A lower factor saves memory but can drop tokens. ## Testing - The HybridEP activation-checkpointing tests also run with an RMSNorm postprocess, as the DeepEP tests do, so remat replay stays exact around the mask. The shared test helper also compares each HybridEP run (blocking and non-blocking) with an AllToAll reference: loss, input grad, and router, W13, W2, and norm weight grads within 2 BF16 eps (normwise). It builds this reference the same way it builds the post-W2 scoring reference for DeepEP. Without the mask, the comparison fails (NaN vs a bound of 0.87). This is the regression it catches. The tests run the mask function eagerly; the loss comparison above covers the compiled region. - `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k HybridEP`: 3 passed. With DeepEP v2: `-k DeepEP`, 2 passed. - Manual check: the AllToAll comparison also passes with `pad_multiple=32`, with and without the postprocess. So the per-expert padding rows inside the offsets do not affect gradients. - `python -m tests.integration_tests.run_tests --test_suite h100 --execution_mode real_pg --ngpu 4 --test_name=fsdp+hybridep` (4x H100, HybridEP at the CI pin f725d29), CUDA graphs on: both configs pass and record a CUDA graph. The Muse Spark config (FSDP2 + TP2 + SP + EP2) keeps local compile on, so CI runs the compiled mask region. SPMD type checking would turn it off; Muse Spark TP+SP+EP type checking is covered by `muse_spark_mm_fsdp+tp+cp+ep+sp`. Muse Spark loss goes from about 7.7 to about 4.9-5.2 in 10 steps across three runs. - `pytest tests/unit_tests/cpu/test_integration_test_definitions.py tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py tests/unit_tests/cpu/config`: 263 passed, 3 xfailed. - `pytest tests/unit_tests/cpu -k "moe or expert or dispatcher or local_compile"`: 147 passed, 1 skipped. ## Known issues / follow-ups - CP + EP with HybridEP is not tested. - Multimodal training with CUDA graphs is not supported for Muse Spark with any dispatcher. - The score multiply in HybridEP's combine also runs over all capacity rows. Moving it into a compiled region would change HybridEP's combine, which DeepSeek-V3 also uses, so it is left for a follow-up. stack-info: PR: #6032, branch: fegin/stack/34
fegin
added a commit
that referenced
this pull request
Nov 12, 2026
## Summary (human-written) Muse Spark currently only supports AllToAll and Dist-MoE backends. The former is slow and the latter cannot be used on Hopper. This PR enables HybridEP. The main design decision is how to run `output_postprocess`, which Muse Spark uses to perform RMSNorm after the experts and before combine. With non-blocking HybridEP, the rows past the last expert offset are never written, so `output_postprocess` needs `torch.where` masks around it to keep those rows out of the forward and the gradients. The masks are slow in eager mode, so we use local_compile to fuse them into the RMSNorm kernels. See the performance section. TL;DR: with local_compile and CUDA graphs, we see about 60% higher TPS than AllToAll (note that the AllToAll performance is also improved after #6030). ## Why On Hopper, Dist-MoE is not available, so Muse Spark's only EP path is the AllToAll dispatcher. AllToAll syncs the CPU in every MoE layer, so it cannot use CUDA graphs. `MuseSparkMoE.Config` rejects HybridEP, which has no CPU sync in non-blocking mode and supports CUDA graphs. The check was added when the per-expert norm could only run after combine. `output_postprocess` (#4623) now runs it before combine, and HybridEP applies scores after it, so the operation order is right. Allowing HybridEP alone is not enough. Non-blocking HybridEP (`non_blocking_capacity_factor` set) sizes the routed rows to its capacity, not to the received token count. Rows past `offsets_E[-1]` are never written: in forward, the grouped GEMMs only write rows inside the expert offsets, and in backward, HybridEP's combine backward only writes grads for received tokens. So those rows hold stale memory in both directions. `output_postprocess` runs on every row, so its parameter grads sum over those rows. The result is a wrong grad, or NaN when the stale memory is not finite. Muse Spark is the only model that sets `output_postprocess`, so no other model hits this. **Example.** ```python config = muse_spark_debugmodel(seq_len) config = apply_transforms(config, [TokenDispatcherTransform( dispatcher=HybridEPTokenDispatcher, num_max_tokens_per_rank=tokens_per_microbatch // (cp * tp), kwargs={"non_blocking_capacity_factor": 1.0}, )]) # main: ValueError("Muse Spark MoE requires LocalTokenDispatcher or AllToAllTokenDispatcher, ...") # only the check removed: "Loss or gradient norm is not finite" at step 1 # this change: trains ``` The stale rows, at EP2, 64 tokens per rank, top-2, capacity factor 1.0, RMSNorm postprocess: ``` routed rows: 256, valid rows (offsets_E[-1]): 128 rows 128..255: stale inputs (abs max ~30) and nonzero incoming grads (abs max ~14) norm weight grad vs AllToAll: relative error 1.2 and 1.5 (all other grads bitwise equal) ``` ## What changed - Shared MoE (`models/common/moe/moe.py`, please review this first): with non-blocking HybridEP and an `output_postprocess`, `RoutedExperts.forward` calls `_masked_output_postprocess`. It masks rows past `offsets_E[-1]` with `torch.where` before the postprocess (finite forward) and after it (zero grad for those rows). `torch.where` instead of a multiply, so NaN rows are dropped too. The mask is built on the GPU from `offsets_E`, so there is no CPU sync and CUDA graph capture still works. The function is a `local_compile` region (`moe_masked_output_postprocess`), so Inductor fuses both masks into the postprocess kernels. Without the region it runs eagerly with the same math. In training, other dispatchers and blocking HybridEP never produce rows past the last offset, so they skip it. HybridEP `pad_multiple` padding rows are inside the offsets, and HybridEP writes zeros to them in both directions, so they need no mask. Dist-MoE does not use this forward. - Muse Spark enables the `moe_masked_output_postprocess` region in its default `local_compile.regions`. - `MuseSparkMoE.Config` accepts `HybridEPTokenDispatcher`. DeepEP stays rejected because it is untested with Muse Spark. - Add the `muse_spark_debugmodel_hybridep` test recipe with CUDA graphs on, like `deepseek_v3_debugmodel_hybridep`. Capacity factor 1.0 reserves the worst case, so no tokens are dropped. - Integration: add a Muse Spark FSDP2 + TP2 (SP) + EP2 run to the H100 HybridEP test, renamed from `deepseek_v3_fsdp+hybridep` to `fsdp+hybridep` because it covers both models. Mechanical: update the test name in `run_8xgpu_integration_tests.sh`, `validate_release_gpu.sh`, and `test_integration_test_definitions.py`. The last also checks every config of the test, not only the first. - README: list HybridEP as supported (verified with FSDP, TP+EP, Ulysses CP+EP, and CUDA graphs), say that on Hopper it is the EP path with CUDA graph support, give its memory cost (about 2x at capacity factor 1.0) and measured speedup, note its BF16 score rounding, and drop MinimalAsyncEP, which was deleted in #4627. ## Alternatives considered - Clean the rows inside HybridEP: only covers backward. The forward stale rows come from w2's grouped GEMM output. Masking in `RoutedExperts` handles both directions in one place. - Mask whenever `output_postprocess` is set: adds the mask cost to Muse Spark with AllToAll, which has no capacity rows. - A dispatcher property such as "may produce rows past the last offset": an interface with one implementer. The check follows the existing `DeepEPDispatchMetadata` branch in the same forward instead. - Reject non-blocking HybridEP with `output_postprocess`: blocking mode syncs the CPU in every MoE layer and cannot use CUDA graphs, which removes most of the reason to use HybridEP on Hopper. ## Numerics No change for other models or for Muse Spark with AllToAll: the mask only runs for non-blocking HybridEP with `output_postprocess`. Compiling the mask region does not change numerics: unfused masks vs the compiled region, `muse_spark_debugmodel_hybridep` on 4x H100, 20 steps, `scripts/loss_compare.py`: loss is bitwise identical at every step, and grad_norm matches. Muse Spark debug model, FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps, `scripts/loss_compare.py`, AllToAll (`muse_spark_debugmodel`) vs HybridEP (`muse_spark_debugmodel_hybridep`): | Step | AllToAll | HybridEP | Diff | | --- | --- | --- | --- | | 1 | 7.782996 | 7.783380 | +0.000383 | | 2 | 6.977194 | 6.979984 | +0.002790 | | 10 | 4.832992 | 4.837770 | +0.004778 | | 20 | 4.407280 | 4.412218 | +0.004938 | Average over 20 steps: 5.233406 vs 5.231284. The differences have no consistent sign. HybridEP rounds the routing scores to BF16 before the combine multiply, while AllToAll multiplies in FP32, and the two combine kernels sum in a different order. The README notes the BF16 rounding. ## Performance Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30. All runs include the fused SwiGLU recompile fix earlier in this stack; without it, AllToAll runs at 2,138 TPS. | Config | TPS | Memory | | --- | --- | --- | | AllToAll | 18,624 | 7.7 GiB | | HybridEP eager, masks unfused | 18,618 | 16.7 GiB | | HybridEP eager, masks compiled | 21,439 (+15%) | 16.7 GiB | | HybridEP CUDA graphs, masks unfused | 24,777 | 16.8 GiB | | HybridEP CUDA graphs, masks compiled | 30,287 (+63%) | 16.8 GiB | - Most of the gain comes from CUDA graphs, which AllToAll cannot use. - Unfused, the masks run over all capacity rows (8x the valid rows at EP8 and top-8), and remat runs them again. Compiling them into the postprocess region removes that cost: +15% eager, +22% with graphs. - The extra memory comes from capacity factor 1.0. A lower factor saves memory but can drop tokens. ## Testing - The HybridEP activation-checkpointing tests also run with an RMSNorm postprocess, as the DeepEP tests do, so remat replay stays exact around the mask. The shared test helper also compares each HybridEP run (blocking and non-blocking) with an AllToAll reference: loss, input grad, and router, W13, W2, and norm weight grads within 2 BF16 eps (normwise). It builds this reference the same way it builds the post-W2 scoring reference for DeepEP. Without the mask, the comparison fails (NaN vs a bound of 0.87). This is the regression it catches. The tests run the mask function eagerly; the loss comparison above covers the compiled region. - `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k HybridEP`: 3 passed. With DeepEP v2: `-k DeepEP`, 2 passed. - Manual check: the AllToAll comparison also passes with `pad_multiple=32`, with and without the postprocess. So the per-expert padding rows inside the offsets do not affect gradients. - `python -m tests.integration_tests.run_tests --test_suite h100 --execution_mode real_pg --ngpu 4 --test_name=fsdp+hybridep` (4x H100, HybridEP at the CI pin f725d29), CUDA graphs on: both configs pass and record a CUDA graph. The Muse Spark config (FSDP2 + TP2 + SP + EP2) keeps local compile on, so CI runs the compiled mask region. SPMD type checking would turn it off; Muse Spark TP+SP+EP type checking is covered by `muse_spark_mm_fsdp+tp+cp+ep+sp`. Muse Spark loss goes from about 7.7 to about 4.9-5.2 in 10 steps across three runs. - Muse Spark debugmodel, FSDP2 + Ulysses CP2 + EP4 (4x H100), seed 42, deterministic, 20 steps. Loss at steps 1 / 10 / 20: HybridEP (capacity 1.0) 7.77302 / 4.83989 / 4.40672, AllToAll 7.77313 / 4.84151 / 4.41106. HybridEP with CUDA graphs prints the same loss as without them. - `pytest tests/unit_tests/cpu/test_integration_test_definitions.py tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py tests/unit_tests/cpu/config`: 263 passed, 3 xfailed. - `pytest tests/unit_tests/cpu -k "moe or expert or dispatcher or local_compile"`: 147 passed, 1 skipped. ## Known issues / follow-ups - Multimodal training with CUDA graphs is not supported for Muse Spark with any dispatcher. - The score multiply in HybridEP's combine also runs over all capacity rows. Moving it into a compiled region would change HybridEP's combine, which DeepSeek-V3 also uses, so it is left for a follow-up.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Summary:
Let
RoutedExperts.Configown an optionaloutput_postprocessModule.Configthat transforms each expert output after W2 and before dispatcher combine. The
name is unambiguous within
RoutedExperts, while the module-based contractsupports learned route-wise operations such as MS post-expert RMSNorm and keeps
their parameters in the module state, checkpoint, optimizer, and FSDP ownership
tree.
The default remains
None, so existing models retain the same execution path.Communication-owning expert backends can translate supported modules to their
native fused descriptors and reject unsupported modules during conversion.
Test Plan:
python -m pytest -q tests/unit_tests/cpu/test_moe.pypre-commit run --files torchtitan/models/common/moe.py tests/unit_tests/cpu/test_moe.py