Skip to content

[MoE] Apply router scores before W2 projection - #4095

Closed
Mystri wants to merge 1 commit into
pytorch:mainfrom
Mystri:router-score-pre-w2-review
Closed

Mystri wants to merge 1 commit into
pytorch:mainfrom
Mystri:router-score-pre-w2-review

Conversation

@Mystri

@Mystri Mystri commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Current RoutedExperts applies router scores to each routed expert output after the W2 projection in TokenDispatcher.combine:

routed_output_RD = (
    routed_output_RD.to(torch.float32)
    * metadata.topk_scores_experts_sorted_N.reshape(-1, 1)
).to(routed_output_RD.dtype)

This multiplication causes the post-W2 routed_output_RD to retain for backward. Because W2 is linear, the router score can be applied earlier to the SwiGLU activation, immediately before W2:

routed_output_RD
 = W2(h_RF) * routed_score_R # current impl
 = W2(h_RF * routed_score_R) # our proposal

This change enables two memory-saving strategies:

  • Activation storage: Save h_RF instead of routed_output_RD. This reduces storage by approximately R × (D − F) elements = R × (D − F) × sizeof(dtype) bytes each layer.

  • Recomputation: With GraphTrainer’s fine-grained full recomputation, since we are not calculating multiplication with routed_output_RD, we don't need it for backward; W2 and the combine operation can be skipped from recomputation.

See the diagram below:

image

Plan

This change affects the full RoutedExperts workflow:

  1. Create a dispatcher that dispatches and permutes router scores together with the routed tokens.
  2. Forward the routed scores from RoutedExperts to GroupedExperts through the metadata produced by permute.
  3. In GroupedExperts, apply routed_scores_R to the SwiGLU activation h_RF after W1/W3 and the SwiGLU operation, but before W2.
  4. Prevent the dispatcher’s combine step from applying router scores a second time when score absorption is enabled.
  5. Add a configuration option in the dispatcher to enable or disable router-score absorption.

Current Scope:

Dispatcher:
The new workflow is supported for the basic local and all-to-all dispatchers. Other dispatchers
GroupedExperts:
GPT-OSS GroupedExperts can absorb the router score if the bias is scaled as well, but we haven't covered it.

Tests and verifications

  • Created float64 precision test between current and router-score-absorb versions to ensure that the change in compute order does not break numerical precision.
  • Verify with computation graph dump that h_RF is saved instead of routed_output_RD.
  • Verify with GraphTrainer Profiling that fine-grained recomputation saves W2 and combine while leaving W1/W3 recomputed.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 9, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/8gpu
  • ciflow/rl

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +135 to +137
absorb_router_scores: bool = False
"""Apply router scores to the expert intermediate before its output
projection, then skip router-score multiplication during combine."""

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Move this configuration to LocalTokenDispatcher.Config

@tianyu-l

Copy link
Copy Markdown
Contributor

Thanks for the proposal. I have some high level questions.

When router scores require gradients, that multiply retains the post-W2 (R, D) expert output for backward.

Sorry I got a bit lost. Could you spend a bit more paragraphs / charts explaining the existing issue, before we dive into the solution?

As for the solution, I see some if-else conditions. If the solution is strictly better than current code, what stops us from applying it for all moe models instead of just deepseek?

@Mystri

Mystri commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the proposal. I have some high level questions.

When router scores require gradients, that multiply retains the post-W2 (R, D) expert output for backward.

Sorry I got a bit lost. Could you spend a bit more paragraphs / charts explaining the existing issue, before we dive into the solution?

As for the solution, I see some if-else conditions. If the solution is strictly better than current code, what stops us from applying it for all moe models instead of just deepseek?

Hey, just updated the PR description, please check it out - I'm stating the gains more clearly: the absorption of expert scores into GroupedExperts removes the backward's dependency on the activation "routed_output_RD", so with GraphTrainer's "full" recomputation strategy, we could save great recomputation cost of the MoE module by avoiding W2 and combine.

@tianyu-l

Copy link
Copy Markdown
Contributor

Thanks a lot for the updated summary, I now understand the optimization.

My thoughts are

  • This PR is only optimizing the non-EP and naive EP (nccl all-to-all) paths, which exist as inefficient references. I feel that with more code complexity, the "optimized" EP paths can be improved as well? although not done in this PR.
  • We are seeing optimizations like distributed kernels which fuse dispatch/combine with experts computation, and we probably will add one soon. I somehow hope we can keep the code succinct when it comes to swapping into other efficient kernels. I would suggest we wait until we finish that exercise and see how well this optimization plugs in. cc @sanketpurandare
  • Speaking of activation recomputation policy, we will be migrating to torch_remat (https://github.com/meta-pytorch/remat) soon. (Not saying that it'd solve the problem here) cc @sdmyzlp

@Mystri
Mystri force-pushed the router-score-pre-w2-review branch from 9be6786 to 4b8fc6a Compare August 26, 2026 09:14
@Mystri
Mystri force-pushed the router-score-pre-w2-review branch 3 times, most recently from ee08c3d to e769ea2 Compare September 7, 2026 02:54
@Mystri
Mystri force-pushed the router-score-pre-w2-review branch from e769ea2 to b077e95 Compare September 28, 2026 13:47
@Mystri
Mystri force-pushed the router-score-pre-w2-review branch from b077e95 to df6ebfd Compare September 29, 2026 07:06
Apply router scores to the expert activations before the down (W2)
projection instead of multiplying the expert output in combine, so the
combine reduces to a plain sum:

- Token dispatchers expose absorb_router_scores. When set, dispatch
  returns routed_scores_R in its metadata and combine skips its score
  multiply. Covered backends: standard (local + all-to-all), TorchAO
  (EP=1 padded and EP>1), and DeepEP/HybridEP (opt-in).
- GroupedLinear.forward takes routed_scores_R and scales the projection
  input in float32, restoring the input dtype before the grouped GEMM.
  RoutedExperts passes it to W2 only, and only when a score is actually
  absorbed, so W2 modules that do not know about scores are unaffected.
- GptOssGroupedLinear scales its post-W2 bias rows by the same scores, so
  the result stays score * (h @ W2 + b2).
- DeepEP/HybridEP dispatchers take the per-row scores the backend already
  tracks and clear them from the dispatch state, which is what makes the
  backend combine skip its fused score multiply.
- make_routed_experts_config leaves the standard backend on auto and the
  DeepEP family off. Auto resolves when RoutedExperts is built: the score
  is absorbed unless output_postprocess owns the expert outputs, because
  absorbing scales W2's input while the postprocess runs after W2, and a
  scale-invariant postprocess (e.g. post-expert RMSNorm) would drop the
  score. Asking for both explicitly raises a ValueError.
- swap_token_dispatcher propagates the flag through MoE quantization.

Squashed from the router-score-pre-w2-review series after rebasing the
work onto main (5dc97a3), which had replaced GroupedExperts with
first-class grouped projections and added routed-expert output
postprocessing. Absorbed and post-combine paths agree to bf16 rounding;
loss convergence on a representative dataset is still pending.
@Mystri
Mystri force-pushed the router-score-pre-w2-review branch 2 times, most recently from df6ebfd to 0bb8665 Compare September 29, 2026 07:38
@tianyu-l tianyu-l closed this Oct 7, 2026
tianyu-l pushed a commit that referenced this pull request Nov 6, 2026
# [MoE] Apply router scores before W2 projection

Supersedes #4095 with a DeepEP-only implementation: router scores are
absorbed before W2 when `output_postprocess` is absent, and DeepEP
combine is one never-replayed remat region.

## Motivation

The original DeepEP path applies router scores to each routed expert
output after the W2 projection in `combine_tokens`:

```python
hidden_states = hidden_states * state.permuted_scores.to(
    hidden_states.dtype
).reshape(-1, 1)
```

This multiplication causes the post-W2 `routed_output_RD` to retain for
backward. Because W2 is linear, the router score can be applied earlier
to the SwiGLU activation, immediately before W2:

```
routed_output_RD
 = W2(h_RF) * routed_score_R # current impl
 = W2(h_RF * routed_score_R) # our proposal
```


See the diagram below:

<img width="4444" height="5508" alt="image"
src="https://github.com/user-attachments/assets/6f4e5155-6cfb-455f-925f-8d9165899666"
/>

### Expected memory gain in full model:
Combine output: `T * D * 2 = 4096 * 7168 * 2 = 56.0 MiB` per layer, `*
58 layers = 3.17 GiB`

W2 output: `(T * top_k) * D * 2 = 4096 * 8 * 7168 * 2 = 448.0 MiB` per
layer, `* 58 layers = 25.4 GiB`

Total per GPU: `25.4 + 3.17 = 28.6 GiB`

### Expected recomputation gain in FullAC
check
#5543 (comment)

#### GPT-OSS scoring overhead

Let `R` denote routed rows, `D` model width, and `F` expert intermediate
width. Assuming post-W2 scoring is inside SAVE combine, while absorbed
multiplications replay:

| Scoring work | Post-W2 | Absorption |
| --- | --- | --- |
| Forward multiplications | `RD` | `RF + RD` |
| Replay multiplications | `0` | `RF + RD` |
| Gradient scaling | `RD` | `RF + RD` |
| Score-gradient dot products | `≈2RD` | `≈2RF + 2RD` |
| **Total** | **`≈4RD`** | **`≈5RF + 5RD`** |

Common bias additions and expert bias-gradient reductions are excluded.
The extra scoring work is approximately `5RF + RD`. For GPT-OSS, `D = F
= 2880`, giving `17280R` additional FLOPs—about `0.026%` of FullAC's W2
GEMM FLOPs.

## Implementation
### Functionalities
- DeepEP dispatch returns per-row router scores explicitly through
`DeepEPDispatchMetadata`, rather than storing them in backend state for
combine.
- When `output_postprocess` is absent, DeepEP absorbs router scores into
W2's input. GPT-OSS additionally scales W2's per-expert bias, computing
`W2(s*h) + s*b2` in exact arithmetic.
- With `output_postprocess`, absorption is disabled and DeepEP applies
scores after postprocessing. Score products compute in FP32 and are cast
back to the activation/output dtype.
- DeepEP combine becomes a pure unpermute/reduction inside one
never-replayed remat region. Remove the redundant W2-output and
combine-output retention markers.

### GPT-OSS bias handling and compute cost

For biased experts:

```text
s * (W2(h) + b2) = W2(s*h) + s*b2
```

Applying scores after W2 makes the score gradient depend on the full
unscaled expert output. Absorption removes that dependency; when W2 and
its bias addition are saved, that output need not remain resident. The
bias branch adds pointwise operations and reductions, with no additional
GEMM.

### Tests
- Extend the existing DeepEP checkpoint tests with a `_PostW2` reference
that applies scores after W2, comparing loss and input/router/expert
gradients while preserving checkpoint equivalence and communication
replay checks.

## Measured memory/recompute improvment

Measured by adding:
```
print(remat.format_saved_tensors_report(loss))
```

in `def _non_pp_forward_backward_microbatch` in `training_engine.py`.

> Note (cc @tianyu-l ): consider making the saved-tensors report a
torchtitan configuration
> instead of a debug print.


### DeepEP dispatcher

#### Memory saved, with Selective AC

`deepseek_v3_debugmodel_deepep` (T=16384, top_k=3, EP=2, RegionAC
save-all), `ep_communication.combine`
region per MoE layer.

Baseline:

```
[rank0]:saved for backward: 2.52 GiB resident -- 6 region(s) 2.50 GiB, outside regions 16.19 MiB
[rank0]:
[rank0]:regions:
[rank0]:  379.38 MiB  layers.0  (17 storages)
[rank0]:  448.01 MiB  layers.1  (21 storages)
[rank0]:  429.44 MiB  layers.2  (21 storages)
[rank0]:  427.61 MiB  layers.3  (21 storages)
[rank0]:  441.39 MiB  layers.4  (21 storages)
[rank0]:  437.97 MiB  layers.5  (21 storages)
[rank0]:  + 118 saves rebuilt on recompute, not resident
[rank0]:
[rank0]:layers.1::moe.routed_experts.token_dispatcher.ep_communication.combine: 27.99 MiB
[rank0]:  109.81 KiB  saved.0          (56225, 1)           bfloat16
[rank0]:   27.45 MiB  saved.1          (56225, 256)         bfloat16
[rank0]:  439.26 KiB  saved.2          (56225, 256)         int64
```

Absorb:

```
[rank0]:saved for backward: 2.43 GiB resident -- 6 region(s) 2.41 GiB, outside regions 16.19 MiB
[rank0]:
[rank0]:regions:
[rank0]:  379.38 MiB  layers.0  (17 storages)
[rank0]:  414.24 MiB  layers.1  (19 storages)
[rank0]:  423.66 MiB  layers.2  (19 storages)
[rank0]:  418.56 MiB  layers.3  (19 storages)
[rank0]:  414.85 MiB  layers.4  (19 storages)
[rank0]:  419.60 MiB  layers.5  (19 storages)
[rank0]:  + 118 saves rebuilt on recompute, not resident
[rank0]:
[rank0]:layers.1::moe.routed_experts.token_dispatcher.ep_communication.combine: 394.53 KiB
[rank0]:  394.53 KiB  saved.0          (50500, 256)         int64
```

Debug model A/B (`deepseek_v3_debugmodel_deepep`, T=16384, top_k=3,
EP=2, RegionAC save-all):

| | `ep_communication.combine` retained |
| --- | --- |
| baseline (score in combine) | 27.99 MiB = w2 output 27.45 MiB + scores
109.8 KiB + indices 439.3 KiB |
| absorb | 394.5 KiB = indices only |

Whole-run resident: 2.52 GiB -> 2.43 GiB. Nothing else in the report
changes.

671B (T=4096, top_k=8, D=7168, 58 MoE layers, per GPU): w2 output
`R*D*2` = 448 MiB/layer
+ scores 1 MiB/layer (absorption-attributable, 25.4 GiB total) + combine
output `T*D*2` =
56 MiB/layer (independent marker cleanup, 3.17 GiB) = **28.6 GiB/GPU**
avoided retention, with no
recompute cost in exchange (w2 GEMM and combine are not replayed).

#### Recompute saved, with FullAC
see
#5543 (comment)

### Numerics

Moving router-score multiplication before a bias-free W2 is equivalent
in exact
arithmetic but changes BF16 rounding and therefore outputs and
gradients. The
original DeepEP path casts the score to the W2-output dtype before
multiplying.
The current implementation computes score products in FP32 via type
promotion,
then casts the product back to the activation/output dtype. When
absorption is
used, the scaled input is cast back to the activation dtype before W2.
GPT-OSS additionally scales its
per-expert bias. With `output_postprocess`, absorption is disabled and
scores
are applied after postprocessing.

FP32 score multiplication preserves score precision during the product,
but
casting the scaled input before W2 still differs from scoring W2's
rounded
output. This change does not preserve bitwise-identical outputs, losses,
or
gradients.

#### Historical 200-step DeepEP comparison against main (BF16 scoring)

The results below were measured at `8b9ced058`, before FP32 score
multiplication
and support for GPT-OSS bias and output-postprocess paths. They document
the
earlier BF16-scoring implementation and do not validate current-head
numerics
or those additional paths. A fresh training comparison is needed to
establish
convergence for the current implementation.

- PR: `8b9ced05834691fa51b3a5fa3c54f5e30c95279d`, DeepEP EP=2,
router scores cast to the activation dtype (BF16) before scaling W2's
input.
- Baseline: main at `b832ae41936a626ac0c8dc9ab1ae8dd556fd428b`, DeepEP
EP=2,
  with the original post-W2 score multiplication in combine. Main has no
  pre-W2 absorption path.

Both runs use two ranks, sequence length 2048, 16384 tokens per
microbatch per
DP rank, seed 42, `debug.deterministic=True`, and 200 steps. The primary
reference now uses the same DeepEP dispatcher as the PR, replacing the
earlier
AllToAll reference.

| DeepEP path | Step 1 loss | Step 200 loss | Mean loss, steps 181-200 |
Step 200 grad_norm |
| --- | ---: | ---: | ---: | ---: |
| Main: score after W2 | 7.98908 | 2.64903 | 2.59972 | 0.34110 |
| Historical PR: BF16 score before W2 | 7.98908 | 2.63242 | 2.58275 |
0.27930 |

Across 200 steps, the mean absolute loss difference is `0.01011365`, the
maximum
is `0.02818`, and the mean relative difference is `0.37725%` (main loss
as the
denominator). The final-20-step mean loss is `0.016978` lower for the PR
(`0.65307%` relative to main). Both loss curves decrease and all
supplied
`grad_norm` values remain finite. The loss and gradient trajectories
differ;
this comparison does not claim bitwise parity or an improvement in model
quality.
Statistics are calculated from the supplied rounded per-step metrics.

This is a single-seed, 200-step training comparison on the bundled
`c4_test`
fixture (`tests/assets/c4_test/data.json`); it does not establish
long-run or
full-C4 convergence. Additional AllToAll and Local runs at EP=1 match,
consistent
with the AllToAll local fallback; they do not provide extra distributed
EP coverage.

Run configuration (recorded in `loss_conv_configs2.py`, based on
`deepseek_v3_debugmodel`):

- Model: dim 256, vocabulary 2048, 16 heads, RoPE dim 64, six layers
  (five MoE, one dense), eight routed experts, two shared experts,
  MoE hidden dim 256, top-k 3, sigmoid router with score normalization.
- Parallelism: two ranks, `expert_parallel_degree=2`, `dp_shard=2` in
both runs;
  DeepEP `num_max_tokens_per_rank=16384`.
- Data: sequence length 2048, 16384 tokens per microbatch per DP rank,
  `ConcatThenSplitPackingConfig`.
- Training: 200 steps, seed 42, `debug.deterministic=True`,
FlexAttention,
  AdamW LR `8e-4`, two warmup steps, linear decay 0.8, minimum LR 0.
- Hardware: two NVLink-connected NVIDIA H800 GPUs (devices 2 and 3),
`EP_DISABLE_GIN=1`, `NCCL_GIN_CROSS_NIC=0` for the no-RDMA environment.
- Dependencies: Python 3.14.7, PyTorch `2.16.0.dev20261029+cu130` (CUDA
13.0),
torchtitan 0.2.2, DeepEP 2.1.0 rebuilt from v2.1.0 against NCCL 2.32.3.

## Verification reports

- [x] DeepEP GPU debug-model memory A/B: W2-output and combine-output
retention removed from `format_saved_tensors_report`, as shown above.
- [x] Historical 200-step C4 test-fixture DeepEP A/B: PR `8b9ced058`
(BF16 score before W2) vs main `b832ae419` (score after W2), both EP=2,
seed 42 and `debug.deterministic=True`; configuration, versions, loss
differences, and final gradient norms are reported above. This run
predates FP32 scoring and GPT-OSS bias/output-postprocess support and
does not validate current-head convergence.
- Coverage added in this PR: the two-GPU DeepEP checkpoint tests compare
loss and input/router/expert gradients against `_PostW2` and check
checkpoint equivalence and dispatch/combine replay counts.

---------

Co-authored-by: mystri <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu 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