Skip to content

Move autograd_backward out of FX custom metadata - #180251

Closed
tugsbayasgalan wants to merge 10 commits into
gh/tugsbayasgalan/139/basefrom
gh/tugsbayasgalan/139/head
Closed

tugsbayasgalan wants to merge 10 commits into
gh/tugsbayasgalan/139/basefrom
gh/tugsbayasgalan/139/head

Conversation

@tugsbayasgalan

@tugsbayasgalan tugsbayasgalan commented Apr 13, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes using setup_stacktrace_preservation_hook.

With this tagging, we can reorder backward nodes during partitioner, so regional_inductor now turns off remat pass. This is fine because, remat pass is intended to be consumed only after:

  1. you torch.compile whole training step
  2. you make_fx d whole training step

In relevant use cases, regional inductor will happen after SAC decision has been applied to the final graph.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @Lucaskabela @jataylo @azahed98

The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes, and update remat/tests to read the top-level meta key. This preserves user annotations in node.meta["custom"] while keeping backward classification separate.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

[ghstack-poisoned]
@tugsbayasgalan
tugsbayasgalan requested a review from zou3519 as a code owner April 13, 2026 18:03
@pytorch-bot

pytorch-bot Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/180251

Note: Links to docs will display an error until the docs builds have been completed.

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 2 New Failures, 1 Cancelled Job, 11 Unrelated Failures

As of commit c420814 with merge base 875381e (image):

NEW FAILURES - The following jobs have failed:

CANCELLED JOB - The following job was cancelled. Please retry:

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo release notes: fx release notes category labels Apr 13, 2026
tugsbayasgalan pushed a commit that referenced this pull request Apr 13, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes, and update remat/tests to read the top-level meta key. This preserves user annotations in node.meta["custom"] while keeping backward classification separate.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

ghstack-source-id: 38be134
Pull Request resolved: #180251
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes, and update remat/tests to read the top-level meta key. This preserves user annotations in node.meta["custom"] while keeping backward classification separate.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo azahed98

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Apr 13, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes, and update remat/tests to read the top-level meta key. This preserves user annotations in node.meta["custom"] while keeping backward classification separate.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

ghstack-source-id: bd739ef
Pull Request resolved: #180251
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@claude Review this PR

@claude

claude Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

Claude finished @tugsbayasgalan's task in 3m 50s —— View job


PR Review: #180251

Summary

Solid, well-scoped fix for a real metadata pollution bug. The root cause — shallow-copy aliasing in set_current_meta() causing nested annotate() calls to mutate shared custom dicts — is correctly diagnosed, and the fix of promoting autograd_backward to a dedicated top-level current_meta field is the right approach. Both regression tests directly exercise the leak scenario.

Code Quality

  • set_autograd_backward() (torch/fx/traceback.py:357-370): Clean save/restore pattern. Correctly distinguishes "key was absent" from "key was False" via the had_autograd_backward flag, ensuring the context manager leaves no residual state.

  • proxy.py:265-266 stamping logic: Placed after replay-node handling, which is correct — replay nodes override custom metadata, and the backward flag should still be set independently based on the tracing context. One minor observation: the custom field is copy.copy()'d at line 245, but autograd_backward is only stamped as True (never copied from current_meta). This asymmetry is fine since it's a boolean, but a brief inline comment explaining why it's handled separately from _COPY_META_FIELDS would help future readers understand the intent.

  • Docstring on set_autograd_backward(): The function has no docstring. The annotate() context manager has thorough documentation explaining its purpose, args, and example usage. set_autograd_backward() should have at least a one-line docstring explaining what it does and when to use it (e.g., "Mark nodes created in this context as belonging to the autograd backward pass").

Testing

The two new tests are well-designed and directly cover the reported bug:

  1. test_patch_autograd_grad_does_not_leak_backward_tag (test_activation_checkpointing.py:2873): Tests the basic scenario — annotate({"ac_region_id": 0}) wrapping an autograd.grad call. Verifies backward nodes exist, forward neg node doesn't leak the tag, and user custom annotations are preserved.

  2. test_flex_attention_backward_tag_does_not_leak (test_fx_annotate.py:242): Tests the FlexAttention-specific regression where the bug was originally observed. Verifies no forward nodes leak the backward tag and that custom annotations are preserved on flex_attention nodes.

Both tests assert the positive case (backward nodes exist / user annotations preserved) alongside the negative case (no leak), which is good.

API Design

  • __all__ export (torch/fx/traceback.py:26): set_autograd_backward is correctly added to __all__, consistent with other context managers like set_stack_trace. However, this is marked @compatibility(is_backward_compatible=False), which is appropriate since this is internal tracing infrastructure.

  • enable parameter (torch/fx/traceback.py:357): The enable: bool = True parameter allows set_autograd_backward(False) to explicitly clear the flag within a backward context. This isn't used in the PR but is a reasonable forward-looking design that matches the pattern of other context managers.

Backward Compatibility

No BC concerns. The old metadata path (node.meta["custom"]["autograd_backward"]) was internal to dynamo/functorch tracing and not a public API. All consumers within the codebase have been updated:

  • remat_using_tags_for_fwd_loss_bwd_graph_pass.py:_is_backward_node() — reads node.meta.get("autograd_backward", False)
  • test_activation_checkpointing.py — updated all assertions
  • No external consumers found

Recommendation

Approve

The fix is correct, well-tested, and properly scoped. The two minor suggestions (docstring on set_autograd_backward, comment in proxy.py explaining the separate handling) are optional polish.


@tugsbayasgalan
tugsbayasgalan requested a review from aorenste April 13, 2026 18:10
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@claude Are you sure? It seems like if we use nested set_autograd_backward() this pollution will happen? But i guess it is always true so even if there is pollution, it is likely fine?

@claude

claude Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

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


  • Read set_autograd_backward() implementation
  • Read annotate() and set_current_meta() to compare
  • Analyze whether nesting causes pollution
  • Post answer

Analysis: Nested set_autograd_backward() and pollution

Good question. The short answer: nested set_autograd_backward() does NOT cause the same kind of pollution that annotate() did, and here's why the mechanisms are fundamentally different.

Why annotate() was broken with set_current_meta():

The original bug was a mutable shared dict problem. set_current_meta(node) at traceback.py:464 does:

current_meta = node.meta.copy()  # shallow copy

This means current_meta["custom"] aliases node.meta["custom"] (same dict object). When annotate({"autograd_backward": True}) then does current_meta["custom"].update(...), it mutates the shared dict in-place, polluting the original node's metadata.

Why set_autograd_backward() avoids this:

set_autograd_backward() at traceback.py:364 does:

current_meta["autograd_backward"] = enable

This is a top-level key assignment on current_meta, not an in-place mutation of a nested mutable object. After set_current_meta()'s shallow copy, current_meta is a different dict from node.meta — assigning a new key to current_meta does not touch node.meta at all. The aliasing problem only existed because annotate() mutated a value inside the shared dict (the nested custom dict), not the dict itself.

As for nested set_autograd_backward() calls specifically: the save/restore logic (traceback.py:360-370) correctly saves whether the key existed and its old value, then restores on exit. Nesting set_autograd_backward(True) inside set_autograd_backward(True) just saves True, sets True, and restores True — no harm done. Nesting set_autograd_backward(False) inside set_autograd_backward(True) would correctly clear the flag in the inner scope and restore it in the outer scope.

So the set_current_meta() interaction is safe because it's a top-level key (no aliasing of nested mutable objects), and nested set_autograd_backward() calls are safe because of the proper save/restore pattern.


@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@claude Any chance we can merge set_autograd_backward with setup_stacktrace_preservation_hooks_from_tensors ?

@claude

claude Bot commented Apr 13, 2026 •

Copy link
Copy Markdown

Claude finished @tugsbayasgalan's task in 1m 4s —— View job


  • Read set_autograd_backward implementation
  • Read setup_stacktrace_preservation_hooks_from_tensors implementation
  • Find all call sites for both functions
  • Analyze compatibility and provide answer

Analysis: Can set_autograd_backward merge with setup_stacktrace_preservation_hooks_from_tensors?

Short answer: probably not worth it — they serve different purposes and have different call patterns.

Here's what I found looking at the code:

