Skip to content

[muse_spark] Support HybridEP expert parallelism - #6032

Merged
fegin merged 1 commit into
mainfrom
fegin/stack/34
Nov 12, 2026
Merged

fegin merged 1 commit into
mainfrom
fegin/stack/34

Conversation

@fegin

@fegin fegin commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[muse_spark] Support HybridEP expert parallelism

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.

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 deprecate minimal_async_ep #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.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Nov 11, 2026
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
fegin marked this pull request as draft November 11, 2026 18:24
@fegin
fegin changed the base branch from fegin/stack/33 to main November 11, 2026 18:24
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 11, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 11, 2026
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
fegin changed the base branch from main to fegin/stack/33 November 11, 2026 18:24
@fegin
fegin marked this pull request as ready for review November 11, 2026 18:24
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 11, 2026
@fegin

fegin commented Nov 11, 2026

Copy link
Copy Markdown
Contributor Author

@claude review this PR

@claude

claude Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @fegin's task in 3m 2s —— View job


Approve -- review posted (one should-consider: fold the new parity test into the existing AC helper's reference branch). A maintainer still needs to review the shared MoE change.

@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 -- the mask fixes a real gradient bug in shared RoutedExperts (non-blocking HybridEP plus output_postprocess) at the layer that owns it, without a CPU sync, and the Muse Spark enablement is small. A maintainer still needs to review, since this touches models/common/moe/moe.py.

What this PR does. Non-blocking HybridEP sizes the routed rows to its capacity, so rows past offsets_E[-1] hold stale memory in both forward (w2 never writes them) and backward (combine backward never writes their grads). output_postprocess runs on every row, so its parameter grads summed over garbage. The PR wraps the postprocess with two torch.where masks built on the GPU from offsets_E, in a local_compile region so they fuse into the norm kernels. It then lets Muse Spark use HybridEP, adds a test recipe, and adds a Muse Spark FSDP2+TP2(SP)+EP2 config to the H100 HybridEP integration test.

Example.

EP2, 64 tokens/rank, top-2, capacity 1.0 -> R = 256 routed rows, offsets_E[-1] = 128
before: norm.weight.grad = sum over rows 0..255 of g_r * xhat_r
        rows 128..255: stale x (|x| ~30) and stale g (|g| ~14) -> rel err ~1.2, or NaN
after:  x[128:] := 0 before the norm, out[128:] := 0 after it
        -> rows 128..255 add exactly 0 to the param grads and to w2's input grad
AllToAll / blocking HybridEP: unchanged path (no capacity rows)

Should consider

  • tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py:480 -- the new parity test could fold into the existing reference branch of _check_ep_activation_checkpointing (see inline).
Details
  • Mask placement. The inner where is needed so that 0 * NaN can't poison weight.grad (RMSNorm of a zero row is zero). The outer one is needed for postprocesses whose output or grad at 0 is nonzero, and for non-finite stale incoming grads. The mask's backward also zeroes w2's output grad for the capacity rows, and w2's grouped GEMM backward only reads rows inside the offsets anyway. torch.arange(R) has a static shape in non-blocking mode, so CUDA graph capture is preserved.
  • pad_multiple. Padding rows lie inside the offsets, so the mask doesn't cover them. The PR says HybridEP zeroes them in both directions, and the author checked this manually with pad_multiple=32.
  • Capacity < 1.0. When tokens are dropped, offsets_E[-1] can reach R, the mask is all true, and nothing changes. Any overflow handling is outside this PR.
  • Region list. moe_masked_output_postprocess is batch_invariant=False. It sits in Muse Spark's default local_compile.regions next to loss, which is also batch_invariant=False, so batch-invariant runs already have to trim that list. Nothing new there.
  • Dispatcher check in shared code. The isinstance(self.token_dispatcher, HybridEPTokenDispatcher) check follows the existing DeepEPDispatchMetadata branch in the same forward. The alternatives the PR lists (fixing it in HybridEP, which covers backward only; masking unconditionally, which costs AllToAll) are worse.
  • Mechanical changes checked: the test rename in both CI scripts and test_integration_test_definitions.py, the loop over all configs in test_specialized_moe_backends_have_ep_coverage, and the README removing MinimalAsyncEP (deleted in #4627) from the row being edited.

Not verified: the GPU parity, AC, and integration runs, and the claim that compiling the mask region gives bitwise-identical loss (both need H100s).

)

@with_comms
def test_matches_all_to_all_with_output_postprocess(self):

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 new method is about 70 lines. It rebuilds the model/seed/compare loop that _check_ep_activation_checkpointing already has, and it is a dispatcher parity test sitting in an activation-checkpointing file.

The helper already builds an optional reference model (now only for DeepEPTokenDispatcher.Config) and compares expected against it normwise within 2 * bf16 eps. After this PR, the HybridEP AC tests already run with the RMSNorm postprocess for both capacity_factor in (None, 1.0). So you could build an AllToAllTokenDispatcher.Config _EPBlock reference when the dispatcher is HybridEP, and skip the bitwise output_postprocess is not None and exact branch for that case. That catches the same regression (stale capacity rows reaching the norm weight grad) in roughly 10 lines, without a new test method or the extra 2-GPU spawn.

If you'd rather keep a separate test, a short note on why the AC helper can't host it would help.

"Muse Spark MoE requires LocalTokenDispatcher or "
"AllToAllTokenDispatcher, "
"Muse Spark MoE requires LocalTokenDispatcher, "
"AllToAllTokenDispatcher, or HybridEPTokenDispatcher, "

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.

DeepEP shouldn't be too hard?

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.

Yes, shouldn't be too hard. Let me create another one for DeepEP.

@fegin
fegin marked this pull request as draft November 11, 2026 22:14
@fegin
fegin changed the base branch from fegin/stack/33 to main November 11, 2026 22:14
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 11, 2026
@fegin
fegin marked this pull request as ready for review November 11, 2026 22:19
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 11, 2026
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)
As title. Enabling DeepEP for Muse Spark is trivial, performance is not
verified though.

