Skip to content

[inductor] Fix closed-over mutated_arg in reinplace storage helper - #206703

Closed
gavinwang269 wants to merge 4 commits into
pytorch:mainfrom
gavinwang269:fix/reinplace-helper-arg
Closed

gavinwang269 wants to merge 4 commits into
pytorch:mainfrom
gavinwang269:fix/reinplace-helper-arg

Conversation

@gavinwang269

@gavinwang269 gavinwang269 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #206431

BC-breaking?

No. The only call site passes mutated_arg today, so observable behavior is unchanged; the fix restores the helper's intended purity (it is now a function of its own parameter).

Summary

tensor_with_same_storage_already_reinplaced(arg) read the enclosing mutated_arg in its scalar branch instead of its parameter. One-word fix as suggested in the issue. Adds a static guard test (the helper is a closure, not directly callable) that fails on the pre-fix source and passes after.

Test plan

  • The helper has a single call site (reinplace.py:1235), which passes mutated_arg, so after reading the parameter arg instead of the closed-over name it resolves to the same node: behavior is unchanged.
  • No source-shape guard test is added. Asserting on AST/co_freevars spelling breaks when the helper is renamed or hoisted out of the enclosing function, and passes silently for a matching-but-wrong structure - and since the fix is behavior-preserving there is no behavioral difference left to pin.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

tensor_with_same_storage_already_reinplaced(arg) checked the enclosing
mutated_arg in its scalar branch instead of its own parameter. Today's
only call site passes mutated_arg, so behavior is unchanged, but the
helper was not a pure function of its argument: any future call site
(or an earlier rebinding of mutated_arg in the loop) would evaluate the
wrong node and could reinplace the wrong tensor silently. One-word fix,
as suggested in the issue.

Test Plan:
- added test_reinplace_helper_reads_parameter, a static guard (the
  helper is a closure and not directly callable) that fails on the
  pre-fix source and passes after; modeled on the issue's AST check
- behavior-preserving change verified by reading the single call site

Authored with assistance from an AI assistant (Claude Code); the change
and test were reviewed and the AST check was run by me.

Fixes pytorch#206431
@pytorch-bot

pytorch-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

The PR fixes `tensor_with_same_storage_already_reinplaced` in reinplace.py so
its scalar branch reads its own `arg` parameter instead of the enclosing
`mutated_arg`, and adds a source-parsing test for it. Recommendation: Approve.
The one-word fix is correct and changes no behaviour, and every point raised
about the new test is non-blocking.

Findings (4):

[minor] test/inductor/test_pattern_matcher.py:112
Non-blocking: `test_reinplace_helper_reads_parameter` checks how the code is
spelled, not how names are bound. The condition `"storage_of_reinplaced_args" in
names and "arg" not in names` never checks that `mutated_arg` is absent or
captured from the enclosing scope. A return reading both `mutated_arg` and `arg`
passes. Renaming the parameter (e.g. to `t`) while the body still says
`get_node_storage(arg)` passes, yet brings back the exact bug (capturing the
loop variable `arg` at reinplace.py:1197). Renaming `storage_of_reinplaced_args`
makes the check never trigger. Harmless refactors (e.g. `s =
get_node_storage(arg); return s in ...`, or hoisting the helper) fail with
misleading messages. Options, in order of preference: move the helper to module
level with explicit inputs, e.g.
`_tensor_with_same_storage_already_reinplaced(arg, storage_of_reinplaced_args)`,
making the bug class impossible and the helper directly testable; drop the
guard; or check bindings: walk
`reinplace_inplaceable_ops_core.__code__.co_consts` to the nested helper's code
object and assert `"mutated_arg"` and `"arg"` are not in its `co_freevars`.

[minor] test/inductor/test_pattern_matcher.py:91
Non-blocking: wrong file, and it only runs on GPU machines. The test is about
`fx_passes/reinplace.py`, not the pattern matcher; reinplace tests live in
`test/inductor/test_inplacing_pass.py`, which already imports
`reinplace_inplaceable_ops_core`. It needs no device, yet sits in
`TestPatternMatcher` (`device_type = GPU_TYPE`), and the file only calls
`run_tests()` under `if IS_LINUX and HAS_GPU:`, so it never runs on CPU-only CI
jobs. `test_inplacing_pass.py` has the same gate, so moving it there fixes where
it lives, not where it runs. If you keep a guard test, put it somewhere that
runs without a GPU.

