Repository navigation
Make AllToAll dispatch and combine single remat regions - #4958
Merged
Merged
Conversation
[ghstack-poisoned]
This was referenced Sep 30, 2026
[ghstack-poisoned]
This was referenced Sep 30, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Sep 30, 2026
The token dispatcher's reordering, EP collectives, and score-weighted combine had no remat regions of their own (only `ep_communication` around the collectives), so RegionAC could not save or recompute them independently, and any region-wrapped producer feeding them had to be pinned. Declare them as follows. AllToAllTokenDispatcher (EP > 1): each side is one region, since profiling replay cost per GiB freed shows the gather, count exchange, dispatch all-to-all and permute free their memory only together, and so do the unpermute and combine all-to-all. - `<fqn>.dispatch` runs `_dispatch`: expert sort and gather, the token-count exchange and its device-to-host split sync, the dispatch all-to-all, and the expert-major permute. A saved dispatch replays neither collective nor the sync (previously the sync ran as a bare op and repeated on every replay, once per MoE layer per step). - `<fqn>.combine` runs `_combine`: unpermute, the combine all-to-all, and the score-weighted scatter-add. Regions return only tensors, so the splits come back as CPU tensors (`tolist()` on them does not sync) and `dispatch()` builds the metadata outside the region. TorchAOTokenDispatcher inherits both regions at EP > 1, with its padded `_permute`/`_unpermute` inside them; the pre-permute shape comes from the splits because padding changes the permuted row count. TorchAO's permute_and_pad reports a shape with an extra zero sentinel row, so its `_unpermute` now allocates that row itself and strips it. EP=1 paths: - `sort` and `gather` (LocalTokenDispatcher._local_reorder). They are separate because the argsort output is small while the gathered rows are activation-sized. - `combine`, the fp32 score multiply plus deterministic scatter-add, shared with TorchAO's EP=1 path via `_weighted_combine`. - `permute` and `unpermute` around TorchAO's EP=1 padded reordering. DeepEP and HybridEP keep `ep_communication.dispatch`/`combine` around their kernels. The combine multiplies bf16 outputs by fp32 scores through type promotion instead of an explicit float32 copy, which the multiply saved for backward at twice the routed output's size. The redundant recompute_needs_tensor on the combine all-to-all output is dropped. Losses are bitwise identical; on qwen3 MoE (TP2 EP2, 4 layers) this frees ~1 GiB under no AC. MoE.forward no longer pins the routed-expert w2 output. The pin existed because a type_as cast and the optional output_postprocess read it with bare ops, and it kept the tensor alive whenever w2 was saved. The cast now runs inside the w2 region, and the pin stays only when output_postprocess consumes the output; the Local, AllToAll and TorchAO combines consume it inside their regions. Under EP the combine backward does not read the w2 output, so a saved w2 no longer keeps it: about 0.29 GiB per layer on qwen3 at TP=2 + EP=2 (save-all 6.68 -> 5.51 GiB, EP=4 11.1 -> 9.08 GiB, losses bitwise identical). At EP=1 combine backward needs it for the score gradient anyway. DeepEP and HybridEP apply scores with bare ops, so their dispatchers pin the input to combine, keeping today's behavior there. User-visible change: with the all-to-all dispatcher, save `token_dispatcher.dispatch` and `token_dispatcher.combine` instead of `token_dispatcher.ep_communication`. Default policies (no dispatcher regions saved) recompute these ops as before. Tests: the all-to-all test saves neither, either, or both regions and counts replayed collectives and split syncs; a TorchAO EP=2 test compares padded vs unpadded dispatch and replay under RegionAC; under EP=2 a saved w2 no longer retains its output, and at EP=1 with grad-requiring scores replay is bitwise identical across w2/combine save policies. ghstack-source-id: 09d5752 Pull-Request: pytorch/torchtitan#4958
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Oct 1, 2026
The token dispatcher's reordering, EP collectives, and score-weighted combine had no remat regions of their own (only `ep_communication` around the collectives), so RegionAC could not save or recompute them independently, and any region-wrapped producer feeding them had to be pinned. Declare them as follows. AllToAllTokenDispatcher (EP > 1): each side is one region, since profiling replay cost per GiB freed shows the gather, count exchange, dispatch all-to-all and permute free their memory only together, and so do the unpermute and combine all-to-all. - `<fqn>.dispatch` runs `_dispatch`: expert sort and gather, the token-count exchange and its device-to-host split sync, the dispatch all-to-all, and the expert-major permute. A saved dispatch replays neither collective nor the sync (previously the sync ran as a bare op and repeated on every replay, once per MoE layer per step). - `<fqn>.combine` runs `_combine`: unpermute, the combine all-to-all, and the score-weighted scatter-add. Regions return only tensors, so the splits come back as CPU tensors (`tolist()` on them does not sync) and `dispatch()` builds the metadata outside the region. TorchAOTokenDispatcher inherits both regions at EP > 1, with its padded `_permute`/`_unpermute` inside them; the pre-permute shape comes from the splits because padding changes the permuted row count. TorchAO's permute_and_pad reports a shape with an extra zero sentinel row, so its `_unpermute` now allocates that row itself and strips it. EP=1 paths: - `sort` and `gather` (LocalTokenDispatcher._local_reorder). They are separate because the argsort output is small while the gathered rows are activation-sized. - `combine`, the fp32 score multiply plus deterministic scatter-add, shared with TorchAO's EP=1 path via `_weighted_combine`. - `permute` and `unpermute` around TorchAO's EP=1 padded reordering. DeepEP and HybridEP keep `ep_communication.dispatch`/`combine` around their kernels. The combine multiplies bf16 outputs by fp32 scores through type promotion instead of an explicit float32 copy, which the multiply saved for backward at twice the routed output's size. The redundant recompute_needs_tensor on the combine all-to-all output is dropped. Losses are bitwise identical; on qwen3 MoE (TP2 EP2, 4 layers) this frees ~1 GiB under no AC. MoE.forward no longer pins the routed-expert w2 output. The pin existed because a type_as cast and the optional output_postprocess read it with bare ops, and it kept the tensor alive whenever w2 was saved. Both now run inside the w2 region, and the Local, AllToAll and TorchAO combines consume the output inside their regions. The dispatchers likewise no longer pin the routed input (the bf16 cast runs inside the w13 region) or the combined output, whose consumers are the saved shared-expert and residual adds; only the token counts and splits, read with bare ops, stay pinned. Under EP the combine backward does not read the w2 output, so a saved w2 no longer keeps it: about 0.29 GiB per layer on qwen3 at TP=2 + EP=2 (save-all 6.68 -> 5.51 GiB, EP=4 11.1 -> 9.08 GiB, losses bitwise identical). At EP=1 combine backward needs it for the score gradient anyway. DeepEP and HybridEP apply scores with bare ops, so their dispatchers pin the input to combine, keeping today's behavior there. User-visible change: with the all-to-all dispatcher, save `token_dispatcher.dispatch` and `token_dispatcher.combine` instead of `token_dispatcher.ep_communication`. Default policies (no dispatcher regions saved) recompute these ops as before. Tests: the all-to-all test saves neither, either, or both regions and counts replayed collectives and split syncs; a TorchAO EP=2 test compares padded vs unpadded dispatch and replay under RegionAC; under EP=2 a saved w2 no longer retains its output, and at EP=1 with grad-requiring scores replay is bitwise identical across w2/combine save policies. ghstack-source-id: 03a020c Pull-Request: pytorch/torchtitan#4958
[ghstack-poisoned]
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Oct 2, 2026
The token dispatcher's reordering, EP collectives, and score-weighted combine had no remat regions of their own (only `ep_communication` around the collectives), so RegionAC could not save or recompute them independently, and any region-wrapped producer feeding them had to be pinned. Declare them as follows. AllToAllTokenDispatcher (EP > 1): each side is one region, since profiling replay cost per GiB freed shows the gather, count exchange, dispatch all-to-all and permute free their memory only together, and so do the unpermute and combine all-to-all. - `<fqn>.dispatch` runs `_dispatch`: expert sort and gather, the token-count exchange and its device-to-host split sync, the dispatch all-to-all, and the expert-major permute. A saved dispatch replays neither collective nor the sync (previously the sync ran as a bare op and repeated on every replay, once per MoE layer per step). - `<fqn>.combine` runs `_combine`: unpermute, the combine all-to-all, and the score-weighted scatter-add. Regions return only tensors, so the splits come back as CPU tensors (`tolist()` on them does not sync) and `dispatch()` builds the metadata outside the region. TorchAOTokenDispatcher inherits both regions at EP > 1, with its padded `_permute`/`_unpermute` inside them; the pre-permute shape comes from the splits because padding changes the permuted row count. TorchAO's permute_and_pad reports a shape with an extra zero sentinel row, so its `_unpermute` now allocates that row itself and strips it. EP=1 paths: - `sort` and `gather` (LocalTokenDispatcher._local_reorder). They are separate because the argsort output is small while the gathered rows are activation-sized. - `combine`, the fp32 score multiply plus deterministic scatter-add, shared with TorchAO's EP=1 path via `_weighted_combine`. - `permute` and `unpermute` around TorchAO's EP=1 padded reordering. DeepEP and HybridEP keep `ep_communication.dispatch`/`combine` around their kernels. The combine multiplies bf16 outputs by fp32 scores through type promotion instead of an explicit float32 copy, which the multiply saved for backward at twice the routed output's size. The redundant recompute_needs_tensor on the combine all-to-all output is dropped. Losses are bitwise identical; on qwen3 MoE (TP2 EP2, 4 layers) this frees ~1 GiB under no AC. MoE.forward no longer pins the routed-expert w2 output. The pin existed because a type_as cast and the optional output_postprocess read it with bare ops, and it kept the tensor alive whenever w2 was saved. Both now run in a w2_output region that shares w2.grouped_mm's policy, and the Local, AllToAll and TorchAO combines consume the output inside their regions. The dispatchers likewise no longer pin the routed input (the bf16 cast runs inside the w13 region) or the combined output, whose consumers are the saved shared-expert and residual adds; only the token counts and splits, read with bare ops, stay pinned. Under EP the combine backward does not read the w2 output, so a saved w2 no longer keeps it: about 0.29 GiB per layer on qwen3 at TP=2 + EP=2 (save-all 6.68 -> 5.51 GiB, EP=4 11.1 -> 9.08 GiB, losses bitwise identical). At EP=1 combine backward needs it for the score gradient anyway. DeepEP and HybridEP apply scores with bare ops, so their dispatchers pin the input to combine, keeping today's behavior there. User-visible change: with the all-to-all dispatcher, save `token_dispatcher.dispatch` and `token_dispatcher.combine` instead of `token_dispatcher.ep_communication`. Default policies (no dispatcher regions saved) recompute these ops as before. Tests: the all-to-all test saves neither, either, or both regions and counts replayed collectives and split syncs; a TorchAO EP=2 test compares padded vs unpadded dispatch and replay under RegionAC; under EP=2 a saved w2 no longer retains its output, and at EP=1 with grad-requiring scores replay is bitwise identical across w2/combine save policies. ghstack-source-id: a56b043 Pull-Request: pytorch/torchtitan#4958
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Oct 3, 2026
The token dispatcher's reordering, EP collectives, and score-weighted combine had no remat regions of their own (only `ep_communication` around the collectives), so RegionAC could not save or recompute them independently, and any region-wrapped producer feeding them had to be pinned. Declare them as follows. AllToAllTokenDispatcher (EP > 1): each side is one region, since profiling replay cost per GiB freed shows the gather, count exchange, dispatch all-to-all and permute free their memory only together, and so do the unpermute and combine all-to-all. - `<fqn>.dispatch` runs `_dispatch`: expert sort and gather, the token-count exchange and its device-to-host split sync, the dispatch all-to-all, and the expert-major permute. A saved dispatch replays neither collective nor the sync (previously the sync ran as a bare op and repeated on every replay, once per MoE layer per step). - `<fqn>.combine` runs `_combine`: unpermute, the combine all-to-all, and the score-weighted scatter-add. Regions return only tensors, so the splits come back as CPU tensors (`tolist()` on them does not sync) and `dispatch()` builds the metadata outside the region. TorchAOTokenDispatcher inherits both regions at EP > 1, with its padded `_permute`/`_unpermute` inside them; the pre-permute shape comes from the splits because padding changes the permuted row count. TorchAO's permute_and_pad reports a shape with an extra zero sentinel row, so its `_unpermute` now allocates that row itself and strips it. EP=1 paths: - `dispatch` runs `_local_reorder`: the expert sort and gather. It shares the EP > 1 region name, and the all-to-all `_dispatch` calls `_local_reorder` inside its own region. - `combine` runs `_score_and_scatter_add`: the fp32 score multiply plus deterministic scatter-add. The all-to-all `_combine` calls it inside its region. - TorchAO's EP=1 path reuses both via `LocalTokenDispatcher.dispatch` and `combine`. - `permute` and `unpermute` around TorchAO's EP=1 padded reordering. DeepEP and HybridEP keep `ep_communication.dispatch`/`combine` around their kernels. The combine multiplies bf16 outputs by fp32 scores through type promotion instead of an explicit float32 copy, which the multiply saved for backward at twice the routed output's size. The redundant recompute_needs_tensor on the combine all-to-all output is dropped. Losses are bitwise identical; on qwen3 MoE (TP2 EP2, 4 layers) this frees ~1 GiB under no AC. MoE.forward no longer pins the routed-expert w2 output. The pin existed because a type_as cast and the optional output_postprocess read it with bare ops, and it kept the tensor alive whenever w2 was saved. Both now run in a w2_output region that shares w2.grouped_mm's policy, and the Local, AllToAll and TorchAO combines consume the output inside their regions. The dispatchers likewise no longer pin the routed input (the bf16 cast runs inside the w13 region) or the combined output, whose consumers are the saved shared-expert and residual adds; only the token counts and splits, read with bare ops, stay pinned. Under EP the combine backward does not read the w2 output, so a saved w2 no longer keeps it: about 0.29 GiB per layer on qwen3 at TP=2 + EP=2 (save-all 6.68 -> 5.51 GiB, EP=4 11.1 -> 9.08 GiB, losses bitwise identical). At EP=1 combine backward needs it for the score gradient anyway. DeepEP and HybridEP apply scores with bare ops, so their dispatchers pin the input to combine, keeping today's behavior there. User-visible change: with the all-to-all dispatcher, save `token_dispatcher.dispatch` and `token_dispatcher.combine` instead of `token_dispatcher.ep_communication`. Default policies (no dispatcher regions saved) recompute these ops as before. Tests: the all-to-all test saves neither, either, or both regions and counts replayed collectives and split syncs; a TorchAO EP=2 test compares padded vs unpadded dispatch and replay under RegionAC; under EP=2 a saved w2 no longer retains its output, and at EP=1 with grad-requiring scores replay is bitwise identical across w2/combine save policies. ghstack-source-id: 82185d2 Pull-Request: pytorch/torchtitan#4958
[ghstack-poisoned]
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Oct 4, 2026
Expand dispatch and combine regions ghstack-source-id: 62d0562 Pull-Request: pytorch/torchtitan#4958
[ghstack-poisoned]
anijain2305
added a commit
that referenced
this pull request
Oct 5, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #4893 * #4958 * __->__ #4956 Key design changes * Every Linear declares its own remat region around `self._linear` (`<fqn>.linear`), the seam that quantized and LoRA linears already override. Callers call the Linear directly instead of wrapping it in a region, since a saved outer region cannot contain a recomputed one. * ColumnParallelLinear and RowParallelLinear put their collectives in separately controlled sibling regions: `<fqn>.tp_gather` before the projection and `<fqn>.tp_reduce` after it. Modules whose projections share one TP input gather it once with `maybe_gather_tp_input`, which declares `<module fqn>.tp_gather`. * GroupedLinear gets the same treatment: a region around `self._grouped_mm` (`routed_experts.w13.grouped_mm` / `w2.grouped_mm`). LoRA adapters call their `_linear` / `_grouped_mm` directly, so they run inside the base projection's region instead of declaring their own. * Attention modules wrap their kernel in `<fqn>.inner_attention`. * Bare operations that read a projection or attention output (norms, rope, splits, gating, residual adds) call `recompute_needs_tensor` immediately before the read, with a comment naming the producer.
anijain2305
marked this pull request as ready for review
October 5, 2026 18:10
anijain2305
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
October 5, 2026 18:10
tianyu-l
approved these changes
Oct 6, 2026
Comment on lines
+429
to
+433
| remat.recompute_needs_tensor( | ||
| num_global_tokens_per_local_expert_e, | ||
| input_splits, | ||
| output_splits, | ||
| ) |
Contributor
There was a problem hiding this comment.
it seems this API handles mixed GPU / CPU tensors well
Comment on lines
+500
to
+501
| output_splits.tolist(), | ||
| input_splits.tolist(), |
Contributor
There was a problem hiding this comment.
should we change this _dispatch_token_exchange API to receive tensors instead of list[ints] -- no particular reasons from me, maybe just consistency
| ep_size: int, | ||
| ) -> tuple[torch.Tensor, list[int], list[int]]: | ||
| """Wait for token counts and materialize CPU split lists. | ||
| ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: |
Contributor
There was a problem hiding this comment.
not sure if GraphTrainer EP overlap passes would be broken by this change
Contributor
Author
There was a problem hiding this comment.
Tried a test - it works.
[ghstack-poisoned]
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Oct 6, 2026
Human note ---------- * With EP > 1, the all-to-all dispatcher declares two remat regions, `dispatch` and `combine`. The previous regions covered only the all-to-all collectives; these also cover the processing around them. * With EP = 1 there is no communication, so dispatch and combine are not regions; they are always recomputed. * The combine now multiplies the bf16 expert outputs by the fp32 router scores instead of casting them to fp32 first. The product is still computed in fp32, but the multiply now saves the bf16 input for backward instead of an fp32 copy. This is unrelated to remat but lands in the same commit. Agent note ---------- Before, the split sync ran as a bare op, so it replayed in every backward (one host sync per MoE layer) even with `ep_communication` saved. The operator-level SelectiveAC avoided this by always saving CUDA -> CPU copies; a saved `dispatch` region gives a torch_remat policy the same behavior. The pins on the all-to-all outputs and on the w2 output are gone, since those tensors are now region inputs or outputs: when w2 and the combine are both saved, the w2 output is no longer kept. Regions return only tensors, so the splits come back as CPU tensors and the pre-permute shape is derived from them; TorchAO's padded `_unpermute` allocates and strips its sentinel row itself. Without EP there is no communication, so the local dispatch and combine stay bare. Bare readers of the routed-expert outputs (the dtype cast and postprocess after w2, the local scatter-add, the TP zero-fill, the shared-expert add, and the DeepEP/HybridEP kernels) call `recompute_needs_tensor` before they read. The combine also multiplies the bf16 expert outputs by the float32 router scores directly instead of casting them to float32 first. Type promotion still computes the product in float32, but the multiply now saves the bf16 output for backward rather than a float32 copy twice its size. The local, all-to-all, and TorchAO EP=1 combines share `_score_and_scatter_add`. Losses are bitwise identical; on qwen3 MoE (30B-A3B width, 4 layers, TP2 EP2) activation memory without AC drops from 6.5 GiB to 5.5 GiB (256 MiB per layer). ghstack-source-id: 8948964 Pull-Request: pytorch/torchtitan#4958
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Human note
dispatchandcombine. The previous regions covered only the all-to-all collectives; these also cover the processing around them.Agent note
Before, the split sync ran as a bare op, so it replayed in every backward
(one host sync per MoE layer) even with
ep_communicationsaved. Theoperator-level SelectiveAC avoided this by always saving CUDA -> CPU copies;
a saved
dispatchregion gives a torch_remat policy the same behavior. Thepins on the all-to-all outputs and on the w2 output are gone, since those
tensors are now region inputs or outputs: when w2 and the combine are both
saved, the w2 output is no longer kept.
Regions return only tensors, so the splits come back as CPU tensors and the
pre-permute shape is derived from them; TorchAO's padded
_unpermuteallocates and strips its sentinel row itself. Without EP there is no
communication, so the local dispatch and combine stay bare. Bare readers of
the routed-expert outputs (the dtype cast and postprocess after w2, the local
scatter-add, the TP zero-fill, the shared-expert add, and the DeepEP/HybridEP
kernels) call
recompute_needs_tensorbefore they read.The combine also multiplies the bf16 expert outputs by the float32 router
scores directly instead of casting them to float32 first. Type promotion still
computes the product in float32, but the multiply now saves the bf16 output for
backward rather than a float32 copy twice its size. The local, all-to-all, and
TorchAO EP=1 combines share
_score_and_scatter_add. Losses are bitwiseidentical; on qwen3 MoE (30B-A3B width, 4 layers, TP2 EP2) activation memory
without AC drops from 6.5 GiB to 5.5 GiB (256 MiB per layer).