Skip to content

Fix HybridEP activation remat and document EP backend selection - #5770

Merged
tianyu-l merged 5 commits into
mainfrom
hybridep-remat-guidance
Nov 3, 2026
Merged

tianyu-l merged 5 commits into
mainfrom
hybridep-remat-guidance

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

  1. add proper remat support for HybridEP
  2. add moe/README.md as a backend selection guidance

Why

HybridEP dispatch and combine run outside torch_remat regions. Consequently,
DefaultActivationRematConfig replays both during backward even though its documented
policy retains EP communication. Users also lack a single guide comparing the
supported EP execution paths and their graph, precision, and memory constraints.

Example. One forward/backward through a routed-expert layer normally needs
one dispatch and one combine in the forward, plus one call to each primitive
for gradient computation. Activation remat can add another replay of the
forward communication pair:

Policy Extra communication before this PR Extra communication after this PR
No remat None None
Default remat 1 extra dispatch and 1 extra combine None
Full remat 1 extra dispatch and 1 extra combine 1 extra dispatch and 1 extra combine

The default policy now retains the forward communication results for expert
recomputation. Normal forward and gradient communication still run; full remat
continues to replay communication as requested.

What changed

  • Declare HybridEP dispatch/combine regions controlled together by ep_communication,
    matching DeepEP. Retain counts and scores consumed outside regions.
  • Pass the forward handle through a CPU tensor ID because torch_remat 0.2.2 accepts
    only tensor region outputs. Garbage collection releases cache entries. A CPU
    lookup op keeps autograd setup contexts traceable with FakeTensor/AOT. Upstream
    opaque-output support is tracked in remat issue #10.
  • Add an EP backend selection guide beside MoE, with configuration examples,
    remat semantics, capacity considerations, and links to public dependency guides.
    No backend is removed or added.
  • Mechanically share the existing DeepEP test harness with HybridEP, then check
    communication counts, exact loss/gradients, and graph capture. Run HybridEP tests
    after its existing CI installer.

Alternatives considered

User-facing changes

Before After
HybridEP communication replays under default remat Default/custom saved policies retain it; full remat still replays it
Backend constraints scattered across recipes and implementation torchtitan/models/common/moe/README.md describes the available choices

Numerics

No changes to routing, expert computation, checkpoint parameter names, or precision.
Against main ff96670a2, DeepSeek V3 debug-model training with FSDP2 x EP2 on two
GB300 GPUs produced bitwise-identical TensorBoard loss and grad_norm for all 10
steps, with seed 42 and deterministic execution. Validation used
scripts/loss_compare.py --steps 10 --no-seed-checkpoint --metrics loss,grad_norm,
exporting main's metrics and asserting equality on the branch with --import-result.

Testing

  • pre-commit run --all-files: passed.
  • Focused MoE, transform, and config-validation CPU tests: 73 passed. The new
    FakeTensor backward test catches host scalar reads in autograd setup contexts.
  • HybridEP GPU remat tests: 3 passed on two GB300 GPUs. Blocking and nonblocking
    dispatch both match no-remat loss/input/router/expert gradients exactly, with
    expected communication counts; saved communication also survives CUDA graph replay.
  • AOT-compiled FakeTensor dispatch/combine forward and backward: passed.
  • HybridEP dependency for local GPU tests: public hybrid-ep commit 4e890fd.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 3, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 3, 2026
@tianyu-l
tianyu-l marked this pull request as ready for review November 3, 2026 08:46
@tianyu-l
tianyu-l requested review from fegin and wwwjn as code owners November 3, 2026 08:46
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 3, 2026
@tianyu-l
tianyu-l requested review from anijain2305 and removed request for sanketpurandare November 3, 2026 08:46
@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

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


Request changes: the new CPU-only hybridep.get_handle op would silently turn off CUDA graphs for HybridEP in graph_trainer. 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 -- the new pure-CPU hybridep.get_handle op is traced into every HybridEP graph, and graph_trainer's all-or-nothing CUDA-graph gate rejects it. This would silently turn off CUDA graphs for the HybridEP graph-trainer recipe.