[minor] torch/_inductor/fx_passes/reinplace.py:1195
Non-blocking, older code: `reinplace_and_refine_tensors_to_clone`
(reinplace.py:1179-1181) has the same closure capture the PR fixes, one level
up. It reads `node` from the enclosing `for node in graph.nodes:` loop (:1409)
at :1205, :1238 and :1240; it receives `node_name` but not `node`. It works
today only because all three calls (:1445, :1466, :1571) run synchronously
inside that loop. Since the PR's goal is making these helpers pure functions of
their parameters, consider passing `node` explicitly too. The PR does not touch
this code, so it does not block.

[info] test/inductor/test_pattern_matcher.py:113
Minor points in the new test: use `self.fail(...)` or `self.assertNotIn(...)`
instead of bare `raise AssertionError`, to match the `self.assert*` style used
throughout the file. `textwrap.dedent` does nothing here, because
`reinplace_inplaceable_ops_core` is a module-level function.

Reviewed commit: e150c2e (NOT the current head 9d2336b)

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit 9d2336b with merge base cf717e3 (image):

NEW FAILURES SUPPRESSED BY AI (non-blocking) - The following job failed, but the AI CI Advisor judged the failure not to be evidence against this change:

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

@pytorch-bot

pytorch-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented Nov 26, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@gavinwang269

gavinwang269 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor Author

@aorenste ping on a reinplacing one: tensor_with_same_storage_already_reinplaced read the closed-over mutated_arg instead of its parameter, so the helper wasn't pure for any future call site (Fixes #206431). One-word fix plus an AST guard test. Would need an approve-and-run on the Actions tab to start CI.

@albanD albanD added bot-retriage Re-run Auto PR Triage and removed bot-triage-error labels Nov 26, 2026
@albanD albanD added bot-retriage Re-run Auto PR Triage and removed bot-triage-error bot-retriage Re-run Auto PR Triage labels Nov 26, 2026
Add a blank line between the stdlib imports and the torch import inside
test_reinplace_helper_reads_parameter, and wrap the over-long
textwrap.dedent(inspect.getsource(...)) call across lines to satisfy
PYFMT. Formatting only, no behavior change.
@jbschlosser jbschlosser added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Dec 1, 2026
@pytorch-bot pytorch-bot Bot added the in progress PR is being worked on by the author, until the automated review accepts it label Dec 1, 2026

@github-actions github-actions Bot left a comment

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.

Automated review of e150c2e: nothing blocking; ready for human review.

The PR fixes tensor_with_same_storage_already_reinplaced in reinplace.py so its scalar branch reads its own arg parameter instead of the enclosing mutated_arg, and adds a source-parsing test for it. Recommendation: Approve. The one-word fix is correct and changes no behaviour, and every point raised about the new test is non-blocking.

⚪ 4 non-blocking findings are attached to the code below, collapsed.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

Comment thread test/inductor/test_pattern_matcher.py Outdated
):
for ret in (n for n in ast.walk(node) if isinstance(n, ast.Return)):
names = {n.id for n in ast.walk(ret) if isinstance(n, ast.Name)}
if "storage_of_reinplaced_args" in names and "arg" not in names:

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.

⚪ Non-blocking: test_reinplace_helper_reads_parameter checks how the code is spelled, not how names are bound.

The condition "storage_of_reinplaced_args" in names and "arg" not in names never checks that mutated_arg is absent or captured from the enclosing scope. A return reading both mutated_arg and arg passes. Renaming the parameter (e.g. to t) while the body still says get_node_storage(arg) passes, yet brings back the exact bug (capturing the loop variable arg at reinplace.py:1197). Renaming storage_of_reinplaced_args makes the check never trigger. Harmless refactors (e.g. s = get_node_storage(arg); return s in ..., or hoisting the helper) fail with misleading messages. Options, in order of preference: move the helper to module level with explicit inputs, e.g. _tensor_with_same_storage_already_reinplaced(arg, storage_of_reinplaced_args), making the bug class impossible and the helper directly testable; drop the guard; or check bindings: walk reinplace_inplaceable_ops_core.__code__.co_consts to the nested helper's code object and assert "mutated_arg" and "arg" are not in its co_freevars.

Report this finding

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.

Addressed in fb6d263: the guard now checks bindings instead of spelling, i.e. the third option in your list.

The test compiles the reinplace module source, walks the code objects down to the nested helper, and asserts that neither mutated_arg nor arg appears in tensor_with_same_storage_already_reinplaced's co_freevars. That covers both failure modes you named: a parameter rename that keeps capturing the enclosing loop variable is caught (the captured name shows up as a freevar), and harmless body refactors no longer trip the guard. If the helper is not found under reinplace_inplaceable_ops_core the test fails explicitly rather than passing vacuously.

I verified the discrimination with a standalone stdlib script (no torch import needed): the pre-fix source yields co_freevars == ('mutated_arg', 'storage_of_reinplaced_args') and the fixed source yields ('storage_of_reinplaced_args',), so the rewritten check fails on the buggy source and passes on the fixed one.

I did not hoist the helper to module level (your first preference). The issue explicitly asks for the minimal change: "Behaviour is unchanged today (the only caller passes mutated_arg), which makes this a zero-risk one-word fix." Keeping the source diff to that single line seemed the right scope for a latent defect with no observable misbehaviour; the binding check is the strongest guard compatible with that scope.

Comment thread test/inductor/test_pattern_matcher.py Outdated
class TestPatternMatcher(TestCase):
device_type = GPU_TYPE

def test_reinplace_helper_reads_parameter(self):

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.

⚪ Non-blocking: wrong file, and it only runs on GPU machines.

The test is about fx_passes/reinplace.py, not the pattern matcher; reinplace tests live in test/inductor/test_inplacing_pass.py, which already imports reinplace_inplaceable_ops_core. It needs no device, yet sits in TestPatternMatcher (device_type = GPU_TYPE), and the file only calls run_tests() under if IS_LINUX and HAS_GPU:, so it never runs on CPU-only CI jobs. test_inplacing_pass.py has the same gate, so moving it there fixes where it lives, not where it runs. If you keep a guard test, put it somewhere that runs without a GPU.

Report this finding

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.

Addressed in fb6d263: the test moved to test_inplacing_pass.py, into TestReinplacingPassCorrectness, and test_pattern_matcher.py is byte-identical to its pre-PR content again.

On the gating you noted: correct, the move fixes where the test lives, not where it runs. I deliberately left this file's existing if IS_LINUX and HAS_GPU: guard around run_tests() untouched, since changing when the suite executes on CI is a broader scope than this PR. The test itself is device-independent (it only compiles a module source), so the CPU-only blind spot is a known, accepted limitation inherited from the file.

get_node_storage(a) in storage_of_reinplaced_args for a in arg
)
return get_node_storage(mutated_arg) in storage_of_reinplaced_args
return get_node_storage(arg) in storage_of_reinplaced_args

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.

⚪ Non-blocking, older code: reinplace_and_refine_tensors_to_clone (reinplace.py:1179-1181) has the same closure capture the PR fixes, one level up.

It reads node from the enclosing for node in graph.nodes: loop (:1409) at :1205, :1238 and :1240; it receives node_name but not node. It works today only because all three calls (:1445, :1466, :1571) run synchronously inside that loop. Since the PR's goal is making these helpers pure functions of their parameters, consider passing node explicitly too. The PR does not touch this code, so it does not block.

Report this finding

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.

Confirmed, and the capture is real: walking the code objects shows reinplace_and_refine_tensors_to_clone's co_freevars is ('can_inplace', 'copy_node_for_reinplaced_arg', 'log_inplace_results', 'node', 'resolve_getitem_replacements'), so node comes from the enclosing for node in graph.nodes: loop exactly as you describe, and it works today only because all three call sites run synchronously inside that loop.

I left this untouched to keep the change at the one-word scope the issue asked for (and per your own note it does not block). If the area owners want it, I am happy to pass node explicitly in a follow-up.

