Skip to content

[MoE] Make the token combine one op that backends can override - #5719

Open
tdalmia-aws wants to merge 2 commits into
pytorch:mainfrom
tdalmia-aws:moe-score-and-scatter-add-op
Open

tdalmia-aws wants to merge 2 commits into
pytorch:mainfrom
tdalmia-aws:moe-score-and-scatter-add-op

Conversation

@tdalmia-aws

@tdalmia-aws tdalmia-aws commented Oct 30, 2026 •

Copy link
Copy Markdown

Summary

The MoE token combine multiplies each routed row by its router score in float32, casts it back to the routed dtype, and adds it into the output with deterministic_scatter_add. Only the scatter is an op, so a backend with a fused combine kernel cannot replace the whole combine without patching token_dispatcher.py. This PR adds a torchtitan::score_and_scatter_add op whose only kernel is CompositeImplicitAutograd, with the existing code as its body: every current backend runs the same ATen ops in the same order, and an out of tree backend can register its own fused kernel for the op on its device. The combine, a full MoE layer and the AOT graphs match main bitwise on CPU, and loss and grad norm match main bitwise on GPU with loss_compare.py --assert-equal. The sections below are AI-assisted.

Why

On main, the MoE token combine in token_dispatcher.py is three steps: a float32 multiply by the router score, a
cast back to the routed dtype, and torchtitan::deterministic_scatter_add. Only the last step is an op. A backend
with a fused combine kernel can register for deterministic_scatter_add, but by then the multiply and the cast have
already run, each as a separate pass over the (N, D) routed tensor. Out-of-tree backends that have such a kernel,
such as torch-neuronx, can reach it today only by patching token_dispatcher.py.

Example.

# main: only the scatter is an op
routed_ND = (routed_ND * scores_N.reshape(-1, 1).to(torch.float32)).to(routed_ND.dtype)
out_TD = deterministic_scatter_add(torch.zeros_like(x_TD), idx_N.reshape(-1, 1).expand(-1, D), routed_ND)

# this PR: the whole combine is one op, and its CompositeImplicitAutograd body is the code above
out_TD = score_and_scatter_add(torch.zeros_like(x_TD), routed_ND, scores_N, idx_N)

# an out-of-tree backend replaces it on its own device, with no torchtitan change
lib = torch.library.Library("torchtitan", "IMPL")
lib.impl("score_and_scatter_add", fused_combine, "AutogradPrivateUse1")

What changed

  • torchtitan/ops/scatter_add.py: new op torchtitan::score_and_scatter_add(out, routed, scores, token_indices).
    Its only kernel is CompositeImplicitAutograd, and its body is the current combine. out is the zeros buffer that
    receives the sums. score_and_scatter_add is the op itself, so eager and compiled runs both go through it, and a
    backend kernel is reached in both.
  • torchtitan/models/common/moe/token_dispatcher.py (mechanical): the local, all-to-all and TorchAO dispatchers call
    the op with torch.zeros_like(x_TD) as out, as they pass it to deterministic_scatter_add on main. The
    _score_and_scatter_add helper only forwarded to it, so it is removed.
  • Not changed: the DeepEP, HybridEP and Dist-MoE combines, which have their own kernels.
  • No new config, flag or dependency.

Alternatives considered

  • A Configurable override of the token dispatchers (torchtitan/config/OVERRIDE.md): needs no torchtitan change.
    But each backend has to subclass the local, all-to-all and TorchAO dispatchers and copy their combine, every recipe
    has to opt in, and the backend package has to import torchtitan.
  • A kernel for deterministic_scatter_add: the multiply and the cast run before that op boundary.
  • torch.library.custom_op with its own autograd: Inductor can no longer fuse the scale and the casts, and DTensor
    needs a sharding rule.

Numerics

With no backend kernel, the op decomposes to the same ATen ops as main, with the same edges. Base: main ad7a9937.
CPU runs use torch 2.16.0.dev20261029+cpu.

Check Config Result
LocalTokenDispatcher.combine, main vs this PR bf16, fp32; eager, torch.compile(backend="aot_eager"), make_fx; output, routed grad, score grad bitwise
Full MoE layer, main vs this PR, separate processes Qwen3 debugmodel_moe and DeepSeek-V3 debugmodel; fp32, bf16; eager and torch.compile(backend="aot_eager") 48 of 48 tensors bitwise (output, input grad, parameter grads)
AOT forward and backward graphs of the combine bf16 same ATen ops and edges; aten.zeros_like now runs before the multiply
spmd_types, all 256 local-type combinations of (routed, scores, token_indices, x_TD), typecheck(local=True) 2-rank fake PG output type or error equal to main in 256 of 256 (216 raise on both)
scripts/loss_compare.py --assert-equal, loss and grad_norm, 10 steps, seed 42, deterministic 8x H200; 5 eager configs (DeepSeek-V3 EP 1, EP 8, HSDP + EP 2, TP 2 + CP 2 + SP + EP 2; Qwen3 MoE FSDP 2 + TP 2 + CP 2 + EP 8) and 1 GraphTrainer config (DeepSeek-V3 FSDP 4 + TP 2 + EP 4) previous revision 3fbd2d4: bitwise in 6 of 6 configs. This revision: rerun pending

Performance

  • No backend kernel: the op runs the same kernels as main, plus one dispatcher call per MoE layer in eager mode. Peak
    memory was the same in all 6 GPU configs (within 0.02 GiB, previous revision).
  • With a fused combine kernel on Neuron, registered for this op by torch-neuronx (kernel in review there):
    trn2.48xlarge, eager FSDP2, full depth, TP 4 x FSDP 16 = 64 ranks, local batch 4, global batch 64, sequence 4096,
    full AC, 12 steps, seed 42. TorchTitan v0.3.0 with this op and its three call sites backported. Step time and MFU =
    median of steps 6-12, one run per arm. Loss and grad norm are bitwise equal to the unfused combine at all 12 steps.
Model Unfused step time, s Fused step time, s Change
Qwen3-30B-A3B 10.449 9.481 -9.3%
DeepSeek-V3-16B 5.603 5.133 -8.4%
GPT-OSS-20B 7.173 6.693 -6.7%
Model Unfused MFU, % Fused MFU, % Unfused peak memory, GiB Fused peak memory, GiB
Qwen3-30B-A3B 6.92 7.63 18.29 14.36
DeepSeek-V3-16B 8.38 9.14 11.52 9.85
GPT-OSS-20B 9.57 10.25 14.27 13.14

Testing

  • TestScoreAndScatterAdd in tests/unit_tests/cpu/models/common/test_moe.py. Each test and the regression it
    catches:
    • test_dispatcher_combine_runs_backend_override: a dispatcher that bypasses the op or passes a wrong out or
      wrong scores, or a backend kernel that is not used or not removed cleanly. Expected values come from
      op.decompose.
    • test_compile_runs_backend_override: a compiled combine that does not reach a backend kernel (for example a
      compile-time bypass of the op), or a graph break (fullgraph=True).
  • pytest tests/unit_tests on a CPU machine: 2055 passed, 37 failed, 336 skipped, 3 xfailed. The same 37 tests fail on
    main ad7a993 (Inductor CppCompileError on this machine, "Torch not compiled with CUDA enabled", and GPU
    distributed tests). The only new test IDs are the two above.
  • MoE test files merged with current main 0f34815: 39 passed, 1 skipped. The spmd_types sweep on the merge also
    equals main in 256 of 256.
  • pre-commit run --all-files: all hooks pass.

Known issues / follow-ups

  • The Python dispatcher caches its kernel choice per op and dispatch key. A backend kernel registered after the op
    was already traced under that key in the same process is not used by AOT tracing. Backends should register at
    import, before the first compile.

The MoE token combine multiplies each routed row by its router score in
float32, casts it back to the routed dtype, and scatter-adds the rows
of each token. Only the scatter is an op today, so a backend with a
fused combine kernel can register for deterministic_scatter_add but
not for the multiply and the cast that run before it.

Add torchtitan::score_and_scatter_add(routed, scores, token_indices,
num_tokens) in torchtitan/ops/scatter_add.py. Its only kernel is
CompositeImplicitAutograd and its body is the existing combine, so a
backend that registers nothing runs the same ops. Under torch.compile
the Python wrapper traces the body directly, so Dynamo graphs keep
their current nodes. The local, all-to-all and TorchAO dispatchers call
the op in place of the _score_and_scatter_add helper, which is removed.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 30, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 30, 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.

@tdalmia-aws
tdalmia-aws marked this pull request as ready for review October 30, 2026 23:03
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 30, 2026
@felipemello1

Copy link
Copy Markdown
Contributor

@claude please review

@claude

claude Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @felipemello1's task in 2m 40s —— View job


Request changes: under torch.compile the override is skipped, and the SPMD type checks in the MoE combine get weaker. 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: Request changes -- Under torch.compile the wrapper skips the op, so a backend's fused kernel only runs in eager mode, and the new signature makes SPMD type checking weaker in the MoE combine.

What this PR does. It turns the MoE combine (multiply by the router score in fp32, cast back, deterministic scatter-add) into one torchtitan::score_and_scatter_add op. The op's only kernel is CompositeImplicitAutograd, and its body is the current combine code. An out-of-tree backend (torch-neuronx) can then register a fused kernel under its own autograd key. The local, all-to-all and TorchAO dispatchers call the op through a Python wrapper. The wrapper skips the op while compiling.

Example.

# Neuron backend registers its fused kernel
lib.impl("score_and_scatter_add", fused_combine, "AutogradPrivateUse1")

model(x)                    # eager: dispatcher -> op -> fused_combine
torch.compile(model)(x)     # compiled: is_compiling() -> reference body; fused_combine never runs

Must fix

  1. torchtitan/ops/scatter_add.py:102-109 -- The is_compiling() bypass means the override never runs on a compiled model, and recipes normally compile the MoE blocks. The PR's AOT/make_fx check shows the aten graphs stay the same without it. Delete the wrapper and call the op directly (inline comment).
  2. torchtitan/models/common/moe/token_dispatcher.py:148 (and :625, :724) -- x_TD.shape[0] takes x_TD out of what the SPMD typechecker sees. By the PR's own sweep, 16 combinations that main rejects now pass, and routed=R, x_TD=V now gives R. Pass torch.zeros_like(x_TD) as an out input so typing stays the same as main (inline comment).
  3. tests/unit_tests/cpu/models/common/test_moe.py:739-783 -- test_matches_inline_combine compares the reference to a copy of itself. Drop it, and drop test_compile_traces_reference_ops once item 1 is done. Keep the dispatcher-override test (inline comment).

Questions

  • Do you have a measurement of the fused combine on Neuron (step time or MoE-layer time) compared with the current three passes? The extension point has no in-repo consumer, so this number is what justifies it.
  • Does the Neuron path run torchtitan with torch.compile, eager, or graph_trainer (make_fx)? The answer decides whether item 1 is a blocker or just needs a comment saying the override is eager-only.
Details
  • Gate. There is a real problem: on main a backend can only hook deterministic_scatter_add, after the fp32 multiply and the cast have already made separate passes over (N, D). Registering a kernel through torch.library under the backend's own dispatch key is PyTorch-native, adds no config, flag or dependency, and leaves core unaware of Neuron. So the approach fits torchtitan's rules. The open points are value evidence (above) and making the hook behave the same in eager and compiled runs.
  • Scope. The DeepEP, HybridEP and Dist-MoE combines are left alone, which is right because they have their own kernels. A backend override therefore covers only the local, all-to-all and TorchAO paths, and the description says so.
  • Remat. remat.recompute_needs_tensor(routed_output_RD) still applies. With a backend kernel, that kernel owns what it saves for backward.
  • Size after the fixes. About 30 lines in scatter_add.py (the schema, the reference body, the _lib.impl call), three call-site edits, and one test of about 30 lines. Net LoC goes from +148 to about +40.

Not verified: whether a PrivateUse1 autograd kernel is picked up during AOT tracing once the bypass is removed, and whether passing out restores exactly main's SPMD rejections. I could not run Python in this environment. A maintainer still needs to review, since this touches models/common/.

Comment thread torchtitan/ops/scatter_add.py Outdated
Comment on lines +102 to +109
if torch.compiler.is_compiling():
# Trace the plain ops so compiled graphs are unchanged.
return _score_and_scatter_add_reference(
routed, scores, token_indices, num_tokens
)
return torch.ops.torchtitan.score_and_scatter_add(
routed, scores, token_indices, num_tokens
)

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.

Under torch.compile this branch calls the reference body directly, so Dynamo never records torchtitan::score_and_scatter_add and a backend's AutogradPrivateUse1 kernel is never reached. torchtitan recipes usually compile the MoE blocks, so on a compiled run the override silently does nothing. That is the case this PR exists for, and nothing tells the backend it was skipped.

The stated reason, "Dynamo graphs keep their current nodes", is about Dynamo-level node identity only. Per the PR's own AOT/make_fx comparison, the aten graphs only change from zeros_like to new_zeros once the CompositeImplicitAutograd kernel decomposes during AOT tracing. Does anything downstream match on Dynamo-level nodes?