What they do:

  • setup_stacktrace_preservation_hooks_from_tensors (logging_utils.py:142) — walks the autograd graph rooted at output tensors and registers pre/post hooks on each grad_fn node. These hooks set/restore fx_traceback stack trace state so that when backward runs under preserve_node_meta(), newly created FX nodes get the correct stack_trace metadata pointing back to the original forward op.

  • set_autograd_backward (traceback.py:357) — sets current_meta["autograd_backward"] = True so that FX nodes created during tracing are tagged as belonging to the backward pass.

Why merging is awkward:

  1. Different abstraction levels. setup_stacktrace_preservation_hooks operates on the autograd engine's grad_fn graph — it registers hooks on torch.autograd.graph.Node objects. set_autograd_backward operates on FX tracing metadata — it's a context manager around current_meta. One is autograd infrastructure, the other is FX traceback infrastructure. Merging them would couple these two layers.

  2. Different call sites. set_autograd_backward is used in two places:

    • torch/compiler/__init__.py:509 (non-strict _patch_autograd_grad) — paired with setup_stacktrace_preservation_hooks_from_tensors at line 507. These could be merged here.
    • torch/_dynamo/variables/torch.py:2443 (dynamo strict tracing) — used without setup_stacktrace_preservation_hooks at all, because in dynamo's strict path, stack trace preservation is handled differently (the proxy is created directly, not via actual backward execution).

    So the dynamo call site would need to either: (a) call the merged function with a flag to skip the hooks part, or (b) keep using set_autograd_backward separately anyway.

  3. setup_stacktrace_preservation_hooks has its own separate callers. It's used in graph_capture_wrappers.py:388 and test_aot_autograd.py:974 and test_functionalization.py:233 — all without set_autograd_backward. These callers don't need the backward tagging at all.

In summary, the two functions happen to be called together in _patch_autograd_grad, but their relationship is coincidental — both are needed for non-strict backward tracing but for independent reasons. Merging would either create an odd API that sometimes does half its work, or force unnecessary coupling between FX metadata and autograd hook registration.


The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes, and update remat/tests to read the top-level meta key. This preserves user annotations in node.meta["custom"] while keeping backward classification separate.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo azahed98

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Apr 13, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes, and update remat/tests to read the top-level meta key. This preserves user annotations in node.meta["custom"] while keeping backward classification separate.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

ghstack-source-id: afe6d17
Pull Request resolved: #180251
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes, and update remat/tests to read the top-level meta key. This preserves user annotations in node.meta["custom"] while keeping backward classification separate.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

cc voznesenskym penguinwu EikanWang jgong5 Guobing-Chen XiaobingSuper zhuhaozhe blzheng wenzhe-nrv jiayisunx kadeng chauhang amjames Lucaskabela jataylo azahed98

[ghstack-poisoned]
tugsbayasgalan pushed a commit that referenced this pull request Apr 13, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes, and update remat/tests to read the top-level meta key. This preserves user annotations in node.meta["custom"] while keeping backward classification separate.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

ghstack-source-id: 4405028
Pull Request resolved: #180251
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Apr 13, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 0 checks:

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 3, 6, linux.rocm.gpu.gfx950.1)

Details for Dev Infra team Raised by workflow job

BoyuanFeng pushed a commit that referenced this pull request Apr 15, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes using setup_stacktrace_preservation_hook.

With this tagging, we can reorder backward nodes during partitioner, so regional_inductor now turns off remat pass. This is fine because, remat pass is intended to be consumed only after:
1. you torch.compile whole training step
2. you make_fx d whole training step

In relevant use cases, regional inductor will happen after SAC decision has been applied to the final graph.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

Pull Request resolved: #180251
Approved by: https://github.com/Skylion007, https://github.com/aorenste
BoyuanFeng pushed a commit that referenced this pull request Apr 15, 2026
This reverts commit 8c49f56.

Reverted #180251 on behalf of https://github.com/jeanschmidt due to sorry, need to revert in order to revert #179731, feel free to resolve conflicts and merge into main after that ([comment](#180251 (comment)))
@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / linux-jammy-rocm-py3.10-mi355 / test (default, 1, 6, linux.rocm.gpu.gfx950.1)

