Skip to content

[dynamo] Hoist requires_grad_(True) on an unused graph input in front of the graph - #193162

Closed
anijain2305 wants to merge 1 commit into
gh/anijain2305/1307/basefrom
gh/anijain2305/1307/head
Closed

anijain2305 wants to merge 1 commit into
gh/anijain2305/1307/basefrom
gh/anijain2305/1307/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Aug 12, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Calling requires_grad_() on a graph input graph breaks. Models that compute
forces by autograd do exactly this - FairChem UMA calls
data_dict["pos"].requires_grad_(True) before generating its graph - so the
frame is split there and the model cannot be captured with fullgraph=True.

Tracing the toggle into the graph, which is what Dynamo already does for
intermediates, does not work for an input: AOTAutograd fixes an input's
differentiability from the metadata it was traced with, so the in-graph toggle
leaves the runtime forward non-differentiable and a later autograd.grad fails
with "element 0 of tensors does not require grad and does not have a grad_fn".

Hoist the call instead. When the input has no users yet, emit
x.requires_grad_(True) into pregraph_bytecode, which runs before the compiled
graph on every call (the mechanism synthetic_graph_input already uses), and flip
the placeholder's fake so the rest of the trace and the backend see a
differentiable input. example_inputs() has to hand the backend that fake rather
than GraphArg.example, because the real tensor's requires_grad is still False at
compile time - the mutation is in the bytecode, not yet executed - and the
backend would otherwise build an inference-only graph.

Guarding is on the entry state, so a fresh tensor per call reuses one graph
rather than recompiling, and a tensor that is passed in already requiring grad
recompiles once and then stabilizes. The hoist is only sound while nothing has
consumed the input: ops traced before the call would otherwise become
differentiable when eager would not have tracked them. Anything else keeps
today's graph break.

Gated behind torch._dynamo.config.hoist_requires_grad_on_inputs, default off,
while the corner cases are explored.

Test plan:

python test/dynamo/test_misc.py                  # with the knob both off and on

matches a baseline run in both cases. Correctness of the hoisted path was
checked against eager for backends eager, aot_eager and inductor, comparing
energy and the gradient taken outside the compiled region, plus the
if x.requires_grad: branch under fullgraph=True, and the recompile behaviour
described above.

On UMA the graph breaks disappear (21 frames -> 19) and total
entire_frame_compile goes from 48.2s to 47.6s; the value here is mostly that
the model becomes capturable rather than the compile time.

This PR was authored with the assistance of an AI coding agent.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 1 Unrelated Failure

As of commit e82bc64 with merge base e289091 (image):

NEW FAILURE - The following job has failed:

  • Lint / lintrunner-pyrefly-partial / lint (gh)
    >>> Lint for torch/fx/experimental/recording.py:

    AI verdict: AI verdict: related

    The PR's ghstack base commit (de9ee8c) modified torch/fx/experimental/recording.py, introducing a new early-exit path that assigns shape_env = args[0] before the isinstance check. This causes pyrefly to see shape_env as type object at line 338, triggering the missing-attribute error for should_record_events and is_recording.

    Full reasoning on HUD →

FLAKY - The following job failed but was likely due to flakiness present 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 labels Aug 12, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 12, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

anijain2305 added a commit that referenced this pull request Aug 12, 2026
… of the graph

Calling requires_grad_() on a graph input graph breaks. Models that compute
forces by autograd do exactly this - FairChem UMA calls
data_dict["pos"].requires_grad_(True) before generating its graph - so the
frame is split there and the model cannot be captured with fullgraph=True.

Tracing the toggle into the graph, which is what Dynamo already does for
intermediates, does not work for an input: AOTAutograd fixes an input's
differentiability from the metadata it was traced with, so the in-graph toggle
leaves the runtime forward non-differentiable and a later autograd.grad fails
with "element 0 of tensors does not require grad and does not have a grad_fn".

Hoist the call instead. When the input has no users yet, emit
x.requires_grad_(True) into pregraph_bytecode, which runs before the compiled
graph on every call (the mechanism synthetic_graph_input already uses), and flip
the placeholder's fake so the rest of the trace and the backend see a
differentiable input. example_inputs() has to hand the backend that fake rather
than GraphArg.example, because the real tensor's requires_grad is still False at
compile time - the mutation is in the bytecode, not yet executed - and the
backend would otherwise build an inference-only graph.

Guarding is on the entry state, so a fresh tensor per call reuses one graph
rather than recompiling, and a tensor that is passed in already requiring grad
recompiles once and then stabilizes. The hoist is only sound while nothing has
consumed the input: ops traced before the call would otherwise become
differentiable when eager would not have tracked them. Anything else keeps
today's graph break.

Gated behind torch._dynamo.config.hoist_requires_grad_on_inputs, default off,
while the corner cases are explored.

Test plan:

```
python test/dynamo/test_misc.py                  # with the knob both off and on
```

matches a baseline run in both cases. Correctness of the hoisted path was
checked against eager for backends eager, aot_eager and inductor, comparing
energy and the gradient taken outside the compiled region, plus the
`if x.requires_grad:` branch under fullgraph=True, and the recompile behaviour
described above.

On UMA the graph breaks disappear (21 frames -> 19) and total
entire_frame_compile goes from 48.2s to 47.6s; the value here is mostly that
the model becomes capturable rather than the compile time.

This PR was authored with the assistance of an AI coding agent.


ghstack-source-id: 21acfec
Pull-Request: #193162
@anijain2305 anijain2305 closed this Sep 4, 2026
@github-actions
github-actions Bot deleted the gh/anijain2305/1307/head branch November 4, 2026 01:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant