Repository navigation
[dynamo] Seed a guarded bound method's function so it is rebuilt, not pruned - #196481
bobrenjc93 wants to merge 11 commits into
Conversation
[ghstack-poisoned]
🔗 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 FailuresAs of commit ad844c3 with merge base 32d114b ( GREEN LIGHT - PR approved to be merged without human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
… 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]
… 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
|
Claude finished @bobrenjc93's task in 15m 37s —— View job PR Review: #196481Two of the three seedings look like dead code, and the commit message justifies one of them with a claim about the code ( Full reviewPR Review: #196481SummarySeeds a guarded bound method's Code Quality
Testing
RecommendationNeeds Discussion Hunk (A) at |
[ghstack-poisoned]
… 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]
… 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
|
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 |
|
Claude finished @bobrenjc93's task in 52m 47s —— View job Re-review: #196481Confirmed the three earlier points are addressed; one remaining suggestion — the seed fires for any Full reviewPR Review: #196481SummarySeeds a guarded bound method's Code Quality
Testing
RecommendationApprove The remaining production concern is a one-predicate narrowing at |
… 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]
|
@pytorchbot merge -i |
Merge startedYour 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 |
Merge failedReason: Merge rule check failed for stacked PR #196473: 4 mandatory check(s) failed. The first few are:
Dig deeper by viewing the failures on hud |
…educer, leaned/parked folded into the __dict__ commit, warnings name code objects and modules, load-bearing tests) + 3.10 fix in #196473 [ghstack-poisoned]
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
… 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
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:
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
selffrom the frame's locals, take its__dict__, look upcbin it,getattr
__name__, compare. A method has no__name__of its own; Pythonforwards
method.__name__tomethod.__func__.__name__. The tree does not seethat hop, so the guard hangs directly off the method's node (TORCH_LOGS=guards):
Two earlier rules meet here.
_reduce_bound_methodsaves a method whose namedoes not resolve back on the receiver (
Recvhas nocb) explicitly as thepair
(func, receiver), so pickle goes on to serializewrapperas a value.The fqn-mismatch rule then rebuilds a function from its code object if it is
in
guard_tree_valuesand 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 byget_generic_dict_managerand is not registered, which changes nothing here):The function is consulted only by CPython's attribute forwarding while the
GetAttrGuardAccessor(__name__)accessor runs, never as a node's value. So thefunction 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:
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:Pickle reaches
wrapperthroughother, writes the sentinel and memoizesthat by identity; when the reducer later sees
cband 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 anattribute is not a leaf of the local scope.
Register the method's
__func__where the method's own guard manager isbuilt, in
GuardBuilder.get_guard_manager_from_source. Every method anywherein 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:
Only a plain function is seeded:
MethodTypeaccepts any callable, and afunctools.partialor builtin__func__cannot be rebuilt by value, soseeding it would just make
_prunecarry it verbatim wherever else itappears.
Test Plan:
Both targeted tests error on the previous commit. The test_package test drives
a full
caching_precompilesave and reload with the function reached first,under
fail_on_recompile, then renames the function's__name__and checksthe reloaded guard rejects (a
fail_on_recompileRuntimeError), so it pinsthat the guard really reads the rebuilt function rather than that nothing
crashed.
Authored with an AI assistant.