Details for Dev Infra team Raised by workflow job

@tugsbayasgalan

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

pytorchmergebot pushed a commit to scotts/pytorch that referenced this pull request Apr 15, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes using setup_stacktrace_preservation_hook.

With this tagging, we can reorder backward nodes during partitioner, so regional_inductor now turns off remat pass. This is fine because, remat pass is intended to be consumed only after:
1. you torch.compile whole training step
2. you make_fx d whole training step

In relevant use cases, regional inductor will happen after SAC decision has been applied to the final graph.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

Pull Request resolved: pytorch#180251
Approved by: https://github.com/Skylion007, https://github.com/aorenste
@github-actions
github-actions Bot deleted the gh/tugsbayasgalan/139/head branch May 16, 2026 02:26
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes using setup_stacktrace_preservation_hook.

With this tagging, we can reorder backward nodes during partitioner, so regional_inductor now turns off remat pass. This is fine because, remat pass is intended to be consumed only after:
1. you torch.compile whole training step
2. you make_fx d whole training step

In relevant use cases, regional inductor will happen after SAC decision has been applied to the final graph.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

Pull Request resolved: pytorch#180251
Approved by: https://github.com/Skylion007, https://github.com/aorenste
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
)"

This reverts commit 8c49f56.

Reverted pytorch#180251 on behalf of https://github.com/jeanschmidt due to sorry, need to revert in order to revert pytorch#179731, feel free to resolve conflicts and merge into main after that ([comment](pytorch#180251 (comment)))
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes using setup_stacktrace_preservation_hook.

With this tagging, we can reorder backward nodes during partitioner, so regional_inductor now turns off remat pass. This is fine because, remat pass is intended to be consumed only after:
1. you torch.compile whole training step
2. you make_fx d whole training step

In relevant use cases, regional inductor will happen after SAC decision has been applied to the final graph.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

Pull Request resolved: pytorch#180251
Approved by: https://github.com/Skylion007, https://github.com/aorenste
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes using setup_stacktrace_preservation_hook.

With this tagging, we can reorder backward nodes during partitioner, so regional_inductor now turns off remat pass. This is fine because, remat pass is intended to be consumed only after:
1. you torch.compile whole training step
2. you make_fx d whole training step

In relevant use cases, regional inductor will happen after SAC decision has been applied to the final graph.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

Pull Request resolved: pytorch#180251
Approved by: https://github.com/Skylion007, https://github.com/aorenste
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
)"

This reverts commit 8c49f56.

Reverted pytorch#180251 on behalf of https://github.com/jeanschmidt due to sorry, need to revert in order to revert pytorch#179731, feel free to resolve conflicts and merge into main after that ([comment](pytorch#180251 (comment)))
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
The old implementation tagged backward nodes by running fx_traceback.annotate({"autograd_backward": True}) around traced autograd.grad. That stored autograd_backward in current_meta["custom"], which is also where user annotations such as {"ac_region_id": 0} live.

This was unsafe because some traceback save/restore paths only shallow-copy metadata. In particular, set_current_meta(node) does current_meta = node.meta.copy(), so current_meta["custom"] aliases node.meta["custom"]. A nested annotate({"autograd_backward": True}) then mutates that shared dict in place. When the nested scope exits, current_meta may be restored, but the source node metadata can stay polluted, which is how forward FlexAttention nodes ended up leaking autograd_backward.

Fix this by treating autograd_backward as internal tracing state instead of user custom metadata. Keep a dedicated current_meta["autograd_backward"] flag during tracing, stamp node.meta["autograd_backward"] on newly created nodes using setup_stacktrace_preservation_hook.

With this tagging, we can reorder backward nodes during partitioner, so regional_inductor now turns off remat pass. This is fine because, remat pass is intended to be consumed only after:
1. you torch.compile whole training step
2. you make_fx d whole training step

In relevant use cases, regional inductor will happen after SAC decision has been applied to the final graph.

Add non-strict tracing and FlexAttention regressions covering the leak.

Authored with Claude.

Pull Request resolved: pytorch#180251
Approved by: https://github.com/Skylion007, https://github.com/aorenste
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo release notes: fx release notes category Reverted topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants