Skip to content

[moe] Compile router score multiplication without changing dispatch order - #6320

Open
bvolpato wants to merge 5 commits into
pytorch:mainfrom
bvolpato:bvolpato/moe-gather-sum-and-score-scale
Open

bvolpato wants to merge 5 commits into
pytorch:mainfrom
bvolpato:bvolpato/moe-gather-sum-and-score-scale

Conversation

@bvolpato

@bvolpato bvolpato commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Summary (reviewed and approved by the author)

Scaling 262,144 BF16 rows of width 2,048 can materialize a 2 GiB FP32 product before the cast. A shared score_scale region lets Inductor fuse the multiply and cast for scored grouped linear layers and dispatcher paths. Qwen3.5 and Qwen3.8 Flash Next enable it by default. Other models can add score_scale to model.local_compile.regions.

The dispatch reorder is unchanged. Scoring replays with the block or the all-to-all combine region under activation checkpointing. Compiling the reduction can change the low bits of the router score gradient.

Example and configuration

With a router score of 0.25, a BF16 expert row [4, -8] becomes [1, -2]. The eager path computes the product in FP32 and casts it back to BF16. Inductor can fuse those operations and avoid writing a full FP32 intermediate. The backward pass sums across the row to compute the score gradient. A different summation order can change that gradient even when forward outputs match.

Configuration Behavior with this PR
Qwen3.5 and Qwen3.8 Flash Next Enable score_scale by default.
Other MoE models using these paths Add score_scale to model.local_compile.regions to opt in.
Batch-invariant mode Remove score_scale from the list. TorchTitan rejects this region in that mode.

Review decision

Keep the default limited to the two Qwen families? Other models can see small loss and gradient changes. Enabling the region more widely would require comparing the A10G and MI350X reference runs for Qwen3 MoE, DeepSeek-V3 and GPT-OSS. #5382 and #5518 also separate implementation from per-model defaults.

If this lands before #6326, that PR replaces the local and all-to-all combine call to score_scale. Scored grouped linear and DeepEP still use the helper. #6326 removed its own compile option. The local dispatcher speedup measured here cannot be assumed for the two PRs together.

Validation

The B200 results are from 7ae95f01. Squashing to eee44acf left every file unchanged.

I compared two layers of Qwen3-30B-A3B on B200 with seed 42, a 2,048-token vocabulary and 20 BF16 AdamW updates at a learning rate of 0.0002. Each update used four 2,048-token C4 sequences. Four separate sequences were held out. I repeated the comparison in reverse order.

Revision Initial held-out loss Final held-out loss Median warm step in each trial Peak allocated
Base b3e6a66 7.95779 3.06627 30.59 / 30.70 ms 11.26 GiB
score_scale enabled at 7ae95f0 7.95779 3.08884 27.43 / 27.79 ms 10.85 GiB

Held-out loss increased by 0.02257. Turning the region off restored the baseline losses, gradient norms and expert selections exactly. Timing and peak allocation start at update 6. This short run does not establish full-model throughput or convergence.

Deterministic loss and gradient comparisons on RTX 5070 Ti

At 7ae95f0, scripts/loss_compare.py used PyTorch 2.15.0+cu132, seed 42, a seed checkpoint, flex attention and four 2,048-token C4 sequences per step. Repeated baselines matched exactly through 20 steps with --assert-equal. The table shows the change when enabling score_scale.

Debug configuration First gradient norm difference First loss difference Step 20 loss change Step 20 gradient norm change
Qwen3.5 MoE +1.19e-7 at step 2 +1.21e-4 at step 3 -8.20e-5 +1.03e-2
Qwen3 MoE -8.20e-5 at step 1 -2.24e-5 at step 2 +4.08e-4 +4.34e-5

Qwen3 MoE mean loss went from 6.017397 to 6.017478. Splitting 4,096 rows into smaller batches preserved forward outputs and input gradients bit for bit. The largest score-gradient difference was 3.82e-6 at width 128 and 7.63e-6 at width 2,048.

At 65,536 rows of width 2,048, median kernel forward and backward time fell from 8.52 to 1.82 ms. At 512 to 4,096 rows of width 256, compilation added 10 to 24 microseconds per call.

Earlier B200 results

