Repository navigation
[inductor] Fix closed-over mutated_arg in reinplace storage helper - #206703
gavinwang269 wants to merge 4 commits into
Conversation
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
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Findings (4): Reviewed commit: 🔗 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 ( 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. |
|
|
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
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. |
|
@aorenste ping on a reinplacing one: |
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.
There was a problem hiding this comment.
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
| ): | ||
| 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: |
There was a problem hiding this comment.
⚪ 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.
There was a problem hiding this comment.
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.
| class TestPatternMatcher(TestCase): | ||
| device_type = GPU_TYPE | ||
|
|
||
| def test_reinplace_helper_reads_parameter(self): |
There was a problem hiding this comment.
⚪ 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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
⚪ 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.
There was a problem hiding this comment.
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.
| 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( |
There was a problem hiding this comment.
⚪ 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.
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
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.
|
@pytorchbot merge |
|
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.
|
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 CI status on fb6d263: all 186 checks are green (the earlier asan |
|
@pytorchbot merge |
Merge failedReason: This PR needs a If not, please add the To add a label, you can comment to pytorchbot, for example For more information, see Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot label "topic: not user facing" |
|
@pytorchbot merge |
Merge startedYour 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 |
Merge failedReason: 1 mandatory check(s) failed. The first few are: Dig deeper by viewing the failures on hud |
|
@pytorchbot merge |
Merge startedYour 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 |
|
Landed as |
Fixes #206431
BC-breaking?
No. The only call site passes
mutated_argtoday, 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 enclosingmutated_argin 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
reinplace.py:1235), which passesmutated_arg, so after reading the parameterarginstead of the closed-over name it resolves to the same node: behavior is unchanged.co_freevarsspelling 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