Smallest fix: delete the wrapper and call torch.ops.torchtitan.score_and_scatter_add from the three dispatcher call sites. Then compiled and eager runs take the same path, and test_compile_traces_reference_ops goes away. If the bypass has to stay, say in a comment that the override is eager-only, and in the PR that the Neuron path does not compile. (Unverified: I couldn't run compile here to confirm that a PrivateUse1 autograd kernel is picked up during AOT tracing.)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I got rid of the wrapper, score_and_scatter_add is now torch.ops.torchtitan.score_and_scatter_add, so the three dispatchers call the op in eager and under torch.compile. On CPU, with no backend kernel, the AOT forward and backward graphs have the same ATen ops and edges as main (zeros_like now runs before the multiply), and outputs and grads are the same as main in eager, aot_eager and make_fx. A backend kernel registered under AutogradCPU is reached while compiling. Note for backends is that they should register the kernel at import, because the Python dispatcher caches its kernel choice per op and key.

Comment on lines +148 to 153
return score_and_scatter_add(
routed_output_RD,
metadata.topk_scores_experts_sorted_N,
metadata.token_indices_experts_sorted_N,
x_TD,
)

def _score_and_scatter_add(
self,
routed_output_ND: torch.Tensor,
topk_scores_N: torch.Tensor,
token_indices_N: torch.Tensor,
x_TD: torch.Tensor,
) -> torch.Tensor:
"""Weight expert-sorted outputs by their router scores and sum them per token."""
# Type promotion computes the product in float32 without materializing a
# float32 copy of the routed output, which the multiply would save for
# backward (twice the bytes of the routed output itself).
routed_output_ND = (
routed_output_ND * topk_scores_N.reshape(-1, 1).to(torch.float32)
).to(routed_output_ND.dtype)
return deterministic_scatter_add(
torch.zeros_like(x_TD),
token_indices_N.reshape(-1, 1).expand(-1, x_TD.shape[-1]),
routed_output_ND,
x_TD.shape[0],
)

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.

Passing x_TD.shape[0] instead of x_TD drops x_TD from what the SPMD typechecker sees. The "Known issues" section says this already: in 16 local-type combinations that main rejects, this PR accepts. For routed=R, x_TD=V the output type also changes from V to R. That weakens checking in the MoE combine, where EP/SP placement mistakes actually happen. .claude/rules/distributed.md asks us to rely on spmd_types rather than lose it.

Smallest fix that keeps typing the same as main: build the buffer at the call site and make it an op input, like deterministic_scatter_add already does.

score_and_scatter_add(torch.zeros_like(x_TD), routed_output_RD, scores_N, token_indices_N)
# schema: score_and_scatter_add(Tensor out, Tensor routed, Tensor scores, Tensor token_indices) -> Tensor

A backend kernel can ignore or reuse out. Another option is a spmd typing rule for the op that checks against x_TD's type. Either way, the 16 combinations main rejects should still raise. (Unverified: I couldn't run the 256-combination sweep.)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Took this suggestion, schema is now score_and_scatter_add(Tensor out, Tensor routed, Tensor scores, Tensor token_indices), and the local, all-to-all and TorchAO dispatchers pass torch.zeros_like(x_TD), like deterministic_scatter_add on main. The spmd_types sweep now matches main in 256/256 cases whereas the previous revision was 238/256.

Comment on lines +739 to +783
def _inline_combine(routed_ND, scores_N, token_indices_N, num_tokens):
# The token dispatcher combine before torchtitan::score_and_scatter_add.
x_TD = torch.empty(num_tokens, routed_ND.shape[-1], dtype=routed_ND.dtype)
routed_ND = (routed_ND * scores_N.reshape(-1, 1).to(torch.float32)).to(
routed_ND.dtype
)
return deterministic_scatter_add(
torch.zeros_like(x_TD),
token_indices_N.reshape(-1, 1).expand(-1, x_TD.shape[-1]),
routed_ND,
)


def _combine_fwd_bwd(combine_fn, num_tokens, top_k, dim, dtype, num_padded_tokens=0):
# N = num_tokens * top_k routed rows; the last num_padded_tokens output
# rows receive no routed row and must stay zero.
g = torch.Generator().manual_seed(0)
num_out = num_tokens + num_padded_tokens
routed_ND = torch.randn(num_tokens * top_k, dim, generator=g).to(dtype)
scores_N = torch.rand(num_tokens * top_k, generator=g)
token_indices_N = torch.randperm(num_tokens * top_k, generator=g) // top_k
grad_TD = torch.randn(num_out, dim, generator=g).to(dtype)
routed_ND.requires_grad_(True)
scores_N.requires_grad_(True)
out_TD = combine_fn(routed_ND, scores_N, token_indices_N, num_out)
out_TD.backward(grad_TD)
return out_TD.detach(), routed_ND.grad, scores_N.grad


