Skip to content

[dynamo] Seed a guarded bound method's function so it is rebuilt, not pruned - #196481

Closed
bobrenjc93 wants to merge 11 commits into
gh/bobrenjc93/1146/basefrom
gh/bobrenjc93/1146/head
Closed

bobrenjc93 wants to merge 11 commits into
gh/bobrenjc93/1146/basefrom
gh/bobrenjc93/1146/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

A bound method is two objects, a function and a receiver, and a guard on it
can depend on the function without ever registering it:

def target(self, x):
    return x

@functools.wraps(target)      # copies target's __module__ and __qualname__
def wrapper(self, x):
    return x * 3

class Recv:
    pass

class M(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.cb = types.MethodType(wrapper, Recv())

    def forward(self, x):
        if self.cb.__name__ == "target":
            x = x + 1
        return x * 2

Guards are not strings Dynamo evals. They are a tree of guard managers, one
node per value, and the edge from a parent node to a child is an ACCESSOR: the
one step that gets from the parent's value to the child's ("look up key cb",
"read attribute __name__"). The checks themselves (TYPE_MATCH, EQUALS_MATCH)
hang off the node whose value they test, and a check walks the tree top down:
fetch self from the frame's locals, take its __dict__, look up cb in it,
getattr __name__, compare. A method has no __name__ of its own; Python
forwards method.__name__ to method.__func__.__name__. The tree does not see
that hop, so the guard hangs directly off the method's node (TORCH_LOGS=guards):

L['self']              accessed_by FrameLocalsGuardAccessor('self')  # the module
  L['self'].__dict__   accessed_by GetGenericDictGuardAccessor      # nn.Module attrs live here
    L['self'].cb       accessed_by DictGetItemGuardAccessor('cb')   # the bound method
      L['self'].cb.__name__  accessed_by GetAttrGuardAccessor(__name__)
        EQUALS_MATCH: == 'target'

Two earlier rules meet here. _reduce_bound_method saves a method whose name
does not resolve back on the receiver (Recv has no cb) explicitly as the
pair (func, receiver), so pickle goes on to serialize wrapper as a value.
The fqn-mismatch rule then rebuilds a function from its code object if it is
in guard_tree_values and replaces it with _Missing("fqn mismatch") if not.
The builder registers the value of each node it builds through
get_guard_manager_from_source (the __dict__ node is created inline by
get_generic_dict_manager and is not registered, which changes nothing here):

L['self']              -> the module         registered
L['self'].__dict__     -> the module's dict  not registered (inline node)
L['self'].cb           -> the bound method   registered
L['self'].cb.__name__  -> 'target'           registered
wrapper                                      NOT registered

The function is consulted only by CPython's attribute forwarding while the
GetAttrGuardAccessor(__name__) accessor runs, never as a node's value. So the
function the guard depends on is exactly what the pruning rule sees as
untouched. At load the tree is rebuilt by walking the same four steps on the
reconstructed locals to re-derive each node's value, and the last step does:

method = types.MethodType(_Missing("fqn mismatch"), Recv())
method.__name__     # AttributeError while the guard manager is rebuilt

The seed cannot live in the reducer. Pickle memoizes every object the first
time it meets it, and it walks the module __dict__ in insertion order:

self.other = wrapper                          # plain attribute, inserted first
self.cb = types.MethodType(wrapper, Recv())

Pickle reaches wrapper through other, writes the sentinel and memoizes
that by identity; when the reducer later sees cb and registers the function,
pickle only emits a back-reference to the sentinel already written. A seed in
pickle_guards_state's leaf loop is no better, since a method inside an
attribute is not a leaf of the local scope.

Register the method's __func__ where the method's own guard manager is
built, in GuardBuilder.get_guard_manager_from_source. Every method anywhere
in the guard tree passes there before anything is pickled, and guard state is
pickled exactly once per builder, so that single seed covers every path pickle
can take to the function:

example_value = self.get(source)
self.guard_tree_values[id(example_value)] = example_value
if self.save_guards and inspect.ismethod(example_value):
    func = example_value.__func__
    if inspect.isfunction(func):
        self.guard_tree_values[id(func)] = func

Only a plain function is seeded: MethodType accepts any callable, and a
functools.partial or builtin __func__ cannot be rebuilt by value, so
seeding it would just make _prune carry it verbatim wherever else it
appears.

Test Plan:

python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k test_guard_rooted_at_fqn_mismatched_bound_method
python test/dynamo/test_package.py -k test_bound_method_name_guard_survives_func_reached_first

Both targeted tests error on the previous commit. The test_package test drives
a full caching_precompile save and reload with the function reached first,
under fail_on_recompile, then renames the function's __name__ and checks
the reloaded guard rejects (a fail_on_recompile RuntimeError), so it pins
that the guard really reads the rebuilt function rather than that nothing
crashed.

Authored with an AI assistant.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit ad844c3 with merge base 32d114b (image):
💚 Looks good so far! There are no failures yet. 💚

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

  • Correctness
    • The seed at torch/_dynamo/guards.py:1736-1739 writes id(__func__) into guard_tree_values, exactly the key the reducer's fqn-mismatch branch tests at :4680 before returning _Missing.
    • inspect.isfunction(func) mirrors the only consumer, the elif inspect.isfunction(obj) branch at :4658, so a partial/builtin __func__ is not added to the _keep set at :4357.
    • The self.save_guards gate is sound: every guard_tree_values read is in GuardsStatePickler or pickle_guards_state (:4762), reachable only under if save_guards: at :5018, and each builder gets a fresh dict at :1388.
  • Preservation
    • Purely additive: no branch, validation, or error handling is removed, and the unconditional registration at :1724 is untouched.
  • Testing
    • test_guard_serialization.py:2107 asserts behavior, not just absence of a raise: _test_check_fn(..., True) then inner.scale_flag = 3.0 and _test_check_fn(..., False), restoring from old_value.
    • test_package.py:699 drives a real caching_precompile save/reload under fail_on_recompile, renames _bound_method_guard_wrapper.__name__, and asserts the reloaded guard rejects.
    • test_package.py:708-709 asserts the other-before-cb __dict__ order the pickle-memoization scenario depends on, so a reorder fails loudly.
  • Scope
    • One production hunk of four code lines in get_guard_manager_from_source plus two tests; no public API, build, or CI file touched, and inspect is already imported at guards.py:27.

reason: clean
Reviewed commit: ad844c3

Inference job

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 9, 2026
bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
… pruned

A guard rooted at a bound method (`self.cb.__name__ == ...`) reads through
`method.__func__`. `_reduce_bound_method` carries that function explicitly,
but the function itself was not in `guard_tree_values`: an fqn-mismatched
`__func__` therefore reduced to `_Missing("fqn mismatch")` and the load
AttributeError'd on `__name__`. Worse, this was order-dependent: if the same
function was ALSO reachable as a plain attribute inserted earlier
(`self.other = wrapper`), pickle memoized the sentinel before it ever reached
the method, so the seed has to be in place before `dump` starts.

Register the method's `__func__` in `guard_tree_values` in three places, each
covering a window the others cannot: in `GuardBuilder.get_guard_manager_from_source`
when the method's own guard manager is built (every method a guard is rooted
at passes here, before any pickling); in `pickle_guards_state` over the
local-scope leaves, before `missing_values` is populated, because
`reducer_override` consults `missing_values` first; and inside
`reducer_override` itself for a kept method, which makes the bound-method
branch a fixed point -- the guard policy serializes guard state twice, and by
the second pass a method's receiver may already have degraded to a sentinel,
so emitting the `(func, self)` binding unconditionally keeps the second pass
stable instead of re-pinning the method's TYPE_MATCH to `_Missing`.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k test_guard_rooted_at_fqn_mismatched_bound_method
python test/dynamo/test_package.py -k test_bound_method_name_guard_survives_func_reached_first
```

Both targeted tests error on the previous commit. The test_package test drives
a full `caching_precompile` save and reload with the function reached first,
under `fail_on_recompile`.

Authored with an AI assistant.


ghstack-source-id: 9e2d54f
Pull-Request: #196481
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
… pruned

A guard rooted at a bound method (`self.cb.__name__ == ...`) reads through
`method.__func__`. `_reduce_bound_method` carries that function explicitly,
but the function itself was not in `guard_tree_values`: an fqn-mismatched
`__func__` therefore reduced to `_Missing("fqn mismatch")` and the load
AttributeError'd on `__name__`. Worse, this was order-dependent: if the same
function was ALSO reachable as a plain attribute inserted earlier
(`self.other = wrapper`), pickle memoized the sentinel before it ever reached
the method, so the seed has to be in place before `dump` starts.

Register the method's `__func__` in `guard_tree_values` in three places, each
covering a window the others cannot: in `GuardBuilder.get_guard_manager_from_source`
when the method's own guard manager is built (every method a guard is rooted
at passes here, before any pickling); in `pickle_guards_state` over the
local-scope leaves, before `missing_values` is populated, because
`reducer_override` consults `missing_values` first; and inside
`reducer_override` itself for a kept method, which makes the bound-method
branch a fixed point -- the guard policy serializes guard state twice, and by
the second pass a method's receiver may already have degraded to a sentinel,
so emitting the `(func, self)` binding unconditionally keeps the second pass
stable instead of re-pinning the method's TYPE_MATCH to `_Missing`.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k test_guard_rooted_at_fqn_mismatched_bound_method
python test/dynamo/test_package.py -k test_bound_method_name_guard_survives_func_reached_first
```