At c720281, median warm step time in the reduced C4 run fell from 30.7 to 27.5 ms. Peak allocation fell from 11.26 to 10.85 GiB. Held-out loss was 3.08884 versus 3.06627 on b3e6a66. The 128-token debug model slowed from 18.8 to 22.5 ms. The earlier run did not record expert selections.

Self-review

At 7ae95f0, moving the multiply into the shared helper is mechanical. Review the compile defaults and the score-gradient reduction. CPU checks covered linear layers, dispatch, Qwen3.5 normalization and compile configuration. The earlier lint and type checks covered the modified files. DeepEP end to end and full-model convergence remain unverified.

@pytorch-bot

pytorch-bot Bot commented Nov 22, 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.

@meta-cla

meta-cla Bot commented Nov 22, 2026

Copy link
Copy Markdown

Hi @bvolpato!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@bvolpato
bvolpato force-pushed the bvolpato/moe-gather-sum-and-score-scale branch from 42a489a to d6e2fcb Compare November 25, 2026 02:16
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 25, 2026
@bvolpato
bvolpato marked this pull request as ready for review November 25, 2026 13:14
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 25, 2026
Comment thread torchtitan/models/qwen3_5/model.py Resolved
@bvolpato bvolpato changed the title [moe] Replace local reorder indexing_backward with gather-sum and fuse router score scaling [moe] Compile router score multiplication without changing dispatch order Nov 28, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes -- review is posted on the PR (see the Reviews section).

@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: Request changes -- Three things are still open: tianyu-l's "any MoE model?" question, the overlap with the author's own #6326, which removes this PR's only measured call site, and a held-out loss gap that is larger than a low-bit gradient change should produce.

What this PR does. It adds one shared helper, scale_rows_by_scores, in linear.py. The helper computes (x * scores.float()).to(x.dtype) and is registered as the opt-in score_scale local_compile region. The three existing copies of that expression call it: the dispatcher's _score_and_scatter_add, GroupedLinear's W2 input scoring, and DeepEP's post-postprocess scoring. Qwen3.5 and Flash-Next turn the region on by default.

Example. BF16 x of shape [262144, 2048] with FP32 scores:

eager:    mul -> FP32 [R, D] (2 GiB) -> cast -> BF16 (1 GiB)
          backward: FP32 grad, FP32 dX, FP32 grad*x before the row sum (2 GiB each)
compiled: one fused kernel writes the BF16 output; backward writes BF16 dX and FP32 [R] dScores
          forward is bitwise equal; dScores can differ in low bits (reduction order)

Must fix

  1. ROUTER_SCORE_ABSORPTION.md:84 -- @tianyu-l's comment on qwen3_5/model.py:329 ("any MoE model?") is unaddressed. The region is enabled only for Qwen3.5 and Flash-Next, while the B200 measurement uses Qwen3-30B-A3B. Enable it in every MoE model's defaults and regenerate any goldens that move, or answer in the thread why it should stay per model.
  2. token_dispatcher.py:218 -- This conflicts with #6326 (same author, open). #6326 deletes _score_and_scatter_add and folds this multiply into moe_weighted_gather_sum. That PR uses batch_invariant=False for the same score-gradient reduction; this PR uses True. State the landing order. Also say what this PR still delivers after #6326: only the DeepEP sites, which were not measured end to end.
  3. Description, Validation -- Held-out loss after 20 updates is 3.089 vs 3.066 (+0.023). The stated numerics change is low bits in the FP32 score gradient. CPU runs (commit c720281) matched loss and grad_norm for 12 steps. A 0.75% gap in 20 steps needs explaining. Run scripts/loss_compare.py with the region on and off at seed 42 in deterministic mode to show the first step where loss and grad_norm diverge, and add a baseline-vs-baseline noise floor. Without that, a bug can't be ruled out.

Questions

  • Were the B200 numbers (30.7 -> 27.5 ms, 11.26 -> 10.85 GiB) measured at c720281? Commit 0c2600a says the earlier GPU numbers included gather-sum. Please name the commit in the description.
  • The 128-token debug model slows from 18.8 to 22.5 ms (+20%). Is that the fixed per-call overhead of the compiled region? Qwen3.5 debug configs in CI will now pay it.
Details

Maintainer comments at HEAD. Rename without "moe": done (score_scale). Restore the type-promotion comment: done, now in the helper docstring. Split out gather-sum: done, moved to #6326. Share one implementation: done (scale_rows_by_scores). "Needs to be updated" on qwen3_5/model.py: the gather-sum entry is gone. "Any MoE model?": open (must-fix 1).

Batch invariance. In batch-invariant mode, sum.dim_IntList is replaced by a fixed-schedule kernel (distributed/batch_invariant.py). Inductor's own reduction for dScores bypasses that override. shared_expert_gate (qwen3_5/moe.py:77) has the same backward reduction and is marked True, so this PR follows existing precedent and #6326 is the outlier. Either way, pick one convention.

Overlap search. I searched for "score_scale", "router score" and token_dispatcher.py. Found: #6326 (rewrites the combine, conflicts), #5765 (draft; DeepEP scores inside the compiled activation, touches the DeepEP site), #5719 (combine as one overridable op), and #5382/#5518 (gather-sum combine).

Goldens. No Qwen3.5 golden exists, so enabling the region there moves no golden files. Enabling it for deepseek_v3, gpt_oss, qwen3 or kimi_k3 may move theirs.

Not verified: GPU timing and memory, whether other models' goldens would shift, DeepEP end to end.

@bvolpato

bvolpato commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

At 7ae95f0, I checked that batch-invariant mode rejects score_scale and accepts a configuration with the region disabled.

I held the expert assignments fixed on a B200 and compared eager execution with score_scale. The input had 8,192 tokens, width 2,048, intermediate width 512 and eight routes per token across 32 experts. Both trials gave similar median times for a warm SGD update.

Path Eager Compiled Relative L2 error in the first router-logit gradient
Local routed experts 5.68 ms 3.93 to 3.94 ms 1.02e-7
Scoring the input to the expert output projection (W2) 2.65 ms 2.32 to 2.33 ms 1.05e-7

The first forward pass, input gradients and weight gradients matched exactly. Loss and gradient norm matched across 14 updates with these fixed routes.

With score_scale off, the two-layer C4 run matched b3e6a66 exactly for loss, gradient norm and selected expert sets. With it on, training loss first differed at step 2. At that step, 116 of 8,192 tokens in layer 1 and 251 in layer 2 selected a different set of eight experts. Held-out loss after 20 updates was 0.02257 higher in both trials. The trace shows when expert selection changed. It cannot tell us how much of the loss difference that explains.

To reproduce the CPU storage and precision check, run pytest tests/unit_tests/cpu/models/common/test_linear.py -k scores_use_fp32. The local combine call measured here goes away if #6326 lands. DeepEP and full-model convergence remain unverified.

…rder

Scaling 262,144 BF16 rows of width 2,048 can materialize a 2 GiB FP32
product before the cast. A shared `score_scale` region lets Inductor
fuse the multiply and cast for scored grouped linear layers and
dispatcher paths. Qwen3.5 and Qwen3.8 Flash Next enable it by default.
Other models can add `score_scale` to `model.local_compile.regions`.

The tested revision 7ae95f0
has the same Git tree as this commit.
Use score_scale in the existing batch-invariance check. The test now
catches an unsafe change to the region's registration.

Explain which paths use the region and how rounding in the score
gradient can affect expert selection after a router update. The model
defaults and dispatch order stay the same.
@bvolpato
bvolpato requested a review from tianyu-l November 30, 2026 22:41
Comment thread torchtitan/models/qwen3_5/model.py Resolved
Enable the shared region in DeepSeek, GPT-OSS, Kimi, Muse Spark and
Qwen3. Keep the other Kimi K2 regions eager in both text and multimodal
configs. Recipes can still remove score_scale for batch-invariant mode.

HybridEP now shares the DeepEP scoring path. Document when both backends
scale W2's input and when they scale the postprocessed output. Dispatch
order and recomputation policies are unchanged.

CPU checks covered model defaults, score precision, checkpoint adapters
and both expert-parallel scoring paths with communication mocked. The
score gradient reduction can change numerics. A10G and MI350X reference
losses and gradient norms still need GPU integration runs.
@bvolpato
bvolpato requested a review from tianyu-l December 2, 2026 04:37

This branch has not been deployed

No deployments
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.

2 participants