Repository navigation
[graph_trainer] Refactor selective activation remat to in-place - #3270
Conversation
0297d4d to
cc06493
Compare
|
@claude Pls review this PR |
|
Claude finished @tugsbayasgalan's task in 2m 37s —— View job PR Review: Refactor selective activation remat to in-place
Overall this is a well-motivated refactoring. The move from "rebuild entire graph + whole-graph DCE" to "mutate in place with targeted erase" is cleaner, preserves node identity, and the offload chain hoisting fixes a real crash. The tests are solid. A few issues worth addressing: Bug:
|
| `MUST_CPU_OFFLOAD` nodes. | ||
| - `selective_activation_remat_pass` — duplicates `MUST_RECOMPUTE` | ||
| ops before backward and DCEs the originals. | ||
| - `remat_using_tags_for_fwd_loss_bwd_graph` — duplicates `MUST_RECOMPUTE` |
There was a problem hiding this comment.
selective_activation_remat_pass is a better name
| annotation) or node.meta["autograd_backward"] == True (set automatically when | ||
| Dynamo traces torch.autograd.grad). When the user provides phase | ||
| annotations, only those annotated regions are used. | ||
| Backward regions are identified by ``custom["phase"] == "backward"`` |
There was a problem hiding this comment.
I don't think custom["phase"] is set anywhere in titan?
There was a problem hiding this comment.
Yeah this is the ultimate fallback. I can do cleanup as follow up. DOn't want to make this PR too big.
There was a problem hiding this comment.
I think we can remove this line.
this is tagging pass's job to ensure end of layer is tagged as SAVED.
|
Show me a tlparse for diffing the graph before and after, sample script https://www.internalfb.com/intern/paste/P2312893118/ |
| gm = raise_getitems(gm) | ||
|
|
||
| return new_gm | ||
| gm.graph.lint() |
There was a problem hiding this comment.
do we still need this line?
There was a problem hiding this comment.
i will do it as followup
There was a problem hiding this comment.
lets just deleteit
cc06493 to
f2470f4
Compare
f2470f4 to
d368c5f
Compare
| bwd_reload_chain.add(n) | ||
| stack.extend(n.all_input_nodes) | ||
|
|
||
| # TODO: when we DO move (chain is currently behind target), all |
There was a problem hiding this comment.
cc: @mlazos Claude tells me this is an issue even in previous implementation. Can this case ever happen?
d368c5f to
cd5700f
Compare
04bc2ae to
258cd84
Compare
| @@ -449,7 +455,7 @@ def joint_transformer_block_bucketing_reordering_pass( | |||
| """ | |||
|
|
|||
| def _is_backward(node: torch.fx.Node) -> bool: | |||
There was a problem hiding this comment.
this layer of wrapper can be removed.
| if _is_backward_node(node): | ||
| if bwd_start is None: | ||
| bwd_start = idx | ||
| needs_remat = False | ||
| if not needs_remat and any( | ||
| must_recompute(inp) for inp in node.all_input_nodes | ||
| ): | ||
| needs_remat = True | ||
| elif bwd_start is not None: | ||
| regions.append((bwd_start, idx, needs_remat)) | ||
| bwd_start = None |
There was a problem hiding this comment.
hmm... would this be broken by chunked loss?
There was a problem hiding this comment.
we can land this first without supporting chunkedloss, just raising the q
There was a problem hiding this comment.
The expectation is that we will find all backward regions and skip all regions that don't need AC.
258cd84 to
70090c6
Compare
| # Backward consumers of offloaded forward nodes were already redirected | ||
| # to their reload chain by the CPU offload pass, so the offload branch | ||
| # of remat_input is a no-op here. | ||
| for bwd_node in bwd_nodes: |
There was a problem hiding this comment.
nit, I think you can just it over the unique value of remat_targets?
i.e. the bw node that triggered the recompute
There was a problem hiding this comment.
we only track forward to first backward that needs this forward. So we will miss some backward nodes that need to be redirected.
There was a problem hiding this comment.
oh well i guess we can go from remat_targets.keys() and derive all backward nodes.
| # is satisfied by the graph's own order — upstream deps appear earlier in | ||
| # the walk, so their duplicates are inserted (and visible via | ||
| # ``recomputed_nodes``) before any downstream duplicate references them. | ||
| for fwd_node in all_nodes[:bwd_start]: |
There was a problem hiding this comment.
all_nodes is kinda of slow, I think you can simplify this by
walking in the original order of remat_targets's keys, sort by order first
| return x | ||
| if x in recomputed_nodes: | ||
| return recomputed_nodes[x] | ||
| reload_node = x.meta.get("cpu_offload_reload_node") |
There was a problem hiding this comment.
it's more reliable to just rely on the target,
ao.reload, ao.wait are the reload chain
There was a problem hiding this comment.
Done. Although now we have one more whole graph scan to populate the targets.
| reload_node = arg.meta.get("cpu_offload_reload_node") | ||
| if reload_node is not None: | ||
| ensure_offload_chain_before(reload_node, bwd_target) |
There was a problem hiding this comment.
same here, don't rely on meta. use target directly.
Summary: The remat pass previously rebuilt the graph wholesale (fx.Graph() + node_copy of every node) and relied on whole-graph DCE to remove dead must_recompute originals. Refactor to mutate gm.graph in place: dups are inserted in front of their first backward consumer, backward args are redirected to the dups, and only originals whose users became empty are erased. Original node identities and names are preserved, the topological-order assumption is explicit (input graph order drives insertion, validated by gm.graph.lint() at the end), and the underlying function takes the standard (gm, example_inputs) graph pass signature. CPU-offload reload chains are handled by hoisting (in-place move) the chain in front of the earliest dup that needs it - the in-place equivalent of upstream's "eagerly copy reload chain into the new graph" trick. This restores offload + remat support that the local port commit (D-equivalent of GitHub PR #3260) silently dropped: on main today, --compile.memory_policy=budget_limited_offload crashes with CUBLAS_STATUS_EXECUTION_FAILED because dups reference the freed-GPU offloaded forward tensors. Review order: selective_activation_remat.py - the core refactor. A pre-pass claim_for records the first backward node that transitively reaches each must_recompute forward node (setdefault gives first-write-wins). The insertion loop walks gm.graph.nodes in forward order, so each dup's must_recompute deps are already in recomputed_nodes by the time remat_input resolves them - no explicit sort. Dups are tagged autograd_backward=True so downstream passes treat them as backward-region nodes. remat_input also handles the cpu_offload_reload_node case: when a dup references an offloaded forward node, ensure_offload_chain_before walks the bwd-region reload chain via an explicit DFS stack, then hoists chain members in graph (topological) order by walking the all_nodes snapshot - again no explicit sort. moved_offload bookkeeping ensures the chain ends up before the earliest target across multiple iterations. raise_getitems still runs at the end for the multi-output-op memory benefit; gm.graph.lint() validates the final graph. common_utils.py / fsdp_passes.py - drops the _is_recomputed_node name-suffix workaround now that dups carry autograd_backward=True directly. passes.py - removes the selective_activation_remat_pass wrapper since the underlying function matches the standard signature; the pass list references it directly. tests/test_passes.py - adds TestSelectiveActivationRematPass with three cases: the reviewer scenario from pytorch/pytorch#168082 (pins topological insertion order), a forward+backward consumer mix (targeted erase keeps originals with surviving forward users), and the offload reload chain hoist - synthesizing the actual ao.offload / ao.reload / ao.wait_tensor graph the offload pass produces and pinning that the chain ends up before the dup with the dup reading from the backward wait_tensor instead of F. Authored with Claude. Test Plan: Unit tests: pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -x -> 68 passed, 1 skipped (3 new in TestSelectiveActivationRematPass) End-to-end on 8xH100 / Llama3 8B / FSDP=4 + TP=2 / aot_fx_trace / no cudagraph, with --debug.seed=42 --debug.deterministic: No offload (memory_policy=default): loss / grad_norm / peak memory at step 10 are bitwise identical to the main baseline (1.65096 / 21.9799 / 30.78 GiB). --compile.memory_policy=budget_limited_offload: refactor matches a baseline patched to invoke upstream remat directly (1.65096 / 21.9799 / 29.42 GiB). main HEAD (which calls the local port) crashes with CUBLAS_STATUS_EXECUTION_FAILED on this same configuration; the refactor incidentally fixes that regression.
70090c6 to
36dcead
Compare
| moved_offload: dict[fx.Node, fx.Node] = {} | ||
|
|
||
| # Build offloaded_fwd -> bwd_wait map by walking the offload op pattern | ||
| # (apply_cpu_offload_pass emits: F -> ao.offload -> ao.wait_tensor -> | ||
| # ao.reload -> ao.wait_tensor). Used to redirect a recompute dup that | ||
| # consumes an offloaded fwd to read from the bwd-region GPU value. | ||
| offloaded_fwd_to_bwd_wait: dict[fx.Node, fx.Node] = {} |
There was a problem hiding this comment.
turn this into a util function
offloaded_fwd_to_bwd_wait = collect_x_and_y_pair()
Summary:
The remat pass previously rebuilt the graph wholesale (fx.Graph() + node_copy of every node) and relied on whole-graph DCE to remove dead must_recompute originals. Refactor to mutate gm.graph in place: dups are inserted in front of their first backward consumer, backward args are redirected to the dups, and only originals whose users became empty are erased. Original node identities and names are preserved, the topological-order assumption is explicit (input graph order drives insertion, validated by gm.graph.lint() at the end), and the underlying function takes the standard (gm, example_inputs) graph pass signature.
CPU-offload reload chains are handled by hoisting the chain in front of the earliest dup that needs it - the in-place equivalent of upstream's "eagerly copy reload chain into the new graph" trick.
Authored with Claude.
Test Plan:
Unit tests:
pytest torchtitan/experiments/graph_trainer/tests/test_passes.py -x
-> 68 passed, 1 skipped (3 new in TestSelectiveActivationRematPass)
End-to-end on 8xH100 / Llama3 8B / FSDP=4 + TP=2 / aot_fx_trace / no cudagraph, with --debug.seed=42 --debug.deterministic:
CPU offload using upstream remat pass
Before: https://manifold.edge.x2p.facebook.net/v0/read/tree/logs/.tmpfmqvbv/index.html?bucketName=tlparse_reports&apiKey=tlparse_reports-key&withPayload=1&timeoutMsec=10000
After: https://manifold.edge.x2p.facebook.net/v0/read/tree/logs/.tmp9ImSg9/index.html?bucketName=tlparse_reports&apiKey=tlparse_reports-key&withPayload=1&timeoutMsec=10000