GeezerVison is showing github.com — [BE] Fix B018 useless-expression violations in inductor and fx unification by HumphreySun98 · Pull Request #191866 · pytorch/pytorch
Conversation
HumphreySun98
commented
Aug 2, 2026
•
edited by pytorch-bot
Bot
Loading
Uh oh!
There was an error while loading. Please reload this page.
Addendum (post-review): F811 evidence and runtime verification
Literal F811 output with the two noqas stripped from the PR's files (CI-pinned ruff 0.14.4):
core.py:140:5: F811 Redefinition of unused `unify` from line 118: `unify` redefined here
variable.py:63:5: F811 Redefinition of unused `isvar` from line 56: `isvar` redefined here
Found 2 errors.
With the noqas present, the full-config check reports All checks passed! — so under RUF100 both the presence and the placement are exactly what ruff requires.
Why only these two sites: ruff's F811 exempts underscore-prefixed names (dummy-variable convention). Minimal repro — two identical @dispatch overload chains, one named _priv, one named pub:
f811_repro.py:9:5: F811 Redefinition of unused `pub` from line 7: `pub` redefined here
Found 1 error.
Only pub is flagged. That is why the five _reify redefinitions (and _eval_is_ge in torch/utils/_sympy/singleton_int.py) need no suppression while the public unify/isvar do.
Runtime verification: imported the changed unification package and the unmodified main version side by side as standalone packages (the subtree is stdlib-only + vendored multipledispatch) and compared 18 aspects: unify/reify/isvar behavior on tuples/lists/dicts/vars including exact exception types and messages for the unsupported-signature cases, plus the complete dispatch registries of unify, isvar, _unify, and _reify. All 18 identical (package-name normalized). This exercises the import-time @dispatch registration side effects directly.
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
…ation
Part of pytorch#106571. Fixes the B018 (useless expression) violations in
torch/_inductor and torch/fx/experimental/unification, following the same
pattern as the recently landed B018 cleanups (pytorch#191831): intentional
side-effect expressions become explicit `_ = expr` bindings, and genuinely
useless statements are deleted.
- torch/_inductor/comm_lowering.py: the two bare attribute accesses are
feature probes inside try/except AttributeError; rewritten as `_ = ...`.
- torch/_inductor/runtime/triton_heuristics.py: the bare `frame.f_locals`
access is load-bearing (it materializes the frame's locals dict so
gc.get_referrers can find the object inside it); rewritten as `_ = ...`
with a comment explaining the side effect.
- torch/fx/experimental/unification: the bare `_reify` / `unify` / `isvar`
statements between @dispatch registrations turn out to be an old hack to
suppress F811 (redefinition of unused name) between multipledispatch
overloads. They are deleted; the two sites where removing them actually
exposes F811 get an explicit `# noqa: F811` on the def line instead,
matching the `# type: ignore[no-redef]` annotations already on those
decorators.
The three bare `dummy` statements in torch/_dynamo/resume_execution.py are
intentionally NOT touched: they are bytecode-template split markers
(rewriting them as `_ = dummy` would change the template bytecode), and a
`# noqa: B018` cannot be added while B018 is still in the ignore list
because RUF100 flags it as unused. They will need suppression in the PR
that eventually flips B018 on.
Test Plan:
All changes are behavior-preserving (deleting no-op statements, `_ =`
bindings of expressions evaluated for their side effects, comments).
Verified with the CI-pinned ruff:
uvx [email protected] check <changed files> --config=pyproject.toml
# -> All checks passed!
uvx [email protected] check <changed files> --select B018 --config "lint.ignore=[]"
# -> All checks passed! (zero B018 left in these files)
uvx [email protected] format --check <changed files>
# -> 4 files already formatted
python -m py_compile <changed files>
Authored with the assistance of an AI coding assistant (Claude).
pytorch-bot
Bot
commented
Aug 2, 2026
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
🔗 Helpful Links
Note: Links to docs will display an error until the docs builds have been completed.
❌ 1 New Failure
As of commit fb00381 with merge base 4ee8fea ( ):
NEW FAILURE - The following job has failed:
This comment was automatically generated by Dr. CI and updates every 15 minutes.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
pytorch-bot
Bot
commented
Aug 2, 2026
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
|
Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
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.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
claude[bot] reacted with eyes emoji
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
claude
Bot
commented
Aug 3, 2026
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
|
Claude finished @jansel's task in 53m 18s —— View job
Reviewed — the mechanical _ = expr / dead-statement changes are correct and behavior-preserving, but the one comment the PR adds to triton_heuristics.py documents behavior that stopped being true in CPython 3.13 (PEP 667), and the asymmetric # noqa: F811 placement in the unification files is left unexplained.
Full review (click to expand)
Summary
Rewrites B018 useless-expression sites in torch/_inductor as _ = expr and deletes the bare _reify/unify/isvar statements in torch/fx/experimental/unification. The mechanical transformations are correct; two documentation/comment problems should be fixed before landing.
Code Quality
1. The added comment in triton_heuristics.py is wrong on Python 3.13+ — the PR's only new prose is the one thing that is inaccurate.
torch/_inductor/runtime/triton_heuristics.py:3334-3336:
# accessing f_locals materializes the frame's locals dict so
# gc.get_referrers below can find obj inside it
_ = frame.f_locals
This is only true on CPython <= 3.12, where reading f_locals on an optimized (function) frame calls PyFrame_FastToLocalsWithError and caches a real dict on the frame. Under PEP 667 (3.13), frame.f_locals on an optimized scope returns a write-through FrameLocalsProxy and materializes/caches nothing — the CPython docs mark PyFrame_FastToLocalsWithError as "This function now does nothing" as of 3.13. So on 3.13+ the whole while loop is a no-op, and FrameLocalsProxy is not a dict, so it would also be rejected by the isinstance(referrer, dict) filter at line 3340 even if it did show up as a referrer.
pyproject.toml:374-379 declares support through 3.15, so this comment is wrong on the majority of supported interpreters going forward.
To be clear about severity: this is pre-existing behavior, not introduced here — the diff is semantically identical to the bare statement, and DebugAutotuner.run already tolerates an empty result via the inductor_meta["kernel_name"] fallback at lines 3424-3428, so the consequence on 3.13+ is a less specific kernel name in bandwidth-info output, not a crash. But a BE cleanup PR should not add a comment that will mislead the next reader into believing the loop still does something. Please scope it, e.g. note that the access only materializes a locals dict on CPython <= 3.12 and that the loop is ineffective under PEP 667.
Fix this →
2. The # noqa: F811 asymmetry in the unification files is load-bearing but undocumented.
The PR deletes a hack whose purpose was non-obvious enough to require a paragraph of commit message, and replaces it with suppressions that are inconsistent in a way nothing in the code explains:
core.py defines _reify five times (lines 27, 33, 38, 43, 48) — no noqa.
core.py:138 — unify, second of two definitions — gets # noqa: F811.
variable.py:61 — isvar, second of two definitions — gets # noqa: F811.
RUF100 (unused-noqa) is enabled (pyproject.toml:576) and there is no per-file-ignores entry covering this subtree, so green Lint means both the presence and the absence are genuinely required today. I could not reproduce the rule locally (ruff is not installed in this sandbox and I could not fetch it), and I could not find a documented ruff/pyflakes rule that explains why a 2-overload chain trips F811 while a 5-overload chain does not — pyflakes' "shadowed binding was unused" model predicts the opposite here, since unify has more references (__all__ at line 20, line 84, line 139) than _reify (only line 67). A comparable un-suppressed case exists at torch/utils/_sympy/singleton_int.py:80-95: three @dispatch _eval_is_ge overloads, never referenced, no noqa, green lint.
Since the behavior rests on an undocumented ruff heuristic that a version bump could flip — turning these into RUF100 errors, or newly requiring noqa on _reify and _eval_is_ge — please add a one-line comment at each noqa recording that it suppresses F811 for the multipledispatch overload chain (replacing the old bare-name hack). Otherwise the next reader will delete it as unexplained cruft, exactly as this PR did to the statements it replaced. It would also help to paste the literal ruff check --select F811 output for both files into the PR description, since the claim currently can't be checked from the diff.
Fix this →
Testing
No new tests, which is right for this change — deleting bare name-load statements and binding side-effecting expressions to _ are both no-ops at the bytecode-semantics level, and the two comm_lowering.py sites still raise AttributeError inside the same try as before. Nothing here needs regression coverage.
One gap in the verification, though: the PR's test plan is entirely lint-based (ruff check, ruff format --check, py_compile). torch/fx/experimental/unification is where the actual runtime risk lives, since it relies on import-time @dispatch registration side effects. python test/test_proxy_tensor.py exercises this module and would take minutes; running it and recording the result in the test plan would close the loop cheaply.
Backward Compatibility
No public API change. __all__ in both unification files is untouched, and the deleted statements were never bindings. _find_names is private.
Recommendation
Approve, conditional on rewording the triton_heuristics.py comment (finding 1) — shipping a comment that is factually wrong on Python 3.13+ inside a cleanup PR is a net negative for the file. Finding 2 is a robustness/readability request on top of that. Neither is functional; CI is fully green (7 runs, 0 failures, including Lint and BC Lint).
Note on scope: the PR correctly discloses that the three dummy statements in torch/_dynamo/resume_execution.py (lines 139, 208, 245) are left alone as bytecode-template split markers. That reasoning holds — _ = dummy would emit STORE_FAST instead of POP_TOP and break the dummy_idx + 1 POP_TOP assertion at resume_execution.py:125-128.
- Read PR diff and repo review guidelines
- Verify the F811 claim in
torch/fx/experimental/unification
- Verify the
frame.f_locals side-effect claim in triton_heuristics.py
- Verify the
comm_lowering.py feature probes
- Post review
Caveats on my verification: ruff is not installed in this sandbox and I could not install or fetch it, so I could not independently reproduce the B018 or F811 lint results — those claims are checked against green CI, pyproject.toml config, and CPython documentation rather than a local run. A grep/AST-level sweep found no remaining bare-expression statements in either subtree, but that is an approximation of B018, not the linter itself.
| Branch: fix-b018-torch
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
soulitzer
added
the
triaged
This issue has been looked at a team member, and triaged and prioritized into an appropriate module
label
Aug 3, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
address automated feedback from claude
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
… noqas
The f_locals comment now states the CPython <= 3.12 materialization
behavior explicitly and notes that under PEP 667 (3.13+) f_locals is a
fresh write-through proxy, making the loop a no-op there. The two
F811 noqas in the unification files get a one-line comment recording
that they suppress the multipledispatch overload redefinition warning,
replacing the old bare-name-statement hack.
|
Both findings addressed in fb00381, plus the requested evidence added to the PR description:
-
f_locals comment — reworded to be version-scoped: it now states the materialization behavior applies on CPython <= 3.12 and that under PEP 667 (3.13+) f_locals is a fresh write-through proxy, making the loop a no-op there (so function-local names are not discoverable on 3.13+).
-
F811 noqas — each now carries a one-line comment recording that it suppresses the multipledispatch overload redefinition and replaces the old bare-name-statement hack. The asymmetry also turned out to have a clean explanation: ruff's F811 exempts underscore-prefixed names (dummy-variable convention). A minimal repro with two identical @dispatch chains named _priv and pub flags only pub — which is why the five _reify redefinitions (and _eval_is_ge in singleton_int.py, the comparable case the review found) need no suppression while the public unify/isvar do. Literal ruff outputs are in the PR description addendum.
-
Runtime verification gap — my environment can't build torch to run test_proxy_tensor.py, so instead I imported the changed unification package and the unmodified main version side by side as standalone packages (the subtree is stdlib-only + vendored multipledispatch) and compared 18 aspects: unify/reify/isvar behavior across tuples/lists/dicts/vars including exact exception types/messages, plus the complete dispatch registries of unify, isvar, _unify, _reify. All 18 identical, which exercises the import-time @dispatch registration side effects directly.
@jansel ready for another look.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
claude[bot] reacted with eyes emoji
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
claude
Bot
commented
Aug 4, 2026
•
edited
Loading
Uh oh!
There was an error while loading. Please reload this page.
|
Claude finished @jansel's task in 5m 18s —— View job
Re-reviewed fb00381: both findings from my previous review are correctly addressed, the reworded f_locals comment is now accurate on every supported CPython, and I found no new issues — approving with two optional nits.
Full re-review (click to expand)
Re-review of #191866 (commit fb00381)
Scope of this pass: the delta since my last review, plus a recheck that the original mechanical changes are unchanged. git diff 4ee8fea..HEAD confirms the PR is still exactly 4 files / 13 additions / 23 deletions, and the comm_lowering.py and _reify hunks are byte-identical to what I reviewed before.
Finding 1 (f_locals comment) — resolved
torch/_inductor/runtime/triton_heuristics.py:3334-3338:
# On CPython <= 3.12 this access materializes the frame's locals
# dict so gc.get_referrers below can find obj inside it. On 3.13+
# f_locals is a fresh write-through proxy (PEP 667) and this loop
# is a no-op, so function-local names are not discoverable there.
_ = frame.f_locals
This is now correct on both sides of the 3.13 boundary, and it's scoped the right way round — a reader on 3.12 sees the access is load-bearing, a reader on 3.13+ sees the loop does nothing. "fresh" is the right word: PEP 667 specifies a new FrameLocalsProxy per access, which is precisely why nothing is cached on the frame and nothing new shows up in gc.get_referrers. The comment doesn't overclaim into "this loop can be deleted," which would be wrong for 3.12.
I re-verified the _ = rewrite is still behavior-neutral here, including the one interaction the comment doesn't mention: on <= 3.12 the new local _ becomes a member of _find_names' own materialized locals dict. That is harmless — _ never aliases obj, and obj itself was already in that dict (and therefore already collected as a name) both before and after this change. No behavior delta.
Finding 2 (F811 noqas) — resolved
core.py:137-140 and variable.py:60-63 now carry:
@dispatch(object, object) # type: ignore[no-redef]
# The noqa suppresses F811 for this multipledispatch overload redefinition
# (it replaces the bare-name-statement hack that previously silenced it).
def unify(u: object, v: object) -> dict[Var, object] | bool: # noqa: F811
This satisfies what I asked for: the next reader will not delete the noqa as unexplained cruft. The mechanism stated is also correct, which matters — a bare unify statement is a load of the name, which marks the line-118 binding as used, and pyflakes' F811 only fires on redefinition of an unused binding. So the deleted statements really were F811 suppression, and swapping them for an explicit noqa is a strict readability win over a hack that looked like dead code.
On the _reify-vs-unify asymmetry: the underscore-exemption explanation in the description is consistent with everything I can see in-tree, and the _priv/pub repro is the right shape of experiment to isolate it — one variable changed, everything else identical. I still can't independently confirm it (see caveats), but that no longer blocks: the literal ruff check output I asked for is now in the description, and with RUF100 enabled (pyproject.toml:576) and no per-file-ignores covering this subtree, green Lint proves the placement is exactly what ruff requires today. If a future ruff version flips the heuristic, RUF100 turns it into a loud lint failure rather than silent rot, and the comment now tells whoever hits it what the directive was for.
I also checked the # type: ignore[no-redef] interaction, since the new comment is inserted between the decorator and the def: the directives are untouched and still on the decorator line, which is where mypy attributes no-redef for a decorated function, so the comment insertion cannot have shifted that. Mypy lint is green, consistent with this.
Nits (both optional, neither worth another round-trip)
-
Comment placement is unusual. Sitting between the decorator and the def splits the decorator from the function it decorates. Legal, and it does put the prose adjacent to the line carrying the noqa, so I see the logic — but above @dispatch reads more conventionally and no in-tree noqa: F811 site (e.g. torch/nn/functional.py:4847, torch/functional.py:1279) does it this way.
-
The most confusing part of this code is documented only in the PR description. The question a reader will actually have is not "what does this noqa do" but "why does unify need one when _reify five definitions above it doesn't." That answer — ruff's F811 exempts underscore-prefixed names — dies with the PR description. Half a clause would carry it, e.g. ... overload redefinition (the private _reify chain above is exempt as an underscore-prefixed name).
Verification
The side-by-side package comparison is a good substitute for the build-blocked test_proxy_tensor.py run, and it targets the right risk: comparing the full dispatch registries of unify/isvar/_unify/_reify is a direct assertion that import-time @dispatch registration is unchanged, which is the only way deleting those statements could have broken anything. Combined with green CI (Lint, BC Lint, and the inductor jobs), coverage is adequate for a change of this size. No new tests needed, as before.
Recommendation
Approve. Both previous findings are properly addressed and I found nothing new. The nits are cosmetic/documentation polish; land as-is if you'd rather not spend another CI cycle.
Caveat carried over from my first pass, unchanged: ruff is still not installed in this sandbox, and I was not able to install it or fetch the rule documentation here, so the F811/RUF100 behavior is verified against pyproject.toml, green CI, and the author's posted output rather than a local run. Everything else above — comment accuracy, _ aliasing, type: ignore attribution, diff scope — I checked directly against the files.
- Read
fb00381 diff and the full PR diff vs merge base
- Verify finding 1 (f_locals comment) is now accurate on all supported CPython
- Verify finding 2 (F811 noqa comments) and the claimed underscore-exemption explanation
- Check for new issues introduced by the follow-up commit
- Post re-review
| Branch: fix-b018-torch
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
pytorch-bot[bot] and HumphreySun98 reacted with thumbs up emoji
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@jansel the merge was blocked by the single ROCm gfx950 failure (trunk / linux-jammy-rocm-py3.10-mi350 / test (default, 6, 8), GPUTests::test__unsafe_masked_index_cuda). I believe it's unrelated to this PR:
- The diff cannot reach that codepath: it's two comments, three
_ = expr bindings that are bytecode-semantically identical to the bare expressions they replace (the triton_heuristics.py one is only on the DebugAutotuner bandwidth-info path, not the default compile path), and dead-statement deletions in fx/experimental/unification verified runtime-equivalent (identical dispatch registries and behavior, 18 aspects — see the PR description addendum).
- Dr.CI's AI verdict for the job is still pending, and there's no existing DISABLED issue for that test — but the same shard is currently running on several main trunk runs (e.g. 30933724384, 30935666174), which should confirm shortly whether it reproduces on trunk.
Could you rerun the failed job or @pytorchbot merge -f at your discretion? Thanks for shepherding this one through!
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
Dug into the ROCm failure properly. Summary: the failing job is a HIP driver-state fault, and the diff is provably not on that code path. Evidence, including things I could check by running rather than by reading:
What actually failed (job 92093838216 log):
RuntimeError: CUDA driver error: 401
Exception raised from launchKernel at torch/csrc/inductor/static_launcher/cuda.cpp:292
HIP 401 = hipErrorIllegalState, returned by AT_CUDA_DRIVER_CHECK(hipModuleLaunchKernel(...)) in the USE_ROCM branch. The stack is triton_heuristics.py:2535 (CachingAutotuner.run) -> <string>:5, in launcher -> static_triton_launcher.py:392, self.C_impl._launch_kernel. The second rerun then dies at a bare torch.randn(8, device=cuda) (distribution_nullary_kernel, DistributionTemplates.h:156) with hipErrorIllegalState again — the context is poisoned by the failed launch, so that is a cascade, not a second bug. No memory-access fault, no HSA queue error, no OOM, no timeout anywhere in the log.
Why the diff cannot reach it — four checks, run against an installed torch:
-
The edited function is not in the failing stack, and cannot execute here. The only runtime function this PR touches is _find_names. Its sole caller is DebugAutotuner.run, and DebugAutotuner is only constructed under if inductor_meta.get("profile_bandwidth"):
line 2343: def _find_names(obj):
line 2434: possible_names = _find_names(self) # inside DebugAutotuner.run (class at line 2414)
line 2533: if inductor_meta.get("profile_bandwidth"): # the only construction site
config.profile_bandwidth default: False
TORCHINDUCTOR_PROFILE appears 0 times in the failing job log, and the test does not patch profile_bandwidth. The failing stack goes through CachingAutotuner.run (line 2535), never DebugAutotuner.
-
_ = expr is bytecode-identical to expr except for the final store.
bare : ['RESUME', 'LOAD_FAST', 'LOAD_ATTR', 'POP_TOP', 'RETURN_CONST']
_ = : ['RESUME', 'LOAD_FAST', 'LOAD_ATTR', 'STORE_FAST', 'RETURN_CONST']
Same evaluation, same exception propagation; only POP_TOP becomes STORE_FAST into an unused local.
-
The unification subtree is never imported on this path. After import torch, torch._dynamo, torch._inductor, torch._inductor.lowering, torch._inductor.runtime.triton_heuristics, [m for m in sys.modules if "unification" in m] is []. Separately, I imported the modified package and the unmodified main version side by side and compared 18 aspects (unify/reify/isvar over tuples/lists/dicts/vars, exact exception types and messages, and the full dispatch registries of unify, isvar, _unify, _reify) — all identical.
-
No cache-key escape hatch. The job log has zero REMOTE_CACHE/MEGACACHE/fx_graph_remote hits, so the torch_key change from touching torch/_inductor files cannot have produced a stale kernel; both trees compile fresh. No codegen file is touched, so the generated Triton source is identical.
Cross-run controls: the same tree minus this diff (merge base 4ee8fea) was green on all 8 mi350 shards in run 30750034794. On main, run 30880141711 ran the identical 520-item selection inductor/test_torchinductor 1/3 on the same gfx950 pool and it was successful. main@240f31ac (run 30917155825, ~2.5h before this failure, same pool) also had all 8 mi350 shards green.
One caveat I want to state rather than hide: this was not a one-off — 9/9 attempts failed across 3 fresh pytest processes, which is why Dr.CI called it NEW FAILURE rather than flaky. But all 9 attempts ran on the same runner node (linux.rocm.gpu.gfx950.1-l9lgr-runner-wvbdr); the retry logic does not reschedule to a different machine, and the first failed launch poisons the HIP context for everything after it. So "consistent" here means consistent on one node, not reproducible on gfx950. The fleet was independently unstable the same day: main run 30880141711 lost a different mi350 shard to inductor/test_cudacodecache exiting with SIGSEGV at teardown while all its tests passed, and an earlier main run lost mi350 shards to "self-hosted runner lost communication".
Suggested next step: a plain re-run of that one job rather than merge -f — it is cheap, lands on a different node, and is the only experiment that separates "bad node" from "latent gfx950 static-launcher bug". If it goes green, Dr.CI reclassifies and the merge can proceed normally; if it fails again on a different node, that is a real gfx950 issue worth its own report and I would file it (something like "test__unsafe_masked_index_cuda: hipErrorIllegalState (401) from hipModuleLaunchKernel in StaticCudaLauncher on gfx950/MI350") — in that case @pytorchbot merge -i would be the milder way to land this.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This was referenced Aug 4, 2026
|
Gentle bump — this is approved and everything else is green (352 passing), with the single ROCm gfx950 job still the only thing holding it. The job has not been re-run since the failed merge attempt, so it is still showing the same run.
If a re-run is inconvenient, @pytorchbot merge -i is the lighter option here: it ignores the currently failing job rather than skipping checks wholesale like -f. The evidence that this one is unrelated is in the comment above — the failure is hipErrorIllegalState from hipModuleLaunchKernel inside the static Triton launcher, and the only runtime function this PR touches (_find_names) is gated behind profile_bandwidth, which the failing job never enables.
Happy to do either — just let me know if you would rather I rebase or drop the triton_heuristics.py hunk to sidestep it entirely.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
pytorch-bot[bot] reacted with thumbs up emoji
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
ankitbhrdwj
pushed a commit
to ankitbhrdwj/pytorch
that referenced
this pull request
Aug 12, 2026
…ation (pytorch#191866)
---
### Addendum (post-review): F811 evidence and runtime verification
**Literal F811 output** with the two noqas stripped from the PR's files (CI-pinned ruff 0.14.4):
```
core.py:140:5: F811 Redefinition of unused `unify` from line 118: `unify` redefined here
variable.py:63:5: F811 Redefinition of unused `isvar` from line 56: `isvar` redefined here
Found 2 errors.
```
With the noqas present, the full-config check reports `All checks passed!` — so under RUF100 both the presence and the placement are exactly what ruff requires.
**Why only these two sites**: ruff's F811 exempts underscore-prefixed names (dummy-variable convention). Minimal repro — two identical `@dispatch` overload chains, one named `_priv`, one named `pub`:
```
f811_repro.py:9:5: F811 Redefinition of unused `pub` from line 7: `pub` redefined here
Found 1 error.
```
Only `pub` is flagged. That is why the five `_reify` redefinitions (and `_eval_is_ge` in `torch/utils/_sympy/singleton_int.py`) need no suppression while the public `unify`/`isvar` do.
**Runtime verification**: imported the changed `unification` package and the unmodified main version side by side as standalone packages (the subtree is stdlib-only + vendored multipledispatch) and compared 18 aspects: `unify`/`reify`/`isvar` behavior on tuples/lists/dicts/vars including exact exception types and messages for the unsupported-signature cases, plus the complete dispatch registries of `unify`, `isvar`, `_unify`, and `_reify`. All 18 identical (package-name normalized). This exercises the import-time `@dispatch` registration side effects directly.
Pull Request resolved: pytorch#191866
Approved by: https://github.com/jansel
pytorchmergebot
pushed a commit
that referenced
this pull request
Aug 21, 2026
### Background
While addressing your review feedback on #191866, your review bot pointed out that a comment I had added to `_find_names` describes behavior that stopped being true in CPython 3.13 (PEP 667). That was correct — and checking it showed the *code* under the comment has a bug of its own. #191866 only corrected the wording; this fixes the function.
### The bug
`_find_names()` resolves the name a `CachingAutotuner` is bound to, so `DebugAutotuner` can label kernels in bandwidth-profiling output. It walked the stack reading `frame.f_locals` **purely for the side effect** of materializing each frame's locals dict, so that the `gc.get_referrers()` scan below would also see frame locals:
```python
frame = inspect.currentframe()
while frame is not None:
frame.f_locals # side effect: materialize + cache a real dict
frame = frame.f_back
```
That walk only ever contributed noise. The frames it exposes are `_find_names`' own frame, which binds the kernel to `obj`, and `DebugAutotuner.run`'s frame, which binds it to `self`. The real name comes from inductor's wrapper codegen binding kernels in a module namespace, and `gc.get_referrers()` finds that on its own.
The damage is in exactly the case the walk was supposed to help. When a kernel is held only by frame locals, `possible_names` came back as `['obj', 'self']` rather than empty, so the fallback below it — and the comment explaining that the AOTI lazy-compile path has no module-level name — was **unreachable**, and `max(possible_names, key=len)` labelled the kernel `"self"`.
CPython 3.13 already removed the walk's effect: under [PEP 667](https://peps.python.org/pep-0667/), `f_locals` on an optimized frame returns a fresh write-through `FrameLocalsProxy` that caches nothing and is not a `dict`, so it is skipped by the `isinstance(referrer, dict)` filter. Nothing regressed when that happened, and the unbound case started falling back correctly on 3.13+. This PR deletes the walk so every supported interpreter behaves the way 3.13 and 3.14 already do.
### Test plan
Added `test_find_names_ignores_frame_locals` and `test_find_names_finds_namespace_binding` to `test/inductor/test_triton_heuristics.py`. The first fails on the current implementation on CPython <= 3.12 (returns `['obj', 'self']` rather than `[]`) and passes on 3.13+; the second pins the namespace lookup the fix must preserve. Both are CPU-only.
The probe is a user-defined class rather than `object()`: `object()` is untracked by gc, so a dict holding one can itself stay untracked and escape `gc.get_referrers` — that made the naive version of this test pass on 3.14 but not on 3.12/3.13.
My environment cannot build torch, so I also ran the current and patched implementations against a faithful copy of the call shape (a method calling `_find_names(self)`, with the object either bound in a namespace or unbound) under three interpreters:
```
python 3.12.9
before: namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> picks 'self'
after : namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
python 3.13.14 / 3.14.6
before: namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
after : namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
```
Lint with the CI-pinned ruff 0.14.4 (`ruff check` and `ruff format --check`) passes on both files.
A larger cleanup is possible — dropping `_find_names` entirely and always using `inductor_meta["kernel_name"]` — but that changes kernel labels for every profiled run, so I kept this diff to the defect. Happy to do it as a follow-up if you'd prefer.
@jansel — follow-up to the finding your bot raised on #191866.
> Authored with the assistance of an AI coding assistant (Claude).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #192123
Approved by: https://github.com/jansel
orrangetabby17
pushed a commit
to orrangetabby17/pytorch
that referenced
this pull request
Sep 2, 2026
### Background
While addressing your review feedback on pytorch#191866, your review bot pointed out that a comment I had added to `_find_names` describes behavior that stopped being true in CPython 3.13 (PEP 667). That was correct — and checking it showed the *code* under the comment has a bug of its own. pytorch#191866 only corrected the wording; this fixes the function.
### The bug
`_find_names()` resolves the name a `CachingAutotuner` is bound to, so `DebugAutotuner` can label kernels in bandwidth-profiling output. It walked the stack reading `frame.f_locals` **purely for the side effect** of materializing each frame's locals dict, so that the `gc.get_referrers()` scan below would also see frame locals:
```python
frame = inspect.currentframe()
while frame is not None:
frame.f_locals # side effect: materialize + cache a real dict
frame = frame.f_back
```
That walk only ever contributed noise. The frames it exposes are `_find_names`' own frame, which binds the kernel to `obj`, and `DebugAutotuner.run`'s frame, which binds it to `self`. The real name comes from inductor's wrapper codegen binding kernels in a module namespace, and `gc.get_referrers()` finds that on its own.
The damage is in exactly the case the walk was supposed to help. When a kernel is held only by frame locals, `possible_names` came back as `['obj', 'self']` rather than empty, so the fallback below it — and the comment explaining that the AOTI lazy-compile path has no module-level name — was **unreachable**, and `max(possible_names, key=len)` labelled the kernel `"self"`.
CPython 3.13 already removed the walk's effect: under [PEP 667](https://peps.python.org/pep-0667/), `f_locals` on an optimized frame returns a fresh write-through `FrameLocalsProxy` that caches nothing and is not a `dict`, so it is skipped by the `isinstance(referrer, dict)` filter. Nothing regressed when that happened, and the unbound case started falling back correctly on 3.13+. This PR deletes the walk so every supported interpreter behaves the way 3.13 and 3.14 already do.
### Test plan
Added `test_find_names_ignores_frame_locals` and `test_find_names_finds_namespace_binding` to `test/inductor/test_triton_heuristics.py`. The first fails on the current implementation on CPython <= 3.12 (returns `['obj', 'self']` rather than `[]`) and passes on 3.13+; the second pins the namespace lookup the fix must preserve. Both are CPU-only.
The probe is a user-defined class rather than `object()`: `object()` is untracked by gc, so a dict holding one can itself stay untracked and escape `gc.get_referrers` — that made the naive version of this test pass on 3.14 but not on 3.12/3.13.
My environment cannot build torch, so I also ran the current and patched implementations against a faithful copy of the call shape (a method calling `_find_names(self)`, with the object either bound in a namespace or unbound) under three interpreters:
```
python 3.12.9
before: namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> picks 'self'
after : namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
python 3.13.14 / 3.14.6
before: namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
after : namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
```
Lint with the CI-pinned ruff 0.14.4 (`ruff check` and `ruff format --check`) passes on both files.
A larger cleanup is possible — dropping `_find_names` entirely and always using `inductor_meta["kernel_name"]` — but that changes kernel labels for every profiled run, so I kept this diff to the defect. Happy to do it as a follow-up if you'd prefer.
@jansel — follow-up to the finding your bot raised on pytorch#191866.
> Authored with the assistance of an AI coding assistant (Claude).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: pytorch#192123
Approved by: https://github.com/jansel
aeytkn
pushed a commit
to aeytkn/pytorch
that referenced
this pull request
Sep 3, 2026
### Background
While addressing your review feedback on pytorch#191866, your review bot pointed out that a comment I had added to `_find_names` describes behavior that stopped being true in CPython 3.13 (PEP 667). That was correct — and checking it showed the *code* under the comment has a bug of its own. pytorch#191866 only corrected the wording; this fixes the function.
### The bug
`_find_names()` resolves the name a `CachingAutotuner` is bound to, so `DebugAutotuner` can label kernels in bandwidth-profiling output. It walked the stack reading `frame.f_locals` **purely for the side effect** of materializing each frame's locals dict, so that the `gc.get_referrers()` scan below would also see frame locals:
```python
frame = inspect.currentframe()
while frame is not None:
frame.f_locals # side effect: materialize + cache a real dict
frame = frame.f_back
```
That walk only ever contributed noise. The frames it exposes are `_find_names`' own frame, which binds the kernel to `obj`, and `DebugAutotuner.run`'s frame, which binds it to `self`. The real name comes from inductor's wrapper codegen binding kernels in a module namespace, and `gc.get_referrers()` finds that on its own.
The damage is in exactly the case the walk was supposed to help. When a kernel is held only by frame locals, `possible_names` came back as `['obj', 'self']` rather than empty, so the fallback below it — and the comment explaining that the AOTI lazy-compile path has no module-level name — was **unreachable**, and `max(possible_names, key=len)` labelled the kernel `"self"`.
CPython 3.13 already removed the walk's effect: under [PEP 667](https://peps.python.org/pep-0667/), `f_locals` on an optimized frame returns a fresh write-through `FrameLocalsProxy` that caches nothing and is not a `dict`, so it is skipped by the `isinstance(referrer, dict)` filter. Nothing regressed when that happened, and the unbound case started falling back correctly on 3.13+. This PR deletes the walk so every supported interpreter behaves the way 3.13 and 3.14 already do.
### Test plan
Added `test_find_names_ignores_frame_locals` and `test_find_names_finds_namespace_binding` to `test/inductor/test_triton_heuristics.py`. The first fails on the current implementation on CPython <= 3.12 (returns `['obj', 'self']` rather than `[]`) and passes on 3.13+; the second pins the namespace lookup the fix must preserve. Both are CPU-only.
The probe is a user-defined class rather than `object()`: `object()` is untracked by gc, so a dict holding one can itself stay untracked and escape `gc.get_referrers` — that made the naive version of this test pass on 3.14 but not on 3.12/3.13.
My environment cannot build torch, so I also ran the current and patched implementations against a faithful copy of the call shape (a method calling `_find_names(self)`, with the object either bound in a namespace or unbound) under three interpreters:
```
python 3.12.9
before: namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> picks 'self'
after : namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
python 3.13.14 / 3.14.6
before: namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
after : namespace-bound -> picks 'triton_poi_fused_add_0'; unbound -> falls back
```
Lint with the CI-pinned ruff 0.14.4 (`ruff check` and `ruff format --check`) passes on both files.
A larger cleanup is possible — dropping `_find_names` entirely and always using `inductor_meta["kernel_name"]` — but that changes kernel labels for every profiled run, so I kept this diff to the defect. Happy to do it as a follow-up if you'd prefer.
@jansel — follow-up to the finding your bot raised on pytorch#191866.
> Authored with the assistance of an AI coding assistant (Claude).
Pull Request resolved: pytorch#192123
Approved by: https://github.com/jansel
Reviewers
jansel
jansel approved these changes
eellison
Awaiting requested review from eellison
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|