## Why
`MuseSparkMoE.Config` rejects `DeepEPTokenDispatcher`, but nothing in Muse Spark needs that. The shared MoE code already supports DeepEP with an `output_postprocess`:
- In training, DeepEP uses its compact, host-synced path. The routed rows match the received token counts, so there are no rows past the last expert offset, and the HybridEP mask from #6032 is not needed.
- `RoutedExperts.forward` already applies the DeepEP routing scores after the postprocess, because Muse Spark's per-expert RMSNorm is nonlinear and must run first.

DeepEP is the EP backend that `search_r1` uses for both its trainer and its CUDA-graphed generator (expand layout), so this also unblocks Muse Spark RL on Hopper.

## What changed
- `MuseSparkMoE.Config` accepts `DeepEPTokenDispatcher`. `TorchAOTokenDispatcher` stays rejected.
- README: list DeepEP as supported. Note that training needs CUDA graphs disabled, and that DeepEP's combine kernel needs the MoE compressed dimension to be a multiple of 256. The production flavors use 4096. `debugmodel` uses 128, so it cannot run with DeepEP.

## Alternatives considered
- Add a `muse_spark_debugmodel_deepep` recipe and an integration test: `debugmodel` cannot run DeepEP (compressed dimension 128), and changing the debug flavor would change every Muse Spark debug run and golden loss.
- Validate the hidden size in `DeepEPTokenDispatcher.Config`: today a bad size fails at the first forward with DeepEP's static assert ("Invalid hidden"). A config-time check belongs to DeepEP in shared code, so it is left for a separate PR.

## Numerics
Muse Spark debug model with compressed dimension 256 (a local config change, see above), FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps:

| Step | AllToAll | DeepEP |
| --- | --- | --- |
| 1 | 7.75888 | 7.75888 |
| 2 | 6.82995 | 6.83072 |
| 10 | 4.81295 | 4.81803 |
| 20 | 4.40471 | 4.39651 |

