Repository navigation
[aot_compile] Rebuild AOTCompilePickler on FunctionPicklerBase - #196685
bobrenjc93 wants to merge 9 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196685
Note: Links to docs will display an error until the docs builds have been completed. ❌ You can merge normally! (1 Unrelated Failure), 1 Unclassified FailureAs of commit d134882 with merge base 0929b23 ( GREEN LIGHT - PR approved to be merged without human review:
reason: UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:
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. |
…e guard, load-bearing tests [ghstack-poisoned]
… check, root-verdict caching, scope-first reduce tuple, load-bearing tests [ghstack-poisoned]
|
Claude finished @bobrenjc93's task in 30m 10s —— View job PR Review: #196685The refactor is mechanically sound, but three of the fixes it claims are pinned only through the sibling guard pickler (not Full reviewPR Review: #196685SummaryRebuilds Backward Compatibility
Code Quality
Testing
RecommendationRequest Changes The (CI is red only with |
A pure move with no behavior change. At this commit the new base class has exactly ONE subclass, `GuardsStatePickler`; the second user is `AOTCompilePickler`, which #196685 (ten commits up this stack) moves onto the base. The extraction happens here so the next five commits have one place to add the by-value function reducers that both picklers will share. `GuardsStatePickler` (guard state) and `AOTCompilePickler` (torch/_dynamo/aot_compile.py, the AOT compile artifact) both have to rebuild objects that pickle cannot do by reference -- code objects, python modules, bound methods -- and each carries its own copy of those reducers. This commit moves `GuardsStatePickler`'s copies into a new `FunctionPicklerBase` in package.py and makes `GuardsStatePickler` subclass it. Bodies are unchanged (one parameter renamed, one return annotation tightened). Until #196685, `AOTCompilePickler` keeps its own copies of these reducers, including the same bugs the commits here fix in the guard pickler (an unguarded `cell_contents` read and the old nested-function rebuild). #196685 changes its base to `FunctionPicklerBase`, deletes the duplicates and rewrites its dispatch around the shared reducers; because the closure-cell, bound-method and by-value function reducers that #196472-#196478 add already live on the base, that commit adds no reducer bodies of its own. The reducers are pickled by reference as `getattr(GuardsStatePickler, name)` (pickle records the bound classmethod's owner), so an artifact records the same reference before and after this move; they have to stay classmethods for that reason. When `AOTCompilePickler` moves onto the base it must consciously replace its own `_unpickle_module` (an `importlib` import) with the inherited `_unpickle_python_module`, since `GuardsStatePickler._unpickle_module` rebuilds an `nn.Module`. guards.py now imports `SerializedCode` at module level (package.py does not import guards.py, so there is no cycle) instead of inside two methods, and drops `import pickle`, whose only use was the base class. Test Plan: ``` python test/dynamo/test_guard_serialization.py ``` Authored with an AI assistant. FAQ Q: The docstring says the base exists "so that a fix cannot be missed in one pickler", but there is exactly one subclass at this commit. A: The same paragraph states that `GuardsStatePickler` is the one subclass today; the clause is the reason `AOTCompilePickler` is moved onto the base separately, not a claim that it already has been. Q: The base shares the reducer bodies, but both `reducer_override`s still duplicate the `iscode`/`ismodule`/`ismethod` dispatch predicates. A: This change is a pure move that prepares the base, and aot_compile.py is deliberately untouched in this stack so the AOT move is one reviewable step. The bound-method predicate does move into the base later in the stack (`FunctionPicklerBase._reduce_bound_method`); the remaining predicates are one-liners whose divergence risk lives in the reducer bodies the base now owns. Pull Request resolved: #196471 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196505, #196470
|
Starting merge as part of PR stack under #196693 |
…its __module__ (#196684) A function rebuilt by value gets `import_module(fn.__module__).__dict__` as its globals at load. For a `functools.wraps` wrapper that is the wrong dict: ```python # decorators.py SCALE = 2 def scaled(func): @functools.wraps(func) def wrapper(x): return func(x) * SCALE # read from wrapper.__globals__ return wrapper # model.py helper = scaled(base) helper.__module__ # 'model', copied from base by wraps helper.__globals__ is sys.modules['decorators'].__dict__ # True ``` Importing `__module__` hands the rebuilt wrapper `model`'s dict, so a call raises NameError on `SCALE`, or silently reads a same-named global of the wrong module. The guard pickler never calls a rebuilt function, so it did not notice; the AOT pickler above this commit does call it. The by-name reduce now carries the compile scope, `fn.__globals__["__name__"]`, as its own argument next to `__module__`: the scope is imported for the globals, `__module__` is restored as an attribute as before. A function whose `__module__` is None still has a scope. A scope of `"__main__"` imports the loading process's `__main__`, which is what pickle itself does for a by-reference `__main__` function: right in-process, and cross-process only as right as the two scripts agree. Both unpicklers now take `(scope, module, code, qualname, name, closure)`, the scope being the module name to import or the snapshot dict itself, so the two reduce tuples differ only in what sits first. The snapshot variant is otherwise unchanged; it already carries the right dict. `AOTCompilePickler` still has its own copy of the old rebuild at this commit (importing `__module__`); #196685 replaces it with the shared one. Both ways to an empty scope -- an import that fails and a scope that is not an importable name (None or "" for a function exec'd into a bare dict) -- log the same debug line, since either surfaces as a NameError at first call for a pickler that calls the function. Two guard-test comments that rationalized the old import of `__module__` are reworded to describe the snapshot and the compile scope; the two-module guard test points at the save-time-value test for what only the snapshot provides, since its wrapper's compile scope is this module's live dict either way. The scope comment also names the one way a scope comes back wrong without being empty: a module that replaced its own `sys.modules` entry with a proxy (`torch.backends.cudnn`), which the old import of `__module__` landed on too. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_guard_serialization.py -k test_rebuilt_wrapper_is_scoped_to_the_module_that_compiled_it ``` The new test wraps a test-module function from an exec-created module and checks the rebuilt wrapper's `__globals__` is that module's dict while its `__module__` is still the test module's, then CALLS it: the wrapper reads a `SCALE` that exists only in the decorator module, so the call resolves the global through the scope the change picks. On the previous commit `__globals__` is the test module's dict and the call raises NameError. The non-str `__module__` test now also asserts the rebuilt function's `__globals__` is its source module's dict, which the previous commit's import of `__module__` left empty. Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196684 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683
|
@pytorchbot merge -i |
Merge startedYour change will be merged while ignoring the following 2 checks: pull, 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 |
…t will not pickle (#196686) A helper the compiled function closes over is rebuilt from its code object at load, and whatever it holds has to survive for the runtime to run it. The previous commit carries what a CALL needs; this one adds `__dict__`, which a decorator commonly writes to: ```python def outer(): def helper(x): return x * 2 helper.tag = 2.0 helper.lock = threading.Lock() # a decorator's bookkeeping return helper helper = outer() def fn(x): return helper(x) + 1 ``` Carried verbatim, `helper.__dict__` fails the save on the lock, for an entry the runtime never reads: `_apply_function_state` assigns `__dict__` back and nothing forces a missing entry. `functools.wraps` makes this the common case, since it stashes `__wrapped__` and copies the wrappee's whole `__dict__` onto the wrapper. So each entry is probed and dropped if it will not pickle: ```python helper.__dict__ -> {"tag": 2.0} # the lock is gone, the save succeeds ``` "Does it pickle?" has no cheaper predicate than trying, and the cache stops a value from being probed twice, not from being dumped again inside an ancestor's probe, so the total work is the reachable bytes times the nesting depth and a user `__reduce__` runs once per probe that reaches it. `_dumps_cleanly` dumps the value into a throwaway pickler of this exact class (same `external_data` and `persistent_id`), memoized by object id in a `_ProbeState` the probe picklers share through the constructor; the always-picklable constants (`FunctionPicklerBase._is_literal`, moved onto the base from the guard pickler) skip the probe. Every probed value is reachable from the function being pickled, which pickle keeps alive until `dump()` returns, so an id is not reused within one dump (a function a user `__reduce__` manufactures inside a probe is not held that way, and a later object at its address would inherit its verdict). A tensor stashed on a function is serialized into the throwaway buffer too, a transient copy of its storage. A recursion overflow counts as unpicklable and is pruned rather than re-raised: a deep-but-finite value in an optional slot must not fail a save that has nothing wrong with it. `__kwdefaults__` stays unpruned: a function cannot be called without it. Three things the probe has to get right from the start. First, cycles: ```python def f(x): ... def g(x): ... f.f, f.g, g.g, g.f, g.lock = f, g, g, f, threading.Lock() ``` Probing `f` reaches `f.g`, whose probe reaches `g.f`, which is `f` again. An in-flight set answers "picklable" for a value whose probe is still running rather than re-probing it forever; the child probe re-serializes the ancestor inline in its own memo, so an unpicklable slot on the ancestor still fails the child. Without it the probe recurses until `RecursionError`, reads that as "unpicklable", and silently drops picklable entries probed after the cycle (here `g` and `f.g` vanish). Second, `persistent_id` records an unmarked `nn.Module` in `errors` rather than raising, so `helper.mod = nn.Linear(1, 1)` dumps cleanly in a probe but would fail the real `serialize()`; a probe that recorded an error counts as unpicklable (the warning names the modules), while a module the user marked as external data is written by reference and kept. A Module reached through `__closure__` or `__defaults__` still fails the save with the hard "mark these as external data" error, since the body needs those slots; a `__dict__` entry is optional to the runtime, so it is dropped with a warning instead of failing a save that has nothing else wrong with it. Third, the optimistic in-flight answer can produce a wrong verdict for a DIFFERENT value: ```python def outer(): lock = threading.Lock() def f(*, k=lock): ... # unpicklable through an UNPRUNED slot def g(): ... def h(): ... f.g, g.f, h.g = g, f, g def top(x): ... top.f, top.h = f, h # f is probed first return top ``` Probing `top.f` dumps `f`, whose reducer probes `f.g`. Probing `g` reaches `g.f`, and `f` is in flight, so the answer is True and `g` keeps `g.f`. `g`'s probe then dumps `f` inline, hits the lock kwdefault and fails, so `g` is recorded as unpicklable. Later `top.h` is probed, `h.g` consults the cache, and `h` silently loses `.g` and dies at call time, although `g` on its own pickles fine once `f` is pruned from it. So a False that leaned on an in-flight id is not cached as final. It is parked (a set of ids read as "unpicklable") for the rest of the probe tree and dropped when the outermost probe returns, so the real dump never consults it; re-deriving it instead is exponential on a cyclic cluster (an 8-clique of `__dict__` edges with one lock kwdefault costs hundreds of thousands of probe dumps, and one whose kwdefaults also form a ring does not finish). Sound because a stale park can only over-prune inside a probe, and over-pruning never flips a probe verdict. A True is final either way: an in-flight lean is always followed by pickling that object inline in the leaning probe's own memo, so an unprunable failure reaches the leaning probe rather than hiding behind its lean. So is the OUTERMOST probe's verdict, leaned or not: the only in-flight id it can lean on is its own, that lean is exact because pickle's memo resolves the back-reference, and the caller acts on it irrevocably. Consulting a park is not a lean: it can make a probe over-prune, and over-pruning CAN flip a probe's verdict False to True, and the real dump may read that True straight from the cache. It cannot hurt: the real dump never reuses a probe's attribute set (the memo is gated on the real pickler), so every prunable edge below such a value is re-decided by an outermost probe of its own, and the non-prunable slots are traversed identically in every probe, so a failure there would have failed the earlier probe too. The lean travels back through a shared flag on `_ProbeState` because the nested probe is reached through pickle's own dump stack (`probe.dump` -> `reducer_override` -> `_pickleable_attributes` -> `_dumps_cleanly`): the child's caller is the probe pickler's reducer, not the parent `_dumps_cleanly` frame, so no return value can carry the lean back to it; the restore sits in a `finally`. The body may read a pruned attribute (`with helper.lock:`), so the real dump warns per dropped entry: ``` dropping outer.<locals>.helper.lock (lock) from the artifact: it does not pickle (TypeError); pass it in external_data to keep it (function defined at model.py:12) ``` The function is named by its code object's qualname (`co_qualname`, 3.11+; 3.10 gets the bare `co_name`), since `functools.wraps` copies the wrappee's `__qualname__` onto the wrapper and the two drops would otherwise be indistinguishable; the reason says whether the value does not pickle, naming the exception type so that a reducer bug (an AttributeError out of the pickler's own machinery, a RecursionError) reads as one in a bug report rather than as the user's value, or holds unmarked `nn.Module`s, naming them. The `__dict__` items are iterated from a snapshot, since a probe runs user `__reduce__` code that may write back onto the function. Probe picklers stay quiet, since a probe's verdict may not be final, and the real dump memoizes each function's kept `__dict__` so a function reduced twice (it closes over itself) is neither re-probed nor re-warned. That memo is for the real dump only: a probe's answer may lean on an in-flight value and must not be reused. FAQ Q: Should the artifact record what was dropped, or a config flag turn a drop into a hard save-time failure? A: Not in this commit. The warning is the same contract the guard pickler's prune has, and it names the function, slot, type, reason and definition site. Recording the drops on `CompileArtifacts` is an artifact-format change, worth making when a load-time consumer for it exists; a strict mode is a config decision for the precompile API as a whole rather than this pickler. Both can be added without touching the probe. Q: Why a shared `leaned` flag with a save/restore rather than a returned tuple? A: The nested `_dumps_cleanly` is called by the probe pickler's reducer, several frames inside `probe.dump`, so its return value goes to that reducer, never to the parent `_dumps_cleanly` that needs the lean. The flag is the only channel between the two frames; the `finally` keeps it exact when a dump aborts. Test Plan: ``` python test/dynamo/test_aot_compile.py python test/dynamo/test_aot_compile.py -k test_pickler_survives_a_reduce_that_writes_back_an_attribute -k test_pickler_never_reuses_a_probes_attribute_set -k test_pickler_carries_a_dict_entry -k test_pickler_breaks_a_dict_cycle_between_nested_functions -k test_pickler_prunes_an_unmarked_module_from_a_nested_functions_dict -k test_aot_compile_prunes_a_lock_behind_functools_wraps_wrapped -k test_pickler_does_not_persist_a_wrong_false_across_an_inflight_seed -k test_pickler_probes_a_cyclic_cluster_in_bounded_time -k test_pickler_warns_once_for_a_function_reduced_twice -k test_pickler_names_the_modules_inside_a_dropped_container -k test_pickler_prunes_an_entry_that_overflows_the_probe ``` The dict-entry test checks a `__dict__` entry round-trips (the previous commit gives an empty `__dict__`) and that a literal entry costs no probe dump. The reduced-twice test pins the real-dump memo: a self-referencing helper with a lock warns once, and asserts the full warning text down to the definition-site prefix (the reason, with the exception type, and the external_data hint). The write-back test stashes a value whose `__reduce__` sets a new attribute on the function mid-walk; without the snapshot the dump raises "dictionary changed size during iteration". The never-reuses test is a three-function chain `a.b, b.c, c.a` with a lock kwdefault on `a`: probing `a` computes an empty attribute set for `b` (its probe of `c` fails on the in-flight `a`), and the real dump must recompute it and keep `b.c`; with the memo written from a probe the reloaded `b` has no `c`. The container test drops a list holding two unmarked Modules and checks the warning names the list's type and both Module classes. The overflow test puts a value whose `__reduce__` recurses without bound in a helper's `__dict__` and checks the entry is dropped with one warning and the save succeeds; the guard pickler makes the opposite call for the same condition (a PackageError bypass), which this pins as deliberate. The cycle test builds two functions with self- and cross-references and a lock; with a cache-only probe the pair loses `g` and `f.g`, with the in-flight guard only the lock is pruned. The wrong-False test is the `f`/`g`/`h` scenario above; without parking `h` loses `.g`. The bounded-time test builds the 8-clique with one lock kwdefault, counts probe dumps through a patched `dump`, and requires fewer than 32 (it takes 16; a quadratic regression on eight nodes would be 64), then checks the lock's owner is pruned and the rest of the clique keeps its edges. The module test puts a `Linear` in a helper's `__dict__`: unmarked it is pruned with a warning naming `Linear` and no error recorded, marked as external data the reloaded attribute is the same object. The end-to-end test puts a lock on the function behind a helper's `__wrapped__` and checks the save succeeds with exactly two warnings, one naming `helper.lock` and one `base.lock` (wraps copied both the `__dict__` and the `__qualname__`), the lock is gone from both and `__wrapped__` is kept; with `__dict__` carried verbatim the save fails on the lock, and with probe picklers warning too there are three. Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196686 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683, #196684, #196685
#196687) The subclass-swap commit carries `__doc__` verbatim, so this fails the whole save for a value nothing on the load path forces: ```python def outer(): def inner(x): return x inner.__doc__ = threading.Lock() # a decorator that misuses __doc__ return inner ``` `_apply_function_state` assigns `__doc__` and that is all, so probe it like a `__dict__` entry and drop it to None when it will not pickle, with the same warning naming the function, the slot and the fix: ``` dropping outer.<locals>.inner.__doc__ (lock) from the artifact: it does not pickle; pass it in external_data to keep it (function defined at ...) ``` A plain `str` docstring is not probed; the probe short-circuits on the trivially picklable types. The kept `__doc__` is memoized for the real dump like the `__dict__` entries, so a function reduced twice (it closes over itself) warns once. FAQ Q: Why a second memo (`docs`) next to `attributes` rather than one memo of the whole function state? A: Each slot has its own prune rule and lands in its own commit (`__dict__` per entry, `__doc__` whole, then annotations per value and type params whole), so each memo sits next to the rule it caches and can be read on its own. They share one key and one gate deliberately, so the warn-once argument is made once; folding them into one tuple-valued memo would save two lines and make every slot's rule read through one helper. Test Plan: ``` python test/dynamo/test_aot_compile.py python test/dynamo/test_aot_compile.py -k test_pickler_prunes_an_unpicklable_docstring ``` The test gives a nested function that closes over itself a native docstring, then assigns a lock to its `__doc__`, and checks the dump succeeds with exactly one warning naming `inner.__doc__`, the reloaded `__doc__` is None (the pruned value overrides the code object's own docstring) and the function still runs; on the previous commit the dump fails on the lock. Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196687 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683, #196684, #196685, #196686
Tests only. The previous commits pin the rebuild at the pickler level; these two
drive it through `torch.compile(...).aot_compile`, `save_compiled_function` and
`load_compiled_function`, so the runtime env's own closure path is covered:
```python
def outer():
scale = None
def helper(x, y=3, *, k=2):
if x is None:
return unset # a cell that is never assigned: EMPTY
if scale is None: # a cell holding None
x = x + 1
return x * k + y
helper.tag = 2.0
if helper is None:
unset = 1
return helper
helper = outer()
def fn(x):
return helper(x) * 2
```
After save, `torch._dynamo.reset()` and reload, the first test reads the helper
back out of `runtime_env.closure` and checks each piece survived: the empty
cell is still empty, the None cell holds None, `__defaults__ == (3,)`,
`__kwdefaults__ == {"k": 2}` and `helper.tag == 2.0`. The old reduce raised on the empty cell and dropped
`__kwdefaults__` and `__dict__`; the None cell is asserted so the empty/None
distinction stays pinned. The second test stashes a lock next to `tag` and
checks the save succeeds with exactly one warning, naming the dropped lock,
the reload (after `torch._dynamo.reset()`, under `fail_on_recompile`) runs,
and the reloaded helper's `__dict__` holds exactly the float.
Test Plan:
```
python test/dynamo/test_aot_compile.py
python test/dynamo/test_aot_compile.py -k test_aot_compile_reloads_a_runtime_env_helper_faithfully -k test_aot_compile_prunes_a_helpers_unpicklable_attribute
```
Authored with an AI assistant.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Pull Request resolved: #196688
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #196683, #196684, #196685, #196686, #196687
…196691) `types.FunctionType(code, ...)` leaves `__annotations__` empty, so a reloaded helper lost them. Carrying them verbatim fails the save in ordinary shapes: ```python def outer(): class Cfg: # a local class: resolves, but pickle pass # cannot reference it by name def inner(x: Cfg, y: int) -> int: return y return inner ``` and on 3.14, where annotations are evaluated lazily (PEP 649), a name that only exists under `TYPE_CHECKING` reads back as a `ForwardRef` proxy even nested in `list[Bar]`, which must not be carried: it holds its owner and may drag the owner's globals along. The runtime must SERIALIZE these, so `_pickleable_annotations` reads them differently from the guard pickler: the shared `_read_raw_annotations` takes an `evaluate=` flag, and this caller passes it, so on 3.14 the read hands back evaluated VALUEs rather than the FORWARDREF proxies the guard pickler reads. A proxy must not be carried (it holds its owner and may drag the owner's globals along). Evaluating runs the function's `__annotate__` and caches the result on it, the same thing `inspect.signature` does. When that read raises, a TYPE_CHECKING-only name being the common case, the whole set is dropped, since `__annotate__` is one function returning the whole dict and there is nothing finer to keep (a FORWARDREF retry that kept the proxy-free siblings would salvage more; not done). That drop is a debug line where the per-value drop below warns, because a set that does not evaluate was not readable at runtime in this process either (`typing.get_type_hints` raises the same), so nothing the body does can depend on it, while a value that resolved but does not pickle is a live object the body may read. Below 3.14 the read hands back the live `__annotations__` dict, whose items are snapshotted since a probe runs user `__reduce__` code that may write back onto the function, and the kept values go into a fresh dict. Each value is probed with `_dumps_cleanly` and kept only if it dumps, with the same warning a dropped `__dict__` entry gets (`__annotations__['x']`), so the example above reloads with `{"y": int, "return": int}` and runs. A failing key is dropped rather than kept with a sentinel as the guard pickler does: this function is CALLED after load, and a sentinel where the body expects a type is a wrong object, while a missing key is the `KeyError` the warning predicts. The kept set is memoized for the real dump like the attributes. Two `<locals>` functions annotated with each other form an annotation cycle, which the probe's in-flight guard handles. Test Plan: ``` python test/dynamo/test_aot_compile.py python test/dynamo/test_aot_compile.py -k annotation ``` The write-back test has an annotation value whose `__reduce__` adds a key to the function's `__annotations__` mid-walk and checks the dump succeeds; a live iteration raises "dictionary changed size during iteration", a hazard that is pre-3.14 only since the 3.14 read returns a copy, and there the test checks no more than that the write-back is harmless. The end-to-end test saves and reloads a compiled function whose helper is annotated with a `<locals>` class and an `int`, and checks the reloaded helper carries the `int` annotations. The dropped-annotation test also checks the warning names `inner.__annotations__['x']`. The ForwardRef test is 3.14-only and pins the resolve path through its debug log, since an empty annotation set alone is what the previous commit produced too. A last test pins the limitation this does not fix: the compiled function's OWN annotations ride on `CompileArtifacts.signature`, which `serialize()` dumps whole, so a `<locals>` class there still fails the save and the nested-helper prune does not reach it. Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196691 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688
…196692) `types.FunctionType(code, ...)` leaves `__type_params__` empty, so a helper that was handed type params reloads without them. Carrying the tuple verbatim is not an option for the common source of one: ```python def outer(): def inner[T](x: T) -> T: # PEP 695: T is a function-scoped TypeVar return x return inner >>> T = outer().__type_params__[0] >>> T.__module__, T.__reduce__() ('typing', 'T') >>> pickle.dumps(T) PicklingError: Can't pickle T: it's not the same object as typing.T ``` A PEP 695 TypeVar pickles by name as `typing.<name>` and fails pickle's identity check against it (or the lookup, for a name `typing` lacks). So the tuple is carried when its elements pickle, and one element that will not dump drops the whole tuple, since a generic cannot be rebuilt around a missing parameter, with the same warning the other pruned slots get (a reloaded generic is no longer generic, so the drop must be visible). The scan stops at the first element that fails: every probe serializes the reachable graph into a throwaway buffer, and only the one element the warning names is used. Ordinary functions carry `()`, which dumps and is kept. A TypeVar the body itself references sits in a closure cell, which is never pruned, so that shape still fails the dump (the comment says so). Nothing aborted before this commit; the previous commits passed `type_params=None`, so the tuple was simply not carried. In practice a generic's params survive only when the user hands the TypeVar over in `external_data` (the probe pickler shares it, so the element is written by reference) or assigns a module-level TypeVar by hand; the drop itself is silent, as `()` is what `FunctionType` gives anyway. Test Plan: ``` python test/dynamo/test_aot_compile.py python test/dynamo/test_aot_compile.py -k test_pickler_keeps_picklable_type_params -k test_pickler_keeps_pep695_type_params_given_as_external_data -k test_pickler_drops_unpicklable_type_params -k test_pickler_warns_once_for_a_generic_reduced_twice ``` The drop is memoized for the real dump like the other slots, so a generic that closes over itself warns once, and it stays quiet below 3.12 where the tuple lives in `__dict__` and the attributes pass has already reported it; the warning names the element that failed, so an unmarked `nn.Module` among the params gets the external-data reason. The external-data test is the realistic kept case: a PEP 695 generic (defined via exec so the file still parses below 3.12) whose `T` is passed in `external_data` reloads with its type params and annotations intact; the previous commit gives `()`. The manual test assigns a module-level `TypeVar` and checks the same object comes back; it is not version-gated, since below 3.12 the slot lives in `__dict__` and the reducer's write has to win over the carried dict, and on 3.12+ it asserts the slot does not leak into `__dict__`. The dropped test checks the generic without external data reloads with `()` and runs, and that the drop is warned about, where a verbatim tuple fails the dump. The warns-once test pins the memo itself: a generic whose body references itself is reduced twice (the closure is a reduce ARGUMENT, so the second pass finds it not yet memoized), and exactly one warning must name `__type_params__`; with the memo deleted it warns twice and the single-line unpack raises. That shape also pins where `T` lands, since the self-reference is the only closure cell -- PEP 695 compiles `T` into the hidden type-params scope, so it is not a freevar of the body, which is what a `T` the body reads would change. The exec-built generic is a module-level helper the tests share, taking the body text so each can pick its own. Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196692 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691
…ickle a value (#196693) A value the artifact carries unpruned fails the dump with pickle's own error and nothing pointing at the fix: ```python def outer(): lock = threading.Lock() def fn(x): def unused(): return lock # makes `lock` a closure cell of fn return x + 1 return fn compiled = torch.compile(outer(), fullgraph=True).aot_compile(((x,), {})) compiled.save_compiled_function(path) # TypeError: cannot pickle '_thread.lock' object ``` `serialize()` now catches that, appends guidance naming the common sources and the escape hatch, and re-raises the SAME exception object: ``` TypeError: cannot pickle '_thread.lock' object Some value reached by the artifact is not picklable (a closure cell, a default/kwdefault, or the top-level function's own signature annotations, which ride unpruned, are the common sources). Mark it as external data by using `external_data={'key': ...}`. ``` The same instance is re-raised because callers and tests match on the original text, and a TypeError subclass from a user `__reduce__` may take a non-message constructor, so rebuilding `type(e)(msg)` could swap the real error for a constructor failure (a subclass whose `__str__` ignores `args` still renders without the guidance; `add_note()` would cover it but is 3.11+). `e.args[0]` becomes the combined string and the tail is kept for a consumer that reads it. The prefix is `str(e.args[0])`, not `str(e)`: for a two-argument exception `str(e)` is `repr(args)`, which would embed the tail twice. `str()` of the result is still a tuple repr in that case, the price of keeping the tail; `.name` and `.obj` on an AttributeError are untouched. Unmarked `nn.Module`s recorded before the failure are named in the same message by class name (a Module repr renders the whole child tree and runs user code inside the handler), so the user does not fix the lock only to hit the module error on the next attempt; the external-data hint is one shared constant for both paths, and a re-raised singleton that already carries it is not decorated twice. `AttributeError` is in the tuple because the C `_pickle` accelerator raises a bare `AttributeError: Can't get local object ...` for a `<locals>` class (the pure-Python pickler and 3.14+ raise PicklingError). `RecursionError` is in it because a deep-but-finite value in an unpruned slot overflows the C pickler, and external data is its fix too. The backend's own pickling of `compiled_fn` stays OUTSIDE the handler, which a comment now records: `external_data` cannot fix an unpicklable graph module, so dressing that failure up with this guidance would misdirect. One gap the guidance cannot close is noted where it lives: nothing threads `external_data` through `AOTCompiledModel.serialize` or `_save_aot_compiled_module`, so on a module save the advice is only actionable by saving the offending function on its own. Threading a parameter through both is a follow-up, not this commit. Test Plan: ``` python test/dynamo/test_aot_compile.py python test/dynamo/test_aot_compile.py -k test_save_guidance -k test_save_fails_loudly_on_a_helpers_unpicklable_kwdefault ``` All five drive `save_compiled_function`. The lock, `<locals>`-class-default (asserting the offender `Cfg` is named, not pickle's per-version wording) and kwdefault tests assert the original message plus the guidance. The lock test matches the join with a regex over a REAL newline, which is what a single-argument exception renders and what a reintroduced `str(e)` prefix would break (the tuple repr escapes it). The kwdefault test overlaps two pins that predate this commit and its comment now says so, keeping it for the one axis neither covers: the unprunable slot belongs to a nested helper reached through the runtime env rather than to the compiled function itself. The identity test raises a `TypeError` subclass with a two-argument constructor from a `__reduce__` and checks the SAME instance comes out, guidance appended, second argument intact and embedded once. The recorded-modules test closes over an unmarked `Linear` and a lock, asserts the freevar order that makes the module dump first, and checks the raised message names both the lock and the module's class. The overflow test puts a value whose `__reduce__` returns a fresh instance in a default, so the C pickler recurses without bound on every version (3.14's no longer overflows on a merely deep list), and checks the `RecursionError` carries the guidance and the handler itself does not overflow. Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196693 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692
…196756) Follow-up to #196505, from its review. A resume frame whose backend artifact is missing when the package is saved is written with `bypassed=True` by `PrecompileCacheEntry.from_cache_entry`, and `install()` skips it, so the next process traces that frame fresh: ```python def fn(x): y = x.sin() torch._dynamo.graph_break() # a resume frame with its own backend return x.sin() + y torch.compile(fn)(x) del PrecompileContext._backend_artifacts_by_key[resume_backend_id] save() # resume entry written bypassed # next process torch.compile(fn)(x) # resume frame traced fresh save() ``` That fresh compile appended its guarded code to the stale one the reload had deserialized, cleared the flag, and re-registered a backend id next to the missing one still listed first. The next save found the missing id again, re-poisoned the entry and wrote the bigger one back over the same path, so the entry never became installable and never stopped growing: ``` base: guarded_codes 1 -> 1 backend_ids 1 -> 7 (33 KB -> 34 KB over six cycles) #196505: guarded_codes 1 -> 7 backend_ids 1 -> 7 (33 KB -> 64 KB) ``` (Byte sizes from the reviewer's environment; the counts reproduce exactly.) The backend-id half predates #196505 (`OutputGraph` registers the id whether or not the entry is bypassed); the guarded-code half is new there, since `add_guarded_code` now appends and clears the flag on such an entry. `CompilePackage.initialize` now loads a bypassed entry without its guarded codes and backend ids: the package's own map gets a `dataclasses.replace` copy, and the caller's entry is untouched, since a store may hand out the object it holds (`InMemoryDynamoStore` does); the containers the fresh compile writes to (`import_sources`, `function_names`) are detached in the copy as well, since `dataclasses.replace` is shallow. `install()` skips such an entry entirely, so nothing on it was installable, every variant of that code object included (`from_cache_entry` flags the whole entry on the first missing artifact); the fresh compile's record is the whole entry and the next save writes an installable one, so the third process hits without compiling anything. The reset lives on the load side rather than in the save-time writer because for an entry already on disk in the stale state the writer cannot tell the missing id from the fresh compile's id listed beside it, so a writer-side clear would discard the fresh code too and converge one save later. The better endpoint, not taken here, is a per-guarded-code prune at write time (drop only the guarded codes whose bytecode names the missing backend), which would keep a multi-variant entry installable and never write the stale bytes; tracked in #196773. The entry docstring says what the writer and the loader each do. Two test cleanups from the same review: `ConfigThatCannotPickle` says why it raises AttributeError specifically (the one exception the bypass mapped before #196470 widened it), and the earlier-variant test pins that only the bypassed inputs compiled after the reload. It counts `counters["frames"]["total"]` rather than the `FRAME_COUNTER` bracket the file's other caching_precompile tests use: `reset()` zeroes `FRAME_COUNTER` and installing a precompiled entry consumes a compile id, so a `+ 1` there holds only by cancellation. Test Plan: ``` python test/dynamo/test_package.py python test/dynamo/test_package.py -k test_a_poisoned_entry_is_reset_on_load_instead_of_growing -k test_bypassed_guards_keep_the_frames_earlier_variant ``` The new test runs the cycle above through `PrecompileContext` and `DynamoCache`: after the second save the resume entry has one guarded code and one backend id and is not bypassed (on the previous commit it has two of each and is bypassed again), and a third load serves both frames with `counters["frames"]["total"]` unchanged under `fail_on_recompile`. It also builds a `CompilePackage` from a loaded entry and checks the entry it was given still holds its guarded code while the package's `cache_entry()` does not. Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196756 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692, #196693
…y, pin the dict-served case (#196764) 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: ```python 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: ```python 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](https://claude.com/claude-code) Pull Request resolved: #196764 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #196683, #196684, #196685, #196686, #196687, #196688, #196691, #196692, #196693, #196756
…t of snapshots, guard the 3.14 annotation read (#196767) Follow-up to the reviews of #196476, #196478 and #196479. `_keep_container_verbatim` decided a plain tuple in two steps: is it in `guard_tree_values`, and is it in `value_guarded_containers`. The second alone is the rule; the first held because `EQUALS_MATCH` registers the value it reads, a separate invariant whose failure would be the silent forever-miss the rule exists to prevent. The tuple case now reads the recording alone: ```python if type(container) is tuple: return id(container) in self.value_guarded_containers if type(container) is dict: return False return self._keep(container) ``` That is a behaviour change for the case the two invariants disagree on: a recorded tuple with no tree entry was pruned per value and is now carried whole. A test builds exactly that state, and it fails on the previous commit. A globals snapshot kept `__builtins__` "as read" when some guard had registered it and replaced it with the `builtins` module only when pruned. For an imported module `f_globals["__builtins__"]` IS `builtins.__dict__`, and a traced module's own dict binds that same object a second time under the `__builtins_dict___N` Dynamo installs; that dict is the one a saved BUILTIN_MATCH guard registers, so wherever one is saved the kept branch was taken and the snapshot carried all of builtins (about 6 KB) next to the filtered copy `G` already holds. The live builtins dict is now exempt from the keep contract by value rather than by name, so every slot holding it -- the alias included -- travels as a reference resolved in the loading process rather than as a copy, one shared `_LiveBuiltins` standing for it so a second slot in the same scope is a pickle memo reference rather than a second reduce. On a scope carrying both keys that takes the dump from 6781 bytes to 729; a cross-module snapshot, which has only `__builtins__`, goes from 6758 to 706. The slot stays a dict, since a guard may have walked through it and rebakes against whatever it holds at load. A dict without the key stays without one, since `FunctionType` falls back to the loading frame's builtins and a guard on the dict's shape must see the same keys; `FunctionType` accepts either value. The key set is the module dict's at save time, names Dynamo installed into it included, so such a guard is only as portable as those names. The snapshot loop iterated the live module dict. A `CleanupHook` pops the name it owns, and it fires from a weakref callback (`CleanupManager` holds a `weakref.ref` per traced code object, whose callback runs the hooks attached to it), so a code object collected during the dump pops a `__compiled_fn_N` or `__builtins_dict___N` key mid-loop and the next iteration raises `RuntimeError: dictionary changed size during iteration`. The loop now walks a copy, `dict(f_globals)`, which also makes the sentence above literally true: the key set is the one the loop entered with, not whatever survived to its end. The rarity is not the loop's own doing -- measured with `gc.callbacks`, snapshotting a scope of 80 `nn.Linear`s runs 82 iterations and takes zero automatic collections at the default gen-0 threshold (zero at 300, one at 10), since it allocates almost nothing GC-tracked. What decides whether a callback lands inside the loop is where the process-wide gen-0 counter already stood when the dump began. Scanning that offset with default thresholds and no forced collection, 1 of 200 positions raises against the live dict, and 0 of 200 once the loop walks a copy; being a flake rather than a reproducible failure is why the test forces the hook to fire from the loop's first `_prune` call instead of waiting for a collection. The copy is `dict(f_globals)` rather than `list(f_globals.items())`: at a gen-0 threshold of 1, where a callback popping a key raises out of a live `for k, v in d.items()` loop in all 50 trials, neither spelling raises once, and the dict copy is shorter and materializes no N-entry list of 2-tuples. The 6 KB is a snapshot's cost, and `_reduce_function_by_value` builds a snapshot only for a function whose own `__globals__` is registered too. A plain `CompilePackage` compile (`torch._dynamo.optimize("eager", package=CompilePackage(fn))`) applies no guard filter and keeps that BUILTIN_MATCH, so building its manager registers the dict the guard reads through -- but the traced function's module dict is not registered there, so no snapshot is built at all. Reading a global through a function's `__globals__` does register that dict, and it also guards the function itself with a CLOSURE_MATCH, which `serialize_guards` refuses outright, so with no filter at all an artifact built that way bypasses rather than saving. The 6 KB is paid where a caller-supplied `guard_filter_fn` drops that function guard and keeps the BUILTIN_MATCH: there the parent embedded the whole dict and the exemption hands back a reference instead. Both high-level entry points filter the BUILTIN_MATCH away instead -- `aot_compile`'s default `guard_filter_fn` drops every `is_global` entry and the alias's BUILTIN_MATCH is one, and `caching_precompile=True` drops it as ID_MATCH-derived -- so under them nothing registers `builtins.__dict__` and the parent embedded no copy of it: it pruned the alias slot to a sentinel and replaced `__builtins__` with the builtins module. There the exemption instead hands those slots back the live dict, 772 bytes to 729 on the same scope, which the same rebake argument covers. On 3.14 the guard pickler read FORWARDREF annotations unguarded, so whatever that read raised failed the dump. FORWARDREF reruns the annotate function, but only NAME lookups are proxied -- the rest of the expression runs for real, so whatever that real work raises comes out: ```python def f(x: f"{Missing}"): # TypeError: the proxy refuses __format__ def f(x: ()[0]): # IndexError: no proxy is involved at all def f(x: "%s" % Missing): # reads fine -- it is the operation, not the name ``` That would fail the dump for a slot the prune exists to make optional, so `_reduce_function_by_value` drops the whole set instead, with a debug log naming the code object by `co_qualname` where the runtime has one and by `co_name` on 3.10. That log line repeats the AOT pickler's `_pickleable_annotations` one rather than sharing it: the two handlers differ in policy (that one swallows a RecursionError too, and afterwards drops unpicklable values key by key instead of sentinelling them) and each logs under its own module's logger, which is what tells the two drops apart in a `TORCH_LOGS` run, so what is left to share is a format string. The handler sits at that caller rather than inside the shared `_read_raw_annotations`, which stays a pure reader raising for either format: the other caller, the AOT pickler's `evaluate=True` one, already handles its own read (it logs the reason it saw), so a keyword that selects a format does not also select an error policy. A RecursionError is re-raised rather than dropped: it is the dump's own limit, which `pickle_guards_state` reports as a bypass, not a property of the annotation, and swallowing it would drop a set that reads fine at any other depth. Dropping the whole set cannot silently break a guard: a guard rooted at `fn.__annotations__` evaluated them at trace time (the VALUE format, cached on the function), so a read that raises at dump time is one no guard performed. The 3.14 path had no test at all, since every annotation in the suite either was an assigned dict or resolved; a 3.14-gated test now pins that the TYPE_CHECKING-only name is genuinely unreadable outside the FORWARDREF read -- a direct `__annotations__` read raises `NameError`, a premise pruning to a sentinel cannot tell from a resolved class -- and that the f-string case drops the set (CI runs this file on 3.14; there is no local 3.14 build). Test and comment cleanups: the guarded-defaults test names the full-compile round trip that can tell a whole-container guard from a per-element one instead of forward-referencing it; the two snapshot tests assert on names their module cannot lose instead of comparing whole key sets against a live module dict a `CleanupHook` can pop from; the `name_beside_unpicklable_default` subtest now says why the default prunes, which is that `bind_args` guards `__defaults__` with SEQUENCE_LENGTH and only `EQUALS_MATCH` records a tuple in `value_guarded_containers`, so a length guard survives per-value pruning; the pickler `__init__` comment no longer claims omitting the recording prunes every container; the snapshot comment names both regimes whose guard filter drops the alias's BUILTIN_MATCH; and the annotations comment says what the keep branch there is for, which is a dict SUBCLASS assigned onto `__annotations__` that a guard registered (an exact dict is never carried whole on any version, and on 3.14 the read hands back a copy, so neither is a subclass one) -- the branch stays, since deleting it would prune that mapping per value and rebuild it as a plain dict. The snapshot comment also says what the exemption costs, which is that a guard walking the slot rebakes against the loading process's builtins rather than the binding the compile saw; and the two builtins tests pin the reference identity alone, since a copy cannot be `is` the live dict, while an absolute byte bound over a stream whose size depends on the pickle protocol and the per-version `SerializedCode` payload adds nothing to it. Kept as one commit rather than split three ways along the paragraphs above (the tuple rule, the builtins exemption, the annotation guard are independent and each carries its own test): this is the bottom PR of an already-submitted pickler stack, so splitting it rebases and renumbers every PR above it; what that buys is a finer bisect over three changes that already sit in disjoint functions and cannot interact. One #196476 comment is not a change here: the AOT pickler's own by-value reducer carried only `__defaults__` at that commit, so an AOT-rebuilt helper lost `__kwdefaults__` and `__dict__` and its `__name__` was the qualname. #196685 and the commits between it and this one moved that pickler onto the shared base, which is where those are already fixed. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_guard_serialization.py -k test_snapshot_survives_a_cleanup_hook_pop_during_the_loop python test/dynamo/test_guard_serialization.py -k snapshot -k verbatim -k alias -k unresolvable_annotation -k raising_annotation_read -k without_builtins -k length_guarded -k name_beside_unpicklable_default python test/dynamo/test_aot_compile.py -k Pickler python test/dynamo/test_package.py ``` The preserves-module snapshot test asserts the rebuilt scope's `__builtins__` comes back as whatever the live dict held (the module when this file runs as `__main__`, the builtins dict when it is imported), and another pins the alias slot: with the exemption keyed on the name that slot arrives as a copy of the whole builtins dict, not the live dict. Six of the seven new tests fail on the previous commit: that alias one, `test_snapshot_of_an_unguarded_builtins_dict_stays_a_dict`, `test_a_recorded_tuple_is_kept_verbatim_without_a_tree_entry` (the behaviour change above), `test_a_raising_annotation_read_drops_the_set_but_not_a_recursion_error` (the parent's read is unguarded and nothing on its save path catches it), `test_snapshot_survives_a_cleanup_hook_pop_during_the_loop` (the parent builds the snapshot as a comprehension over the same live dict) and, on a 3.14 shard, `test_reduce_prunes_an_unresolvable_annotation_and_drops_a_raising_one` via its f-string case. Only `test_snapshot_of_a_scope_without_builtins_stays_without` passes there, and is kept for the contract the exemption must not break: a scope that has no `__builtins__` does not gain one. The TYPE_CHECKING test is 3.14-only and runs in CI, while the raising-read test patches the read itself, so the drop, its log and the RecursionError re-raise are covered on every shard, 3.10 included. Authored with an AI assistant. Co-Authored-By: Claude Opus 5 <[email protected]> ## FAQ > **FAQ: why is this not three commits (tuple rule / builtins exemption / 3.14 > annotation guard)?** The three changes are independent, each already carries its > own test, and the message's paragraphs are the seam -- but #196767 is the > pre-existing bottom PR of the pickler stack, not part of the #195354 re-slice > this round is doing. Splitting it renumbers and rebases every PR above it, and > what that buys is a finer bisect over three behaviour changes that already sit in > disjoint functions (`_keep_container_verbatim`, `_globals_snapshot`, the > annotation read in `_reduce_function_by_value`) and cannot interact. The commit > message keeps the three-way structure so a bisect landing here can tell which > behaviour it is. > **FAQ: isn't the `_keep_container_verbatim(raw_annotations)` keep branch dead code > now?** No, only on 3.14. Below 3.14 the read hands back `fn.__annotations__` > itself, and CPython lets that be a `dict` subclass; a subclass instance falls past > the `type(container) is dict` rule to the identity check, so a guard-registered > one is still carried whole (verified: it round-trips as the subclass, while > unregistered it comes back a plain dict of sentinels). Deleting the call would > silently change that case, so the call stays and the comment now states exactly > when it fires instead of the misleading 3.14-specific parenthetical it replaced. > **FAQ: the review asked for "FORWARDREF raises for an operation the proxy will > not represent". Why does the comment say something else?** Because that is not > the rule either, and the comment now has to be right in both directions. On > 3.14.7 the discriminator is `_Stringifier.__format__`, which > `annotationlib.py:520` raises from outright, not string formatting as a class: > `f"{Missing}"` and `f"{Missing:>10}"` raise, while `f"{Missing!r}"`, > `f"{Missing!s}"`, `f"{Missing=}"`, `"%s" % Missing` and `str(Missing)` all read > fine and give `{'x': 'Missing'}` -- those convert to `str` before the format > opcode, so the proxy's `__str__`/`__repr__` answers. And the proxy is not the > only way out: `()[0]`, `1/0` and `{}["k"]` raise with no proxy involved at all, > and `"".join([Missing])` raises from a real callee rejecting the proxy (`expected > str instance, _Stringifier found`). One sentence covers all three: only NAME > lookups are proxied, and the rest of the expression runs for real. That is what > the comment now says, and it is why `[Missing][0]` -- an expression with real > work that does not fail -- still reads back a `ForwardRef`. > **FAQ: the review says the `expected_keys` assertions can flake in either > direction. Isn't a `list()` at the capture the matching fix?** No, on both > counts. `CleanupHook.__call__` only ever `pop`s and nothing on the dump path > installs a name into a traced module dict, so the snapshot can only ever come > back a subset of the captured key set -- one direction, not two. And a `list()` > would not close it, because the hole is not inside an iteration: it is the gap > between `expected_keys = set(g)` and the dump, on a dict that is this test > module's live globals. That capture is itself a third exposure the finding did > not name -- `set(g)` iterates the live dict, so a hook firing during that > statement raises `RuntimeError` from the test body. Both tests therefore stop > comparing whole key sets and assert `assertIn` on names their module cannot > lose, which is what each was pinning (the module's own state arrived; the shared > scope is not the half-loaded copy) without depending on a key Dynamo owns. > **FAQ: Was `list(f_globals.items())` really exposed to a `CleanupHook` pop, > and is that what `dict(f_globals)` fixes?** > > Measured on 3.12.14 with `gc.set_threshold(1, 1, 1)` and a `gc.callbacks` > entry that pops a key out of a 5000-entry dict: a live > `for k, v in d.items()` loop that allocates per step raises > `RuntimeError: dictionary changed size during iteration` in all 50 trials, > while `list(d.items())` and `dict(d)` each raise in 0 of 50 -- both see one > or two collections during the call, but those land at a bytecode boundary > outside the C-level copy rather than between two iterator steps. The window > inside `list()` therefore did not reproduce on this interpreter, and the > change is not a bug fix: the loop walks `dict(f_globals)` because it is the > shorter spelling and materializes no N-entry list of 2-tuples, and the > comment above it now claims only what the measurement supports, which is > that iterating the LIVE dict while pruning is what raises. > **FAQ: the annotation on `raw_annotations: dict[str, Any] = {}` is redundant > and sits on the fallback rebinding -- the `try` binding two statements up > already comes from `_read_raw_annotations`, declared `-> dict[str, Any]`, so > drop it and leave `raw_annotations = {}`.** Declined: dropping it turns > PYREFLY red. `pyrefly.toml:143-146` switches `implicit-any` on for > `torch/_dynamo/**`, and pyrefly types each binding on its own rather than > joining the branches, so a bare empty literal is an error regardless of what > the other branch binds. Measured with pyrefly 0.58.0, the version pinned in > `tools/linter/adapters/pyrefly_linter.py`, on a standalone reduction of > exactly this shape (a `-> dict[str, Any]` callee in the `try`, a bare `= {}` > in the `except`): `Cannot infer type of empty container; it will be treated > as containing Any [implicit-any]` on the fallback line without the > annotation, and clean with it. The callee's declared return type does not > reach the `except` branch -- only a declaration gives `{}` a contextual type > -- and `torch/_dynamo/guards.py` is otherwise clean today (`pyrefly check > --config pyrefly.toml torch/_dynamo/guards.py` reports 0 errors, 28 > suppressed), so this would be a new error on a line the PR touches. The one > variant that also measures clean is moving the annotation up onto the `try` > binding; it was not taken because there it merely restates the callee's > declared return type, whereas on the fallback it is the only binding pyrefly > cannot infer. > **FAQ: the review says the 3.14 test's fixture rots "if that name ever gets > defined at this module's scope". Doesn't the new `NameError` assertion pin a > premise that a stray `TYPE_CHECKING` import could already break?** No -- that > particular vector cannot reach the fixture, and the assertion went in anyway > because the rest of the finding is right. `inner` is built by `exec` into a fresh > namespace, `ns = {"__name__": __name__}` > (`test/dynamo/test_guard_serialization.py:1767`), so the annotate function's > globals are `ns` and not this module's: measured on 3.14.7 with `class > OnlyUnderTypeChecking` defined at the module scope of the running file, > `inner.__annotate__.__globals__ is ns` is `True`, `"OnlyUnderTypeChecking" in ns` > is `False`, and the direct read still raises `NameError: name > 'OnlyUnderTypeChecking' is not defined`. The reachable rot is an edit to that > seed dict or to the `exec` string. What does hold is the non-discrimination: > every unguarded annotation prunes to a sentinel (`torch/_dynamo/guards.py:4535` > over `_prune` at `:4380-4383`, which keeps only a literal or a guard-registered > value), so measured on 3.12.14 a fully RESOLVED class annotation comes back > `_Missing` as well, and the assertion at `:1787` could not tell a proxy from a > resolved class. One line can: `inner.__annotations__` raising `NameError` before > the dump, which is the exact premise `_read_raw_annotations` cites for asking for > the FORWARDREF format at all (`torch/_dynamo/package.py:320-322`). It passes on > the fixture as written and fails loudly on the seeded namespace. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Pull Request resolved: #196767 Approved by: https://github.com/pytorchgreenlight
Stack from ghstack (oldest at bottom):
torch.compile(fn).aot_compile(...).save_compiled_function(path)pickleseverything the compiled function needs to run later, including the nested
helpers it closes over.
AOTCompilePicklerhad its own copies of the cell,module, code and bound-method reducers, and rebuilt a function from its code
object only when its qualname carried
<locals>:wrappercarriesbase's names, so the old dispatch let pickle save it byreference and pickle refused. The
<locals>rebuild it did have was also wrongin three ways:
It passed
__qualname__as the NAME (a reloaded helper reportedouter.<locals>.fas its__name__), its cell reducer readcell_contentsunguarded (an EMPTY cell raised ValueError out of the pickler), and it dropped
__kwdefaults__(adef helper(x, *, k=2)reloaded and then failed withTypeError: missing 1 required keyword-only argument).Subclass the shared base instead: dispatch on
_fqn_resolves, reduce cells,modules, code and bound methods through the shared reducers, and rebuild a
function through
_reduce_functioncarrying defaults, keyword defaults,closure and
__doc__. The rebuilt function is scoped to the module thatcompiled it (the previous commit), which a wrapper reloaded from another
module needs to run.
__dict__, annotations and type params are added by thenext commits, each pruned per value (so at this commit a wraps wrapper reloads
without its
__wrapped__, as the old rebuild did);__doc__is carriedverbatim here. The old rebuild (
types.FunctionTypeover the code object) kepta native docstring and dropped an assigned one; on this base
_apply_function_stateassigns__doc__unconditionally, so passing Nonewould drop both.
One bound-method case stays local. The receiver of a method reached here is
served by
persistent_id(external data, or anynn.Module), so at load it isthe LIVE object and pickle's default
getattr(receiver, name)resolves themethod on it. The shared reducer would carry
__func__instead (annn.Moduledefines
__getattr__), rebuilding a local subclass's method by value andfailing on the
__class__cell of itssuper()call:So the shared reducer gains a
receiver_is_livekeyword: for such a receiverit skips the gates that exist for a receiver that is REBUILT (possibly as a
different type) and goes straight to its probe, which takes pickle's rule only
on proof that
getattrhands back a method over THIS receiver and THIS function(a rebound
a.forward = b.forwardresolves to b's, so it takes the explicit(func, receiver)pair) and falls back to the pair when the probe raises. Oneprobe, no copy. An unmarked
nn.Moduleis recorded inerrorsand failsserialize()anyway, so for it the keyword only keeps the dump going.BC note: a nested function's
__kwdefaults__now travel with it, so a helperwith an unpicklable keyword default fails
save_compiled_functionwhere it usedto serialize with the default silently dropped (a
TypeErrorfor the missingkeyword at call time).
__doc__travels as pickle state too, so a helper whose__doc__was reassigned to an unpicklable object fails the save here where itused to serialize with that doc dropped; #196687 prunes it with a warning
instead. The pickle targets
_unpickle_nested_functionand_unpickle_cellare removed and_unpickle_moduleis renamed_unpickle_python_module; an artifact saved by an earlier build hits them as apickle AttributeError in
deserialize, which runs beforecheck_compatibilitygets to reject the
torch_versionmismatch (the same ordering any removedreducer has always had). And a nested helper whose compile scope cannot be
imported at load now gets an empty scope and fails with a NameError at its
first call, where the old rebuild failed the load with ModuleNotFoundError;
helpers that read no module global load and run either way, which is why the
shared base swallows the import failure. A helper compiled in a script has the
scope
"__main__", which imports the LOADING process's__main__; that ispickle's own rule for a by-reference
__main__function, right in-process andcross-process only as right as the two scripts agree.
Test Plan:
The first test saves and reloads a compiled function that calls a wraps wrapper
of a module-level function; the second builds the decorator in its own module
with its own
SCALE, escapes the wrapper from the compiled function and checksthe reloaded wrapper still reads the decorator module's value; the third pins
the BC note at the pickler level; the fourth pickles a local
nn.Linearsubclass's
forwardwith the module as external data and checks the reloadedmethod is the class's own (with the shared reducer alone the dump fails with
Can't get local object); the fifth checks a native and an assigned docstringboth survive; the sixth pins the three old-rebuild bugs on THIS pickler: the
reloaded
__name__and__qualname__are the values reassigned afterdefinition (the code object's co_name/co_qualname would give the originals), an
EMPTY cell round-trips, and a reloaded
def scaled(x, *, k=2)called withoutkapplies the default (the old reduce raised TypeError).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