Both targeted tests error on the previous commit. The test_package test drives
a full `caching_precompile` save and reload with the function reached first,
under `fail_on_recompile`.

Authored with an AI assistant.


ghstack-source-id: 6482c3f
Pull-Request: #196481
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 15m 37s —— View job


PR Review: #196481

Two of the three seedings look like dead code, and the commit message justifies one of them with a claim about the code (guard state is serialized twice) that I could not substantiate.

Full review

PR Review: #196481

Summary

Seeds a guarded bound method's __func__ into guard_tree_values so an fqn-mismatched __func__ is rebuilt by value rather than reduced to _Missing. The bug and the fix at guards.py:1718-1727 are real and correctly placed, but the other two seedings appear unreachable-as-useful, and the commit message's justification for one of them rests on a claim about the code I could not verify.

Code Quality

  • torch/_dynamo/guards.py:4699-4703 is dead code. The write is gated on self._keep(obj), i.e. id(obj) in self.guard_tree_values. The only production write that can put a bound method into guard_tree_values is line 1717 in get_guard_manager_from_source — line 4559 only inserts inner tensors of traceable wrapper subclasses, and lines 4703/4793 are the new hunks themselves. So _keep(obj) is true only when line 1717 recorded this exact method, and in that case the new lines 1724-1727 already did setdefault(id(obj.__func__), obj.__func__) in the same pass. The assignment can only ever re-write an entry that is already there. No in-repo GuardsStatePickler unit test reaches it either: every direct construction that passes a method (test_guard_serialization.py:1310, :1324, :1335, test_opaque_obj_v2.py:1183) passes an empty or tensor-only guard_tree_values, so _keep(m) is False there too.

  • torch/_dynamo/guards.py:4787-4793 is dead code for the same reason, and it is strictly weaker than hunk (A): it is gated on the identical condition (id(leaf) in guard_tree_values), it only visits local_scope pytree leaves rather than every guard-rooted value, and it runs after guard building has completed. Its stated rationale in the comment — "register the func here, before missing_values is populated below" — does not hold up: the elif id(leaf) not in guard_tree_values branch at line 4803 keys on the leaf, so it can never enter a func that hunk (A) already registered into missing_values. Note also that hunk (C) adds a second full pass over leaves immediately before the existing one, when the guard, being a strict subset of the existing loop's condition, could have been folded into it — but the recommendation is to drop it, not fold it.

  • The commit message's justification for hunk (B) describes behavior I cannot find in the code. It says "the guard policy serializes guard state twice, and by the second pass a method's receiver may already have degraded to a sentinel". pickle_guards_state is reached only from serialize_guards (guards.py:5221), which is called exactly once per CheckFunctionManager, under if save_guards: at guards.py:5047. The double guard-build at guards.py:4946 / :4969 is real, but the pre-filter build passes save_guards=False and its builder — with its own fresh guard_tree_values (initialized per-builder at guards.py:1383) — is discarded; only the second builder reaches the pickler. If there is a second serialization pass I am missing (something in PrecompileContext / caching_precompile re-entering serialize_guards on the same builder), please point at it, because the whole argument for (B) hangs on it. If not, please drop (B) and (C) and keep only (A), whose comment already states the correct and sufficient invariant ("Seed it here, where every method a guard is rooted at is already known, so pickle ordering cannot beat it").

    Three overlapping mechanisms for one invariant is also a maintenance cost independent of correctness: a future reader cannot tell which one the tests actually exercise, and the two redundant ones will be preserved through refactors on the assumption that something depends on them. If (B) and (C) are being kept deliberately as belt-and-braces against a shape you have seen but cannot express as a test, say so in the comment explicitly — "defensive; (A) should already cover this" — rather than giving each a distinct-sounding rationale that reads as load-bearing.

Testing

  • Both new tests exercise the path that hunk (A) fixes; neither can distinguish (A) from (B)/(C), which is consistent with (B) and (C) being redundant. Please confirm empirically before landing: reverting only (A) should fail both tests, while reverting only (B) or only (C) should fail neither. If a revert of (B) or (C) does fail something, that is the missing evidence and the corresponding comment should name the test.

  • test/dynamo/test_guard_serialization.py:1666-1673 hardcodes the restore value: inner.scale_flag = 3.0 inside try, finally: inner.scale_flag = 2.0. 2.0 is correct today — keep_attribute (test_guard_serialization.py:103-104) sets func.scale_flag = 2.0 at decoration time on exactly this __wrapped__ function — but this mutates a module-level object that the parametrized FQN_MISMATCH_CASES "attribute" subtest (:560) also mutates, so a wrong restore silently corrupts a sibling test rather than failing here. The existing parametrized test at :1518-1523 already does this correctly with old_value = getattr(inner, attr); follow that pattern instead of duplicating the decorator's constant.

  • test/dynamo/test_package.py:607 (test_bound_method_name_guard_survives_func_reached_first) depends on self.other being inserted into the module __dict__ before self.cb to get the pickle-ordering it is testing. That ordering requirement is explained in the class comment at :66-72 but not restated at the assignment site (:76-78), where someone reordering two innocuous-looking attribute assignments would break the regression coverage without any test failing. A one-line note at the assignment ("order matters: see class comment") would protect it.

Recommendation

Needs Discussion

Hunk (A) at guards.py:1718-1727 looks correct and sufficient. I would like the double-serialization claim substantiated or the commit message corrected, and (B)/(C) either removed or re-commented as explicitly defensive, before this lands. The test-hygiene items are small but should be fixed in the same pass.

· Branch: `gh/bobrenjc93/1146/head`

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
… pruned

A guard rooted at a bound method (`self.cb.__name__ == ...`) reads through
`method.__func__`. `_reduce_bound_method` carries that function explicitly,
but the function itself was not in `guard_tree_values`: an fqn-mismatched
`__func__` therefore reduced to `_Missing("fqn mismatch")` and the load
AttributeError'd on `__name__`. The seed also cannot wait for the reducer to
see the method: if the same function is reachable as a plain attribute
inserted earlier (`self.other = wrapper`), pickle has memoized the sentinel
before it reaches the method.

Register the method's `__func__` in `guard_tree_values` where the method's own
guard manager is built, in `GuardBuilder.get_guard_manager_from_source`. Every
method a guard is rooted at passes there before anything is pickled, and guard
state is pickled exactly once per builder, so that single seed suffices; a
seed in the reducer or in `pickle_guards_state`'s leaf loop can never fire for
a method the builder did not already see.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k test_guard_rooted_at_fqn_mismatched_bound_method
python test/dynamo/test_package.py -k test_bound_method_name_guard_survives_func_reached_first
```

Both targeted tests error on the previous commit. The test_package test drives
a full `caching_precompile` save and reload with the function reached first,
under `fail_on_recompile`.

Authored with an AI assistant.

ghstack-source-id: 05c90e9
Pull-Request: #196481
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Sep 9, 2026
… pruned

A guard rooted at a bound method (`self.cb.__name__ == ...`) reads through
`method.__func__`. `_reduce_bound_method` carries that function explicitly,
but the function itself was not in `guard_tree_values`: an fqn-mismatched
`__func__` therefore reduced to `_Missing("fqn mismatch")` and the load
AttributeError'd on `__name__`. The seed also cannot wait for the reducer to
see the method: if the same function is reachable as a plain attribute
inserted earlier (`self.other = wrapper`), pickle has memoized the sentinel
before it reaches the method.

Register the method's `__func__` in `guard_tree_values` where the method's own
guard manager is built, in `GuardBuilder.get_guard_manager_from_source`. Every
method a guard is rooted at passes there before anything is pickled, and guard
state is pickled exactly once per builder, so that single seed suffices; a
seed in the reducer or in `pickle_guards_state`'s leaf loop can never fire for
a method the builder did not already see.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k test_guard_rooted_at_fqn_mismatched_bound_method
python test/dynamo/test_package.py -k test_bound_method_name_guard_survives_func_reached_first
```

Both targeted tests error on the previous commit. The test_package test drives
a full `caching_precompile` save and reload with the function reached first,
under `fail_on_recompile`.

Authored with an AI assistant.

ghstack-source-id: 9dd6c49
Pull-Request: #196481
@bobrenjc93 bobrenjc93 added the topic: not user facing topic category label Sep 9, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Updated. The review above ran against the previous head; the reducer and leaf-loop seeds and the double-serialization claim were already removed in that update. From the remaining points: the bound-method test restores scale_flag from the saved value, and the assignment order in BoundMethodNameGuardModule.__init__ is called out at the assignment site.

@claude

@claude

claude Bot commented Sep 9, 2026 •

Copy link
Copy Markdown

Claude finished @bobrenjc93's task in 52m 47s —— View job


Re-review: #196481

Confirmed the three earlier points are addressed; one remaining suggestion — the seed fires for any MethodType, but only a __func__ that is a real function can ever be rebuilt by value, so seeding a functools.partial/builtin __func__ adds it to the keep set with no upside.

Full review

PR Review: #196481

Summary

Seeds a guarded bound method's __func__ into guard_tree_values so an fqn-mismatched __func__ is rebuilt by value instead of pruned to _Missing. Previous round's points are resolved: the diff against origin/gh/bobrenjc93/1146/base now contains exactly one production hunk (torch/_dynamo/guards.py:1723-1732), the double-serialization claim is gone from both the comment and the commit message, test_guard_serialization.py:2011-2015 restores scale_flag from old_value = inner.scale_flag, and test_package.py:75 carries the ordering note at the assignment. Three items remain, all narrow.

Code Quality

  • torch/_dynamo/guards.py:1729 seeds too broadly: gate on inspect.isfunction(example_value.__func__), not just inspect.ismethod(example_value). types.MethodType accepts any callable, and _reduce_bound_method itself is written for that (package.py:296-299 explicitly handles a __func__ with no __name__). For types.MethodType(functools.partial(f), obj) or types.MethodType(len, obj) the seed registers the partial/builtin in guard_tree_values, but the reducer branch that consumes the seed is elif inspect.isfunction(obj) (guards.py:4616-4637) — a partial never reaches it, so the entry buys nothing there. It is not inert, though: guard_tree_values is the keep set for _keep (guards.py:4336), so that partial is now carried verbatim by _prune wherever else it appears — a module global in a _globals_snapshot (guards.py:4382), a __defaults__/__dict__ slot (:4421, :4438), a closure cell's contents (:4397) — and functools.partial.__reduce__ carries its args with no pruning, so an unpicklable neighbour can now fail a dump that previously sentinelled it. Matching the reducer's isfunction gate also keeps payload growth to exactly the funcs the reducer rebuilds; each newly kept func costs a full serialized code object where all of them previously shared one interned _Missing (guards.py:4340-4342). Fix this →

  • The self.save_guards half of the gate is inconsistent with the line directly above it. guards.py:1722 writes self.guard_tree_values[id(example_value)] = example_value with no save_guards check, and guard_tree_values is read only on the save path — every read is inside GuardsStatePickler (guards.py:4336, :4486, :4529, :4535, :4635, :4649) or pickle_guards_state (:4727, :4733), both reachable only under if save_guards: (guards.py:4973), and the two builders each get their own dict (:1385), so the discarded pre-filter builder cannot lose a seed the real one needs. The gate is therefore a memory micro-opt on a dict that is already populated unconditionally one line earlier. The trailing comment ("Save-path only (read by the serializer)") is equally true of line 1722, so as written it explains a gate whose absence would be just as correct. Either drop self.save_guards and to match the neighbouring write, or say in the comment that the gate exists only to keep the non-serializing path from growing the dict.

Testing

  • Neither new test asserts the thing it is protecting, so both pass by not raising and can silently stop covering the fix. In test_guard_serialization.py:1995, coverage depends on _test_serialization's guard_filter_fn (:1023-1029) keeping only EQUALS_MATCH: calling f(x) inside fn makes Dynamo build AttrSource(self.source, "__func__") (variables/user_defined.py:3188), and if any guard on f.__func__ were ever retained, get_guard_manager_from_source would register the func at guards.py:1722 regardless of the new seed and the test would keep passing while testing nothing. In test_package.py:647, coverage depends on self.other preceding self.cb in __dict__ insertion order — now commented at :75, but still unasserted. One assertion covers both: after reload, check the deserialized method's __func__ is a real function rather than a _Missing sentinel (e.g. self.assertTrue(inspect.isfunction(loaded_state...__func__)) in test 1, or assert on mod.__dict__ key order in test 2). Fix this →

Recommendation

Approve

The remaining production concern is a one-predicate narrowing at guards.py:1729; I would land it in this PR since the seed is the whole change, but it does not block. The save_guards gate wording and the test assertions are small and can ride along.

· Branch: `gh/bobrenjc93/1146/head`

bobrenjc93 added a commit that referenced this pull request Sep 11, 2026
… pruned

A bound method is two objects, a function and a receiver, and a guard on it
can depend on the function without ever registering it:

```python
def target(self, x):
    return x

@functools.wraps(target)      # copies target's __module__ and __qualname__
def wrapper(self, x):
    return x * 3

class Recv:
    pass

class M(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.cb = types.MethodType(wrapper, Recv())

    def forward(self, x):
        if self.cb.__name__ == "target":
            x = x + 1
        return x * 2
```

Guards are not strings Dynamo evals. They are a tree of guard managers, one
node per value, and the edge from a parent node to a child is an ACCESSOR: the
one step that gets from the parent's value to the child's ("look up key `cb`",
"read attribute `__name__`"). The checks themselves (TYPE_MATCH, EQUALS_MATCH)
hang off the node whose value they test, and a check walks the tree top down:
take the locals dict, fetch `self`, fetch `cb` off it, getattr `__name__`,
compare. A method has no `__name__` of its own; Python forwards
`method.__name__` to `method.__func__.__name__`. The tree does not see that
hop, so the guard hangs directly off the method's node:

```python
L['self']              accessed_by DictGetItem('self')   # the module
  L['self'].cb         accessed_by DictGetItem('cb')     # the bound method
    L['self'].cb.__name__  accessed_by GetAttr('__name__')
      EQUALS_MATCH: == 'target'
```

Two earlier rules meet here. `_reduce_bound_method` saves a method whose name
does not resolve back on the receiver (`Recv` has no `cb`) explicitly as the
pair `(func, receiver)`, so pickle goes on to serialize `wrapper` as a value.
The fqn-mismatch rule then rebuilds a function from its code object if it is
in `guard_tree_values` and replaces it with `_Missing("fqn mismatch")` if not.
The builder registers the value of each node it builds:

```python
L['self']              -> the module         registered
L['self'].cb           -> the bound method   registered
L['self'].cb.__name__  -> 'target'           registered
wrapper                                      NOT registered
```

The function is consulted only by CPython's attribute forwarding while the
`GetAttr('__name__')` accessor runs, never as a node's value. So the function
the guard depends on is exactly what the pruning rule sees as untouched. At
load the tree is rebuilt by walking the same three steps on the reconstructed
locals to re-derive each node's value, and the third step does:

```python
method = types.MethodType(_Missing("fqn mismatch"), Recv())
method.__name__     # AttributeError while the guard manager is rebuilt
```

The seed cannot live in the reducer. Pickle memoizes every object the first
time it meets it, and it walks the module `__dict__` in insertion order:

```python
self.other = wrapper                          # plain attribute, inserted first
self.cb = types.MethodType(wrapper, Recv())
```

Pickle reaches `wrapper` through `other`, writes the sentinel and memoizes
that by identity; when the reducer later sees `cb` and registers the function,
pickle only emits a back-reference to the sentinel already written. A seed in
`pickle_guards_state`'s leaf loop is no better, since a method inside an
attribute is not a leaf of the local scope.

Register the method's `__func__` where the method's own guard manager is
built, in `GuardBuilder.get_guard_manager_from_source`. Every method anywhere
in the guard tree passes there before anything is pickled, and guard state is
pickled exactly once per builder, so that single seed covers every path pickle
can take to the function:

```python
example_value = self.get(source)
self.guard_tree_values[id(example_value)] = example_value
if self.save_guards and inspect.ismethod(example_value):
    func = example_value.__func__
    if inspect.isfunction(func):
        self.guard_tree_values[id(func)] = func
```

Only a plain function is seeded: `MethodType` accepts any callable, and a
`functools.partial` or builtin `__func__` cannot be rebuilt by value, so
seeding it would just make `_prune` carry it verbatim wherever else it
appears.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_package.py
python test/dynamo/test_guard_serialization.py -k test_guard_rooted_at_fqn_mismatched_bound_method
python test/dynamo/test_package.py -k test_bound_method_name_guard_survives_func_reached_first
```

Both targeted tests error on the previous commit. The test_package test drives
a full `caching_precompile` save and reload with the function reached first,
under `fail_on_recompile`.

Authored with an AI assistant.

ghstack-source-id: 62379be
Pull-Request: #196481
… check, root-verdict caching, scope-first reduce tuple, load-bearing tests

[ghstack-poisoned]
@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 0 checks:

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473

[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Sep 11, 2026
… getattr cannot resolve it (#196473)

A bound method (`obj.method`) is a pair: the function, and the object it was
fetched from -- the receiver, the `self` it will run against. Normally the pair
comes from a class attribute lookup, so it can be re-derived: `getattr(obj,
"method")` gives it back. Python also lets you build the pair by hand with
`types.MethodType(func, obj)`, in which case `obj`'s class may have no
attribute of that name at all. pickle's built-in rule for a bound method
stores the receiver and the NAME and does `getattr(receiver, name)` at load;
it never stores the function. The guard pickler therefore has an explicit
alternative that stores `(func, receiver)` -- the function by value (its code
object, rebuilt with `types.FunctionType`) and the receiver as the pickler
would store it anyway -- and rebuilds with `types.MethodType`.

Dynamo needs this whenever a compiled function receives a bound method:

    def on_step(state, x):
        return x + state.offset

    class State:
        offset = 1

    callback = types.MethodType(on_step, State())  # bind the state as `self`

    def fn(f, x):
        if callable(f):
            x = x + 1
        return f(x)

    torch.compile(fn)(callback, torch.randn(3))

`callable(f)` installs a TYPE_MATCH on `f`, and inlining `f(x)` adds an
ID_MATCH on `f.__func__.__code__` and a TYPE_MATCH on `f.__self__`. To
precompile, the bound method object is pickled with the guard state, and at
load those sources are re-walked against the reconstructed object, so it must
carry the same function and the same receiver.

The old code chose between pickle's rule and the explicit pair with a probe,
`getattr(receiver, func.__name__)`, taking the explicit pair only when the
probe did not return the same function. The probe was the bug:

- For `callback` it ran `getattr(State(), "on_step")`; `State` has no such
  attribute, and the AttributeError escaped the reducer: a PackageError under
  strict precompile, a bypass of a fine frame otherwise (an internal error
  before #196470 mapped every reducer exception to a PackageError). pickle's rule would have failed the same way at
  load, so the explicit pair is the only form that works here.
- A `functools.partial` as the method's function has no `__name__`, so the
  probe raised before looking anything up.
- A class holding the function as a `staticmethod` under that name makes the
  probe return the raw function, so `func is inner` held, pickle's rule ran,
  and the object loaded back as a plain function where a bound method was.
- Any receiver whose class defines `__getattr__` -- every nn.Module -- runs
  that user code in the probe, which can have side effects or recurse. And its
  answer means nothing for this pickler: a non-referenceable module is rebuilt
  as a bare `torch.nn.Module` placeholder at load, on which `getattr` would
  not find `forward`.

The nn.Module case also shows why the explicit pair, not the class, is what
makes the method reloadable. A module whose class is not a module-level name
cannot be pickled by reference, so the guard pickler stores its state and
rebuilds it as a plain `torch.nn.Module` with that state; the class is
forgotten. pickle's rule would then look `forward` up on the plain module and
find nn.Module's placeholder. With the explicit pair the loaded method is that
plain module with `forward`'s own code attached by `types.MethodType`, which is
all the guards read (the pickler-level test pins this; end to end this exact
shape is refused earlier by the local-class TYPE_MATCH check).

The fix moves the decision into `FunctionPicklerBase._reduce_bound_method`,
which stores the explicit pair unless it can PROVE pickle's rule will produce
the same bound method at load:

1. A receiver whose class defines `__getattr__` is never probed; the pair is
   stored without touching the instance. This is deliberately coarse; a false
   "store the pair" is still correct, and narrowing it per name with
   `getattr_static` at every guard build buys nothing but cost.
2. A name served per instance (in the instance `__dict__`, or a `__slots__`
   member) is stored as the pair: `getattr` at load hands back whatever the
   dict or slot holds -- a raw function or a method bound to another object --
   never a method over this pair (and in the self-cycle case the slot is not
   restored yet).
3. Otherwise probe, under a `try`: `getattr(receiver, name)` can raise anything
   through a `__getattribute__` override, a property or a metaclass
   `__getattr__`, and any exception falls back to the pair instead of escaping
   the reducer. A function without `__name__` skips the probe.
4. pickle's rule is taken only on proof: the probe must return a method bound
   to THIS receiver over THIS function (`inspect.ismethod(inner) and
   inner.__func__ is func and inner.__self__ is receiver`).

A method the class genuinely supplies to a plain instance still takes pickle's
compact rule, so ordinary bound methods pickle exactly as before.

Test Plan:

```
python test/dynamo/test_guard_serialization.py
python test/dynamo/test_guard_serialization.py -k bound_method
```

Eight of the thirteen tests matched by the second command fail or error
against the previous commit's logic: seven new pickler-level tests (name self
lacks, slot, `__getattr__` proxy, raising probes, staticmethod name, a
`functools.partial` as `__func__`, the nn.Module method) and the one new
capture test. The fall-through test pins that plain methods and classmethods
keep pickle's compact `getattr` form (an always-explicit implementation fails
it); the four pre-existing `bound_method` capture tests pass on both. A known
gap closed by #196481: an nn.Module method whose `__func__` is fqn-mismatched
now reaches the `isfunction` branch and is pruned to `_Missing` unless a guard
registers the function, where pickle's name-based rule never needed the fqn.
The staticmethod case also fails against a plain `func is inner` check,
loading a function. The proxy test asserts the receiver's `__getattr__` was
never asked for the method name (pickle itself may probe protocol names on
the instance); the nn.Module test uses a function-local class so the receiver
is rebuilt as a bare `nn.Module`, where the default reconstruction would
resolve `forward` to the placeholder.

Authored with an AI assistant.

FAQ

Q: Should the `__getattr__` gate be narrowed with `getattr_static` so that
nn.Module methods stay on pickle's default path?

A: No. The default path rebuilds the method as `getattr(self, name)` on the
RELOADED receiver, and `GuardsStatePickler` rebuilds any nn.Module whose class
cannot be pickled by reference as a bare `torch.nn.Module`, on which `forward`
resolves to `_forward_unimplemented`. Empirically the narrowed gate loads that
placeholder and raises `NotImplementedError` on call; the coarse gate loads the
right function. A class-body lambda `forward` on a module-level class degrades
to `_Missing` under both gates, because the name a bound method reduces by is
`__func__.__name__`, i.e. `<lambda>`, not `forward` (on a function-local class
its qualname contains `<locals>`, so it is rebuilt from its code object and
loads fine); it raised `AttributeError` before this change, so it is not a
regression. The same fact covers the `functools.partial` case: pickle's own
`method.__reduce__` reads `__func__.__name__`, so a partial `__func__` is
unpicklable on the default path regardless of this reducer.

Q: Could the three receiver tests be one parametrized test?

A: Each asserts something different (the bound-method type for the
staticmethod case, `.func` of the partial, the receiver class for the module)
and documents a distinct failure mode; a shared body would need per-case
assertions.

Pull Request resolved: #196473
Approved by: https://github.com/pytorchgreenlight, https://github.com/aorenste
ghstack dependencies: #196505, #196470, #196471, #196472
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1146/head branch November 18, 2026 01:46
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