Skip to content

[DeepEP] Fix silently wrong MoE gradients under activation checkpointing - #5115

Merged
tianyu-l merged 3 commits into
pytorch:mainfrom
francesco-bertolotti:f14-deterministic-deepep
Oct 8, 2026
Merged

tianyu-l merged 3 commits into
pytorch:mainfrom
francesco-bertolotti:f14-deterministic-deepep

Conversation

@francesco-bertolotti

Copy link
Copy Markdown
Collaborator

Why

deepep.dispatch returns an EPHandle that records the layout of the received rows: which row came from which source token on which rank, in what order..

When activation checkpointing replays the DeepEP ops, this breaks:

  1. Forward: dispatch returns rows in order A. The autograd nodes keep handle on ctx. The tensors saved for backward are dropped, to be recomputed.
  2. Backward: the recompute runs dispatch. With the default ElasticBuffer(deterministic=False), two identical dispatches do not return rows in the same order, so the recomputed tensors (received tokens, expert activations) are in order B.
  3. ctx attributes are not recomputed, so the original nodes map order-B gradients with the order-A layout.

The forward output is correct, so the loss looks normal. But every gradient through the MoE is wrong: the router, the expert weights, and the block input.

When this happens:

AC policy DeepEP ops replayed?
FullAC always (dispatch). The deepep ops register no effect, so eager SAC does not save them
SelectiveAC, default save set no (deepep.dispatch/combine are in comm_ops)
SelectiveAC subclass overriding get_save_ops() yes, unless both ops are in the new set
RegionAC yes, unless save_regions matches *.token_dispatcher.ep_communication (default [])

What

  • get_buffer(..., deterministic: bool | None = None) (torchtitan/distributed/deepep/deepep.py)
    • None keeps the current behavior and follows torch.are_deterministic_algorithms_enabled().
    • Requesting a different setting for an existing same-group buffer raises ValueError instead of rebuilding. All dispatchers share one process-global buffer, so a rebuild would silently change the setting for dispatchers built earlier.
  • DeepEPTokenDispatcher.Config.deterministic: bool | None = None
    • Resolved at construction, which runs after set_determinism, and passed to get_buffer by init_buffer.
    • Can be set through TokenDispatcherTransform(dispatcher=DeepEPTokenDispatcher, kwargs={"deterministic": True}).
    • The class docstring now states that "both replayed" requires deterministic=True.
  • Startup guard _check_deepep_replay (torchtitan/distributed/activation_checkpoint.py)
    • Raises ValueError when a policy would replay the dispatch or combine of a DeepEP dispatcher with deterministic=False.
    • It runs in each policy's _wrap_block, so it sees the save set the policy actually uses for that block (some SelectiveAC subclasses vary get_save_ops() per block).
      • FullAC: always replays.
      • SelectiveAC: replays unless both deepep.dispatch and deepep.combine are in get_save_ops().
      • RegionAC: dispatcher.remat_should_recompute("ep_communication").
    • The error names the dispatcher FQN and both fixes:
      • set deterministic=True, which adds a sort to every dispatch;
      • or save both ops: the SAC save set, or a RegionAC save_regions pattern.
    • This is a configuration check, not a runtime check like "dispatch running inside backward", which would also fire on legitimate patterns such as a chunked MoE that dispatches inside a custom backward.

No behavior change for configurations that were already correct. The default SelectiveAC saves the DeepEP ops, and debug.deterministic=True already gave a deterministic buffer through the None path.

Numerics

Measured on one GH200 node, EP=4, D=6144, F=1792, 96 experts per rank, top-8. The block is h + moe(rms_norm(h)) with an fp32 router, and gradients are compared against the same block without checkpointing (relative L2 error):

setup grad h grad router / norm grad experts
no checkpoint, run twice exact exact 5e-5 (run-to-run noise)
SAC saving only aten.topk, default buffer 0.49 1.4 1.4
SAC saving DeepEP ops too, default buffer exact exact 5e-5
SAC saving only aten.topk, deterministic=True exact exact exact

Cost of deterministic=True at that shape:

measurement default deterministic=True
dispatch 10.3 ms 14.3 ms (+4.0 ms, the sort)
combine 9.6 ms 9.6 ms
block fwd+bwd, topk-only SAC 360.8 ms 371.6 ms (+3%)

The alternative, saving the DeepEP ops, keeps the received-token tensors per layer (about 3 GiB per layer at this shape).

Tests

  • tests/unit_tests/cpu/test_deepep_activation_checkpoint.py (needs deep_ep importable, no GPU). Checks that the guard:
    • rejects FullAC, topk-only SAC, dispatch-only and combine-only SAC, and RegionAC with no save regions when deterministic=False;
    • allows all of them when deterministic=True;
    • allows default SAC, SAC saving both ops, and RegionAC saving ep_communication;
    • follows torch.use_deterministic_algorithms when deterministic=None.
  • tests/unit_tests/gpu/test_deepep_activation_checkpoint.py (multi_gpu, EP=min(4, GPUs)). Requires output, input grad and all parameter grads to be bitwise equal to no checkpointing under FullAC, topk-only SAC and RegionAC, with deterministic=True.
    • TODO: only run at EP=1 so far. EP=1 cannot catch the bug: the default buffer returns the same order with one rank, so the test also passes with the guard off. Still to do: a run at EP≥2, plus a negative control at EP≥2 (guard off, deterministic=False) that must fail.
  • Existing tests still pass: tests/unit_tests/cpu/test_{inference_moe,transforms,moe}.py, tests/unit_tests/gpu/test_{activation_checkpoint,remat}.py.
  • pre-commit is clean on the changed files, except pyrefly errors in untouched code (_set_lru_cache, F.scaled_addmm_, MixedPrecisionPolicy(param_dtype_override_fn=...), dist_moe runtime), which come from the torch nightly API.

Notes for users

  • Any run with DeepEP plus FullAC, a custom SelectiveAC.get_save_ops(), or RegionAC without ep_communication in save_regions had wrong MoE gradients. Throughput numbers from such runs are valid; loss curves are not.
  • These configurations now fail at startup. To fix, set deterministic=True on the DeepEP dispatcher, or save both DeepEP ops.

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

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

@tianyu-l
tianyu-l requested a review from anijain2305 October 7, 2026 17:55
@tianyu-l

tianyu-l commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Thanks, I'm also seeing a related PR #5123 just so you know. @anijain2305 will review both.

@anijain2305

anijain2305 commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

@francesco-bertolotti Thanks for the contribution.

There are a few developments happening in parallel that should resolve the issue this PR is targetting

The benefit of this PR is that it actually allows you to recompute dispatch and therefore save memory. However, deterministic=True also increases the dispatch time. So the tradeoff is skewed - we are paying higher recompute time than deterministic=False to save memory.

Currently, my take is that we should just always save dispatch and combine for DeepEP for simplicity. But I am happy to reconsider.

Do you have any real runs where recomputing dispatch really saves you considerable memory that it is a must have?

Update - After talking to @tianyu-l , I think as a framework, we should provde the option to recompute. Can you please do a followup

@anijain2305

Copy link
Copy Markdown
Contributor

Copying the modified update from last message to avoid notification suppression.

After talking to @tianyu-l , I think as a framework, we should provide the option to recompute dispatch. Can you please do a followup?

num_topk=num_topk,
use_fp8_dispatch=use_fp8_dispatch,
deterministic=torch.are_deterministic_algorithms_enabled(),
deterministic=deterministic,

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.

concretely, could we determine this flag somewhere in this file, where we have access to module.remat_should_recompute("dispatch")

"""Whether RegionAC replays dispatch/combine during backward."""
# Without RegionAC the remat regions have no fqn and do not affect execution
# (remat_should_recompute is then True, since nothing is saved).
return bool(self._remat_module_fqn) and self.remat_should_recompute(

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.

Is bool(self._remat_module_fqn) for FullAC, which is not migrated to remat yet?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Yes

@anijain2305 anijain2305 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.

Looks great! One question.

@tianyu-l
tianyu-l merged commit 70ad4c9 into pytorch:main Oct 8, 2026
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