Repository navigation
[MoE] Make the token combine one op that backends can override - #5719
tdalmia-aws wants to merge 2 commits into
Conversation
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.
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
|
@claude please review |
|
Claude finished @felipemello1's task in 2m 40s —— View job Request changes: under |
There was a problem hiding this comment.
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 runsMust fix
torchtitan/ops/scatter_add.py:102-109-- Theis_compiling()bypass means the override never runs on a compiled model, and recipes normally compile the MoE blocks. The PR's AOT/make_fxcheck shows the aten graphs stay the same without it. Delete the wrapper and call the op directly (inline comment).torchtitan/models/common/moe/token_dispatcher.py:148(and:625,:724) --x_TD.shape[0]takesx_TDout of what the SPMD typechecker sees. By the PR's own sweep, 16 combinations that main rejects now pass, androuted=R, x_TD=Vnow givesR. Passtorch.zeros_like(x_TD)as anoutinput so typing stays the same as main (inline comment).tests/unit_tests/cpu/models/common/test_moe.py:739-783--test_matches_inline_combinecompares the reference to a copy of itself. Drop it, and droptest_compile_traces_reference_opsonce 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 throughtorch.libraryunder 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.implcall), 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/.
| 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 | ||
| ) |
There was a problem hiding this comment.
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.)
There was a problem hiding this comment.
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.
| 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], | ||
| ) |
There was a problem hiding this comment.
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) -> TensorA 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.)
There was a problem hiding this comment.
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.
| 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), | ||
| ) |
There was a problem hiding this comment.
_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.
There was a problem hiding this comment.
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.
|
Thanks for the review. I addressed the three specific requested changes. For the questions,
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( |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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
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 patchingtoken_dispatcher.py. This PR adds atorchtitan::score_and_scatter_addop 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 withloss_compare.py --assert-equal. The sections below are AI-assisted.Why
On main, the MoE token combine in
token_dispatcher.pyis three steps: a float32 multiply by the router score, acast back to the routed dtype, and
torchtitan::deterministic_scatter_add. Only the last step is an op. A backendwith a fused combine kernel can register for
deterministic_scatter_add, but by then the multiply and the cast havealready 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.
What changed
torchtitan/ops/scatter_add.py: new optorchtitan::score_and_scatter_add(out, routed, scores, token_indices).Its only kernel is CompositeImplicitAutograd, and its body is the current combine.
outis the zeros buffer thatreceives the sums.
score_and_scatter_addis the op itself, so eager and compiled runs both go through it, and abackend kernel is reached in both.
torchtitan/models/common/moe/token_dispatcher.py(mechanical): the local, all-to-all and TorchAO dispatchers callthe op with
torch.zeros_like(x_TD)asout, as they pass it todeterministic_scatter_addon main. The_score_and_scatter_addhelper only forwarded to it, so it is removed.Alternatives considered
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.
deterministic_scatter_add: the multiply and the cast run before that op boundary.torch.library.custom_opwith its own autograd: Inductor can no longer fuse the scale and the casts, and DTensorneeds 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.LocalTokenDispatcher.combine, main vs this PRtorch.compile(backend="aot_eager"),make_fx; output, routed grad, score graddebugmodel_moeand DeepSeek-V3debugmodel; fp32, bf16; eager andtorch.compile(backend="aot_eager")aten.zeros_likenow runs before the multiply(routed, scores, token_indices, x_TD),typecheck(local=True)scripts/loss_compare.py --assert-equal, loss and grad_norm, 10 steps, seed 42, deterministicPerformance
memory was the same in all 6 GPU configs (within 0.02 GiB, previous revision).
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.
Testing
TestScoreAndScatterAddintests/unit_tests/cpu/models/common/test_moe.py. Each test and the regression itcatches:
test_dispatcher_combine_runs_backend_override: a dispatcher that bypasses the op or passes a wrongoutorwrong 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 acompile-time bypass of the op), or a graph break (
fullgraph=True).pytest tests/unit_testson a CPU machine: 2055 passed, 37 failed, 336 skipped, 3 xfailed. The same 37 tests fail onmain ad7a993 (Inductor
CppCompileErroron this machine, "Torch not compiled with CUDA enabled", and GPUdistributed tests). The only new test IDs are the two above.
equals main in 256 of 256.
pre-commit run --all-files: all hooks pass.Known issues / follow-ups
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.