Average over 20 steps: 5.18424 vs 5.18254. Step 1 matches. Later steps differ by the combine kernels' summation order, with no consistent sign.

Unit check, the RMSNorm postprocess setup from `test_matches_all_to_all_with_output_postprocess` with DeepEP instead of HybridEP (2x H100): loss, input grad, and router, W13, W2, and norm weight grads match AllToAll within relative error 4.7e-3, below the 1.56e-2 bound. Loss and the expert and norm weight grads are bitwise equal.

## Performance
Not reported. DeepEP's expected benefit is multi-node communication, and I only have single-node H100 runs, which would not show it.

## Testing
- `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k DeepEP` with DeepEP v2 at the CI pin 01dc3aa: 2 passed. These tests already run with an RMSNorm postprocess and check the score order against a reference.
- No new test. The existing DeepEP tests cover the postprocess path, and the unit check above was a one-off run.
- `pytest tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py`: 40 passed, 3 xfailed.

stack-info: PR: #6037, branch: fegin/stack/35
@fegin
fegin marked this pull request as draft November 11, 2026 23:14
@fegin
fegin changed the base branch from fegin/stack/33 to main November 11, 2026 23:14
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 11, 2026
fegin added a commit that referenced this pull request Nov 11, 2026
## Summary (human-written)
As title. Enabling DeepEP for Muse Spark is trivial, performance is not
verified though.

## Why
`MuseSparkMoE.Config` rejects `DeepEPTokenDispatcher`, but nothing in Muse Spark needs that. The shared MoE code already supports DeepEP with an `output_postprocess`:
- In training, DeepEP uses its compact, host-synced path. The routed rows match the received token counts, so there are no rows past the last expert offset, and the HybridEP mask from #6032 is not needed.
- `RoutedExperts.forward` already applies the DeepEP routing scores after the postprocess, because Muse Spark's per-expert RMSNorm is nonlinear and must run first.

DeepEP is the EP backend that `search_r1` uses for both its trainer and its CUDA-graphed generator (expand layout), so this should also unblock Muse Spark RL on Hopper. I have not run the generator's expand layout with Muse Spark.

## What changed
- `MuseSparkMoE.Config` accepts `DeepEPTokenDispatcher`. `TorchAOTokenDispatcher` stays rejected.
- README: list DeepEP as supported, and add it to the CUDA graphs row: training needs graphs disabled. Note that CP is not verified with DeepEP, and that DeepEP's combine kernel needs the MoE compressed dimension to be a multiple of 256. Add a TODO for the config-time check. The production flavors use 4096. `debugmodel` uses 128, so it cannot run with DeepEP.

## Alternatives considered
- Add a `muse_spark_debugmodel_deepep` recipe and an integration test: `debugmodel` cannot run DeepEP (compressed dimension 128), and changing the debug flavor would change every Muse Spark debug run and golden loss.
- Validate the hidden size in `DeepEPTokenDispatcher.Config`: today a bad size fails at the first forward with DeepEP's static assert ("Invalid hidden"). A config-time check belongs to DeepEP in shared code, so it is left for a separate PR.

## Numerics
Muse Spark debug model with compressed dimension 256 (a local config change, see above), FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps:

| Step | AllToAll | DeepEP |
| --- | --- | --- |
| 1 | 7.75888 | 7.75888 |
| 2 | 6.82995 | 6.83072 |
| 10 | 4.81295 | 4.81803 |
| 20 | 4.40471 | 4.39651 |

Average over 20 steps: 5.18424 vs 5.18254. Step 1 matches. Later steps differ by the combine kernels' summation order, with no consistent sign.

One-off unit check, the AllToAll comparison from the HybridEP tests run with DeepEP and an RMSNorm postprocess (2x H100): loss, input grad, and router, W13, W2, and norm weight grads match AllToAll within relative error 4.7e-3, below the 1.56e-2 bound. Loss and the expert and norm weight grads are bitwise equal.

## Performance
Not reported. DeepEP's expected benefit is multi-node communication, and I only have single-node H100 runs, which would not show it.