What this PR does. It wraps HybridEP dispatch and combine in remat.regions keyed by ep_communication, as DeepEP already does. Region outputs must be tensors, so the forward now returns a CPU handle_id instead of the opaque DispatchHandle; a module cache maps the id back to the handle. A new CPU custom op hybridep.get_handle resolves the id inside setup_context. The PR also adds an EP backend selection guide (models/common/moe/README.md), extends the DeepEP GPU remat test harness to HybridEP, and runs those tests in CI after the HybridEP installer.

Example. graph_trainer_deepseek_v3_debugmodel_hybridep() (disable_accelerator_graphs = False, nonblocking dispatch):

main:  dispatch -> getitem[3] (opaque handle) -> combine / combine_bwd
       every node CUDA-graph compatible -> cuda_graph_pass wraps the step
PR:    dispatch -> getitem[3] (CPU handle_id) -> hybridep.get_handle(handle_id)
       get_handle: only tensor is CPU -> is_cuda_graph_node_compatible == False
       -> "Skipping cuda_graph: graph is not compatible ..." (warning), eager step

In eager training with the default remat policy, the forward dispatch/combine pair is no longer replayed in backward (2+0 calls instead of 2+1), and the PR shows bitwise loss and grad_norm against main.

Must fix

  1. torchtitan/distributed/deepep/hybridep.py:394 (and :412) -- get_handle in setup_context is a pure-CPU traced node, so graph_trainer skips CUDA graphs for HybridEP even without remat. CI won't catch it because both graph-trainer HybridEP integration tests disable accelerator graphs. Fix: delete get_handle, pass handle_id to combine_bwd/dispatch_bwd, save it with save_for_backward, and resolve the cache entry in the CUDA impls. This deletes the op and keeps FakeTensor tracing clean.

Should consider

  • torchtitan/distributed/deepep/hybridep.py:217-221 -- duplicates DeepEP's handle-id cache scheme; share one helper so remat#10 removes it in one place.
  • tests/unit_tests/cpu/models/common/test_moe.py:165 -- tests distributed/deepep/hybridep.py; move it under tests/unit_tests/cpu/distributed/.
  • tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py:342 -- fold capture into _check_hybridep_activation_checkpointing instead of repeating the config.
  • Scope: the backend selection guide is independent of the remat fix. Consider landing it separately so the remat fix can be reviewed on its own.
Details
  • Gate: the problem is real on main. HybridEP's ops ran outside any region, so under DefaultActivationRematConfig they were recomputed (code outside regions is always recomputed), which contradicts the policy docstring. Fixing it in the dispatcher is the right layer, and the opaque-output workaround has a TODO pointing at meta-pytorch/remat#10.
  • Why the gate fires: _iter_tensors returns [] for the opaque DispatchHandle output, and the input handle_id FakeTensor is on CPU, so all(t.device.type == "cpu") holds. dispatch and combine themselves stay compatible because they mix CUDA and CPU tensors. cuda_graph_pass calls is_cuda_graph_compatible(gm) and returns gm unwrapped on any incompatible node.
  • With the proposed fix, combine_bwd/dispatch_bwd each take a CUDA grad plus the CPU id and stay compatible. Their arg positions are unchanged for paged_stash_memory_policy.py, which matches on combine_bwd by seq_nr. Under CUDA graph replay the impls' .item() runs only at capture time, which matches today's opaque-handle behaviour.
  • README claims spot-checked against code: dispatcher class names, TokenDispatcherTransform path, deepseek_v3_671b(seq_len=...), check_hybridep_over_budget, Dist-MoE SM100/bf16 requirement, and default save/recompute regions all exist as described.

Not verified: I didn't run anything. The CUDA-graph skip follows from cuda_graph.py; please confirm by running the graph-trainer HybridEP recipe and checking for the "Skipping cuda_graph" warning. A maintainer still needs to review.

_, _, _, dispatch_handle = output
ctx.dispatch_handle = dispatch_handle
_, _, _, handle_id = output
ctx.dispatch_handle = torch.ops.hybridep.get_handle(handle_id)

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.