class TestScoreAndScatterAdd(unittest.TestCase):
def _assert_bitwise(self, actual, expected):
for a, e in zip(actual, expected, strict=True):
self.assertEqual(a.dtype, e.dtype)
self.assertTrue(torch.equal(a, e))

def test_matches_inline_combine(self):
for dtype in (torch.bfloat16, torch.float32):
for shape in ((64, 2, 32, 0), (37, 6, 48, 11)):
num_tokens, top_k, dim, num_padded_tokens = shape
args = (num_tokens, top_k, dim, dtype, num_padded_tokens)
with self.subTest(dtype=dtype, shape=shape):
self._assert_bitwise(
_combine_fwd_bwd(score_and_scatter_add, *args),
_combine_fwd_bwd(_inline_combine, *args),
)

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.

_inline_combine is a copy of _score_and_scatter_add_reference (only zeros_like vs new_zeros differs). After merge, test_matches_inline_combine compares two copies of the same code, so it guards nothing that the bitwise refactor evidence in the PR description doesn't already cover. If the reference body changes on purpose, someone edits both copies. Please drop this test, and test_compile_traces_reference_ops too if the compile bypass is removed. test_dispatcher_combine_runs_backend_override is the one that guards the contract (the dispatchers must go through the op), and it can build its expected values from op.decompose instead of _inline_combine.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I dropped test_matches_inline_combine and test_compile_traces_reference_ops. test_dispatcher_combine_runs_backend_override builds its expected values from op.decompose. New test_compile_runs_backend_override checks that an AutogradCPU kernel is reached under torch.compile (fullgraph=True`). Putting the bypass back makes it fail

Remove the Python wrapper that skipped the op under torch.compile.
score_and_scatter_add is now the op itself, so eager and compiled runs
both reach a backend kernel. With no backend kernel, AOT decomposes the
op to the same ATen ops as before.

Change the schema to score_and_scatter_add(out, routed, scores,
token_indices). The dispatchers pass torch.zeros_like(x_TD) as out, as
the combine did before the op, so the SPMD typechecker sees x_TD again
and the combine types the same as on main.

Replace the tests with a dispatcher override test whose expected values
come from op.decompose, and a compile test that checks a backend kernel
is reached under torch.compile.
@tdalmia-aws

tdalmia-aws commented Nov 3, 2026 •

Copy link
Copy Markdown
Author

Thanks for the review. I addressed the three specific requested changes. For the questions,

  1. On Neuron, the fused combine reduces step time by -9.3% for Qwen3-30B-A3B (10.449 to 9.481 s), -8.4% DeepSeek-V3-16B (5.603 to 5.133 s), -6.7% GPT-OSS-20B (7.173 to 6.693 s).
  2. We run both eager and torch.compile, so removing the bypass was the right fix. Our compile time fusion pass will match this op on the torch-neuronx side. Torchtitan needs no change for that.

cc: @felipemello1

# The scatter-add reads the expert outputs with bare ops.
remat.recompute_needs_tensor(routed_output_RD)
return self._score_and_scatter_add(
return score_and_scatter_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.

Are you working on a non-EP case?

With EP, all other dispatcher backend have other operations, in addition to score and scatter_add. What makes this the only way to organize code?

Like, tomorrow if someone else comes and say they have a kernel for slightly bigger region, what should we do?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes, we are working on a non-EP case (TP + FSDP, EP=1)

I picked score_and_scatter_add because it's the step all three dispatchers (local, all-to-all, TorchAO) end with, and everything EP-specific (all-to-all, permute/unpermute) stays outside it. Agreed that a backend that wants to fuse more in an EP case wouldn't be able to use it though

Would you prefer an override at the dispatcher level instead, e.g. letting a backend replace TokenDispatcher.combine (or pick a dispatcher class via config/registry)? That would cover larger fused regions without adding a custom op to the model code. Happy to rework the PR that way

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 a backend replacing token dispatcher would suffice.

On the other hand, you don't really need to land a PR to enable that? You could either use your customized dispatcher when building up any model config. Alternatively, you could use any existing config, and override the dispatcher with your customized one. See https://github.com/pytorch/torchtitan/blob/main/torchtitan/config/OVERRIDE.md and https://github.com/pytorch/torchtitan/tree/main/torchtitan_recipes/overrides

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.

3 participants