Skip to content

[dynamo] Probe a bound method's function name inside the reducer's try, pin the dict-served case - #196764

Closed
bobrenjc93 wants to merge 6 commits into
gh/bobrenjc93/1161/basefrom
gh/bobrenjc93/1161/head
Closed

bobrenjc93 wants to merge 6 commits into
gh/bobrenjc93/1161/basefrom
gh/bobrenjc93/1161/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Follow-up to the reviews of #196473 and #196474.

_reduce_bound_method read func.__name__ before its try. getattr with a
default swallows only AttributeError, and __func__ is an arbitrary callable
by the reducer's own premise, so a proxy that raises anything else escaped the
reducer while the receiver-side probe two lines down was already guarded:

class ProxyFunc:
    def __getattr__(self, name):
        raise RuntimeError(f"proxy has no {name}")

pickler._reduce_bound_method(types.MethodType(ProxyFunc(), Plain()))
# before: RuntimeError: proxy has no __name__
# now:    (_unpickle_bound_method, (ProxyFunc(), Plain()))

The read moves inside the try, after the __getattr__ gate (which takes the
pair without probing func at all), where explicit is already built for the
except to return.

The __dict__ half of the per-instance condition had no test: SlottedByName
has no instance dict, so the slot test lands on the getattr_static half, and
ablating the __dict__ clause left the suite green while the shape it exists
for broke at load:

obj = Plain()
obj.global_add = types.MethodType(global_add, obj)
# with the clause:    loads back as MethodType(global_add, Plain)
# without the clause: AttributeError: 'Plain' object has no attribute 'global_add'

Pinned now, and the comment says which receivers reach that clause: one that
HAS an instance dict, which a pure-slots receiver does not (a slotted subclass
of a non-slotted base has both, and either clause gives the same answer), and a
class defining __getattr__ (every nn.Module) takes the pair before it either
way.

Two tests from #196474 were not pinning what they said. The shared-closure-cell
test used a <locals> pair, whose branch returns before the guard_tree_values
gate, so the dict it built was inert and the test passed on the parent; it now
uses two module-level functools.wraps wrappers sharing one cell, which only
the gate carries. The module-method test's comment described the <locals>
rebuild bug from the commit that fixed it; the comment is gone and the test
asserts the rebuilt function's __name__ is forward, which is a record of
what the rebuild carries rather than a regression guard (the name path is
pinned by test_rebuilt_locals_function_keeps_its_name), so the comment now
points at the call as the assertion that catches the placeholder.

Type nits from the same reviews: object instead of Any for the resolution
walk and both rebuilt scopes; the bound-method reducer returns its real shape,
tuple[Callable[..., Any], tuple[Any, ...]] | None; the state tuple stays
Any, since its elements are assigned to typed function slots and the checker
rejects object there.

One #196474 comment is not a code change here: at that commit the by-value
payload carried every closure cell and default unconditionally, so a wraps
wrapper capturing a lock no guard read failed the dump. #196476, two commits
above it, prunes each cell and default through the same guard_tree_values
test, and that is where the prune lives in this stack.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k bound_method -k shared_closure_cell
python test/dynamo/test_aot_compile.py -k Pickler

The proxy test fails on the previous commit with the RuntimeError above. Its
second case pins the ORDERING rather than the try: the receiver is a proxy
whose class defines __getattr__, so the gate takes the pair and the name is
never asked for, which the fixture records; moving the read back above the gate
fails that assertion while the rest of the test stays green. The
monkeypatched-method test fails against the __dict__ clause ablated. The
shared-cell test fails when the fqn-mismatched pair is not in
guard_tree_values (both prune to _Missing), which the old <locals> pair
could not show.

Authored with an AI assistant.

🤖 Generated with Claude Code

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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 84cdcbe with merge base 0929b23 (image):

GREEN LIGHT - PR approved to be merged without human review:

  • Correctness
    • The only behavioral edit moves name = getattr(func, "__name__", None) into the existing try at torch/_dynamo/package.py:395, so a raising __name__ returns explicit instead of escaping.
    • The __getattr__ gate at package.py:388 returns before that read and never used name, so skipping it there is behavior-neutral.
    • No defensive branch was dropped: the getattr(..., None) default, the exempt checks, and the except Exception: return explicit fallback at package.py:409 all remain.
  • Testing
    • test_bound_method_monkeypatched_onto_a_plain_instance reaches the __dict__ clause because PlainMethods (test:​802) defines no __getattr__, pinning the previously untested half.
    • test_bound_method_whose_func_raises_on_name_takes_the_pair covers both the raising func and the ordering, via RaisingNameProxy.probed and the GetattrProxy receiver at test:​748.
    • The repointed shared-cell test asserts assertNotIsInstance(..., _Missing) at test:​1292, which _prune_cell's identity memo at guards.py:4420 leaves as the only distinguishing line.
  • Scope
    • Two files: torch/_dynamo/package.py and test/dynamo/test_guard_serialization.py; no CI, build, or release plumbing touched.
    • _reduce_bound_method is private and its narrowed return is accepted by both call sites, guards.py:4655 and aot_compile.py:147, which only test is not None.
    • The Any to object annotation changes feed types.FunctionType and getattr walks, so no runtime or public API behavior changes.

reason: clean
Reviewed commit: 84cdcbe

Inference job

UNSTABLE - The following job is marked as unstable, possibly due to flakiness on trunk:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 11, 2026
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 11, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 17m 48s —— View job


Reviewed: the reducer fix and the two new tests are correct, but the name read landed one line higher than it needs to (it now probes func.__name__ on the __getattr__/nn.Module path that discards it, contradicting the "without probing" comment right below), and the new assertIsNot(out["a"], a) in the shared-cell test is vacuous.

Full review

PR Review: #196764

Summary

Moves _reduce_bound_method's func.__name__ read inside its try so a proxy raising non-AttributeError falls through to the explicit reduce, pins the previously untested __dict__ half of the per-instance condition, and repoints two tests from #196474 at the shapes they claim to cover. The core change is right and the new tests do fail on the parent as claimed; four smaller issues below.

Code Quality

  • torch/_dynamo/package.py:381 — the name read is one line too high. Inside the try it now sits above the __getattr__ early return:

    try:
        name = getattr(func, "__name__", None)
        if not is_type and hasattr(cls, "__getattr__"):
            return explicit

    That branch never reads name, so every __getattr__-defining receiver — which the comment at :366 notes is every nn.Module, i.e. the dominant case — now performs a __name__ lookup whose result is thrown away. Worse, it directly contradicts the comment two lines below it, which says such a class "takes the pair before it, without probing": the reducer now probes func (an arbitrary callable, by this reducer's own premise) before deciding it does not need to. Moving the read to just after the early return keeps the RuntimeError guarantee the PR is adding while restoring the no-probe property and dropping the discarded lookup from the hot path. Fix this →

  • torch/_dynamo/package.py:365 — "Only a plain receiver reaches the __dict__ clause" is not accurate. A __slots__ receiver reaches and evaluates that clause too — getattr(receiver, "__dict__", None) returns None, the isinstance(self_dict, dict) test fails, and control falls to the getattr_static half; that is exactly what SlottedByName (test line 737) exercises. What is true is that only a plain receiver can be carried by the __dict__ clause. The reflow also left two colons chained in one sentence ("...reaches the __dict__ clause: a class defining __getattr__ ... takes the pair before it, without probing: the probe would run..."), which reads worse than the original.

  • torch/_dynamo/package.py:226 — the dict[str, Any] → dict[str, object] sweep missed a sibling. _unpickle_fn_from_snapshot still declares scope: dict[str, Any] and forwards it straight into _build_function(f_globals: dict[str, object]) at :239, while _unpickle_fn_from_module's local is now dict[str, object] (:206). Not a checker error (Any is consistent with object), but the two unpicklers now disagree on the annotation for the same forwarded value, which is the inconsistency this PR set out to remove.

  • torch/_dynamo/package.py:350 — tuple[object, ...] | None is a downgrade for this particular return. Unlike the other three changes, this return's shape is fully known: it is always (callable, args_tuple). tuple[object, ...] erases that, and the existing test at test/dynamo/test_guard_serialization.py:1739 already indexes through it (reduced[1][0]), which is unwritable against object — it only passes CI because .lintrunner.toml's MYPY/PYREFLY blocks cover torch/** and not test/, so nothing type-checks that file. tuple[Callable[..., Any], tuple[Any, ...]] | None is both the real shape and what GuardsStatePickler.reducer_override already declares at torch/_dynamo/guards.py:4491.

Testing

  • test/dynamo/test_guard_serialization.py:1287 — self.assertIsNot(out["a"], a) # rebuilt by value, not by reference cannot fail, and its comment misdescribes it. pickle.loads can only hand back the identical live object via a by-reference save or a persistent_id/persistent_load pair; GuardsStatePickler defines no persistent_id, and a by-reference save of a functools.wraps wrapper raises PicklingError at dump (pickle verifies getattr(module, qualname) is obj, which resolves global_func, not the wrapper) — so the by-value/by-reference distinction the comment names can never show up as a loads result. The only other failure mode, _Missing pruning when the guard_tree_values gate is not satisfied, is already caught one line earlier at :1286, since a _Missing has no __closure__. Either drop the line or replace it with something that actually distinguishes the outcomes — e.g. asserting the rebuilt closure cell's contents survived rather than pruned to _Missing, which is what the gate the test now exercises decides. Fix this →

Verified as correct, for the record: the new RaisingNameProxy test does raise RuntimeError out of the reducer on the parent commit (getattr with a default swallows only AttributeError), and the monkeypatch test genuinely lands on the __dict__ clause — PlainMethods defines no __getattr__, so "global_add" in obj.__dict__ is what returns explicit, and ablating it makes the self-referential getattr() reconstruction fail at load as described. The <locals> vs. wraps claim also holds: guards.py:4641 returns before the gate, guards.py:4651 consults it.

I could not execute the test plan — this checkout has no built torch (no torch/version.py, no .so, no build/) and no .venv, so all four commands would fail at import. Everything above is from reading the code. Note also that -k test_rebuilt_module_method_that_cannot_be_referenced in the PR description matches nothing; the test asserting __name__ == "forward" is test_bound_method_of_a_module_keeps_its_function (line 1768).

Recommendation

Approve — the reducer fix is correct and each new test pins a real shape that was previously unguarded. Nothing here blocks landing; the name-read placement is the one I would fix before merge, since it makes the code disagree with the comment sitting two lines under it.

| Branch: `gh/bobrenjc93/1161/head`

… longer overflows on a deep list)

[ghstack-poisoned]
@bobrenjc93 bobrenjc93 added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 11, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

This was referenced Sep 11, 2026
@bobrenjc93
bobrenjc93 marked this pull request as ready for review September 12, 2026 03:11
@bobrenjc93
bobrenjc93 requested a review from aorenste September 12, 2026 03:11
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable)

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

@github-actions
github-actions Bot deleted the gh/bobrenjc93/1161/head branch November 19, 2026 01:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants