Skip to content

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

Merged
tianyu-l merged 41 commits into
pytorch:mainfrom
Mystri:router-score-pre-w2-review
Nov 6, 2026
Merged

tianyu-l merged 41 commits into
pytorch:mainfrom
Mystri:router-score-pre-w2-review

Conversation

@Mystri

@Mystri Mystri commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

[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:

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:

image

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:

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

  • DeepEP GPU debug-model memory A/B: W2-output and combine-output retention removed from format_saved_tensors_report, as shown above.
  • 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.

@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 19, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 19, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Oct 19, 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/rl
  • ciflow/fake-pg

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.

@Mystri

Mystri commented Oct 26, 2026

Copy link
Copy Markdown
Contributor Author

@tianyu-l, could you take a look when you have time, particularly at moving router scores before W2 and the never-replayed combine regions? I’ve included dispatcher parity tests and before/after saved-tensor reports.

If another maintainer would be better placed to review this, please point me to them. Thanks!

@tianyu-l
tianyu-l requested a review from acisseJZhong October 27, 2026 05:21
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude explain the gain from this PR for different combinations of (remat policy, deepep / hybridep dispatcher) combinations. The complexity is quite high, so I wanted to understand if the change is worth it; and if so if there are other ways to make it more maintainable.

Some notes:

  • It doesn't seem to apply to DistMoE, which is the main optimized MoE backend
  • the AllToAllTokenDispatcher is a reference impl and not something we care perf about

@claude

claude Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 40s —— View job


Is this PR worth its complexity? Gain by (remat policy × dispatcher)

Short answer: the memory gain is real and large for one combination: DeepEP + a policy that saves w2 (Default or save-all), and only when the user opts in to absorb_router_scores=True. For HybridEP the gain is about zero as written. DistMoE is untouched. The rest of the PR is the AllToAll/Local/TorchAO reference paths plus config plumbing. Under FullAC + DeepEP with the default absorb=False, it looks like the PR makes memory worse.

I got the numbers below by reading the code, not by running it. Sizes are for 671B per GPU: T=4096, top_k=8, D=7168, F=2048, so R = T·top_k = 32768. Per layer, the w2 output R·D·bf16 is 448 MiB, the combine output T·D·bf16 is 56 MiB, and h (the SwiGLU output) R·F·bf16 is 128 MiB.

Dispatcher Remat policy main This PR, absorb=True This PR, absorb=False (DeepEP/HybridEP default)
DistMoE any — not affected. dist_moe.routed_experts is one opaque recompute=False region that owns dispatch, the expert GEMMs, activation storage and combine (dist_moe/routed_experts.py:224) same
DeepEP Default (save *, recompute w13) / save-all w2 output pinned as SAVE_OUTPUT by recompute_needs_tensor in combine (448 MiB). Combine output pinned (56 MiB) −448 MiB −56 MiB/layer (~28.6 GiB/GPU). The real win w2 output now held by the mul inside the never-replayed combine region instead of the pin: same 448 MiB. −56 MiB from removing the combine-output pin
DeepEP Full nothing resident. Combine is replayed, so the combine kernel runs again in backward memory about the same (combine keeps only indices). Saves the combine replay in backward (one EP combine per layer) ⚠️ Looks like a regression: the combine region is forced recompute=False and its mul saves the w2 output. That is +448 MiB/layer resident where main had nothing. It also affects muse_spark on the standard path, since its output_postprocess resolves auto to absorb=False
DeepEP no AC mul saves the w2 output (448 MiB) w2 output freed, but GroupedLinear adds an fp32 copy of h (see below): +256 MiB. Net −192 MiB/layer (−448 with the fix) unchanged
HybridEP Default / save-all w2 output pinned by recompute_needs_tensor(routed_output_RD). Dispatch and combine have no remat region, so they are bare and replayed ≈ 0. The pin is still there (token_dispatcher.py, HybridEPTokenDispatcher.combine), so the w2 output stays resident even though nothing needs it for backward any more unchanged
HybridEP Full nothing resident ≈ 0 unchanged
HybridEP no AC mul saves the w2 output −448 + 256 (fp32 h) = −192 MiB/layer unchanged
AllToAll / Local / TorchAO — reference paths; perf doesn't matter auto-absorbs —

Notes on the table:

  1. HybridEP gets nothing under any remat policy. To get the DeepEP win it needs a never-replayed combine region, as DeepEP has in this PR, or at least dropping the pin when the scores were absorbed. The PR says HybridEP was not tested (GB200 only), and the code changes there are plumbing with no benefit.
  2. The 56 MiB/layer (3.17 GiB) is separate from absorption. It comes from deleting remat.recompute_needs_tensor(combined) in deepep.combine_tokens. The next consumer is the shared_add region, which is recompute=False and saves nothing. This could land on its own as a one-line PR. Without shared experts, the TP zero-fill at moe.py:918 pins the output again anyway.
  3. fp32 copy in GroupedLinear.forward. input_RI.float() * routed_scores_R.reshape(-1, 1) saves a float32 copy of h (R·F·4 = 256 MiB/layer) for the score gradient. This is the pattern that the comment in _score_and_scatter_add explicitly avoids. Writing (input_RI * routed_scores_R.reshape(-1, 1)).to(input_RI.dtype) uses type promotion and saves only the bf16 input. Under replay policies this copy is short-lived but still raises the backward peak; with no AC it stays resident.
  4. Numerics. Absorbing rounds h * s to bf16 before the GEMM, where main rounds the GEMM output and multiplies in fp32. So the results are not bitwise identical, and CLAUDE.md requires a convergence run. The PR's C4 checkbox is still open.

Is it worth it?

For DeepEP with the Default policy, yes: the w2 output is the largest MoE tensor still resident under Default (D=7168 > F=2048), so removing it is a big win for little compute. Everything else in the 1353-line diff exists to support paths you said you don't care about (AllToAll, Local, TorchAO), a path with no gain (HybridEP), or the opt-in and auto-resolution machinery.

How to make it more maintainable

  1. Decide in RoutedExperts, not in dispatcher configs. Whether absorption is valid depends on the experts (an output_postprocess, or a w2 bias as in gpt_oss), not on the dispatcher. Every dispatcher could always return per-row routed_scores_R in a common metadata base, and combine(..., apply_scores: bool) would follow from that. This removes:

    • absorb_router_scores on every dispatcher config;
    • the None-means-auto value that RoutedExperts.__init__ overwrites on an already-built module (and LocalTokenDispatcher.Config defaults to False while its comment says None is auto);
    • the make_routed_experts_config, swap_token_dispatcher and TokenDispatcherTransform(kwargs=...) plumbing;
    • the getattr(metadata, "routed_scores_R", None) and w2_kwargs duck typing in moe.py.
  2. Make absorption unconditional whenever it is valid. With a single path, the forced never-replayed combine is always cheap (it keeps only indices), so the FullAC regression goes away. When it is not valid (postprocess or bias), keep the old combine as it is. That also lets you drop the gpt_oss bias-rescaling special case, which only exists to keep s·(hW+b) correct.

  3. Have the backend wrappers return scores instead of clearing them. deepep.dispatch_tokens and hybridep.dispatch_tokens could return the per-row scores, and their combine_tokens would stop multiplying. Today the dispatcher sets state.permuted_scores = None / state.recv_scores = None after the fact to turn off a multiply inside the backend, which is fragile coupling.

  4. Split the PR:

    • (a) a one-line PR dropping the combine-output pin (−56 MiB/layer, separate from absorption);
    • (b) absorption + the never-replayed combine for DeepEP only, with FullAC and Default saved-tensor reports for both absorb settings, plus the C4 loss comparison;
    • (c) HybridEP later, together with a combine region so it actually gains something.

    The AllToAll/TorchAO changes can stay minimal or be skipped, since they are reference paths.

  5. Tests. The 417-line pure-PyTorch ElasticBuffer stub test (test_deepep_absorb_router_scores.py) will be a maintenance burden. If absorption is decided in RoutedExperts (point 1), a parity test with the Local dispatcher plus the existing GPU DeepEP test probably covers the same contract.

Fix the fp32 copy in GroupedLinear →

@tianyu-l
tianyu-l requested a review from anijain2305 October 27, 2026 06:36
@acisseJZhong

Copy link
Copy Markdown
Contributor

@Mystri wouldn't recomputing W2(h_RF) using h_RF serve the same purpose as this optimization?

@Mystri

Mystri commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

@Mystri wouldn't recomputing W2(h_RF) using h_RF serve the same purpose as this optimization?

Yes, recomputing W2(h_RF) serves the same memory-saving goal. But this PR moves further by removes the two dependencies that require its output, and the recomputation can be dropped as well:

  • Score-gradient dependency: routed_output_RD * expert_scores needs the unweighted expert output for backward. Moving scores before W2 removes this dependency on W2’s output.
  • Replay dependency: replaying combine’s unpermute needs the routed_output_RD * expert_scores values. Making the entire combine a never-replayed region removes this dependency.

Also, reconstructing the score multiplication’s input does not cost just W2(h_RF) for every backend:

  • DistMoE BF16: scoring follows the fused W2-and-combine operation, so reconstruction includes both computation and communication.
  • AllToAll: scoring follows unpermutation and return communication, so reconstruction requires those operations as well as W2.
  • DeepEP/HybridEP: scoring precedes combine communication, so reconstructing the local W2 output can suffice.

@acisseJZhong

Copy link
Copy Markdown
Contributor

why the computation can be dropped? you still need to recompute W2(h_RF) for the gradient?

@Mystri

Mystri commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

why the computation can be dropped? you still need to recompute W2(h_RF) for the gradient?

@acisseJZhong, the implementation moves expert scoring before W2, disables the original scoring in combine, so the score gradient needed the unweighted W2 output, W2(h_RF), after moving, it only need h_RF and the gradient flowing back through W2.

# In GroupedLinear.forward, before W2's grouped GEMM:
input_RI = (input_RI.float() * routed_scores_R.reshape(-1, 1)).to(
    input_RI.dtype
)

The dispatcher then ensures the score is applied exactly once:

  • Local/AllToAll: dispatch returns the aligned scores as routed_scores_R and sets metadata.topk_scores_experts_sorted_N = None. This skips the if topk_scores_N is not None multiplication in _score_and_scatter_add.
  • DeepEP: dispatch returns the tracked scores as routed_scores_R and clears state.permuted_scores (or state.recv_scores for the CUDA-graph layout). This skips the corresponding multiplication in _scored_combine; unpermutation and combine still run.

So in theory we don't depend on the activation W2(h_RF) in backward calculation anymore.

After that it was just some tweaks with remat to ensure that output is not to be recomputed.

@Mystri

Mystri commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

why the computation can be dropped? you still need to recompute W2(h_RF) for the gradient?

Compared the output of these 3 configs with 5-moe-layer Deepseek-V3 debug model:

recompute_false_baseline - W2 output is saved:

  config.activation_remat = ActivationRematConfig(
      save_regions=["*routed_experts.w2.grouped_mm"]
  ),
...
  TokenDispatcherTransform(
      dispatcher=DeepEPTokenDispatcher,
      kwargs={"absorb_router_scores": False},
  )

do_recompute_baseline - recompute everything, including W2(h_RF), your proposal:

  config.activation_remat = FullActivationRematConfig()
...
  TokenDispatcherTransform(
      dispatcher=DeepEPTokenDispatcher,
      kwargs={"absorb_router_scores": False},
  )

recompute_false_absorb- my proposal, dropped the W2(h_RF) dependency:

  config.activation_remat = FullActivationRematConfig()
...
  TokenDispatcherTransform(
      dispatcher=DeepEPTokenDispatcher,
      kwargs={"absorb_router_scores": True},
  )
Config W2 remat absorb CUDA grouped-GEMM combine holds W2 output? resident saved-for-backward (r0)
recompute_false_baseline saved False 35 yes — 20.54 MiB/layer 121–184 MiB
do_recompute_baseline recomputed False 40 no (rebuilt on recompute) 21–22 MiB
recompute_false_absorb saved True 35 / 35 no ~21 MiB

This shows that W2(h_RF) is neither recomputed or saved.

@Mystri

Mystri commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

why the computation can be dropped? you still need to recompute W2(h_RF) for the gradient?

NVIDIA/Megatron-LM@2659630 some reference PR.

@acisseJZhong

Copy link
Copy Markdown
Contributor

@Mystri

Original: apply the score after W2

# Forward
z = W @ h
y = s * z

# Backward
dz = s * g
dh = W.T @ dz          # GEMM 1: input gradient
dW = dz @ h.T          # GEMM 2: weight gradient

z = W @ h             # GEMM 3: recompute the discarded forward output
ds = dot(g, z)        # Router-score gradient requires z

Modified: apply the score before W2

# Forward
a = s * h
y = W @ a

# Backward
a = s * h             # Rebuild the input using elementwise multiplication
da = W.T @ g          # GEMM 1: gradient with respect to W2's input
dW = g @ a.T          # GEMM 2: weight gradient

ds = dot(da, h)       # Router-score gradient reuses the already-computed da
dh = s * da

is this the overall idea? essentially you just save one matmul(GEMM 3) but introduces one more elementwise multiplication(dh = s * da). I wonder how much compute saving this is, do you have some data on real training run?

@Mystri

Mystri commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@Mystri

Original: apply the score after W2

# Forward
z = W @ h
y = s * z

# Backward
dz = s * g
dh = W.T @ dz          # GEMM 1: input gradient
dW = dz @ h.T          # GEMM 2: weight gradient

z = W @ h             # GEMM 3: recompute the discarded forward output
ds = dot(g, z)        # Router-score gradient requires z

Modified: apply the score before W2

# Forward
a = s * h
y = W @ a

# Backward
a = s * h             # Rebuild the input using elementwise multiplication
da = W.T @ g          # GEMM 1: gradient with respect to W2's input
dW = g @ a.T          # GEMM 2: weight gradient

ds = dot(da, h)       # Router-score gradient reuses the already-computed da
dh = s * da

is this the overall idea? essentially you just save one matmul(GEMM 3) but introduces one more elementwise multiplication(dh = s * da). I wonder how much compute saving this is, do you have some data on real training run?

Setting: experts_per_gpu = 2 (4 experts / ep=2), router_top_k = 3, 1 layer of DeepSeek-V3 671B MoE layer

Result: applying expert-score-absorb drops the W2 recompute GEMM — a [7168, 1408] @ [61614, 7168] matmul (weights×input, M=61614, N=7168, K=1408, bf16) — entirely out of the backward recomputation path. In the do_recompute_baseline trace this is the 4th grouped GEMM (~1.244 TFLOPs), and it runs ~1965 µs on device (~633 TFLOPS ≈ 64% of H800 bf16 peak).

image

PS. we're not "introducing one more elementwise multiplication(dh = s * da)" - we just moved the elementwise multiplication of each token from after w2 to before w2.

@acisseJZhong

Copy link
Copy Markdown
Contributor

thanks for the detailed data! so you are saying for each backward it could save us 1.244 TFLOPs?

we're not "introducing one more elementwise multiplication(dh = s * da)" - we just moved the elementwise multiplication of each token from after w2 to before w2.

could you help me understand using my example? thanks!

@Mystri

Mystri commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

thanks for the detailed data! so you are saying for each backward it could save us 1.244 TFLOPs?

we're not "introducing one more elementwise multiplication(dh = s * da)" - we just moved the elementwise multiplication of each token from after w2 to before w2.

could you help me understand using my example? thanks!

Oh, I was reading it wrong. I was talking about dh = s * da replaces the original dz = s * g; there is a score multiplication in backward either way.

Indeed a = s * h needs to be rebuilt.

@Mystri

Mystri commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

thanks for the detailed data! so you are saying for each backward it could save us 1.244 TFLOPs?

we're not "introducing one more elementwise multiplication(dh = s * da)" - we just moved the elementwise multiplication of each token from after w2 to before w2.

could you help me understand using my example? thanks!

for each recompute phase we expect to save around 1.244 TFLOPs (W2), depending on the number of routed tokens per rank.

mystri added 4 commits October 29, 2026 17:11
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.

Replay: with router scores absorbed, combine no longer scales expert
outputs, so the DeepEP compact combine would read the W2 output from a
bare _unpermute_tokens on the replay path. Fold the score multiply,
unpermute and combine kernel into one never-replayed region, which keeps
the W2 and combine outputs off the saved-tensor set. On the standard
all-to-all path the absorbed scores are an output of the saved dispatch
region, so mark them before W2's bare scaling; that marker is a no-op on
the DeepEP/HybridEP paths and without an active checkpoint.

Squashed from the router-score-pre-w2-review series and rebased onto
current upstream main. Absorbed and post-combine paths agree to bf16
rounding; loss convergence on a representative dataset is still pending.
Give the local, all-to-all and TorchAO dispatchers the combine structure
DeepEP got with router-score absorption: one never-replayed
"<fqn>.combine" region whose body reads the w2 output, instead of bare
ops guarded by recompute_needs_tensor markers.

- Local and TorchAO EP=1 ran the scatter-add (and the padded unpermute)
  as bare ops, so replay needed the w2 output persisted: the marker
  pinned the full expert-output tensor (R x D) per MoE layer even with
  absorbed scores, where no backward consumer needs it (the scatter-add
  saves only indices).
- The EP>1 combine region was policy-replayable. Replaying it re-ran the
  combine all-to-all and required the w2 output real on the replay path
  (pinning it under policies that save w2), while saving it retains only
  the small permutation indices and scores, so no policy benefits from
  replaying it. Dispatch stays policy-driven everywhere, like DeepEP's
  dispatch.

Replay: the combine body runs only on the original forward; replay skips
it, so nothing on the replay path reads the w2 or combine outputs, and
with absorbed scores the w2 output is freed after the forward. Also fix
the stale DeepEP docs and AC test left by the absorption commit: the
DeepEP combine region is never replayed, so only dispatch call counts
grow under the full policy.

Tests:
- New tests/unit_tests/cpu/models/common/test_token_dispatcher.py: the
  combine body runs exactly once under every policy while the w2
  projection's replay still follows the policy; with absorbed scores and
  w2 saved, the w2 output storage is freed after the forward; loss and
  grads match the un-checkpointed run bitwise. It fails on the previous
  code.
- test_remat_all_to_all: the combine never replays, so the full policy
  replays 2 collectives (was 3) and saving dispatch alone stops all
  replay; the w2-retention test now saves only w2.grouped_mm, pinning
  that the combine is always saved.

Docs: REMAT.md and the activation-remat config docstrings now state that
the dispatcher combines are always saved and only dispatch follows the
policy.

Numerics: remat-structure change only. On CPU, loss and gradients are
bitwise identical to the un-checkpointed run (and to the previous code)
for the local and EP=1 paths and for the EP>1 path through a 1-rank EP
mesh, absorbed and not, under the full, default and save-w2-only
policies.
…hers

Add two named debug recipes so the token-dispatcher backend matrix is
runnable on DeepSeek V3, alongside the existing HybridEP config:

- deepseek_v3_debugmodel_alltoall: the stock dispatcher at EP=2, so
  routed tokens actually cross ranks. The plain deepseek_v3_debugmodel
  (EP=1) already runs the same dispatcher's local fallback, which covers
  the local backend without a duplicate config.
- deepseek_v3_debugmodel_deepep: DeepEP v2 at EP=2 via
  TokenDispatcherTransform, following qwen3_moe_deepep: the compact,
  host-synced training path, buffer capacity from the microbatch shape,
  CUDA graphs off like the stock all-to-all, plus the NVLink-only env
  notes for local devgpu.

Both keep the default activation-remat policy, under which every
dispatcher's combine is saved (never replayed) and the standard backend
absorbs router scores before W2, so these exercise the paths changed by
the never-replayed-combine work. Registered in the debug-config defaults
test.

Validated on CPU: both configs build, DeepEPTokenDispatcher.Config gets
hidden_dim=256 (from w13.in_features) and num_max_tokens_per_rank=16384
(the 8 x 2048 microbatch over CP x TP), and the base EP=1 config keeps
CUDA graphs on while both EP=2 configs disable them.
One fp64 parity test per dispatcher family: with rounding gone, the
absorbed and post-combine paths compute the same function, so a dropped,
doubled or misaligned router score is an O(1) error. Both tests assert
the loss and every input/parameter gradient at the float32 scale W2's
input scaling applies.

- Standard dispatchers (GPU, world 2): local, all-to-all at EP=1 (local
  fallback) and EP=2, TorchAO at EP=1 (padded permute, zero-sentinel
  scores) and EP=2, through the existing _grouped_mm override seam.
- DeepEP (CPU, gloo, world 2): stub deep_ep's ElasticBuffer with a
  pure-PyTorch implementation (all_gather + local selection,
  deterministic layout, autograd-correct dispatch/combine backward), so
  the dispatcher, the torchtitan deepep wrapper, its custom ops and
  their autograd run in float64 without the bf16-only CUDA kernels. The
  stub module is injected only when deep_ep is absent, and the CPU op
  impls reuse the wrapper's CUDA impls.

Replaces the bf16-tolerance and activation-replay variants and the
HybridEP-only file. Verified the DeepEP test fails on double-applied
and on misaligned (rolled) scores.
@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 1m 32s —— View job


Rows 1 and 2 are right, but row 3 is wrong. In this PR, setting W2 to "recompute" changes nothing. The W2 GEMM is not replayed either way, so "PR + recompute W2" saves the same 2.6–4.8% FLOPs against "main + recompute W2" as row 1 does. The ~0.0023% figure is the FLOP change for row 2, not row 3.

Details: why the W2 policy doesn't matter in this PR

Symbols: h = SwiGLU output (R×F), z = W2 output (R×D), s = per-row score, a = s*h.

How a W2 policy works in torch_remat

The policy only decides how backward gets two tensors:

  • W2's saved input. On main this is h; in this PR it is a. Both come from bare ops, which replay always rebuilds (see activation_remat.py:195, "its saved input is the activation output, which replay rebuilds anyway").
  • W2's output z, but only if something in backward or replay reads it.

So the policy only matters when something needs z.

  • On main, two things need z:

    • the score gradient ds = rowsum(g*z) from the bare multiply in combine;
    • the combine replay.

    So the policy picks between them: W2 saved keeps z resident (pinned with recompute_needs_tensor), and W2 recomputed replays the W2 GEMM (GEMM 3).

  • In this PR, nothing needs z:

    • ds = rowsum(da*h) doesn't read z;
    • DeepEP combine is a recompute=False region that keeps only its indices.

    So z is never kept and the W2 GEMM is never replayed, whichever policy W2 has.

The four cases (DeepEP, per MoE layer per microbatch)

W2 saved ("no W2 recompute") W2 recomputed
main z resident (R·D bf16, 448 MiB at DSv3 671B), no extra GEMM z not resident, +1 W2 GEMM (2RDF), and under FullAC +1 combine replay
this PR z not resident, no extra GEMM same as the cell to the left

Your three rows, corrected

Comparison Memory FLOPs Your row
1. PR + no W2 recompute vs main + recompute W2 same −2.6–4.8% e2e (GEMM 3 gone), plus one combine replay skipped under FullAC ✅ correct
2. PR + no W2 recompute vs main + no W2 recompute −R·D per layer (z) about the same (elementwise term only, ~0.0023%) ✅ correct
3. PR + recompute W2 vs main + recompute W2 same −2.6–4.8% e2e, the same as row 1 ❌ the ~0.0023% belongs to row 2

In short, the PR removes the trade-off that main forces on W2. With either policy, the PR has the lower memory of main's "save" and the lower FLOPs of main's "recompute".

Evidence and caveats

  • Mystri's grouped-GEMM counts (5 MoE layers) match this:

    • main with W2 saved: 35;
    • main + FullAC: 40;
    • PR + FullAC (W2 recomputed by policy): 35.

    That count, together with the PR's test that combine is replayed 0 times, is my evidence that the W2 GEMM really isn't replayed. I didn't read torch_remat's replay code or run anything on GPUs.

  • The 2.6–4.8% range was computed against a FullAC baseline. If the rest of the policy is Default and only W2 is switched, the total is smaller, so the same 2RDF saving is a somewhat larger percentage.

  • Separately from absorbing the scores, the PR also drops the combine-output pin (T·D per layer, 56 MiB at 671B). That gain shows up only in the cases where that pin was holding memory on main.

@acisseJZhong

Copy link
Copy Markdown
Contributor

@claude so is this the conclusion?

  • this PR + no W2 recompute, compared with main + recompute W2, memory is the same, and it saves 2.6–4.8% e2e FLOPs.
  • this PR + no W2 recompute, compared with main + no W2 recompute, it saves decent memory, and compute is almost the same.
  • this PR + recompute W2, compared with main + recompute W2, memory is the same, and it saves 2.6–4.8% e2e FLOPs.

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 34s —— View job


Yes, all three rows are right, with a few qualifiers. They hold only for DeepEP, the 2.6–4.8% is a FLOP estimate rather than a measured step time, and "same memory" means within a few hundred KiB per layer.

Comparison (DeepEP) Memory per MoE layer Compute
1. PR + no W2 recompute vs main + recompute W2 same −2.6–4.8% e2e FLOPs (W2 GEMM no longer replayed), plus one DeepEP combine replay skipped ✅
2. PR + no W2 recompute vs main + no W2 recompute −R·D bf16 (448 MiB/layer, ~25 GiB/GPU at DSv3 671B) about the same (~0.0023%, elementwise only) ✅
3. PR + recompute W2 vs main + recompute W2 same −2.6–4.8% e2e FLOPs, same as row 1 ✅

In short: on main you choose between keeping the W2 output (memory) and replaying W2 (compute). In this PR nothing in backward reads the W2 output, so you get both savings whichever W2 policy you set. Rows 1 and 3 are therefore the same PR configuration.

Qualifiers
  • "Same memory" is approximate. The never-replayed combine region keeps its index state, about R int64 per layer (~256 KiB at 671B). Under the PR, the scaled input a = s*h is rebuilt in backward instead of z. That transient is R×F rather than R×D, so the peak in backward goes slightly down, not up.
  • Row 2's memory saving can be a bit larger than R·D. The PR also drops the combine-output pin, which is T·D per layer (56 MiB at 671B). It only counts where that pin was actually holding memory on main.
  • What the 2.6–4.8% means.
    • It is a paper FLOP estimate against a full-FullAC baseline (main + FullAC). If only W2 is recomputed and the rest of the policy is Default, the absolute saving (2·R·D·F per MoE layer per microbatch) is the same, but the percentage is somewhat higher because the total is smaller.
    • It doesn't count the skipped combine communication.
    • No end-to-end step-time A/B has been measured yet.
  • Evidence. The memory effect (row 2) is in the PR description's save-all report: ep_communication.combine goes from 27.99 MiB to 394.5 KiB per layer. The compute effect (rows 1 and 3) comes from Mystri's grouped-GEMM counts: 35 / 40 / 35 for main+save / main+FullAC / PR+FullAC. The num_combine_replays=0 test also supports it. I didn't run anything on GPUs.
  • Default policy. main's Default policy saves W2 (activation_remat.py:195), so for anyone on Default, row 2 is the relevant comparison: memory saved, no compute saved.
  • Scope. This is DeepEP only. HybridEP (which the in-repo DSv3 recipes use) and DistMoE are unchanged. The in-repo DeepEP users are Qwen3 MoE and RL. gpt_oss and muse_spark are rejected with DeepEP (w2 bias / output_postprocess).

@tianyu-l tianyu-l 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.

@Mystri Thank you very much. Having some more questions.

Comment on lines +804 to +808
@dataclass(frozen=True, kw_only=True)
class DeepEPDispatchMetadata(EPDispatchMetadata):
"""DeepEP dispatch state and per-row router scores."""

routed_scores_R: torch.Tensor # noqa: N815

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.

I think we should do this optimization to both DeepEP and HybridEP

  • all-to-all dispatcher is more of a reference implementation, which is OK to be not optimized
  • DistMoE handles its own optimizations

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.

Would it be okay to work on HybridEP in a follow-up PR? I'd prefer to keep this PR focused and not introduce more changes

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.

Conceptually I'm OK, but practically I don't know if the change is going to be bigger or smaller.
E.g. DeepEPDispatchMetadata doesn't need to be introduced if we directly work on EPDispatchMetadata which is shared by both.

Comment thread torchtitan/models/common/moe/moe.py Outdated
if self.w2.num_linears != 1:
raise ValueError("w2 must contain one down projection")
if isinstance(self.token_dispatcher, DeepEPTokenDispatcher.Config) and (
self.output_postprocess is not None or self.w2.bias

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.

It seems you are making absorption the default and the only choice -- it makes the PR look much more succinct, but it means gpt-oss would no longer work with DeepEP (or HybridEP per other comment). Is it intended?

@acisseJZhong acisseJZhong Nov 4, 2026 •

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 PR would require no bias and no post expert norm, so gpt-oss and muse spark wouldn't work with this particular optimization.

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.

That's claude's idea lol. Is anyone really training GPT-OSS?

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.

@Mystri Mystri Nov 4, 2026 •

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.

apparently yes?

also it breaks muse spark open

Sorry, should've checked the updates before questioning the use case. Anyway, for context, I removed the post-W2 scoring path following #5543 (comment), which explicitly recommended rejecting these combinations to simplify the implementation.

So, before revising it again, lets align on the approach:

  • s * (W2(h) + b2) = W2(s * h) + s * b2
  • fallback to post-expert scoring when output_postprocess is enabled:

This might add some complexity to the code, but the models will not break.

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.

could you help me understand why you do W2(s * h) + s * b2 instead of just s * (W2(h) + b2)? how much compute saving this will bring?

similar to what we derived above, #5543 (comment)

on a side note, I think this is worth mentioning in the pr description for future reference.

Comment thread torchtitan/models/gpt_oss/moe.py Outdated
return remat.region(
self._add_grouped_bias,
self.remat_region_name("bias_add"),
recompute=self.remat_should_recompute("bias_add"),

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 feel cheap op to me, why making remat policy configurable, instead of always recompute like before?

With DeepEP, router scores scale W2's input and its per-expert bias:

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

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.

the formula itself is not obviously correct; it's only correct because _expand_grouped_bias expands on the tokens dimension -- maybe add a note

if routed_scores_R is not None:
# The bare multiply reads scores produced by the dispatch region.
remat.recompute_needs_tensor(routed_scores_R)
input_RI = input_RI * routed_scores_R.to(input_RI.dtype).reshape(-1, 1)

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.

I know this is a separate request, but I think we should do fp32 multiply here, according to https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/moe/token_dispatcher.py#L163-L168. We should duplicate the note as well.

Should also do this for HybridEP, but can leave to next PR together with the other request.

Comment thread torchtitan/models/common/moe/moe.py Outdated
Comment on lines +92 to +96
if (
isinstance(self.token_dispatcher, DeepEPTokenDispatcher.Config)
and self.output_postprocess is not None
):
raise ValueError("DeepEP does not support output_postprocess")

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.

Can we still support output_postprocess, without applying this optimization? o/w model like Muse Spark Open couldn't run with DeepEP any more.

input_RI: torch.Tensor,
offsets_E: torch.Tensor,
*,
routed_scores_R: torch.Tensor | None = None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
routed_scores_R: torch.Tensor | None = None,
scores_R: torch.Tensor | None = None,

to be more neutral to MoE

Args:
input_RI: Input rows grouped by the selected linear.
offsets_E: Exclusive cumulative row end for each group.
routed_scores_R: Optional per-row scores absorbed into the input.

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.

add more docstring about "this normally is applied to w2 in MoE to reduce overhead"

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.

@tianyu-l tianyu-l 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.

very cool! thanks a lot!

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.

I feel we could say more about the motivation, on reducing memory / compute overhead, at least qualitatively if not quantatively.

But can be done in follow-up PR.

@tianyu-l

tianyu-l commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 5m 35s —— View job


Approve -- please address the listed items before merging: see the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verdict: Approve -- please address the items below before merging. The new commits fix the GPT-OSS and muse_spark breakage correctly: bias experts absorb with s*b2, and postprocess models keep post-expert scoring. What's left is docs and the PR description.

What changed since the last review.

  • Postprocess models (muse_spark): with DeepEP plus an output_postprocess, the scores are now multiplied in RoutedExperts.forward after the postprocess, instead of being banned.
  • GPT-OSS: GptOssGroupedLinear scales its expanded per-row bias by the scores. The bias add moves into a bias_add region that follows the grouped_mm policy, replacing the old pin on the W2 output.
  • FP32 scoring: all score multiplies now compute in FP32 by type promotion, as @tianyu-l requested.
  • Combine: DeepEP combine is always a SAVE region, so it always receives rows that are already weighted.
  • Docs and test: a new ROUTER_SCORE_ABSORPTION.md doc, and the GPU test now runs all four expert configs against a _PostW2 reference.

Example (DeepEP, per routed row):

bias-free:     main s*W2(h)           -> PR W2(s*h)
GPT-OSS:       main s*(W2(h) + b)     -> PR W2(s*h) + s*b       (exact algebra)
postprocess:   main s*post(W2(h))     -> PR s*post(W2(h))       (unchanged order, now FP32 multiply)
combine:       main replays under FullAC -> PR never replays (keeps R int64 indices)

Earlier items

  • Resolved:
    • The silent wrong numerics for w2 bias / output_postprocess (previous must-fix 2) is fixed by supporting both paths correctly instead of banning them.
    • The _permute rewraps are reverted.
    • The combine docstring now states the weighted-input contract.
    • The end-to-end compute question was answered analytically in the thread, and @acisseJZhong confirmed the conclusion.
  • Still open: deepep.py:62 ("Under FullAC with absorbed scores") and deepep.py:113 ("absorbed combine is never replayed"). Combine is now saved on every path, including the unabsorbed postprocess path, so drop "with absorbed scores" and "absorbed".

Must fix

  1. The PR description is stale on numerics.
    • It says the PR "casts the score to the hidden dtype before scaling W2's input". At HEAD, every score multiply is FP32 by type promotion (linear.py:598, gpt_oss/moe.py:974, moe.py:784).
    • The 200-step run is from 8b9ced058 (BF16 scores, no bias or postprocess paths), so it doesn't measure HEAD's numerics. Either rerun it at HEAD, or say explicitly that FP32 scoring and the GPT-OSS/postprocess paths came after the run.
    • The Implementation section also doesn't mention that output_postprocess turns absorption off.
  2. torchtitan/distributed/REMAT.md:296-301 is now wrong for DeepEP. It says DeepEP and HybridEP "both save or replay dispatch and combine together, following ep_communication" and that "FullActivationRematConfig replays both backends' communication". This PR updated the same text in moe/README.md but not here. Mirror that wording: DeepEP always saves combine, and only dispatch follows ep_communication.
  3. ROUTER_SCORE_ABSORPTION.md:102: "FullAC can still replay the W2 GEMM" contradicts the PR's main gain unless it is scoped to the cast/postprocess cases (inline).
Details
  • All GroupedLinear subclasses still compose with scores_R. MXFP8, NVFP4 and LoRA all override _grouped_mm, not forward. LoRA on W2 stays linear, so W2(s*h) + c*B(A(s*h)) = s*(W2 h + c*BAh). Each projection's forward is only overridden by GptOssGroupedLinear, which forwards scores_R.
  • The bias_add region costs no memory.
    • w13 (no scores): save-all keeps the bias-add output (pinned by recompute_needs_tensor(gate_up_R2F)) instead of the pinned grouped_mm output, which is the same R x 2F. Default recomputes both, as before.
    • Absorbed w2: nothing reads the bias-add output, so it is neither kept nor replayed.
  • GPT-OSS without AC. bias_RO * scores_R saves the expanded bias (R x D) for the score gradient. So the no-AC memory gain does not apply to GPT-OSS, though it is no worse than main. Under any remat policy, _expand_grouped_bias is a bare op and is rebuilt cheaply. This doesn't block; a fused rowsum(g * b[expert(r)]) could avoid it if no-AC GPT-OSS + DeepEP ever matters.
  • RL. The trainer (compact layout) and the generator (expand layout) both absorb through the same GroupedLinear path. Per-row expand scores are still sum over the single valid entry, now computed in dispatch. So trainer/generator parity keeps the same form.
  • Scope. HybridEP is deferred to a follow-up, as agreed with @tianyu-l. When it lands, put scores_R on the shared EPDispatchMetadata and replace the isinstance(metadata, DeepEPDispatchMetadata) checks in RoutedExperts.forward.

Not verified:

  • The GPU checkpoint tests at the 2 * eps relative-norm tolerance for router/expert gradients (all four expert configs).
  • The REMAT/README memory claims for the GPT-OSS path.

@tianyu-l has approved this. It touches shared MoE and linear code, so this approval doesn't replace a maintainer's review.

Comment on lines +99 to +102
output; saving both avoids this dependency. Other replayed consumers, such as a
dtype conversion, can still need W2's output, so saved combine alone does not
guarantee its complete removal from retained memory. FullAC can still replay
the W2 GEMM and its bias addition.

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.

"FullAC can still replay the W2 GEMM and its bias addition" reads like a general statement, and it contradicts the main gain of this PR. In the common case (bf16 routed input, no output_postprocess) nothing in backward reads W2's output: the type_as is a no-op, moe.py doesn't pin it, and combine is a SAVE region whose backward needs only indices. So under FullAC the W2 GEMM is not replayed, which is exactly the 40 -> 35 grouped-GEMM count in the thread. The replay only happens when a bare op reads W2's output: a real dtype cast (the moe.py pin), or a postprocess, which also turns absorption off.

Scope the sentence to those cases:

Suggested change
output; saving both avoids this dependency. Other replayed consumers, such as a
dtype conversion, can still need W2's output, so saved combine alone does not
guarantee its complete removal from retained memory. FullAC can still replay
the W2 GEMM and its bias addition.
output; saving both avoids this dependency. A bare consumer of W2's output,
such as a real dtype cast or an output postprocess (which also disables
absorption), still needs it: with W2 saved it stays resident, and under FullAC
the W2 GEMM and bias addition replay. In the common bf16 case without a
postprocess, W2's output is neither retained nor rebuilt.

@tianyu-l

tianyu-l commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

numerics change is not introduced in this PR, so merging

@tianyu-l
tianyu-l merged commit 6d9a929 into pytorch:main Nov 6, 2026
Mystri added a commit to Mystri/torchtitan that referenced this pull request Nov 9, 2026
Keep the pytorch#5543 motivation and memory/recompute explanation in ROUTER_SCORE_ABSORPTION.md. Leave README and remat communication-policy updates to the HybridEP support follow-up.
Mystri added a commit to Mystri/torchtitan that referenced this pull request Nov 9, 2026
Embed the original PR schematic in the motivation section, with a short caption scoping activation labels, hidden-width storage, and the W2 SAVE replay benefit.
Mystri added a commit to Mystri/torchtitan that referenced this pull request Nov 9, 2026
Remove the mocked CPU HybridEP scoring test and its unused imports. Keep the existing GPU checkpoint suite's post-W2 reference, gradient, bias, postprocess, padding, and replay coverage, matching the approach in pytorch#5543.
Mystri added a commit to Mystri/torchtitan that referenced this pull request Nov 10, 2026
Follow SHARDING.md with an implementation intro, illustrated Overview, Configurations tables, and Submodule behavior notes. Consolidate duplicate diagrams while retaining the pytorch#5543 graph, backward dependency, remat tradeoffs, analytical examples, and correctness caveats.
tianyu-l added a commit that referenced this pull request Nov 26, 2026
…er override; agent self-review; rl/transport (#6407)

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why

Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it
approved,
30 then got a formal "request changes" from a maintainer, and about 20
more got
substantive inline asks. In nearly all of them the bot either saw the
problem
and approved anyway, or never asked the questions maintainers ask most
("does
the repo already do this?", "who should own this?"). The opposite
failure, the
bot blocking something a maintainer was fine with, is rare: in the PRs
we
sampled, 2 of its 81 must-fix items were wrong and about a third were
minor
(the empty human-written summary was the biggest source).

**Example** (#6112, controller sizes the rollout worker pool):

```
before: bot approved 10 times; tianyu-l then blocked: "the controller reads
        rollouter.rollouts_per_worker to compute a count it hands back to the
        Rollouter -- violates encapsulation"
after:  same commit, new skill -> Request changes, must-fix #1:
        "controller.py:589 -- wrong owner for the worker count ..."
```

There was also no way for a code owner to overrule the bot except
dismissing
its review in the GitHub UI, and a later `@claude review again` would
block
again.

## What changed

**Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`):
- Verdict rules: Approve only when every remaining item is an edit the
bot
could write itself. Anything the author still owes (a design change, an
unexplained golden change, evidence the PR rests on) is Request changes;
anything only a maintainer can decide is Needs discussion. A hedge like
"a
  maintainer should decide" can't come with Approve.
- Always must-fix: a violated written rule, a silent wrong result, a
second
  definition of an existing concept, a gate finding.
- Design gate: new questions for the existing counterpart, in-repo
ownership,
and the design behind a bug; "ban only what doesn't work on main"; read
the
numbers behind a claim. The overlapping-PR search is mandatory and
reported.
- Re-review covers every commit since the last full review, including
code
taken from the bot's own suggestions. A scoped question gets a
`COMMENT`, not
  a whole-PR verdict.
- The bot fact-checks its own proposed fixes, and cites a source for
claims
  about external tools or marks them unverified (never must-fix).
- An empty "Summary (human-written)" is a one-line "Before merge" note
that
  never affects the verdict.
- Checklist: config ownership direction, general shared wrappers, dead
code the
PR creates, model variants as flavors, a mechanical pass over every new
or
  changed function.

**Code owner override** (`SKILL.md`, `claude-code.yml`,
`CONTRIBUTING.md`): a
code owner comments `@claude override` (optionally `@claude override
2,3:
<reason>`); the bot approves if nothing else is open and doesn't
re-raise the
overridden items. A code owner's GitHub approval or "LGTM" is not an
override,
so a teammate can approve without the bot dropping its findings.
Dismissing the
bot's review still unblocks the PR, but isn't an override: the bot can't
tell
who dismissed it.

**Agent self-review** (`CLAUDE.md`, `pr-description`): an agent
preparing a PR
runs `pr-review` in branch mode first and records unaddressed items in
an
optional "Self-review" section. PRs written without an agent are
unaffected; a
missing section is never a finding.

Where each new rule comes from (maintainer asks the bot missed):

| Change | PRs |
| --- | --- |
| No Approve with open design/evidence items or a "maintainer should
decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 |
| Author waiver can't clear a must-fix | #6201, #6202, #6203 |
| Existing counterpart; one source of truth | #5228, #6169, #5881,
#5823, #5824, #6059, #5812 |
| Responsibility owner; config ownership direction | #6112, #6332,
#5802, #5803, #6325 |
| Fix the design behind the bug; a TODO doesn't justify a workaround |
#5572, #5689, #5657 |
| Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819,
#5543 |
| Re-review covers all new commits; scoped asks don't approve | #5824,
#5842 |
| Mandatory overlap search | #5885, #6248 |
| Ban only what doesn't work on main | #5543 |
| Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868
|

**Rules**: `design.md` gets the one-general-wrapper rule (moved from
`models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the
consumer owning its values; `config.md` gets ownership direction and "a
Config
doesn't read runtime state"; `direction.md` calls all-to-all the MoE
reference
implementation, so a new vendor-specific dispatch path (e.g. #6242)
needs a
reason the existing backends can't serve.

**Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/`
-> d4l3k.

**Mechanical, skim**: `torchtitan/rl/transport/` holds data movement
between RL
actors.
- `rl/model_state_dict_transport.py` ->
`rl/transport/model_state_dict.py`
- `rl/MODEL_STATE_DICT_TRANSPORT.md` ->
`rl/transport/MODEL_STATE_DICT_TRANSPORT.md`
- `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py`
- tests:
`tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py`
->
`tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py`
- imports, READMEs and `scripts/install_rl_env.sh` updated; no code
changes.

## User-facing changes

| Before | After |
| --- | --- |
| Overrule the bot: dismiss its review in the UI, and it blocks again on
the next run | `@claude override [items]: <reason>`; the bot approves
and doesn't re-raise them |
| Empty human-written summary: bot must-fix | One "Before merge" line,
no effect on the verdict |
| `from torchtitan.rl.model_state_dict_transport import ...` | `from
torchtitan.rl.transport.model_state_dict import ...` |
| `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from
torchtitan.rl.transport.rdma_microbatch import ...` |

## Testing

Backtest: the new skill run locally (nothing posted) on each PR at the
commit
and thread state the bot originally saw.

| PR | Bot then | New skill | What the maintainer asked |
| --- | --- | --- | --- |
| #6112 | Approve | Request changes | worker-count ownership (caught) |
| #5837 | Approve | Request changes | apply to `dp_shard` too (caught) |
| #5572 | Approve | Request changes | delete the injection design
(caught) |
| #6201 | Approve after author waived pins | Request changes, waiver
ignored | pins broke GPU tests after merge (caught) |
| #6007 | Approve | Request changes | fold K3.1 into K3 (caught) |
| #5543 | Request changes: "ban it" | Request changes: keep main's path
| don't break gpt-oss + DeepEP (fixed) |
| #6144, #5905 (controls) | Approve | Approve | -- |
| #6137 (control) | Approve | Needs discussion | -- (merge gate on an
upstream API) |

Code owner override, simulated on #6201: override by a code owner lifts
the
named item; `@claude override` from the author changes nothing; a code
owner's
"LGTM" approval followed by "review again" keeps Request changes.

Transport move: 83 RL CPU unit tests pass locally
(`transport/test_model_state_dict.py`, `test_trainer.py`,
`test_engine_loop.py`). `transport/test_rdma_microbatch.py`,
`test_generator.py` and
`test_batcher_actor.py` fail to collect in my env on `origin/main` too
(stale
attention-gym / Monarch), so CI is the check for those.

## Known issues / follow-ups
- Open PRs that edit the moved files rebase cleanly (git follows the
renames),
but new imports of the old module paths will break: #6309 (adds a delta
transport that should live in `rl/transport/`), #6237, #6176, #6177,
#5862,
  and drafts #6127, #6393, #6163, #5764.
- The Actions bot can't read dependency source (e.g. SGLang); follow-up
for the
  workflow.

## Self-review
pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch
mode diffs
against `origin/main` and skips description findings before a
description
exists; the "Config doesn't read runtime state" rule no longer
contradicts
hardware validation; dismissal dropped as an override form (the bot
can't tell
who dismissed); `test_rdma_microbatch.py` added to the transport area.
Not
addressed:
- One concern per PR -- the five changes ship together at the
maintainer's
  request.
- Open PRs touching the moved files -- listed above; the maintainer will
  coordinate.
tianyu-l pushed a commit that referenced this pull request Dec 1, 2026
## Summary (human-written)

Follow up on #5543 by extending router-score absorption to the HybridEP
dispatcher backend. Avoid W2-output replay/retention when HybridEP is
selected.

## Scope

HybridEP now passes per-row router scores to the same expert path as
DeepEP. With absorption, the router gradient uses W2's input and input
gradient. HybridEP combine receives weighted outputs and its backward
uses the dispatch handle. Default FullAC still replays the W2 forward
GEMM. Skipping that replay is a separate change.

```text
Before: s * (W2(h) + b2)
After:  W2(s * h) + s * b2
```

![Router-score absorption graph from
#5543](https://github.com/user-attachments/assets/6f4e5155-6cfb-455f-925f-8d9165899666)

When an expert has an output norm, both backends apply the router score
after the norm. HybridEP now uses DeepEP’s FP32 product and casts the
result back to the output dtype. This changes BF16 rounding on HybridEP.
The shared dispatch metadata carries the per-row scores for both
backends.

## Validation

Absorption changes BF16 rounding. In a paired 200-update C4 run on two
H800s, the 83M-parameter debug model processed 13,107,200 training
tokens per arm. Pre-PR HybridEP (`8e63247`) and the absorption
implementation (`56a213b`) had mean training losses of 6.62618 and
6.62351 over the final 20 steps. Final held-out losses were 6.625461 and
6.629344. Both arms had finite losses and gradient norms. This is a
single-seed, short-run comparison.

The HybridEP checkpoint test covers biased experts, output
postprocessing, blocking and nonblocking dispatch, and zero combine
replays.

All 3 HybridEP checkpoint tests passed (0 skipped) at `3b617c823`,
before the post-norm precision change. GPU validation of the FP32
post-norm path is pending.

GPU environment: 2× NVIDIA H800, PyTorch `2.16.0.dev20261029+cu130`,
CUDA 13.0, DeepEP HybridEP build.
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