Must fix. hybridep.get_handle is traced into the forward graph: setup_context runs during make_fx/AOT tracing, which is the reason this op exists. Its only tensor is the CPU handle_id, and its output is opaque. graph_trainer/cuda_graph.py:132-140 ("Pure-CPU op: every tensor in its inputs and output lives on CPU") therefore marks the node incompatible. cuda_graph_pass is all-or-nothing (is_cuda_graph_compatible -> logger.warning("Skipping cuda_graph ...")), so graph_trainer_deepseek_v3_debugmodel_hybridep, which sets disable_accelerator_graphs = False, would quietly run without CUDA graphs. This happens even with remat disabled, because setup_context always runs. CI won't catch it: both HybridEP graph-trainer integration tests turn accelerator graphs off. The new test_saved_communication_is_graph_capturable uses raw torch.cuda.graph and skips this partitioner.

Smallest fix, which also deletes code: drop get_handle. Have combine_bwd and dispatch_bwd take handle_id: Tensor, the same way combine already does. Keep handle_id with ctx.save_for_backward, and resolve _handle_cache[handle_id.item()] inside the real CUDA impls. FakeTensor tracing never reaches .item(). Every node then has a CUDA tensor next to the CPU id, and the saved handle_id keeps the cache entry alive until backward. Unverified at runtime: this follows from the predicate code, so please confirm by running the graph-trainer HybridEP recipe and checking for the "Skipping cuda_graph" warning.

Comment on lines +217 to +221
_handle_counter += 1
handle_key = _handle_counter
handle_id = torch.tensor([handle_key], dtype=torch.int64, device="cpu")
_handle_cache[handle_key] = DispatchHandle(value=handle)
weakref.finalize(handle_id, lambda: _handle_cache.pop(handle_key, None))

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.

Should consider: this is a second copy of the _handle_cache / _handle_counter / weakref.finalize scheme in deepep.py:59-79,187-191, in the same package and with the same TODO lifetime (remat#10). A small deep_ep-free helper shared by both adapters (for example put_handle(obj) -> Tensor / get_handle(id_tensor)) would make the eventual removal touch one place.



class TestMoE(unittest.TestCase):
def test_hybridep_backward_is_fake_tensor_traceable(self):

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.

Should consider: this tests torchtitan/distributed/deepep/hybridep.py and does not touch models/common/moe. Per rules/tests.md (tests mirror the source tree), move it under tests/unit_tests/cpu/distributed/. If the backward ops take handle_id directly (see the comment on hybridep.py:394), keep the test: it still guards that setup_context/backward never reads the host scalar under FakeTensor.

)

@with_comms
def test_saved_communication_is_graph_capturable(self):

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.

Should consider: this repeats the HybridEPTokenDispatcher.Config(...) and the buffer/method arguments from _check_hybridep_activation_checkpointing. Adding capture: bool = False to that helper and calling it here (with capacity factor 1.0 only) would remove about 15 lines. Note also that raw torch.cuda.graph capture doesn't exercise graph_trainer's cuda_graph_pass compatibility gate, so this test can't catch the regression described on hybridep.py:394.

@tianyu-l

tianyu-l commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 14s —— View job


Approve, with two small items to address before merging. The CUDA-graph must-fix is resolved. 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: Approve -- please address the items below before merging. The CUDA-graph regression from the last review is fixed: hybridep.get_handle is gone, and a new graph_trainer test guards against it coming back.

What changed since the last review. The backward ops (combine_bwd, dispatch_bwd) now take handle_id: Tensor, the same way combine does. They resolve _handle_cache[handle_id.item()] only inside the real CUDA implementations, so setup_context no longer traces a CPU-only op. setup_context keeps handle_id as a ctx attribute rather than calling save_for_backward. The reason is that saved-tensor hooks could copy the tensor and let the original, which owns the cache entry, be collected. The GPU test exercises this with a cloning saved_tensors_hooks.

Example. graph_trainer_deepseek_v3_debugmodel_hybridep() traced graph:

previous rev: dispatch -> handle_id -> hybridep.get_handle(handle_id)   # pure-CPU node -> cuda_graph skipped
HEAD:         dispatch -> handle_id -> combine(x, handle_id) / combine_bwd(g, s, handle_id)
              every node mixes CUDA and CPU tensors -> is_cuda_graph_fully_compatible(gm) == True

Earlier findings

  • Must fix: the get_handle CPU node disabled CUDA graphs. Resolved. test_hybridep_autograd_setup_keeps_cuda_graph_compatible in graph_trainer's test_passes.py now guards it.
  • Test placement: resolved. The test moved to tests/unit_tests/cpu/distributed/test_expert_parallel.py.
  • Fold capture into the HybridEP helper: resolved.
  • Duplicated handle-id cache in deepep.py and hybridep.py: still open (should consider). Both now point at remat#10, so the eventual removal is at least discoverable from either file.

Must fix

  1. PR description: "A CPU lookup op keeps autograd setup contexts traceable with FakeTensor/AOT" describes the op this revision deleted. Please replace it with the current mechanism: the backward ops take handle_id, and the cache is resolved inside the CUDA implementations.

Should consider

  • tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py:264 -- the move into the shared harness dropped the explanatory DeepEP comments (see inline).
Details
  • Lifetime: the cache entry stays alive while any of these references handle_id: DispatchState, the dispatch node's ctx, or the combine node's ctx. Without remat, handle_id is freed after backward frees the graph. Under no_grad, it is freed after combine. When remat replays the communication, the replayed dispatch creates its own id, and the replayed nodes' ctx keeps it. Because the region policy is ep_communication, dispatch and combine are always both saved or both replayed. A saved dispatch can never be paired with a replayed combine, so a missing _handle_cache key isn't reachable.
  • No hidden sync: .item() reads a CPU tensor. Under CUDA-graph replay it runs only at capture time, the same as the previous opaque handle.
  • The ctx.handle_id attribute doesn't create a reference cycle. handle_id is a non-differentiable int64 tensor with no grad_fn.
  • Moving test_passes.py to device="cuda" under FakeTensorMode follows existing precedent in the same file (around line 3152).

Not verified: I didn't run the GPU remat tests or the graph-trainer HybridEP recipe with accelerator graphs on. This touches torchtitan/distributed/, so a maintainer still needs to review.

)

@with_comms
def test_dispatch_and_combine_are_saved_not_replayed(self):

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.

Should consider: moving these tests into the shared harness also removed the comments explaining why DeepEP saves rather than replays. Atomics-ordered receive slots mean a replay can pair the wrong token gradients, and full remat is exact only because of the deterministic buffer. That reasoning is non-obvious and isn't written anywhere else in this file. Without it, exact=bool(num_replays) reads like an arbitrary choice. Please restore them. For example:

Suggested change
def test_dispatch_and_combine_are_saved_not_replayed(self):
def test_dispatch_and_combine_are_saved_not_replayed(self):
# DeepEP fills receive slots with atomics, so a replayed dispatch can
# receive rows in another order than the forward's handle records.
# Backward would then pair each token's gradient with another token's
# activations. These policies save dispatch and combine instead.

Add the matching comment ("DeepEP then uses a deterministic buffer, which receives rows in the forward's order, so the gradients match the run without AC bitwise") to test_region_ac_replay_is_exact.

@tianyu-l
tianyu-l merged commit a87db08 into main Nov 3, 2026
@tianyu-l
tianyu-l deleted the hybridep-remat-guidance branch November 3, 2026 19:11
felipemello1 pushed a commit that referenced this pull request Nov 5, 2026
…ipemello1/deepep/expand-training

Conflict: tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py.
#5770 on main split the test into a shared _EPActivationCheckpointing harness with
DeepEP and HybridEP subclasses (_DeepEPBlock -> _EPBlock(num_experts, dispatcher_config)).
Kept main's harness; moved this PR's two tests (test_matches_all_to_all_dispatcher,
test_saved_dispatch_keeps_one_row_per_token) into TestDeepEPActivationCheckpointing,
building each model with its dispatcher config instead of swapping the dispatcher.

Also updates the DeepEP row of #5770's moe/README.md: training now dispatches into
the expand layout.
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