GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [inductor] Drop the dead frame walk in _find_names by HumphreySun98 · Pull Request #192123 · pytorch/pytorch

Conversation

@HumphreySun98

@HumphreySun98 HumphreySun98 commented Aug 4, 2026 •
edited by pytorch-bot Bot
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown
Contributor

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:

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, 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

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.

All reactions
@pytorch-bot

pytorch-bot Bot commented Aug 4, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

🔗 Helpful Links

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

  • 📄 Preview Python docs built from this PR
  • 📄 Preview C++ docs built from this PR
  • ❓ Need help or want to give feedback on the CI? Visit the bot commands wiki

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

✅ You can merge normally! (3 Unrelated Failures)

As of commit 87a653d with merge base 8f988c9 (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

  • torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8) (gh) (detected as infra flaky with no log or failing log classifier)

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

  • crcr/pytorch/crcr-test/CRCR L3 CI - Checking if PR check run is successfully created/test-L3-xcancel-checkrun-creation (gh)
  • crcr/pytorch/crcr-test/CRCR L3 CI - Checking if PR check run is successfully created/test-L3-xfail-checkrun-creation (gh)

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

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: inductor labels Aug 4, 2026
@pytorch-bot

pytorch-bot Bot commented Aug 4, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

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

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pytorch-bot

pytorch-bot Bot commented Aug 4, 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.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HumphreySun98
HumphreySun98 force-pushed the fix-find-names-pep667 branch from 63fbfce to 9424d9f Compare August 4, 2026 20:13
@HumphreySun98 HumphreySun98 changed the title [inductor] Fix _find_names on CPython 3.13+ (PEP 667) [inductor] Drop the dead frame walk in _find_names Aug 4, 2026
@HumphreySun98

