Skip to content

[overrides] Stop recompiling the fused SwiGLU kernels for every row count - #6030

Merged
fegin merged 1 commit into
mainfrom
fegin/stack/32
Nov 11, 2026
Merged

fegin merged 1 commit into
mainfrom
fegin/stack/32

Conversation

@fegin

@fegin fegin commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

Stacked PRs:


[overrides] Stop recompiling the fused SwiGLU kernels for every row count

Summary (human-written)

NUM_ROWS is defined as constexpr. But that number is not always a
constant, for example with the AllToAll backend. As a result, Triton
recompiles SwiGLU every time it sees a new NUM_ROWS. Removing
tl.constexpr gives a large speedup. In one setting, TPS improves 8x.
The actual improvement depends on the workload.

According to the microbenchmark, the change can slow the backward kernel
by about 0.2 us at small shapes without offsets. Our models do not train
at these shapes, and the MoE path (with offsets) is not affected.

Why

NUM_ROWS is a tl.constexpr in both fused SwiGLU Triton kernels, so Triton compiles a new kernel for every new row count. When the routed row count changes every step and every MoE layer, the grouped-expert SwiGLU recompiles all the time. These recipes turn on the override with a changing row count:

  • Muse Spark with the AllToAll dispatcher (muse_spark_debugmodel and the base muse_spark_816b_a42b).
  • The trainer of rl_grpo_qwen3_30b_a3b_varlen_perf (AllToAll, EP4).
  • The trainer of search_r1 (DeepEP compact path).

Example. 40 calls of silu_and_mul_op with offsets, each with a new row count (4096 + 7i, F = 1024, one H100):

Forward kernel variants compiled ms per call (calls 10-39)
Before 40 2.96
After 2 0.29

What changed

  • NUM_ROWS is a runtime argument in _silu_and_mul_forward_kernel and _silu_and_mul_backward_kernel. The 2 variants left come from Triton's divisibility-by-16 specialization of integer arguments.
  • The strides stay constexpr. They do not depend on the row count.

Numerics

No change. Outputs and grads of the old and new kernels are bitwise equal for 4 shapes (row counts 37 to 4103, F 640 to 4096), with and without offsets.

Performance

Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the AllToAll dispatcher and the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30:

TPS, run 1 TPS, run 2 Memory, run 1 Memory, run 2
Before 2,138 2,401 7.33 GiB 7.53 GiB
After 18,624 (8.7x) 19,048 (7.9x) 7.67 GiB 7.17 GiB

The memory change has no consistent sign across the two runs, so it is noise.

I measured only the Muse Spark AllToAll case. The RL trainers above should gain too, but I did not measure them.

Callers with a constant row count compile once either way. These include dense feed-forwards, HybridEP non-blocking, the RL EXPAND layout, and the RL generators. For them, the runtime NUM_ROWS costs about 0.2 us in backward at small shapes without offsets, and nothing with offsets (the MoE path). Old vs new kernel, constant shape, one H100, triton.testing.do_bench, best of 3:

Rows x F Offsets Forward old / new (us) Backward old / new (us) Total
64 x 2048 no 8.69 / 8.70 7.06 / 7.09 +0.2%
256 x 4096 no 10.63 / 10.67 10.58 / 10.81 +1.3%
256 x 4096 yes 11.11 / 11.10 11.13 / 11.12 -0.1%
4096 x 1024 no 17.17 / 17.19 25.56 / 25.68 +0.3%
16384 x 18432 no 822 / 822 1391 / 1388 -0.1%

The 256 x 4096 case without offsets is consistently about +1.5% over 10 repeated runs. Dropping the row mask when the rows fill the blocks did not recover it, so the mask is not the cause.

Alternatives considered

  • Two kernels, one with a constexpr NUM_ROWS for constant row counts: the override only sees gate_up and offsets, not the dispatcher. Choosing the kernel needs a flag from the dispatcher through RoutedExperts, which adds a knob to shared MoE code to save about 0.2 us on tiny kernels.

Testing

  • pytest tests/unit_tests/cpu/recipes/test_fused_swiglu.py tests/unit_tests/gpu/recipes/test_fused_swiglu.py tests/unit_tests/gpu/recipes/test_fused_swiglu_override.py: 11 passed.
  • No new test. A recompile check would depend on Triton's private kernel cache layout.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 11, 2026
@fegin
fegin marked this pull request as draft November 11, 2026 18:24
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 marked this pull request as ready for review November 11, 2026 18:24
@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 51s —— View job


Approve: making NUM_ROWS a runtime argument fixes the recompiles at their cause and doesn't change numerics. Review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- this fixes the real cause (NUM_ROWS is part of Triton's compile key) with the smallest possible change, and it does not change numerics.

What this PR does. It makes NUM_ROWS a runtime argument instead of tl.constexpr in _silu_and_mul_forward_kernel and _silu_and_mul_backward_kernel. Before, Triton compiled a new kernel for every distinct routed row count. Under the AllToAll dispatcher that count changes every step and in every MoE layer. Every other constexpr (NUM_COLS, NUM_OFFSETS, HAS_OFFSETS, the strides, the block sizes) is fixed for a given model, so after this change the remaining variants come only from Triton's integer specialization (divisibility by 16, and possibly ==1).

Example.

# grouped experts, gate_up [R, 2, F], offsets = per-expert cumsum
step 1, layer 0: R = 4096 -> compile, run
step 1, layer 1: R = 4103 -> before: compile again | after: reuse (R % 16 != 0 variant)
step 2, layer 0: R = 4112 -> before: compile again | after: reuse (R % 16 == 0 variant)
Details
  • Strides stay constexpr, and that is correct. gate_up is [R, 2, F] with strides (2F, F, 1). After unbind(-2), gate and up have strides (2F, 1), and out / grad_gate_up from empty_like(..., contiguous_format) have strides (F, 1) / (2F, 1). None of them depend on R, so they don't cause recompiles. The dense path gate_up.reshape(-1, *gate_up.shape[-2:]) (fused_swiglu.py:353) gives the same strides.
  • Overflow. Row offsets are still computed from row_start, which is tl.program_id(0).to(tl.int64) * BLOCK_M. A runtime NUM_ROWS passed as i32 is only compared against rows, so dropping constexpr doesn't change the index width.
  • With offsets, NUM_ROWS is never read (row_limit comes from offsets[-1]). It still forced recompiles only because it was in the specialization key, which matches the measured speedup on the MoE path and the flat perf with offsets.
  • Consistent with the repo. torchtitan_recipes/overrides/higher_precision_rms_norm.py:120,201,270 already passes NUM_ROWS as a runtime argument.
  • Two kernels / dispatcher flag (rejected alternative). I agree with the description: selecting the kernel by a dispatcher flag through RoutedExperts would bend shared MoE code to save about 0.2 us.
  • No new test. I agree: a recompile-count check would have to depend on Triton's private cache layout, and the existing fused SwiGLU tests already cover numerics.

Not verified: the microbenchmarks and the Muse Spark TPS numbers (these need a GPU).

@fegin
fegin marked this pull request as draft November 11, 2026 22:14
@fegin
fegin marked this pull request as ready for review November 11, 2026 22:15
…ount

## Summary (human-written)
`NUM_ROWS` is defined as constexpr. But that number is not always a
constant, for example with the AllToAll backend. As a result, Triton
recompiles SwiGLU every time it sees a new `NUM_ROWS`. Removing
`tl.constexpr` gives a large speedup. In one setting, TPS improves 8x.
The actual improvement depends on the workload.

According to the microbenchmark, the change can slow the backward kernel
by about 0.2 us at small shapes without offsets. Our models do not train
at these shapes, and the MoE path (with offsets) is not affected.

## Why
`NUM_ROWS` is a `tl.constexpr` in both fused SwiGLU Triton kernels, so Triton compiles a new kernel for every new row count. When the routed row count changes every step and every MoE layer, the grouped-expert SwiGLU recompiles all the time. These recipes turn on the override with a changing row count:
- Muse Spark with the AllToAll dispatcher (`muse_spark_debugmodel` and the base `muse_spark_816b_a42b`).
- The trainer of `rl_grpo_qwen3_30b_a3b_varlen_perf` (AllToAll, EP4).
- The trainer of `search_r1` (DeepEP compact path).