## Testing
- `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k DeepEP` with DeepEP v2 at the CI pin 01dc3aa: 2 passed. These tests already run with an RMSNorm postprocess and check the score order against a reference.
- No new test. The existing DeepEP tests cover the postprocess path, and the unit check above was a one-off run.
- `pytest tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py`: 40 passed, 3 xfailed.

stack-info: PR: #6037, branch: fegin/stack/35
@fegin
fegin changed the base branch from main to fegin/stack/33 November 11, 2026 23:14
@fegin
fegin marked this pull request as ready for review November 11, 2026 23:15
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 11, 2026
routed_output_RD = routed_output_RD.type_as(routed_input_RD)
if self.output_postprocess is not None:
routed_output_RD = self.output_postprocess(routed_output_RD)
if (

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.

nit: maybe add an one line comment to indicate why we branch out for hybrid ep + non blocking mode?

Comment thread torchtitan/models/muse_spark/README.md Outdated
capacity factor of `1.0` reserves the worst case, so no tokens are dropped, at
the cost of memory. See [`models/common/moe/README.md`](../common/moe/README.md)
for choosing a lower factor. HybridEP is verified with FSDP and with TP+EP. CP is
not verified with HybridEP.

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.

what could be the issues for CP+HybridEP? can we verify it with a debug model?

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.

uh, I don't think there is an issue, let me try it.

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.

Done

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)
As title. Enabling DeepEP for Muse Spark is trivial, performance is not
verified though.

## Why
`MuseSparkMoE.Config` rejects `DeepEPTokenDispatcher`, but nothing in Muse Spark needs that. The shared MoE code already supports DeepEP with an `output_postprocess`:
- In training, DeepEP uses its compact, host-synced path. The routed rows match the received token counts, so there are no rows past the last expert offset, and the HybridEP mask from #6032 is not needed.
- `RoutedExperts.forward` already applies the DeepEP routing scores after the postprocess, because Muse Spark's per-expert RMSNorm is nonlinear and must run first.

DeepEP is the EP backend that `search_r1` uses for both its trainer and its CUDA-graphed generator (expand layout), so this should also unblock Muse Spark RL on Hopper. I have not run the generator's expand layout with Muse Spark.

## What changed
- `MuseSparkMoE.Config` accepts `DeepEPTokenDispatcher`. `TorchAOTokenDispatcher` stays rejected.
- README: list DeepEP as supported, and add it to the CUDA graphs row: training needs graphs disabled. Note that CP is not verified with DeepEP, and that DeepEP's combine kernel needs the MoE compressed dimension to be a multiple of 256. Add a TODO for the config-time check. The production flavors use 4096. `debugmodel` uses 128, so it cannot run with DeepEP.

## Alternatives considered
- Add a `muse_spark_debugmodel_deepep` recipe and an integration test: `debugmodel` cannot run DeepEP (compressed dimension 128), and changing the debug flavor would change every Muse Spark debug run and golden loss.
- Validate the hidden size in `DeepEPTokenDispatcher.Config`: today a bad size fails at the first forward with DeepEP's static assert ("Invalid hidden"). A config-time check belongs to DeepEP in shared code, so it is left for a separate PR.

## Numerics
Muse Spark debug model with compressed dimension 256 (a local config change, see above), FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps:

| Step | AllToAll | DeepEP |
| --- | --- | --- |
| 1 | 7.75888 | 7.75888 |
| 2 | 6.82995 | 6.83072 |
| 10 | 4.81295 | 4.81803 |
| 20 | 4.40471 | 4.39651 |

Average over 20 steps: 5.18424 vs 5.18254. Step 1 matches. Later steps differ by the combine kernels' summation order, with no consistent sign.

One-off unit check, the AllToAll comparison from the HybridEP tests run with DeepEP and an RMSNorm postprocess (2x H100): loss, input grad, and router, W13, W2, and norm weight grads match AllToAll within relative error 4.7e-3, below the 1.56e-2 bound. Loss and the expert and norm weight grads are bitwise equal.

## Performance
Not reported. DeepEP's expected benefit is multi-node communication, and I only have single-node H100 runs, which would not show it.

## Testing
- `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k DeepEP` with DeepEP v2 at the CI pin 01dc3aa: 2 passed. These tests already run with an RMSNorm postprocess and check the score order against a reference.
- No new test. The existing DeepEP tests cover the postprocess path, and the unit check above was a one-off run.
- `pytest tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py`: 40 passed, 3 xfailed.

stack-info: PR: #6037, branch: fegin/stack/35
@fegin
fegin changed the base branch from fegin/stack/33 to main November 12, 2026 00:44
## 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.

stack-info: PR: #6032, branch: fegin/stack/34
@fegin
fegin marked this pull request as draft November 12, 2026 00:54
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
fegin added a commit that referenced this pull request Nov 12, 2026
## Summary (human-written)
As title. Enabling DeepEP for Muse Spark is trivial, performance is not
verified though.

## Why
`MuseSparkMoE.Config` rejects `DeepEPTokenDispatcher`, but nothing in Muse Spark needs that. The shared MoE code already supports DeepEP with an `output_postprocess`:
- In training, DeepEP uses its compact, host-synced path. The routed rows match the received token counts, so there are no rows past the last expert offset, and the HybridEP mask from #6032 is not needed.
- `RoutedExperts.forward` already applies the DeepEP routing scores after the postprocess, because Muse Spark's per-expert RMSNorm is nonlinear and must run first.

DeepEP is the EP backend that `search_r1` uses for both its trainer and its CUDA-graphed generator (expand layout), so this should also unblock Muse Spark RL on Hopper. I have not run the generator's expand layout with Muse Spark.

## What changed
- `MuseSparkMoE.Config` accepts `DeepEPTokenDispatcher`. `TorchAOTokenDispatcher` stays rejected.
- README: list DeepEP as supported, and add it to the CUDA graphs row: training needs graphs disabled. Note that DeepEP's combine kernel needs the MoE compressed dimension to be a multiple of 256. Add a TODO for the config-time check. The production flavors use 4096. `debugmodel` uses 128, so it cannot run with DeepEP.

## Alternatives considered
- Add a `muse_spark_debugmodel_deepep` recipe and an integration test: `debugmodel` cannot run DeepEP (compressed dimension 128), and changing the debug flavor would change every Muse Spark debug run and golden loss.
- Validate the hidden size in `DeepEPTokenDispatcher.Config`: today a bad size fails at the first forward with DeepEP's static assert ("Invalid hidden"). A config-time check belongs to DeepEP in shared code, so it is left for a separate PR.

## Numerics
Muse Spark debug model with compressed dimension 256 (a local config change, see above), FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps:

| Step | AllToAll | DeepEP |
| --- | --- | --- |
| 1 | 7.75888 | 7.75888 |
| 2 | 6.82995 | 6.83072 |
| 10 | 4.81295 | 4.81803 |
| 20 | 4.40471 | 4.39651 |

Average over 20 steps: 5.18424 vs 5.18254. Step 1 matches. Later steps differ by the combine kernels' summation order, with no consistent sign.

One-off unit check, the AllToAll comparison from the HybridEP tests run with DeepEP and an RMSNorm postprocess (2x H100): loss, input grad, and router, W13, W2, and norm weight grads match AllToAll within relative error 4.7e-3, below the 1.56e-2 bound. Loss and the expert and norm weight grads are bitwise equal.

## Performance
Not reported. DeepEP's expected benefit is multi-node communication, and I only have single-node H100 runs, which would not show it.

## Testing
- `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k DeepEP` with DeepEP v2 at the CI pin 01dc3aa: 2 passed. These tests already run with an RMSNorm postprocess and check the score order against a reference.
- Muse Spark debugmodel with compressed_dim 256, FSDP2 + Ulysses CP2 + EP4 (4x H100), seed 42, deterministic, 20 steps. Loss at steps 1 / 10 / 20: DeepEP 7.74766 / 4.80887 / 4.40117, AllToAll 7.74766 / 4.80533 / 4.39565.
- No new test. The existing DeepEP tests cover the postprocess path, and the unit check above was a one-off run.
- `pytest tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py`: 40 passed, 3 xfailed.

stack-info: PR: #6037, branch: fegin/stack/35
@fegin
fegin marked this pull request as ready for review November 12, 2026 00:54
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 12, 2026
@fegin
fegin merged commit 09d76a5 into main Nov 12, 2026
fegin added a commit that referenced this pull request Nov 12, 2026
## Summary (human-written)
As title. Enabling DeepEP for Muse Spark is trivial, performance is not
verified though.

## Why
`MuseSparkMoE.Config` rejects `DeepEPTokenDispatcher`, but nothing in Muse Spark needs that. The shared MoE code already supports DeepEP with an `output_postprocess`:
- In training, DeepEP uses its compact, host-synced path. The routed rows match the received token counts, so there are no rows past the last expert offset, and the HybridEP mask from #6032 is not needed.
- `RoutedExperts.forward` already applies the DeepEP routing scores after the postprocess, because Muse Spark's per-expert RMSNorm is nonlinear and must run first.

DeepEP is the EP backend that `search_r1` uses for both its trainer and its CUDA-graphed generator (expand layout), so this should also unblock Muse Spark RL on Hopper. I have not run the generator's expand layout with Muse Spark.

## What changed
- `MuseSparkMoE.Config` accepts `DeepEPTokenDispatcher`. `TorchAOTokenDispatcher` stays rejected.
- README: list DeepEP as supported, and add it to the CUDA graphs row: training needs graphs disabled. Note that DeepEP's combine kernel needs the MoE compressed dimension to be a multiple of 256. Add a TODO for the config-time check. The production flavors use 4096. `debugmodel` uses 128, so it cannot run with DeepEP.

## Alternatives considered
- Add a `muse_spark_debugmodel_deepep` recipe and an integration test: `debugmodel` cannot run DeepEP (compressed dimension 128), and changing the debug flavor would change every Muse Spark debug run and golden loss.
- Validate the hidden size in `DeepEPTokenDispatcher.Config`: today a bad size fails at the first forward with DeepEP's static assert ("Invalid hidden"). A config-time check belongs to DeepEP in shared code, so it is left for a separate PR.

## Numerics
Muse Spark debug model with compressed dimension 256 (a local config change, see above), FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps:

| Step | AllToAll | DeepEP |
| --- | --- | --- |
| 1 | 7.75888 | 7.75888 |
| 2 | 6.82995 | 6.83072 |
| 10 | 4.81295 | 4.81803 |
| 20 | 4.40471 | 4.39651 |

Average over 20 steps: 5.18424 vs 5.18254. Step 1 matches. Later steps differ by the combine kernels' summation order, with no consistent sign.

One-off unit check, the AllToAll comparison from the HybridEP tests run with DeepEP and an RMSNorm postprocess (2x H100): loss, input grad, and router, W13, W2, and norm weight grads match AllToAll within relative error 4.7e-3, below the 1.56e-2 bound. Loss and the expert and norm weight grads are bitwise equal.

## Performance
Not reported. DeepEP's expected benefit is multi-node communication, and I only have single-node H100 runs, which would not show it.

## Testing
- `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k DeepEP` with DeepEP v2 at the CI pin 01dc3aa: 2 passed. These tests already run with an RMSNorm postprocess and check the score order against a reference.
- Muse Spark debugmodel with compressed_dim 256, FSDP2 + Ulysses CP2 + EP4 (4x H100), seed 42, deterministic, 20 steps. Loss at steps 1 / 10 / 20: DeepEP 7.74766 / 4.80887 / 4.40117, AllToAll 7.74766 / 4.80533 / 4.39565.
- No new test. The existing DeepEP tests cover the postprocess path, and the unit check above was a one-off run.
- `pytest tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py`: 40 passed, 3 xfailed.