HumphreySun98 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Note for anyone who saw the first revision: I force-pushed a correction. The original diff made the stack walk work again on 3.13+ (scanning f_locals directly). Testing it against the real call shape showed that was backwards — the walk's only reachable contributions are obj (this function's own parameter) and self (DebugAutotuner.run's), so restoring it would have made 3.13+ label unbound kernels "self" the way <= 3.12 does today, rather than fixing anything. The walk is now deleted instead, which is what 3.13+ has effectively been doing since PEP 667.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pytorchbot pytorchbot added the open source label Aug 4, 2026
@HumphreySun98 HumphreySun98 mentioned this pull request Aug 4, 2026
Enable flake8-bugbear B007 (unused loop control variable) #189319
Closed
@HumphreySun98

HumphreySun98 commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

pytorch-bot[bot] reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Aug 5, 2026
@jansel

jansel commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@claude review this

HumphreySun98 reacted with thumbs up emoji claude[bot] reacted with eyes emoji
All reactions
  • 👍 1 reaction
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@claude

claude Bot commented Aug 5, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Claude finished @jansel's task in 36m 12s —— View job


Reviewed — the code change is correct, but the new comment makes a claim the code contradicts, and neither new test covers the actual user-visible bug (the "self" label).

Full review

PR Review: #192123

Summary

Deletes a dead frame.f_locals stack walk in _find_names (torch/_inductor/runtime/triton_heuristics.py:3328) so unbound kernels fall back to inductor_meta["kernel_name"] instead of being labelled "self" on CPython <= 3.12. I confirmed the core claim: no frame on the stack during DebugAutotuner.run() binds the autotuner to a local with a real kernel name — generated wrappers bind kernels at module scope (torch/_inductor/codegen/wrapper.py:3328), and the only local bindings are in wrapper_benchmark.get_triton_kernel (v, cand_list, triton_kernel), which is not on the stack during call(). The deletion is safe. Four problems below.

Code Quality

triton_heuristics.py:3331 — "Only namespace dicts are searched" is inaccurate. The filter is isinstance(referrer, dict), which matches any dict holding the object, not just module namespaces. Concretely, torch/_inductor/runtime/triton_lazy_compile.py:124 does pending_kernels[kernel_name] = kernel_obj, a plain dict keyed by the real kernel name, and lines 145-146 show kernel_obj can be the CachingAutotuner itself (not just a CodeCacheFuture). Since profile_bandwidth returns a DebugAutotuner from the same factory (triton_heuristics.py:3549-3568), that path can reach _find_names with the autotuner live in pending_kernels — so _find_names returns [kernel_name] rather than empty. The resolved label is identical either way, so this is not a behavior bug, but both the new comment and the pre-existing one at triton_heuristics.py:3422-3424 ("the CachingAutotuner is not bound to a module-level name, so _find_names returns empty") overstate the case. Say what the code does — matches any referring dict — rather than asserting a reachability property that isn't guaranteed.

triton_heuristics.py:3331-3334 — the comment documents deleted code. Four lines explaining what a walk that no longer exists would have done, including "which is how an unbound kernel used to end up named self". CLAUDE.md asks for comments that "remind the reader about some global context that is non-obvious and can't be inferred locally"; a reader who never saw the removed walk cannot check any of this against the code in front of them, and the rationale belongs in the commit message (where it already is, at length). Either drop the comment or reduce it to one line about the referrer filter's scope.

Testing

No test covers the behavior the PR set out to fix. The defect is that DebugAutotuner.run labelled an unbound kernel "self"; both new tests exercise only the _find_names helper. Nothing pins that run() now reaches the inductor_meta["kernel_name"] fallback (triton_heuristics.py:3419-3425), so a future change that reintroduces a spurious name — or that breaks the fallback branch itself, which remained unreachable for years without anyone noticing — still passes. Construct a DebugAutotuner (or a SimpleNamespace standing in for one, as TestMakeLaunchersMemory already does in this file) with inductor_meta={"kernel_name": "triton_poi_fused_add_0"} and assert the resolved kernel_name. That is the regression test; the helper tests are supporting detail.

test_triton_heuristics.py:117-120 — the try/finally: del namespace is inert. namespace is a method local that dies when the frame returns, and the del runs after _find_names has already been called, so it cannot influence the result. If it exists to silence ruff F841 (pyflakes counts del as a use), make the use real instead — e.g. follow the assertIn with self.assertIs(namespace["triton_poi_fused_add_0"], probe) — so the reader isn't left inferring a cleanup requirement that doesn't exist.

test_triton_heuristics.py:106-110 — the docstring describes the removed implementation. "The stack walk used to leak _find_names' own obj and the caller's self into the result" will read as a description of live behavior to the next person, same problem as the source comment. State the invariant: a kernel reachable only from frame locals has no name.

test_triton_heuristics.py:105-120 — placement means the version that has the bug is the only one that runs the test, and only by luck. The module raises unittest.SkipTest("requires triton") at line 36, so these two CPU-only tests are skipped in every triton-less config. Per .github/workflows/inductor-unittest.yml:41,54,79, the GPU+triton jobs are py3.10, where the pre-fix path does return ['obj', 'self'] — so the test is meaningful today. But it is vacuous on 3.13+ by construction (PEP 667), and it will silently stop testing anything the moment those jobs move to 3.13, with no signal that coverage was lost. Since neither test needs triton or a GPU, a home that isn't behind the triton import guard would keep them honest; failing that, note the version dependence in the test so the vacuity is discoverable.

Recommendation

Request Changes

The deletion is right and I would take it as-is if the comment were accurate. Blocking items are the "Only namespace dicts" claim, which triton_lazy_compile.py:124 contradicts, and the absence of a test on DebugAutotuner.run's label — the fallback branch this PR makes reachable is still untested, which is how the original defect survived. The comment/docstring style points and the inert try/finally are small but should go in the same push.

| Branch: `fix-find-names-pep667`
All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HumphreySun98
HumphreySun98 force-pushed the fix-find-names-pep667 branch from 9424d9f to 0eaa3a7 Compare August 5, 2026 21:20
@HumphreySun98

HumphreySun98 commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto main (0eaa3a7) — #191866 landing put this into conflict, since that PR touched the exact two lines this one deletes. Resolved by keeping the deletion; the resulting _find_names is the same function the review was looking at, just without the now-stale _ = frame.f_locals hunk in between. Back to MERGEABLE, lint and format --check still clean on both files.

@jansel your review bot run was against the pre-rebase commit, but the diff is unchanged apart from that conflict resolution. This one is 0 failures across 210 checks if you want to take it.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

jansel
jansel requested changes Aug 5, 2026
View reviewed changes
Comment thread torch/_inductor/runtime/triton_heuristics.py
# 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

@jansel jansel Aug 5, 2026

Copy link
Copy Markdown
Contributor

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.

This smells like a workaround for a GC bug -- where the point of the code is to materialize f_locals. Why is this workaround no longer needed?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
@jansel

jansel commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@claude go through the history to find when this workaround was added, do we have a test that checks for what this workaround originally was fixing?

claude[bot] reacted with eyes emoji
All reactions
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@claude

claude Bot commented Aug 5, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Claude finished @jansel's task in 13m 50s —— View job


Short answer: no test ever covered the workaround, and I could not reach the introducing commit from this sandbox.

  • Search for the introducing commit
  • Check for tests covering the original fix
  • Answer "why is this no longer needed?"

History: not retrieved. This runner has a 20-commit shallow clone and network egress is blocked, so git fetch --unshallow, git fetch --deepen, gh api .../commits?path=..., gh api graphql blame, and curl to raw.githubusercontent all failed. The one command that would settle it, for whoever has history:

git log -S'f_locals' --oneline --follow -- \
  torch/_inductor/runtime/triton_heuristics.py \
  torch/_inductor/triton_heuristics.py \
  torch/_inductor/triton_ops/autotune.py

I deliberately did not guess a SHA. One thing I can confirm locally: the explanatory comment above the walk is not original rationale — it was added three days ago by #191866 (e9cfafa), which also changed bare frame.f_locals to _ = frame.f_locals for B018. There is no older comment text to appeal to, so the walk's intent is undocumented in-tree.

Tests: verified — nothing covered it, in either direction

At the pre-PR commit e9cfafa, zero hits for _find_names under test/. The only test touching DebugAutotuner at all is test/profiler/test_profiler.py:3275 test_profiler_debug_autotuner, and it does not test naming:

  • it compiles the same mm with and without profile_bandwidth and asserts the two profiles' event-name sets are equal (line 3319), filtering on "mm" in ev.name or "triton" in ev.name (line 3314) — a kernel mislabeled "self" would not fail it;
  • it is gated by unittest.skipIf(IS_LINUX or TEST_WITH_ROCM or TEST_WITH_SLOW, ...) (line 3269, ref DISABLED test_profiler_debug_autotuner (__main__.TestExperimentalUtils) #158727) plus CUDA and is_big_gpu(), so it does not run in normal CI.

Other profile_bandwidth tests (test_analysis.py:219,237, test_aot_inductor.py:3986,4003,4015, test_combo_kernels.py:2970, test_torchinductor.py:20850) assert bandwidth/kernel_num_gb numbers, never the resolved name.

So: the frame walk was never pinned by a test, and nothing would have caught the "self" mislabel it caused. The two tests in this PR are the first coverage _find_names has had.

On "why is this workaround no longer needed?"

Framing it as no longer needed is the weak version of the argument, and I think that is what makes it smell. The stronger claim available from the code is that for the case it looks like it targets, it never worked — it produced a wrong label rather than a missing one:

  • The only consumer of the result is the kernel_name string used for bandwidth-profiling labels (triton_heuristics.py:3418-3425, then :3456-3462). Nothing functional depends on it.
  • The name that actually matters comes from the generated module's globals() — async_compile.wait(globals()) at codegen/wrapper.py:1779 binds each triton_* kernel there, and that is a plain dict, so gc.get_referrers() finds it with no frame walk. get_triton_kernel() reads the same binding out of mod.__dict__ at wrapper_benchmark.py:66-70.
  • So when a kernel is module-bound, the walk changes nothing; when it is not (the AOTI lazy-compile path the fallback comment at :3422 describes), the walk turned an empty list into ['obj', 'self'], making that documented fallback unreachable and max(..., key=len) pick "self".

The load-bearing evidence that this is safe is that 3.13+ has already been running this way. pyproject.toml:348 declares requires-python = ">=3.10" and 3.13/3.14 are supported classifiers; under PEP 667 f_locals on an optimized frame is a FrameLocalsProxy, not a dict, so the isinstance(referrer, dict) filter at :3337 skips it and the walk has been a no-op there since 3.13 shipped. Nothing regressed. This PR makes 3.10-3.12 match — so it is a real behavior change on those versions, not a pure no-op cleanup, and it is worth saying so plainly rather than calling the code dead.

One precision issue I would fix regardless of the outcome. The new comment (and the commit message) claim the walk can only ever surface obj and self. That is not quite true — it depends on the caller stack, and there is a counterexample in-tree: benchmark_all_kernels() holds the same autotuner in a local named triton_kernel (wrapper_benchmark.py:98) and can reach DebugAutotuner.run via kernel_mod.call(args) at :146 when benchmark_kernel and profile_bandwidth are both set. On <=3.12 the walk would surface triton_kernel too. The conclusion survives — that kernel came out of mod.__dict__, so it is module-bound and the longer codegen name wins — but the stated reasoning is overstated and should be softened to something like "the frame locals it exposes are incidental binding names, never the codegen name."

Suggested way to de-risk this for review: the possible_names/frame-walk question is separable from what the profiler actually wants. inductor_meta["kernel_name"] is already the authoritative name and is already the fallback at :3425. If the goal is to stop guessing names by GC introspection, deleting _find_names entirely is the honest fix — the author offers exactly that in the PR description and defers it because it changes labels for every profiled run. Given there is no test pinning the current labels, that follow-up is cheap to land behind this one. Fix this →

I did not change any files. · branch fix-find-names-pep667

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HumphreySun98
HumphreySun98 force-pushed the fix-find-names-pep667 branch from 0eaa3a7 to eb5284b Compare August 6, 2026 00:38
@HumphreySun98

HumphreySun98 commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Good question, and the history answers it in a way I did not expect. I have a full clone, so here is what the bot could not fetch.

The walk was introduced in #95355 (01c861a, Feb 2023, "Added utilities to instrument kernel bandwidth numbers" — you approved it), in exactly the form you are describing, as a way to make caller frame locals visible to gc.get_referrers:

frame = inspect.currentframe()
for frame in iter(lambda: frame.f_back, None):
    frame.f_locals

Note what that original does: iter(lambda: frame.f_back, None) starts at frame.f_back, so it walks the caller frames and never touches _find_names' own frame. It could not report obj.

It was rewritten in #110823 (192477b, Oct 2023, "Enable flake8-bugbear B020 lint") — B020 fires because the loop variable frame shadows the name captured by the lambda:

-    for frame in iter(lambda: frame.f_back, None):  # type: ignore[union-attr]
+    while frame is not None:
         frame.f_locals
+        frame = frame.f_back

That rewrite is where obj came from: the new loop starts at currentframe() instead of currentframe().f_back, so it materializes _find_names' own frame too. So the obj half of the pollution is a three-year-old lint-refactor bug, not the original design. (Uncomfortably on the nose, given what I am doing in the B007 PRs.)

So, on "why is this no longer needed": I would put it as two separate claims.

  1. It has been provably inert on 3.13+ since PEP 667 shipped — f_locals on an optimized frame is a FrameLocalsProxy, which the isinstance(referrer, dict) filter skips — and nothing regressed. Kernel labels still come out right there, because the name that matters is bound in the generated module's globals by async_compile.wait(globals()) and gc.get_referrers finds that plain dict without any help.
  2. On <= 3.12 it is now actively harmful. [AOTI] Support AOTI lazy autotune with dual-wrapper #184735 later added the possible_names empty fallback with a comment saying the AOTI lazy-compile path has no module-level binding. The walk means that list is never empty there — it is ['obj', 'self'] — so the fallback is unreachable and max(..., key=len) labels the kernel "self". Deleting the walk makes <= 3.12 behave the way 3.13/3.14 already do, which is a real behavior change on those versions, not a no-op cleanup.

You are right that there is no test pinning any of this in either direction — I checked, there never was one. I have added the missing one: test_unbound_kernel_falls_back_to_inductor_meta_name reproduces the label path (_find_names(self) from a method, then max(..., key=len) with the inductor_meta fallback) and asserts the kernel is labelled triton_poi_fused_add_0. On the current implementation it returns "self" on 3.12 and passes on 3.13+; after the fix it passes everywhere.

I also softened the comment — the claim that the walk can only surface obj and self was overstated. benchmark_all_kernels holds the same autotuner in a local named triton_kernel, so on <= 3.12 that name would surface too. The conclusion is unchanged (that kernel came out of mod.__dict__, so the longer codegen name wins), but the comment now says "incidental binding names, never the codegen name".

Rebased onto main after #191866 landed; 2 files, +49/-10, and the earlier CI run was 210 checks with 0 failures.

On the bigger cleanup: inductor_meta["kernel_name"] is already authoritative and already the fallback, so deleting _find_names outright is the honest end state. I kept it out of this PR only because it changes labels for every profiled run and there is nothing pinning them. Happy to send it as a follow-up if you want it.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jansel

jansel commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

@claude review this again; have the prior comments been addressed? do we now have test coverage for the issue the remove code was fixing?

claude[bot] reacted with eyes emoji
All reactions
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

1 similar comment
@jansel

jansel commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

@claude review this again; have the prior comments been addressed? do we now have test coverage for the issue the remove code was fixing?

claude[bot] reacted with eyes emoji
All reactions
  • 👀 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jansel
jansel self-requested a review August 6, 2026 21:11
jansel
jansel approved these changes Aug 7, 2026
View reviewed changes
@HumphreySun98

HumphreySun98 commented Aug 8, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the approval. One thing before this can land: the force-push that answered your history question reset the workflow-approval gate, so CI has not run on the current commit (eb5284b) — the PR shows only the 2 always-on checks and mergeStateStatus: BLOCKED. The previous commit was 210 checks / 0 failures, and the only delta since then is the added test plus the softened comment.

Could you approve the workflow run (bottom of the PR page), or fire @pytorchbot merge and let it trigger trunk itself — whichever you prefer?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HumphreySun98
[inductor] Drop the dead frame walk in _find_names
87a653d
_find_names() resolves the name a CachingAutotuner is bound to so that
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.

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`; inductor's wrapper codegen binds kernels in a module
namespace, and that path is found through gc.get_referrers() without any help.
The damage is in the case the walk was supposed to help: when a kernel is held
only by frame locals, `possible_names` came back as ['obj', 'self'] instead of
empty, so the documented fallback to inductor_meta["kernel_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 f_locals on an
optimized frame returns a fresh write-through proxy 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 change 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.

This environment cannot build torch, so the behavior was also checked by
running 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:

```
uvx [email protected] check torch/_inductor/runtime/triton_heuristics.py test/inductor/test_triton_heuristics.py --config=pyproject.toml
uvx [email protected] format --check torch/_inductor/runtime/triton_heuristics.py test/inductor/test_triton_heuristics.py --config=pyproject.toml
```

Authored with the assistance of an AI coding assistant (Claude).
@HumphreySun98
HumphreySun98 force-pushed the fix-find-names-pep667 branch from eb5284b to 87a653d Compare August 16, 2026 05:51
@HumphreySun98

HumphreySun98 commented Aug 16, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest main (87a653d) — it was 50 commits behind and I would rather it not go stale while it waits. Cherry-picked cleanly, no conflicts; still 2 files, +49/-10, lint and format --check clean, and your approval carried over.

The only thing left is the workflow approval. Because I have force-pushed, the fork-PR gate reset and this currently shows just the two always-on checks, so @pytorchbot merge would sit waiting for checks that were never started. If you approve the run at the bottom of the page, it should go green and land on its own.

Happy to hold if you would rather I fold the follow-up you mentioned (dropping _find_names entirely in favour of inductor_meta["kernel_name"]) into this one instead of a separate PR.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@jansel

jansel commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

pytorch-bot[bot] and HumphreySun98 reacted with thumbs up emoji
All reactions
  • 👍 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

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

pytorchmergebot commented Aug 21, 2026

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

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@pytorchmergebot pytorchmergebot added the Merged label Aug 21, 2026
@pytorchmergebot pytorchmergebot closed this in b78a4fe Aug 21, 2026
@pytorchmergebot pytorchmergebot removed the merging label Aug 21, 2026
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
@HumphreySun98 @orrangetabby17
[inductor] Drop the dead frame walk in _find_names (pytorch#192123)
b91aaaf
### 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
@HumphreySun98 @pytorchmergebot
[inductor] Drop the dead frame walk in _find_names (pytorch#192123)
2a21a70
### 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
@HumphreySun98 HumphreySun98 mentioned this pull request Sep 7, 2026
[BE] Fix B007 unused loop control variables in tools/, torchgen/ and functorch/ #192151
Closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@jansel jansel jansel approved these changes

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor open source topic: not user facing topic category

Projects

None yet

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.

4 participants

@HumphreySun98 @jansel @pytorchmergebot @pytorchbot
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.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.