**Example.** 40 calls of `silu_and_mul_op` with offsets, each with a new row count (4096 + 7i, F = 1024, one H100):

| | Forward kernel variants compiled | ms per call (calls 10-39) |
| --- | --- | --- |
| Before | 40 | 2.96 |
| After | 2 | 0.29 |

## What changed
- `NUM_ROWS` is a runtime argument in `_silu_and_mul_forward_kernel` and `_silu_and_mul_backward_kernel`. The 2 variants left come from Triton's divisibility-by-16 specialization of integer arguments.
- The strides stay `constexpr`. They do not depend on the row count.

## Numerics
No change. Outputs and grads of the old and new kernels are bitwise equal for 4 shapes (row counts 37 to 4103, F 640 to 4096), with and without offsets.

## Performance
Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the AllToAll dispatcher and the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30:

| | TPS, run 1 | TPS, run 2 | Memory, run 1 | Memory, run 2 |
| --- | --- | --- | --- | --- |
| Before | 2,138 | 2,401 | 7.33 GiB | 7.53 GiB |
| After | 18,624 (8.7x) | 19,048 (7.9x) | 7.67 GiB | 7.17 GiB |

The memory change has no consistent sign across the two runs, so it is noise.

I measured only the Muse Spark AllToAll case. The RL trainers above should gain too, but I did not measure them.

Callers with a constant row count compile once either way. These include dense feed-forwards, HybridEP non-blocking, the RL EXPAND layout, and the RL generators. For them, the runtime `NUM_ROWS` costs about 0.2 us in backward at small shapes without offsets, and nothing with offsets (the MoE path). Old vs new kernel, constant shape, one H100, `triton.testing.do_bench`, best of 3:

| Rows x F | Offsets | Forward old / new (us) | Backward old / new (us) | Total |
| --- | --- | --- | --- | --- |
| 64 x 2048 | no | 8.69 / 8.70 | 7.06 / 7.09 | +0.2% |
| 256 x 4096 | no | 10.63 / 10.67 | 10.58 / 10.81 | +1.3% |
| 256 x 4096 | yes | 11.11 / 11.10 | 11.13 / 11.12 | -0.1% |
| 4096 x 1024 | no | 17.17 / 17.19 | 25.56 / 25.68 | +0.3% |
| 16384 x 18432 | no | 822 / 822 | 1391 / 1388 | -0.1% |

The 256 x 4096 case without offsets is consistently about +1.5% over 10 repeated runs. Dropping the row mask when the rows fill the blocks did not recover it, so the mask is not the cause.

## Alternatives considered
- Two kernels, one with a constexpr `NUM_ROWS` for constant row counts: the override only sees `gate_up` and `offsets`, not the dispatcher. Choosing the kernel needs a flag from the dispatcher through `RoutedExperts`, which adds a knob to shared MoE code to save about 0.2 us on tiny kernels.

## Testing
- `pytest tests/unit_tests/cpu/recipes/test_fused_swiglu.py tests/unit_tests/gpu/recipes/test_fused_swiglu.py tests/unit_tests/gpu/recipes/test_fused_swiglu_override.py`: 11 passed.
- No new test. A recompile check would depend on Triton's private kernel cache layout.

stack-info: PR: #6030, branch: fegin/stack/32
@fegin
fegin marked this pull request as draft November 11, 2026 22:19
@fegin
fegin marked this pull request as ready for review November 11, 2026 22:19
@fegin
fegin merged commit b8cebbf into main 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 12, 2026
## Summary (human-written)
Muse Spark currently only supports AllToAll and Dist-MoE backends. The
former is slow and the latter cannot be used on Hopper. This PR enables
HybridEP.