stack-info: PR: #6037, branch: fegin/stack/35
fegin added a commit that referenced this pull request Nov 12, 2026
## Summary (human-written)
As title. Enabling DeepEP for Muse Spark is trivial, performance is not
verified though.

## Why
`MuseSparkMoE.Config` rejects `DeepEPTokenDispatcher`, but nothing in Muse Spark needs that. The shared MoE code already supports DeepEP with an `output_postprocess`:
- In training, DeepEP uses its compact, host-synced path. The routed rows match the received token counts, so there are no rows past the last expert offset, and the HybridEP mask from #6032 is not needed.
- `RoutedExperts.forward` already applies the DeepEP routing scores after the postprocess, because Muse Spark's per-expert RMSNorm is nonlinear and must run first.

DeepEP is the EP backend that `search_r1` uses for both its trainer and its CUDA-graphed generator (expand layout), so this should also unblock Muse Spark RL on Hopper. I have not run the generator's expand layout with Muse Spark.

## What changed
- `MuseSparkMoE.Config` accepts `DeepEPTokenDispatcher`. `TorchAOTokenDispatcher` stays rejected.
- `RoutedExperts.forward`: comment at the HybridEP mask gate on why DeepEP needs no mask. Training uses the compact layout, which has no rows past the last offset. The expand layout runs only without grad: `dispatch_tokens` forces the compact layout when grad is enabled, and the DeepEP kernel forbids backward in expand mode.
- README: list DeepEP as supported, and add it to the CUDA graphs row: training needs graphs disabled. Note that DeepEP's combine kernel needs the MoE compressed dimension to be a multiple of 256. Add a TODO for the config-time check. The production flavors use 4096. `debugmodel` uses 128, so it cannot run with DeepEP.

## Alternatives considered
- Add a `muse_spark_debugmodel_deepep` recipe and an integration test: `debugmodel` cannot run DeepEP (compressed dimension 128), and changing the debug flavor would change every Muse Spark debug run and golden loss.
- Validate the hidden size in `DeepEPTokenDispatcher.Config`: today a bad size fails at the first forward with DeepEP's static assert ("Invalid hidden"). A config-time check belongs to DeepEP in shared code, so it is left for a separate PR.

## Numerics
Muse Spark debug model with compressed dimension 256 (a local config change, see above), FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps:

| Step | AllToAll | DeepEP |
| --- | --- | --- |
| 1 | 7.75888 | 7.75888 |
| 2 | 6.82995 | 6.83072 |
| 10 | 4.81295 | 4.81803 |
| 20 | 4.40471 | 4.39651 |

Average over 20 steps: 5.18424 vs 5.18254. Step 1 matches. Later steps differ by the combine kernels' summation order, with no consistent sign.

One-off unit check, the AllToAll comparison from the HybridEP tests run with DeepEP and an RMSNorm postprocess (2x H100): loss, input grad, and router, W13, W2, and norm weight grads match AllToAll within relative error 4.7e-3, below the 1.56e-2 bound. Loss and the expert and norm weight grads are bitwise equal.

## Performance
Not reported. DeepEP's expected benefit is multi-node communication, and I only have single-node H100 runs, which would not show it.

## Testing
- `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k DeepEP` with DeepEP v2 at the CI pin 01dc3aa: 2 passed. These tests already run with an RMSNorm postprocess and check the score order against a reference.
- Muse Spark debugmodel with compressed_dim 256, FSDP2 + Ulysses CP2 + EP4 (4x H100), seed 42, deterministic, 20 steps. Loss at steps 1 / 10 / 20: DeepEP 7.74766 / 4.80887 / 4.40117, AllToAll 7.74766 / 4.80533 / 4.39565.
- No new test. The existing DeepEP tests cover the postprocess path, and the unit check above was a one-off run.
- `pytest tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py`: 40 passed, 3 xfailed.

stack-info: PR: #6037, branch: fegin/stack/35
fegin added a commit that referenced this pull request Nov 13, 2026
Stacked PRs:
 * __->__#6037
 * #6032
 * #6031
 * #6030


--- --- ---

### [muse_spark] Support DeepEP expert parallelism


## Summary (human-written)
As title. Enabling DeepEP for Muse Spark is trivial, performance is not
verified though.

## Why
`MuseSparkMoE.Config` rejects `DeepEPTokenDispatcher`, but nothing in
Muse Spark needs that. The shared MoE code already supports DeepEP with
an `output_postprocess`:
- In training, DeepEP uses its compact, host-synced path. The routed
rows match the received token counts, so there are no rows past the last
expert offset, and the HybridEP mask from #6032 is not needed.
- `RoutedExperts.forward` already applies the DeepEP routing scores
after the postprocess, because Muse Spark's per-expert RMSNorm is
nonlinear and must run first.

DeepEP is the EP backend that `search_r1` uses for both its trainer and
its CUDA-graphed generator (expand layout), so this should also unblock
Muse Spark RL on Hopper. I have not run the generator's expand layout
with Muse Spark.

## What changed
- `MuseSparkMoE.Config` accepts `DeepEPTokenDispatcher`.
`TorchAOTokenDispatcher` stays rejected.
- `RoutedExperts.forward`: comment at the HybridEP mask gate on why
DeepEP needs no mask. Training uses the compact layout, which has no
rows past the last offset. The expand layout runs only without grad:
`dispatch_tokens` forces the compact layout when grad is enabled, and
the DeepEP kernel forbids backward in expand mode.
- README: list DeepEP as supported, and add it to the CUDA graphs row:
training needs graphs disabled. Note that DeepEP's combine kernel needs
the MoE compressed dimension to be a multiple of 256. Add a TODO for the
config-time check. The production flavors use 4096. `debugmodel` uses
128, so it cannot run with DeepEP.

## Alternatives considered
- Add a `muse_spark_debugmodel_deepep` recipe and an integration test:
`debugmodel` cannot run DeepEP (compressed dimension 128), and changing
the debug flavor would change every Muse Spark debug run and golden
loss.
- Validate the hidden size in `DeepEPTokenDispatcher.Config`: today a
bad size fails at the first forward with DeepEP's static assert
("Invalid hidden"). A config-time check belongs to DeepEP in shared
code, so it is left for a separate PR.

## Numerics
Muse Spark debug model with compressed dimension 256 (a local config
change, see above), FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42,
deterministic, 20 steps:

| Step | AllToAll | DeepEP |
| --- | --- | --- |
| 1 | 7.75888 | 7.75888 |
| 2 | 6.82995 | 6.83072 |
| 10 | 4.81295 | 4.81803 |
| 20 | 4.40471 | 4.39651 |

Average over 20 steps: 5.18424 vs 5.18254. Step 1 matches. Later steps
differ by the combine kernels' summation order, with no consistent sign.

One-off unit check, the AllToAll comparison from the HybridEP tests run
with DeepEP and an RMSNorm postprocess (2x H100): loss, input grad, and
router, W13, W2, and norm weight grads match AllToAll within relative
error 4.7e-3, below the 1.56e-2 bound. Loss and the expert and norm
weight grads are bitwise equal.

## Performance
Not reported. DeepEP's expected benefit is multi-node communication, and
I only have single-node H100 runs, which would not show it.

## Testing
- `pytest
tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k
DeepEP` with DeepEP v2 at the CI pin 01dc3aa: 2 passed. These tests
already run with an RMSNorm postprocess and check the score order
against a reference.
- Muse Spark debugmodel with compressed_dim 256, FSDP2 + Ulysses CP2 +
EP4 (4x H100), seed 42, deterministic, 20 steps. Loss at steps 1 / 10 /
20: DeepEP 7.74766 / 4.80887 / 4.40117, AllToAll 7.74766 / 4.80533 /
4.39565.
- No new test. The existing DeepEP tests cover the postprocess path, and
the unit check above was a one-off run.
- `pytest tests/unit_tests/cpu/models/muse_spark
tests/unit_tests/cpu/recipes/test_muse_spark.py`: 40 passed, 3 xfailed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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