Repository navigation
Fix HybridEP activation remat and document EP backend selection - #5770
Conversation
|
@claude review |
There was a problem hiding this comment.
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
torchtitan/distributed/deepep/hybridep.py:394(and:412) --get_handlein 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: deleteget_handle, passhandle_idtocombine_bwd/dispatch_bwd, save it withsave_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-- testsdistributed/deepep/hybridep.py; move it undertests/unit_tests/cpu/distributed/.tests/unit_tests/gpu/distributed/test_deepep_activation_checkpoint.py:342-- foldcaptureinto_check_hybridep_activation_checkpointinginstead 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
DefaultActivationRematConfigthey 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_tensorsreturns[]for the opaqueDispatchHandleoutput, and the inputhandle_idFakeTensor is on CPU, soall(t.device.type == "cpu")holds.dispatchandcombinethemselves stay compatible because they mix CUDA and CPU tensors.cuda_graph_passcallsis_cuda_graph_compatible(gm)and returnsgmunwrapped on any incompatible node. - With the proposed fix,
combine_bwd/dispatch_bwdeach take a CUDA grad plus the CPU id and stay compatible. Their arg positions are unchanged forpaged_stash_memory_policy.py, which matches oncombine_bwdbyseq_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,
TokenDispatcherTransformpath,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) |
There was a problem hiding this comment.
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.
| _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)) |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
|
@claude review again |
There was a problem hiding this comment.
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_handleCPU node disabled CUDA graphs. Resolved.test_hybridep_autograd_setup_keeps_cuda_graph_compatiblein graph_trainer'stest_passes.pynow guards it. - Test placement: resolved. The test moved to
tests/unit_tests/cpu/distributed/test_expert_parallel.py. - Fold
captureinto the HybridEP helper: resolved. - Duplicated handle-id cache in
deepep.pyandhybridep.py: still open (should consider). Both now point at remat#10, so the eventual removal is at least discoverable from either file.
Must fix
- 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_idis freed after backward frees the graph. Underno_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 isep_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_cachekey 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_idattribute doesn't create a reference cycle.handle_idis a non-differentiable int64 tensor with nograd_fn. - Moving
test_passes.pytodevice="cuda"underFakeTensorModefollows 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): |
There was a problem hiding this comment.
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:
| 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.
…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.
Summary (human-written)
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:
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
ep_communication,matching DeepEP. Retain counts and scores consumed outside regions.
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.
remat semantics, capacity considerations, and links to public dependency guides.
No backend is removed or added.
communication counts, exact loss/gradients, and graph capture. Run HybridEP tests
after its existing CI installer.
Alternatives considered
policy intends to recompute.
it. The tensor-only contract comes from External remat.op redesign — single-tape SAVE/RECOMPUTE, drop native_op and pytree (#2) meta-pytorch/remat#2; upstream opaque
output support would allow removal of the tensor-ID cache.
User-facing changes
torchtitan/models/common/moe/README.mddescribes the available choicesNumerics
No changes to routing, expert computation, checkpoint parameter names, or precision.
Against main
ff96670a2, DeepSeek V3 debug-model training with FSDP2 x EP2 on twoGB300 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.FakeTensor backward test catches host scalar reads in autograd setup contexts.
dispatch both match no-remat loss/input/router/expert gradients exactly, with
expected communication counts; saved communication also survives CUDA graph replay.
4e890fd.