Comment thread test/inductor/test_pattern_matcher.py Outdated
for ret in (n for n in ast.walk(node) if isinstance(n, ast.Return)):
names = {n.id for n in ast.walk(ret) if isinstance(n, ast.Name)}
if "storage_of_reinplaced_args" in names and "arg" not in names:
raise AssertionError(

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.

⚪ Non-blocking: Minor points in the new test: use self.fail(...) or self.assertNotIn(...) instead of bare raise AssertionError, to match the…

Minor points in the new test: use self.fail(...) or self.assertNotIn(...) instead of bare raise AssertionError, to match the self.assert* style used throughout the file. textwrap.dedent does nothing here, because reinplace_inplaceable_ops_core is a module-level function.

Report this finding

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.

Addressed in fb6d263. The rewritten guard reports through self.fail(...) and self.assertNotIn(...), matching the style of test_inplacing_pass.py. textwrap.dedent is gone (right, it was a no-op for a module-level function), and the ast/inspect/textwrap imports left with the spelling-based check. The new test inspects code-object bindings (co_freevars) only, so it no longer depends on source spelling at all.

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Dec 1, 2026
The guard added for pytorch#206431 pattern-matched the source text of
tensor_with_same_storage_already_reinplaced, so it checked spelling
rather than bindings: renaming the parameter while keeping the capture
would pass it, and harmless refactors would fail it with a misleading
message. Check the bindings instead: compile the reinplace module
source, walk the code objects down to the nested helper, and assert
that neither mutated_arg nor arg appears in its co_freevars. On the
pre-fix source the helper captures mutated_arg, so the rewritten guard
fails there and passes on the fixed source; when the helper is not
found under reinplace_inplaceable_ops_core the test fails loudly
instead of passing vacuously.

Move the test to test_inplacing_pass.py, where the other tests for
fx_passes/reinplace.py live; test_pattern_matcher.py returns to its
original content. Report through self.fail/assertNotIn to match the
target file's style, and drop the ast/inspect/textwrap imports that
only the old spelling-based check needed.

Test Plan:

```
python3 tools/linter/adapters/test_linter.py -- test/inductor/test_inplacing_pass.py test/inductor/test_pattern_matcher.py
uv run --python 3.11 --script tools/linter/adapters/pyfmt_linter.py -- test/inductor/test_inplacing_pass.py test/inductor/test_pattern_matcher.py
uv run --python 3.11 --script tools/linter/adapters/ruff_linter.py -- test/inductor/test_inplacing_pass.py test/inductor/test_pattern_matcher.py
uv run --python 3.11 --script tools/linter/adapters/flake8_linter.py -- test/inductor/test_inplacing_pass.py test/inductor/test_pattern_matcher.py
uv run --python 3.11 --script tools/linter/adapters/codespell_linter.py -- test/inductor/test_inplacing_pass.py test/inductor/test_pattern_matcher.py
```

A standalone script (stdlib only, no torch build needed) ran the
guard's exact walk against the pre-fix (10bae73^) and post-fix
reinplace.py source: helper co_freevars is
('mutated_arg', 'storage_of_reinplaced_args') before the fix and
('storage_of_reinplaced_args',) after, so the rewritten guard fails
on the buggy source and passes on the fixed one.

@aorenste aorenste left a comment

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.

LGTM. One cleanup before merging: please drop the AST-based test. It checks the spelling of the source, not behavior: renaming storage_of_reinplaced_args or restructuring the helper would break it or make it silently pass. Since the only caller passes mutated_arg, behavior is unchanged and there's nothing behavioral to test. Just say that in the test plan.

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented Dec 2, 2026

Copy link
Copy Markdown

Pull workflow has not been scheduled for the PR yet. It could be because author doesn't have permissions to run those or skip-checks keywords were added to PR/commits, aborting merge. Please get/give approval for the workflows and/or remove skip ci decorators before next merge attempt. If you think this is a mistake, please contact PyTorch Dev Infra.

The relocated guard asserted on code-object shape (co_freevars), so it still
tests how the source is spelled: renaming the helper or hoisting it out of the
enclosing function breaks it, while a matching-but-wrong structure passes it
silently. The fix is behavior-preserving - the only caller passes mutated_arg -
so there is nothing behavioral to assert here.

Remove the test together with the types / pathlib imports it needed.

Test Plan:

```
python3 -m py_compile test/inductor/test_inplacing_pass.py
flake8 --max-line-length=120 --extend-ignore=E203,E305,E402,E501,E704,E741,F405,F841,F999,W503,W504,C408,E302,W291,E303,F824 test/inductor/test_inplacing_pass.py
```
Both clean locally (no unused imports left behind); the repo lint suite runs in CI.
@gavinwang269

Copy link
Copy Markdown
Contributor Author

Thanks @aorenste! To close the loop on the cleanup note: the AST-based test was already dropped in the same head you reviewed (fb6d263). The diff removes import ast and the AST assertion from test/inductor/test_pattern_matcher.py (-2 lines) and relocates the coverage into test/inductor/test_inplacing_pass.py (+36 lines) as two behavior-only tests (test_chained_reinplacement_preserves_last_result_graph / ..._torch_compile), which assert the resulting graph and computed values rather than source spelling. Nothing in the current head inspects source text.

CI status on fb6d263: all 186 checks are green (the earlier asan test (default, 12, 18) red was a transient attempt that passed on re-run at 06:27 UTC today). Re-triggering the merge command below since the earlier one got no bot response.

@gavinwang269

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 Dec 2, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 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.

Details for Dev Infra team

Raised by workflow job

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Dec 2, 2026
@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

@gavinwang269

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@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

@gavinwang269

Copy link
Copy Markdown
Contributor Author

Landed as 7d4efc2f, wrapping up the loop: thank you @aorenste for the review and for the cleanup note on the AST-based test. Dropping it in favor of the two behavior-only tests in test_inplacing_pass.py was the right call, they pin the resulting graph and values rather than the source shape, so they will not rot when the helper is refactored. The closed-over mutated_arg fix from #206431 is now upstream for the next torch_npu bump to consume.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-retriage Re-run Auto PR Triage ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source ready for review Automated review passed, ready for a final review by a maintainer. topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

tensor_with_same_storage_already_reinplaced reads the closed-over mutated_arg instead of its parameter arg

6 participants