Skip to content

[graph_trainer] Refactor selective activation remat to in-place - #3270

Merged
tugsbayasgalan merged 1 commit into
mainfrom
tugsuu/remat_refactor
May 11, 2026
Merged

tugsbayasgalan merged 1 commit into
mainfrom
tugsuu/remat_refactor

Conversation

@tugsbayasgalan

@tugsbayasgalan tugsbayasgalan commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

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:

Screenshot 2026-05-07 at 5 16 08 PM

CPU offload using upstream remat pass

Screenshot 2026-05-07 at 5 16 23 PM CPU offload using our refactor

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

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 7, 2026
@tugsbayasgalan
tugsbayasgalan requested a review from mlazos May 7, 2026 21:34
@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/remat_refactor branch 2 times, most recently from 0297d4d to cc06493 Compare May 7, 2026 21:39
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@claude Pls review this PR

@claude

claude Bot commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tugsbayasgalan's task in 2m 37s —— View job


PR Review: Refactor selective activation remat to in-place

  • Read changed files and understand the refactoring
  • Review selective_activation_remat.py (main logic)
  • Review test additions in test_passes.py
  • Review supporting changes (passes.py, fsdp_passes.py, common_utils.py, CLAUDE.md)
  • Post comprehensive review feedback

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: _is_backward_node in ensure_offload_chain_before ignores use_phase

selective_activation_remat.py:203 — The call _is_backward_node(n) inside ensure_offload_chain_before always uses the default use_phase=False, meaning it checks node.meta["autograd_backward"]. But the outer function uses use_phase (determined by _has_user_phase_annotation) to identify backward regions. If a graph uses the user-level custom["phase"] == "backward" annotation but doesn't set autograd_backward on reload-chain nodes, the offload chain walk will stop early (treating backward-region nodes as forward because their autograd_backward is False), and the chain won't be hoisted.

This works today because the CPU-offload pass sets autograd_backward=True on reload/wait nodes, but it's fragile and inconsistent with the rest of the pass. Consider threading use_phase through or capturing it in the closure.


Potential issue: order dict becomes stale after node insertion/removal

selective_activation_remat.py:153 — order is built once from the initial all_nodes list. After ensure_offload_chain_before calls target.prepend(n) (which moves nodes in the graph), and after gm.graph.erase_node(orig) at line 269, the order dict no longer reflects actual graph positions. Currently this only matters at line 206 (order[prev] <= order[target]) which checks whether a previous hoist was already "early enough." Since target nodes (backward consumers) never move and come from the original all_nodes, this is safe today, but it's worth a comment documenting that order is intentionally stale and why that's okay.


Linear scan inside ensure_offload_chain_before

selective_activation_remat.py:211 — The for n in all_nodes: loop iterates the full node list to find and prepend nodes in bwd_reload_chain. This preserves topological order (nice), but if called multiple times with large graphs, the cost is O(N × num_offloaded_args). For typical transformer models this is probably fine, but worth noting if profiling ever shows this pass is slow. An alternative would be to sort bwd_reload_chain by order[n] and iterate that.


Minor: _collect_backward_regions uses idx after the loop

selective_activation_remat.py:75 — regions.append((bwd_start, idx + 1, needs_remat)) uses idx from the loop variable. This works because the loop body always executes (the graph always has nodes), but if gm.graph.nodes were ever empty with a non-None bwd_start (impossible in practice), idx would be unbound. Not a real bug, just a style nit—could use len(list(gm.graph.nodes)) for clarity if desired.


Cleanup: _is_recomputed_node removal is sound

The removal of _is_recomputed_node from common_utils.py and fsdp_passes.py is correct. Since duplicates now have dup.meta["autograd_backward"] = True (line 248), _is_backward_node(node) catches them, making the name-based workaround unnecessary. Good cleanup.


Tests: well-structured, cover the key cases

The three new tests (test_topological_insertion_order, test_forward_consumer_keeps_original, test_offload_reload_chain_hoisted) directly target the main invariants of the refactored pass. The offload test is especially valuable since it validates the fix for the CUBLAS crash scenario.


Summary

The core refactoring is sound and well-tested. The main concern is the use_phase inconsistency in the offload chain walk—it's latent today but could bite if the phase-annotation path is exercised with CPU offload in the future.

`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`

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.

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"``

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.

I don't think custom["phase"] is set anywhere in titan?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yeah this is the ultimate fallback. I can do cleanup as follow up. DOn't want to make this PR too big.

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.

I think we can remove this line.

this is tagging pass's job to ensure end of layer is tagged as SAVED.

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.

deprecate use_phase

@SherlockNoMad

SherlockNoMad commented May 7, 2026 •

Copy link
Copy Markdown
Contributor

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()

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.

gm.recompile

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ok

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.

do we still need this line?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

i will do it as followup

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

lets just deleteit

bwd_reload_chain.add(n)
stack.extend(n.all_input_nodes)

# TODO: when we DO move (chain is currently behind target), all

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

cc: @mlazos Claude tells me this is an issue even in previous implementation. Can this case ever happen?

@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/remat_refactor branch from d368c5f to cd5700f Compare May 8, 2026 17:17
@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/remat_refactor branch 2 times, most recently from 04bc2ae to 258cd84 Compare May 11, 2026 12:17
@@ -449,7 +455,7 @@ def joint_transformer_block_bucketing_reordering_pass(
"""

def _is_backward(node: torch.fx.Node) -> bool:

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.

this layer of wrapper can be removed.

Comment on lines +48 to 58
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

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.

hmm... would this be broken by chunked loss?

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.

we can land this first without supporting chunkedloss, just raising the q

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The expectation is that we will find all backward regions and skip all regions that don't need AC.

@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/remat_refactor branch from 258cd84 to 70090c6 Compare May 11, 2026 17:26
# 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:

@SherlockNoMad SherlockNoMad May 11, 2026 •

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.

nit, I think you can just it over the unique value of remat_targets?

i.e. the bw node that triggered the recompute

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

we only track forward to first backward that needs this forward. So we will miss some backward nodes that need to be redirected.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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]:

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.

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

return x
if x in recomputed_nodes:
return recomputed_nodes[x]
reload_node = x.meta.get("cpu_offload_reload_node")

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.

it's more reliable to just rely on the target,
ao.reload, ao.wait are the reload chain

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done. Although now we have one more whole graph scan to populate the targets.

Comment on lines +258 to +260
reload_node = arg.meta.get("cpu_offload_reload_node")
if reload_node is not None:
ensure_offload_chain_before(reload_node, bwd_target)

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.

same here, don't rely on meta. use target directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ditto

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.
@tugsbayasgalan
tugsbayasgalan force-pushed the tugsuu/remat_refactor branch from 70090c6 to 36dcead Compare May 11, 2026 18:15
@tugsbayasgalan tugsbayasgalan added the ciflow/h100.8 Trigger H100.8 CI label May 11, 2026
Comment on lines +148 to +154
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] = {}

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.

turn this into a util function

offloaded_fwd_to_bwd_wait = collect_x_and_y_pair()

@tugsbayasgalan
tugsbayasgalan merged commit e9dbff6 into main May 11, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100.8 Trigger H100.8 CI ciflow/8gpu 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