The main design decision is how to run `output_postprocess`, which Muse
Spark uses to perform RMSNorm after the experts and before combine. With
non-blocking HybridEP, the rows past the last expert offset are never
written, so `output_postprocess` needs `torch.where` masks around it to
keep those rows out of the forward and the gradients. The masks are
slow in eager mode, so we use local_compile to fuse them into the
RMSNorm kernels.

See the performance section. TL;DR: with local_compile and CUDA graphs,
we see about 60% higher TPS than AllToAll (note that the AllToAll
performance is also improved after #6030).

## Why
On Hopper, Dist-MoE is not available, so Muse Spark's only EP path is the AllToAll dispatcher. AllToAll syncs the CPU in every MoE layer, so it cannot use CUDA graphs. `MuseSparkMoE.Config` rejects HybridEP, which has no CPU sync in non-blocking mode and supports CUDA graphs. The check was added when the per-expert norm could only run after combine. `output_postprocess` (#4623) now runs it before combine, and HybridEP applies scores after it, so the operation order is right.

Allowing HybridEP alone is not enough. Non-blocking HybridEP (`non_blocking_capacity_factor` set) sizes the routed rows to its capacity, not to the received token count. Rows past `offsets_E[-1]` are never written: in forward, the grouped GEMMs only write rows inside the expert offsets, and in backward, HybridEP's combine backward only writes grads for received tokens. So those rows hold stale memory in both directions. `output_postprocess` runs on every row, so its parameter grads sum over those rows. The result is a wrong grad, or NaN when the stale memory is not finite. Muse Spark is the only model that sets `output_postprocess`, so no other model hits this.

**Example.**
```python
config = muse_spark_debugmodel(seq_len)
config = apply_transforms(config, [TokenDispatcherTransform(
    dispatcher=HybridEPTokenDispatcher,
    num_max_tokens_per_rank=tokens_per_microbatch // (cp * tp),
    kwargs={"non_blocking_capacity_factor": 1.0},
)])
# main: ValueError("Muse Spark MoE requires LocalTokenDispatcher or AllToAllTokenDispatcher, ...")
# only the check removed: "Loss or gradient norm is not finite" at step 1
# this change: trains
```

The stale rows, at EP2, 64 tokens per rank, top-2, capacity factor 1.0, RMSNorm postprocess:
```
routed rows: 256, valid rows (offsets_E[-1]): 128
rows 128..255: stale inputs (abs max ~30) and nonzero incoming grads (abs max ~14)
norm weight grad vs AllToAll: relative error 1.2 and 1.5 (all other grads bitwise equal)
```

## What changed
- Shared MoE (`models/common/moe/moe.py`, please review this first): with non-blocking HybridEP and an `output_postprocess`, `RoutedExperts.forward` calls `_masked_output_postprocess`. It masks rows past `offsets_E[-1]` with `torch.where` before the postprocess (finite forward) and after it (zero grad for those rows). `torch.where` instead of a multiply, so NaN rows are dropped too. The mask is built on the GPU from `offsets_E`, so there is no CPU sync and CUDA graph capture still works. The function is a `local_compile` region (`moe_masked_output_postprocess`), so Inductor fuses both masks into the postprocess kernels. Without the region it runs eagerly with the same math. In training, other dispatchers and blocking HybridEP never produce rows past the last offset, so they skip it. HybridEP `pad_multiple` padding rows are inside the offsets, and HybridEP writes zeros to them in both directions, so they need no mask. Dist-MoE does not use this forward.
- Muse Spark enables the `moe_masked_output_postprocess` region in its default `local_compile.regions`.
- `MuseSparkMoE.Config` accepts `HybridEPTokenDispatcher`. DeepEP stays rejected because it is untested with Muse Spark.
- Add the `muse_spark_debugmodel_hybridep` test recipe with CUDA graphs on, like `deepseek_v3_debugmodel_hybridep`. Capacity factor 1.0 reserves the worst case, so no tokens are dropped.
- Integration: add a Muse Spark FSDP2 + TP2 (SP) + EP2 run to the H100 HybridEP test, renamed from `deepseek_v3_fsdp+hybridep` to `fsdp+hybridep` because it covers both models. Mechanical: update the test name in `run_8xgpu_integration_tests.sh`, `validate_release_gpu.sh`, and `test_integration_test_definitions.py`. The last also checks every config of the test, not only the first.
- README: list HybridEP as supported (verified with FSDP, TP+EP, and CUDA graphs; CP is not verified), say that on Hopper it is the EP path with CUDA graph support, give its memory cost (about 2x at capacity factor 1.0) and measured speedup, note its BF16 score rounding, and drop MinimalAsyncEP, which was deleted in #4627.

## Alternatives considered
- Clean the rows inside HybridEP: only covers backward. The forward stale rows come from w2's grouped GEMM output. Masking in `RoutedExperts` handles both directions in one place.
- Mask whenever `output_postprocess` is set: adds the mask cost to Muse Spark with AllToAll, which has no capacity rows.
- A dispatcher property such as "may produce rows past the last offset": an interface with one implementer. The check follows the existing `DeepEPDispatchMetadata` branch in the same forward instead.
- Reject non-blocking HybridEP with `output_postprocess`: blocking mode syncs the CPU in every MoE layer and cannot use CUDA graphs, which removes most of the reason to use HybridEP on Hopper.

## Numerics
No change for other models or for Muse Spark with AllToAll: the mask only runs for non-blocking HybridEP with `output_postprocess`.

Compiling the mask region does not change numerics: unfused masks vs the compiled region, `muse_spark_debugmodel_hybridep` on 4x H100, 20 steps, `scripts/loss_compare.py`: loss is bitwise identical at every step, and grad_norm matches.

Muse Spark debug model, FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps, `scripts/loss_compare.py`, AllToAll (`muse_spark_debugmodel`) vs HybridEP (`muse_spark_debugmodel_hybridep`):

| Step | AllToAll | HybridEP | Diff |
| --- | --- | --- | --- |
| 1 | 7.782996 | 7.783380 | +0.000383 |
| 2 | 6.977194 | 6.979984 | +0.002790 |
| 10 | 4.832992 | 4.837770 | +0.004778 |
| 20 | 4.407280 | 4.412218 | +0.004938 |

Average over 20 steps: 5.233406 vs 5.231284. The differences have no consistent sign. HybridEP rounds the routing scores to BF16 before the combine multiply, while AllToAll multiplies in FP32, and the two combine kernels sum in a different order. The README notes the BF16 rounding.

## Performance
Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30. All runs include the fused SwiGLU recompile fix earlier in this stack; without it, AllToAll runs at 2,138 TPS.

| Config | TPS | Memory |
| --- | --- | --- |
| AllToAll | 18,624 | 7.7 GiB |
| HybridEP eager, masks unfused | 18,618 | 16.7 GiB |
| HybridEP eager, masks compiled | 21,439 (+15%) | 16.7 GiB |
| HybridEP CUDA graphs, masks unfused | 24,777 | 16.8 GiB |
| HybridEP CUDA graphs, masks compiled | 30,287 (+63%) | 16.8 GiB |

- Most of the gain comes from CUDA graphs, which AllToAll cannot use.
- Unfused, the masks run over all capacity rows (8x the valid rows at EP8 and top-8), and remat runs them again. Compiling them into the postprocess region removes that cost: +15% eager, +22% with graphs.
- The extra memory comes from capacity factor 1.0. A lower factor saves memory but can drop tokens.

## Testing
- The HybridEP activation-checkpointing tests also run with an RMSNorm postprocess, as the DeepEP tests do, so remat replay stays exact around the mask. The shared test helper also compares each HybridEP run (blocking and non-blocking) with an AllToAll reference: loss, input grad, and router, W13, W2, and norm weight grads within 2 BF16 eps (normwise). It builds this reference the same way it builds the post-W2 scoring reference for DeepEP. Without the mask, the comparison fails (NaN vs a bound of 0.87). This is the regression it catches. The tests run the mask function eagerly; the loss comparison above covers the compiled region.
- `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k HybridEP`: 3 passed. With DeepEP v2: `-k DeepEP`, 2 passed.
- Manual check: the AllToAll comparison also passes with `pad_multiple=32`, with and without the postprocess. So the per-expert padding rows inside the offsets do not affect gradients.
- `python -m tests.integration_tests.run_tests --test_suite h100 --execution_mode real_pg --ngpu 4 --test_name=fsdp+hybridep` (4x H100, HybridEP at the CI pin f725d29), CUDA graphs on: both configs pass and record a CUDA graph. The Muse Spark config (FSDP2 + TP2 + SP + EP2) keeps local compile on, so CI runs the compiled mask region. SPMD type checking would turn it off; Muse Spark TP+SP+EP type checking is covered by `muse_spark_mm_fsdp+tp+cp+ep+sp`. Muse Spark loss goes from about 7.7 to about 4.9-5.2 in 10 steps across three runs.
- `pytest tests/unit_tests/cpu/test_integration_test_definitions.py tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py tests/unit_tests/cpu/config`: 263 passed, 3 xfailed.
- `pytest tests/unit_tests/cpu -k "moe or expert or dispatcher or local_compile"`: 147 passed, 1 skipped.

## Known issues / follow-ups
- CP + EP with HybridEP is not tested.
- Multimodal training with CUDA graphs is not supported for Muse Spark with any dispatcher.
- The score multiply in HybridEP's combine also runs over all capacity rows. Moving it into a compiled region would change HybridEP's combine, which DeepSeek-V3 also uses, so it is left for a follow-up.

stack-info: PR: #6032, branch: fegin/stack/34
fegin added a commit that referenced this pull request Nov 12, 2026
## Summary (human-written)
Muse Spark currently only supports AllToAll and Dist-MoE backends. The
former is slow and the latter cannot be used on Hopper. This PR enables
HybridEP.

The main design decision is how to run `output_postprocess`, which Muse
Spark uses to perform RMSNorm after the experts and before combine. With
non-blocking HybridEP, the rows past the last expert offset are never
written, so `output_postprocess` needs `torch.where` masks around it to
keep those rows out of the forward and the gradients. The masks are
slow in eager mode, so we use local_compile to fuse them into the
RMSNorm kernels.

See the performance section. TL;DR: with local_compile and CUDA graphs,
we see about 60% higher TPS than AllToAll (note that the AllToAll
performance is also improved after #6030).

## Why
On Hopper, Dist-MoE is not available, so Muse Spark's only EP path is the AllToAll dispatcher. AllToAll syncs the CPU in every MoE layer, so it cannot use CUDA graphs. `MuseSparkMoE.Config` rejects HybridEP, which has no CPU sync in non-blocking mode and supports CUDA graphs. The check was added when the per-expert norm could only run after combine. `output_postprocess` (#4623) now runs it before combine, and HybridEP applies scores after it, so the operation order is right.

Allowing HybridEP alone is not enough. Non-blocking HybridEP (`non_blocking_capacity_factor` set) sizes the routed rows to its capacity, not to the received token count. Rows past `offsets_E[-1]` are never written: in forward, the grouped GEMMs only write rows inside the expert offsets, and in backward, HybridEP's combine backward only writes grads for received tokens. So those rows hold stale memory in both directions. `output_postprocess` runs on every row, so its parameter grads sum over those rows. The result is a wrong grad, or NaN when the stale memory is not finite. Muse Spark is the only model that sets `output_postprocess`, so no other model hits this.

**Example.**
```python
config = muse_spark_debugmodel(seq_len)
config = apply_transforms(config, [TokenDispatcherTransform(
    dispatcher=HybridEPTokenDispatcher,
    num_max_tokens_per_rank=tokens_per_microbatch // (cp * tp),
    kwargs={"non_blocking_capacity_factor": 1.0},
)])
# main: ValueError("Muse Spark MoE requires LocalTokenDispatcher or AllToAllTokenDispatcher, ...")
# only the check removed: "Loss or gradient norm is not finite" at step 1
# this change: trains
```

The stale rows, at EP2, 64 tokens per rank, top-2, capacity factor 1.0, RMSNorm postprocess:
```
routed rows: 256, valid rows (offsets_E[-1]): 128
rows 128..255: stale inputs (abs max ~30) and nonzero incoming grads (abs max ~14)
norm weight grad vs AllToAll: relative error 1.2 and 1.5 (all other grads bitwise equal)
```

## What changed
- Shared MoE (`models/common/moe/moe.py`, please review this first): with non-blocking HybridEP and an `output_postprocess`, `RoutedExperts.forward` calls `_masked_output_postprocess`. It masks rows past `offsets_E[-1]` with `torch.where` before the postprocess (finite forward) and after it (zero grad for those rows). `torch.where` instead of a multiply, so NaN rows are dropped too. The mask is built on the GPU from `offsets_E`, so there is no CPU sync and CUDA graph capture still works. The function is a `local_compile` region (`moe_masked_output_postprocess`), so Inductor fuses both masks into the postprocess kernels. Without the region it runs eagerly with the same math. In training, other dispatchers and blocking HybridEP never produce rows past the last offset, so they skip it. HybridEP `pad_multiple` padding rows are inside the offsets, and HybridEP writes zeros to them in both directions, so they need no mask. Dist-MoE does not use this forward.
- Muse Spark enables the `moe_masked_output_postprocess` region in its default `local_compile.regions`.
- `MuseSparkMoE.Config` accepts `HybridEPTokenDispatcher`. DeepEP stays rejected because it is untested with Muse Spark.
- Add the `muse_spark_debugmodel_hybridep` test recipe with CUDA graphs on, like `deepseek_v3_debugmodel_hybridep`. Capacity factor 1.0 reserves the worst case, so no tokens are dropped.
- Integration: add a Muse Spark FSDP2 + TP2 (SP) + EP2 run to the H100 HybridEP test, renamed from `deepseek_v3_fsdp+hybridep` to `fsdp+hybridep` because it covers both models. Mechanical: update the test name in `run_8xgpu_integration_tests.sh`, `validate_release_gpu.sh`, and `test_integration_test_definitions.py`. The last also checks every config of the test, not only the first.
- README: list HybridEP as supported (verified with FSDP, TP+EP, Ulysses CP+EP, and CUDA graphs), say that on Hopper it is the EP path with CUDA graph support, give its memory cost (about 2x at capacity factor 1.0) and measured speedup, note its BF16 score rounding, and drop MinimalAsyncEP, which was deleted in #4627.

## Alternatives considered
- Clean the rows inside HybridEP: only covers backward. The forward stale rows come from w2's grouped GEMM output. Masking in `RoutedExperts` handles both directions in one place.
- Mask whenever `output_postprocess` is set: adds the mask cost to Muse Spark with AllToAll, which has no capacity rows.
- A dispatcher property such as "may produce rows past the last offset": an interface with one implementer. The check follows the existing `DeepEPDispatchMetadata` branch in the same forward instead.
- Reject non-blocking HybridEP with `output_postprocess`: blocking mode syncs the CPU in every MoE layer and cannot use CUDA graphs, which removes most of the reason to use HybridEP on Hopper.

## Numerics
No change for other models or for Muse Spark with AllToAll: the mask only runs for non-blocking HybridEP with `output_postprocess`.

Compiling the mask region does not change numerics: unfused masks vs the compiled region, `muse_spark_debugmodel_hybridep` on 4x H100, 20 steps, `scripts/loss_compare.py`: loss is bitwise identical at every step, and grad_norm matches.

Muse Spark debug model, FSDP2 + TP2 (SP) + EP2 on 4x H100, seed 42, deterministic, 20 steps, `scripts/loss_compare.py`, AllToAll (`muse_spark_debugmodel`) vs HybridEP (`muse_spark_debugmodel_hybridep`):

| Step | AllToAll | HybridEP | Diff |
| --- | --- | --- | --- |
| 1 | 7.782996 | 7.783380 | +0.000383 |
| 2 | 6.977194 | 6.979984 | +0.002790 |
| 10 | 4.832992 | 4.837770 | +0.004778 |
| 20 | 4.407280 | 4.412218 | +0.004938 |

Average over 20 steps: 5.233406 vs 5.231284. The differences have no consistent sign. HybridEP rounds the routing scores to BF16 before the combine multiply, while AllToAll multiplies in FP32, and the two combine kernels sum in a different order. The README notes the BF16 rounding.

## Performance
Scaled-up Muse Spark (dim 2048, 8 layers, 64 experts, top-8, compressed dim 1024, seq 4096) with the fused SwiGLU override, FSDP8 + EP8 on 8x H100, mean TPS over steps 11-30. All runs include the fused SwiGLU recompile fix earlier in this stack; without it, AllToAll runs at 2,138 TPS.

| Config | TPS | Memory |
| --- | --- | --- |
| AllToAll | 18,624 | 7.7 GiB |
| HybridEP eager, masks unfused | 18,618 | 16.7 GiB |
| HybridEP eager, masks compiled | 21,439 (+15%) | 16.7 GiB |
| HybridEP CUDA graphs, masks unfused | 24,777 | 16.8 GiB |
| HybridEP CUDA graphs, masks compiled | 30,287 (+63%) | 16.8 GiB |

- Most of the gain comes from CUDA graphs, which AllToAll cannot use.
- Unfused, the masks run over all capacity rows (8x the valid rows at EP8 and top-8), and remat runs them again. Compiling them into the postprocess region removes that cost: +15% eager, +22% with graphs.
- The extra memory comes from capacity factor 1.0. A lower factor saves memory but can drop tokens.

## Testing
- The HybridEP activation-checkpointing tests also run with an RMSNorm postprocess, as the DeepEP tests do, so remat replay stays exact around the mask. The shared test helper also compares each HybridEP run (blocking and non-blocking) with an AllToAll reference: loss, input grad, and router, W13, W2, and norm weight grads within 2 BF16 eps (normwise). It builds this reference the same way it builds the post-W2 scoring reference for DeepEP. Without the mask, the comparison fails (NaN vs a bound of 0.87). This is the regression it catches. The tests run the mask function eagerly; the loss comparison above covers the compiled region.
- `pytest tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py -k HybridEP`: 3 passed. With DeepEP v2: `-k DeepEP`, 2 passed.
- Manual check: the AllToAll comparison also passes with `pad_multiple=32`, with and without the postprocess. So the per-expert padding rows inside the offsets do not affect gradients.
- `python -m tests.integration_tests.run_tests --test_suite h100 --execution_mode real_pg --ngpu 4 --test_name=fsdp+hybridep` (4x H100, HybridEP at the CI pin f725d29), CUDA graphs on: both configs pass and record a CUDA graph. The Muse Spark config (FSDP2 + TP2 + SP + EP2) keeps local compile on, so CI runs the compiled mask region. SPMD type checking would turn it off; Muse Spark TP+SP+EP type checking is covered by `muse_spark_mm_fsdp+tp+cp+ep+sp`. Muse Spark loss goes from about 7.7 to about 4.9-5.2 in 10 steps across three runs.
- Muse Spark debugmodel, FSDP2 + Ulysses CP2 + EP4 (4x H100), seed 42, deterministic, 20 steps. Loss at steps 1 / 10 / 20: HybridEP (capacity 1.0) 7.77302 / 4.83989 / 4.40672, AllToAll 7.77313 / 4.84151 / 4.41106. HybridEP with CUDA graphs prints the same loss as without them.
- `pytest tests/unit_tests/cpu/test_integration_test_definitions.py tests/unit_tests/cpu/models/muse_spark tests/unit_tests/cpu/recipes/test_muse_spark.py tests/unit_tests/cpu/config`: 263 passed, 3 xfailed.
- `pytest tests/unit_tests/cpu -k "moe or expert or dispatcher or local_compile"`: 147 passed, 1 skipped.

## Known issues / follow-ups
- Multimodal training with CUDA graphs is not supported for Muse Spark with any dispatcher.
- The score multiply in HybridEP's combine also runs over all capacity rows. Moving it into a compiled region would change HybridEP's combine, which DeepSeek-V3 also uses, so it is left for a follow-up.
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

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants