Repository navigation
[guards] Reconstruct fqn-mismatched functions when a guard is rooted at them - #195353
bobrenjc93 wants to merge 52 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/195353
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit be43fcc with merge base 9d5a710 ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
…at them One of the enabler fixes the precompile PR at the top of this stack needs. That PR serializes a Dynamo guard tree per captured variant and rebuilds it at load; this is what stops the rebuild from failing on ordinary library code. A serialized guard set cannot be loaded if any guard's source walks through a function whose qualname does not resolve back to it. `GuardsStatePickler` looks the function up by `__module__` and `__qualname__` and substitutes a `_Missing` sentinel when that finds something else. For a function nothing depends on that is correct. For one a guard is rooted at, evaluating the source against the sentinel raises while the guard manager is still being built, and the whole load fails. Any `functools.wraps` decorator produces the mismatch, since the wrapper copies the wrapped function's `__module__` and `__qualname__` while living in the decorator's file. That makes this ordinary rather than exotic: it is why a transformers model cannot be loaded from a compile package at all today. The sentinel stays for functions no guard needs. A function in `guard_tree_values` is pickled by value instead, rebuilt from its code object through the same path the `<locals>` branch already used. Most of the diff is what reaching that path from the fqn branch turned out to require, and the reason it is so much is that the reconstruction is directly observable: `load_guard_manager` re-runs guard construction against the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any attribute the reconstruction gets wrong does not fail the load, it produces a guard that never passes again. `__name__` (the old code passed `__qualname__` there), `__module__` (`FunctionType` derives it from the globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the length and keys of the signature containers are all load-bearing for that reason, and each has a round-trip test that mutates the live function and asserts the loaded guard rejects it. Rebuilding drags along whatever the function holds, and carrying all of it would let an unpicklable neighbour fail a package that never needed it. So the policy is to carry only what some guard tree node references and to prune the rest to sentinels -- the inverse of pickling the function wholesale, which is simpler but regresses the failure mode this PR exists to remove. Pruning is shape-preserving for the signature (a rebaked guard reads the container's length and keys) but not for `__dict__`, which holds whatever a decorator happened to stash. The module scope is snapshotted once per module dict, so N functions from one module cost one copy of the scope rather than N. Everything a rebuilt function holds beyond what `FunctionType()` needs -- its defaults, kwdefaults, attributes and the module scope -- travels as pickle state rather than as a reduce argument, and so do a cell's contents. pickle memoizes an object only after saving its reduce arguments, so a value that reaches back to the function being reduced recurses until RecursionError. That is not a corner case: `wrapped = deco(base)` at module level puts the wrapper in its own globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching decorator stashes `wrapper` in its own `__dict__`. Only the globals were handled that way at first; the closure and `__dict__` cases were found in review, and since RecursionError was not among the exceptions `pickle_guards_state` mapped to `PackageError`, they escaped compilation as InternalTorchDynamoError. State is applied after memoization, so all of these now resolve to the pickle already built. An empty cell -- a free variable only assigned on a path that did not run -- has no contents to read, and reading them raised `ValueError` out of the pickler. Such a cell is now rebuilt empty. `AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped `__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the shared pieces -- how a code object, cell, module, bound method and function are rebuilt -- now live in `FunctionPicklerBase` in package.py. Each pickler keeps its own dispatch and decides what a function carries: the guard pickler prunes to what a guard reads, the AOT one prunes nothing because the runtime env has to run the function. `pickle_guards_state` turned only AttributeError into `PackageError`; anything else `dump` raised -- TypeError for an unpicklable value, PicklingError, the RecursionError above -- escaped as InternalTorchDynamoError. Every such failure means some guarded value cannot be serialized, which is exactly what `PackageError` is for: a bypass for non-strict callers and an error under `strict_precompile`, with the cause chained. So `dump` now maps any Exception to `PackageError`, and a test pins that with a guarded value whose own `__reduce__` raises. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py ``` Each behavior above was also checked by blunting one aspect of the reconstruction at a time and confirming a named test fails: cells or function attributes carried as reduce arguments again, an empty cell read unguarded, and `__module__` not restored each fail exactly one of the new tests. Authored with an AI assistant. ghstack-source-id: 8924927 Pull-Request: #195353
…at them One of the enabler fixes the precompile PR at the top of this stack needs. That PR serializes a Dynamo guard tree per captured variant and rebuilds it at load; this is what stops the rebuild from failing on ordinary library code. A serialized guard set cannot be loaded if any guard's source walks through a function whose qualname does not resolve back to it. `GuardsStatePickler` looks the function up by `__module__` and `__qualname__` and substitutes a `_Missing` sentinel when that finds something else. For a function nothing depends on that is correct. For one a guard is rooted at, evaluating the source against the sentinel raises while the guard manager is still being built, and the whole load fails. Any `functools.wraps` decorator produces the mismatch, since the wrapper copies the wrapped function's `__module__` and `__qualname__` while living in the decorator's file. That makes this ordinary rather than exotic: it is why a transformers model cannot be loaded from a compile package at all today. The sentinel stays for functions no guard needs. A function in `guard_tree_values` is pickled by value instead, rebuilt from its code object through the same path the `<locals>` branch already used. Most of the diff is what reaching that path from the fqn branch turned out to require, and the reason it is so much is that the reconstruction is directly observable: `load_guard_manager` re-runs guard construction against the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any attribute the reconstruction gets wrong does not fail the load, it produces a guard that never passes again. `__name__` (the old code passed `__qualname__` there), `__module__` (`FunctionType` derives it from the globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the length and keys of the signature containers are all load-bearing for that reason, and each has a round-trip test that mutates the live function and asserts the loaded guard rejects it. Rebuilding drags along whatever the function holds, and carrying all of it would let an unpicklable neighbour fail a package that never needed it. So the policy is to carry only what some guard tree node references and to prune the rest to sentinels -- the inverse of pickling the function wholesale, which is simpler but regresses the failure mode this PR exists to remove. Pruning is shape-preserving for the signature (a rebaked guard reads the container's length and keys) but not for `__dict__`, which holds whatever a decorator happened to stash. The module scope is snapshotted once per module dict, so N functions from one module cost one copy of the scope rather than N. Everything a rebuilt function holds beyond what `FunctionType()` needs -- its defaults, kwdefaults, attributes and the module scope -- travels as pickle state rather than as a reduce argument, and so do a cell's contents. pickle memoizes an object only after saving its reduce arguments, so a value that reaches back to the function being reduced recurses until RecursionError. That is not a corner case: `wrapped = deco(base)` at module level puts the wrapper in its own globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching decorator stashes `wrapper` in its own `__dict__`. Only the globals were handled that way at first; the closure and `__dict__` cases were found in review, and since RecursionError was not among the exceptions `pickle_guards_state` mapped to `PackageError`, they escaped compilation as InternalTorchDynamoError. State is applied after memoization, so all of these now resolve to the pickle already built. An empty cell -- a free variable only assigned on a path that did not run -- has no contents to read, and reading them raised `ValueError` out of the pickler. Such a cell is now rebuilt empty. `AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped `__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the shared pieces -- how a code object, cell, module, bound method and function are rebuilt -- now live in `FunctionPicklerBase` in package.py. Each pickler keeps its own dispatch and decides what a function carries: the guard pickler prunes to what a guard reads, the AOT one prunes nothing because the runtime env has to run the function. `pickle_guards_state` turned only AttributeError into `PackageError`; anything else `dump` raised -- TypeError for an unpicklable value, PicklingError, the RecursionError above -- escaped as InternalTorchDynamoError. Every such failure means some guarded value cannot be serialized, which is exactly what `PackageError` is for: a bypass for non-strict callers and an error under `strict_precompile`, with the cause chained. So `dump` now maps any Exception to `PackageError`, and a test pins that with a guarded value whose own `__reduce__` raises. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py ``` Each behavior above was also checked by blunting one aspect of the reconstruction at a time and confirming a named test fails: cells or function attributes carried as reduce arguments again, an empty cell read unguarded, and `__module__` not restored each fail exactly one of the new tests. Authored with an AI assistant. ghstack-source-id: 8924927 Pull-Request: #195353
[ghstack-poisoned]
…at them One of the enabler fixes the precompile PR at the top of this stack needs. That PR serializes a Dynamo guard tree per captured variant and rebuilds it at load; this is what stops the rebuild from failing on ordinary library code. A serialized guard set cannot be loaded if any guard's source walks through a function whose qualname does not resolve back to it. `GuardsStatePickler` looks the function up by `__module__` and `__qualname__` and substitutes a `_Missing` sentinel when that finds something else. For a function nothing depends on that is correct. For one a guard is rooted at, evaluating the source against the sentinel raises while the guard manager is still being built, and the whole load fails. Any `functools.wraps` decorator produces the mismatch, since the wrapper copies the wrapped function's `__module__` and `__qualname__` while living in the decorator's file. That makes this ordinary rather than exotic: it is why a transformers model cannot be loaded from a compile package at all today. The sentinel stays for functions no guard needs. A function in `guard_tree_values` is pickled by value instead, rebuilt from its code object the way the `<locals>` branch already did; both branches now share one reconstruction, so a `<locals>` function also gets the fixes below and is pruned the same way (it used to carry its defaults and closure verbatim, so one unpicklable neighbour failed the package). Most of the diff is what that reconstruction turned out to require, and the reason it is so much is that it is directly observable: `load_guard_manager` re-runs guard construction against the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any attribute the reconstruction gets wrong does not fail the load, it produces a guard that never passes again. `__name__` (the old code passed `__qualname__` there), `__module__` (`FunctionType` derives it from the globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the length and keys of the signature containers are all load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__` attribute, a default's value and the defaults' length, a kwdefault's value and the kwdefaults' keys, a global's value and the globals' key set has a capture-driven test that mutates the live function and asserts the loaded guard rejects it. Rebuilding drags along whatever the function holds, and carrying all of it would let an unpicklable neighbour fail a package that never needed it. So the policy is to carry only what some guard tree node references and to prune the rest to sentinels -- the inverse of pickling the function wholesale, which is simpler but regresses the failure mode this PR exists to remove. Pruning is shape-preserving for the signature (a rebaked guard reads the container's length and keys) but not for `__dict__`, which holds whatever a decorator happened to stash. The module scope is snapshotted once per module dict, so N functions from one module cost one copy of the scope rather than N. Everything a rebuilt function holds beyond what `FunctionType()` needs -- its defaults, kwdefaults, attributes and the module scope -- travels as pickle state rather than as a reduce argument, and so do a cell's contents. pickle memoizes an object only after saving its reduce arguments, so a value that reaches back to the function being reduced recurses until RecursionError. That is not a corner case: `wrapped = deco(base)` at module level puts the wrapper in its own globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching decorator stashes `wrapper` in its own `__dict__`. State is applied after memoization, so all of these resolve to the pickle already built. A cell's contents are wrapped in a 1-tuple on the way: pickle skips the state step when the state object is None, and `scale = None` is an ordinary closure variable that must not come back as an empty cell. An empty cell -- a free variable only assigned on a path that did not run -- has no contents to read, and reading them raised `ValueError` out of the pickler. Such a cell is now rebuilt empty. `AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped `__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the shared pieces -- how a code object, cell, module, bound method and function are rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers already depend on for `SerializedCode`. Each pickler keeps its own dispatch and decides what a function carries: the guard pickler prunes to what a guard reads, the AOT one prunes nothing because the runtime env has to run the function. The old pickle targets `_unpickle_nested_function`, `_unpickle_cell` and `_apply_function_globals` are gone; artifacts are gated on an exact `torch.__version__` match before any guard bytes are unpickled, so no saved artifact can reference them. `pickle_guards_state` turned only AttributeError into `PackageError`; anything else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped as InternalTorchDynamoError. Every such failure means some guarded value cannot be serialized, which is exactly what `PackageError` is for: a bypass for non-strict callers and an error under `strict_precompile`, with the cause chained. So `dump` now maps any Exception to `PackageError`, except RecursionError, which means a cycle the reducers did not route through state and should stay loud. The bypass itself did not work end to end: `bypass_package` clears the package on the output graph, but convert_frame checked the package it had been handed and then asserted on the missing guards state. It now checks the output graph's, and a non-strict caching_precompile test compiles a frame whose guarded default refuses to pickle and asserts it runs with a bypass and no cache entry. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py ``` Each behavior above was also checked by blunting one aspect of the fix at a time and confirming a named test fails: cells or function attributes carried as reduce arguments again, a cell's contents as bare state, an empty cell read unguarded, `__module__` not restored, and convert_frame checking the package it was handed. Authored with an AI assistant. ghstack-source-id: 0d7df67 Pull-Request: #195353
…at them One of the enabler fixes the precompile PR at the top of this stack needs. That PR serializes a Dynamo guard tree per captured variant and rebuilds it at load; this is what stops the rebuild from failing on ordinary library code. A serialized guard set cannot be loaded if any guard's source walks through a function whose qualname does not resolve back to it. `GuardsStatePickler` looks the function up by `__module__` and `__qualname__` and substitutes a `_Missing` sentinel when that finds something else. For a function nothing depends on that is correct. For one a guard is rooted at, evaluating the source against the sentinel raises while the guard manager is still being built, and the whole load fails. Any `functools.wraps` decorator produces the mismatch, since the wrapper copies the wrapped function's `__module__` and `__qualname__` while living in the decorator's file. That makes this ordinary rather than exotic: it is why a transformers model cannot be loaded from a compile package at all today. The sentinel stays for functions no guard needs. A function in `guard_tree_values` is pickled by value instead, rebuilt from its code object the way the `<locals>` branch already did; both branches now share one reconstruction, so a `<locals>` function also gets the fixes below and is pruned the same way (it used to carry its defaults and closure verbatim, so one unpicklable neighbour failed the package). Most of the diff is what that reconstruction turned out to require, and the reason it is so much is that it is directly observable: `load_guard_manager` re-runs guard construction against the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any attribute the reconstruction gets wrong does not fail the load, it produces a guard that never passes again. `__name__` (the old code passed `__qualname__` there), `__module__` (`FunctionType` derives it from the globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the length and keys of the signature containers are all load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__` attribute, a default's value and the defaults' length, a kwdefault's value and the kwdefaults' keys, a global's value and the globals' key set has a capture-driven test that mutates the live function and asserts the loaded guard rejects it. Rebuilding drags along whatever the function holds, and carrying all of it would let an unpicklable neighbour fail a package that never needed it. So the policy is to carry only what some guard tree node references and to prune the rest to sentinels -- the inverse of pickling the function wholesale, which is simpler but regresses the failure mode this PR exists to remove. Pruning is shape-preserving for the signature (a rebaked guard reads the container's length and keys) but not for `__dict__`, which holds whatever a decorator happened to stash. The module scope is snapshotted once per module dict, so N functions from one module cost one copy of the scope rather than N. Everything a rebuilt function holds beyond what `FunctionType()` needs -- its defaults, kwdefaults, attributes and the module scope -- travels as pickle state rather than as a reduce argument, and so do a cell's contents. pickle memoizes an object only after saving its reduce arguments, so a value that reaches back to the function being reduced recurses until RecursionError. That is not a corner case: `wrapped = deco(base)` at module level puts the wrapper in its own globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching decorator stashes `wrapper` in its own `__dict__`. State is applied after memoization, so all of these resolve to the pickle already built. A cell's contents are wrapped in a 1-tuple on the way: pickle skips the state step when the state object is None, and `scale = None` is an ordinary closure variable that must not come back as an empty cell. An empty cell -- a free variable only assigned on a path that did not run -- has no contents to read, and reading them raised `ValueError` out of the pickler. Such a cell is now rebuilt empty. `AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped `__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the shared pieces -- how a code object, cell, module, bound method and function are rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers already depend on for `SerializedCode`. Each pickler keeps its own dispatch and decides what a function carries: the guard pickler prunes to what a guard reads, the AOT one prunes nothing because the runtime env has to run the function. The old pickle targets `_unpickle_nested_function`, `_unpickle_cell` and `_apply_function_globals` are gone; artifacts are gated on an exact `torch.__version__` match before any guard bytes are unpickled, so no saved artifact can reference them. `pickle_guards_state` turned only AttributeError into `PackageError`; anything else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped as InternalTorchDynamoError. Every such failure means some guarded value cannot be serialized, which is exactly what `PackageError` is for: a bypass for non-strict callers and an error under `strict_precompile`, with the cause chained. So `dump` now maps any Exception to `PackageError`, except RecursionError, which means a cycle the reducers did not route through state and should stay loud. The bypass itself did not work end to end: `bypass_package` clears the package on the output graph, but convert_frame checked the package it had been handed and then asserted on the missing guards state. It now checks the output graph's, and a non-strict caching_precompile test compiles a frame whose guarded default refuses to pickle and asserts it runs with a bypass and no cache entry. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py ``` Each behavior above was also checked by blunting one aspect of the fix at a time and confirming a named test fails: cells or function attributes carried as reduce arguments again, a cell's contents as bare state, an empty cell read unguarded, `__module__` not restored, and convert_frame checking the package it was handed. Authored with an AI assistant. ghstack-source-id: 0d7df67 Pull-Request: #195353
[ghstack-poisoned]
…at them One of the enabler fixes the precompile PR at the top of this stack needs. That PR serializes a Dynamo guard tree per captured variant and rebuilds it at load; this is what stops the rebuild from failing on ordinary library code. A serialized guard set cannot be loaded if any guard's source walks through a function whose qualname does not resolve back to it. `GuardsStatePickler` looks the function up by `__module__` and `__qualname__` and substitutes a `_Missing` sentinel when that finds something else. For a function nothing depends on that is correct. For one a guard is rooted at, evaluating the source against the sentinel raises while the guard manager is still being built, and the whole load fails. Any `functools.wraps` decorator produces the mismatch, since the wrapper copies the wrapped function's `__module__` and `__qualname__` while living in the decorator's file. That makes this ordinary rather than exotic: it is why a transformers model cannot be loaded from a compile package at all today. The sentinel stays for a module-level function no guard needs. A function in `guard_tree_values` is pickled by value instead, rebuilt from its code object the way the `<locals>` branch already did; both branches now share one reconstruction, so a `<locals>` function also gets the fixes below and is pruned the same way (it used to carry its defaults and closure verbatim, so one unpicklable neighbour failed the package). Most of the diff is what that reconstruction turned out to require, and the reason it is so much is that it is directly observable: `load_guard_manager` re-runs guard construction against the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any attribute the reconstruction gets wrong does not fail the load, it produces a guard that never passes again. `__name__` (the old code passed `__qualname__` there), `__module__` (`FunctionType` derives it from the globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the length and keys of the signature containers are all load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__` attribute, a default's value and the defaults' length, a kwdefault's value and the presence of its key, a global's value and the globals' length has a capture-driven test that mutates the live function and asserts the loaded guard rejects it; an empty and a None-valued closure cell round-trip through a capture as well. Rebuilding drags along whatever the function holds, and carrying all of it would let an unpicklable neighbour fail a package that never needed it. So the policy is to carry only what some guard tree node references and to prune the rest to sentinels -- the inverse of pickling the function wholesale, which is simpler but regresses the failure mode this PR exists to remove. Pruning is shape-preserving for the signature (a rebaked guard reads the container's length and keys) but not for `__dict__`, which holds whatever a decorator happened to stash. Pruned values share one `_Missing` per reason, so a snapshot of a large module costs one sentinel rather than thousands, and the module scope is snapshotted once per module dict, so N functions from one module cost one copy of the scope rather than N. A rebuilt function whose `__globals__` no guard reads is instead given `import_module(__module__).__dict__`, which for a `functools.wraps` wrapper is the wrapped function's module; only a guard that walks `__globals__` forces the snapshot. Everything a rebuilt function holds beyond what `FunctionType()` needs -- its defaults, kwdefaults, attributes and the module scope -- travels as pickle state rather than as a reduce argument, and so do a cell's contents. pickle memoizes an object only after saving its reduce arguments, so a value that reaches back to the function being reduced recurses until RecursionError. That is not a corner case: `wrapped = deco(base)` at module level puts the wrapper in its own globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching decorator stashes `wrapper` in its own `__dict__`. State is applied after memoization, so all of these resolve to the pickle already built. A cell's contents are wrapped in a 1-tuple on the way: pickle skips the state step when the state object is None, and `scale = None` is an ordinary closure variable that must not come back as an empty cell. An empty cell -- a free variable only assigned on a path that did not run -- has no contents to read, and reading them raised `ValueError` out of the pickler. Such a cell is now rebuilt empty. `AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped `__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the shared pieces -- how a code object, cell, module, bound method and function are rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers already depend on for `SerializedCode`. Each pickler keeps its own dispatch and decides what a function carries: the guard pickler prunes to what a guard reads, the AOT one prunes nothing because the runtime env has to run the function. The pickle targets `_unpickle_nested_function` and `_unpickle_cell` are gone and the AOT `_unpickle_module` is renamed `_unpickle_python_module`. Precompile artifacts are gated on an exact `torch.__version__` match before any guard bytes are unpickled, and an `aot_compile` artifact from another version was never loadable (its version check runs after the outer unpickle, as before), so no loadable artifact references the old names. `pickle_guards_state` turned only AttributeError into `PackageError`; anything else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped as InternalTorchDynamoError. Every such failure means some guarded value cannot be serialized, which is exactly what `PackageError` is for: a bypass for non-strict callers and an error under `strict_precompile`, with the cause chained. So `dump` now maps any Exception to `PackageError`, except RecursionError, which means a cycle the reducers did not route through state and should stay loud. The bypass itself did not work end to end: `bypass_package` clears the package on the output graph, but convert_frame checked the package it had been handed and then asserted on the missing guards state. It now checks the output graph's. A bypassed entry also drops the backend ids it already registered and accepts no new ones, since it is never installed and its backends would otherwise be serialized for nothing. A non-strict caching_precompile test compiles a frame whose guarded default refuses to pickle and asserts it runs with a bypass, saves with no backend, and installs nothing on reload. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py ``` Each behavior above was also checked by blunting one aspect of the fix at a time and confirming a named test fails: cells or function attributes carried as reduce arguments again, a cell's contents as bare state, an empty cell read unguarded, `__module__` not restored, convert_frame checking the package it was handed, and a bypassed entry keeping its backend ids. Authored with an AI assistant. ghstack-source-id: f4a0551 Pull-Request: #195353
…at them One of the enabler fixes the precompile PR at the top of this stack needs. That PR serializes a Dynamo guard tree per captured variant and rebuilds it at load; this is what stops the rebuild from failing on ordinary library code. A serialized guard set cannot be loaded if any guard's source walks through a function whose qualname does not resolve back to it. `GuardsStatePickler` looks the function up by `__module__` and `__qualname__` and substitutes a `_Missing` sentinel when that finds something else. For a function nothing depends on that is correct. For one a guard is rooted at, evaluating the source against the sentinel raises while the guard manager is still being built, and the whole load fails. Any `functools.wraps` decorator produces the mismatch, since the wrapper copies the wrapped function's `__module__` and `__qualname__` while living in the decorator's file. That makes this ordinary rather than exotic: it is why a transformers model cannot be loaded from a compile package at all today. The sentinel stays for a module-level function no guard needs. A function in `guard_tree_values` is pickled by value instead, rebuilt from its code object the way the `<locals>` branch already did; both branches now share one reconstruction, so a `<locals>` function also gets the fixes below and is pruned the same way (it used to carry its defaults and closure verbatim, so one unpicklable neighbour failed the package). Most of the diff is what that reconstruction turned out to require, and the reason it is so much is that it is directly observable: `load_guard_manager` re-runs guard construction against the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any attribute the reconstruction gets wrong does not fail the load, it produces a guard that never passes again. `__name__` (the old code passed `__qualname__` there), `__module__` (`FunctionType` derives it from the globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the length and keys of the signature containers are all load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__` attribute, a default's value and the defaults' length, a kwdefault's value and the presence of its key, a global's value and the globals' length has a capture-driven test that mutates the live function and asserts the loaded guard rejects it; an empty and a None-valued closure cell round-trip through a capture as well. Rebuilding drags along whatever the function holds, and carrying all of it would let an unpicklable neighbour fail a package that never needed it. So the policy is to carry only what some guard tree node references and to prune the rest to sentinels -- the inverse of pickling the function wholesale, which is simpler but regresses the failure mode this PR exists to remove. Pruning is shape-preserving for the signature (a rebaked guard reads the container's length and keys) but not for `__dict__`, which holds whatever a decorator happened to stash. Pruned values share one `_Missing` per reason, so a snapshot of a large module costs one sentinel rather than thousands, and the module scope is snapshotted once per module dict, so N functions from one module cost one copy of the scope rather than N. A rebuilt function whose `__globals__` no guard reads is instead given `import_module(__module__).__dict__`, which for a `functools.wraps` wrapper is the wrapped function's module; only a guard that walks `__globals__` forces the snapshot. Everything a rebuilt function holds beyond what `FunctionType()` needs -- its defaults, kwdefaults, attributes and the module scope -- travels as pickle state rather than as a reduce argument, and so do a cell's contents. pickle memoizes an object only after saving its reduce arguments, so a value that reaches back to the function being reduced recurses until RecursionError. That is not a corner case: `wrapped = deco(base)` at module level puts the wrapper in its own globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching decorator stashes `wrapper` in its own `__dict__`. State is applied after memoization, so all of these resolve to the pickle already built. A cell's contents are wrapped in a 1-tuple on the way: pickle skips the state step when the state object is None, and `scale = None` is an ordinary closure variable that must not come back as an empty cell. An empty cell -- a free variable only assigned on a path that did not run -- has no contents to read, and reading them raised `ValueError` out of the pickler. Such a cell is now rebuilt empty. `AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped `__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the shared pieces -- how a code object, cell, module, bound method and function are rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers already depend on for `SerializedCode`. Each pickler keeps its own dispatch and decides what a function carries: the guard pickler prunes to what a guard reads, the AOT one prunes nothing because the runtime env has to run the function. The pickle targets `_unpickle_nested_function` and `_unpickle_cell` are gone and the AOT `_unpickle_module` is renamed `_unpickle_python_module`. Precompile artifacts are gated on an exact `torch.__version__` match before any guard bytes are unpickled, and an `aot_compile` artifact from another version was never loadable (its version check runs after the outer unpickle, as before), so no loadable artifact references the old names. `pickle_guards_state` turned only AttributeError into `PackageError`; anything else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped as InternalTorchDynamoError. Every such failure means some guarded value cannot be serialized, which is exactly what `PackageError` is for: a bypass for non-strict callers and an error under `strict_precompile`, with the cause chained. So `dump` now maps any Exception to `PackageError`, except RecursionError, which means a cycle the reducers did not route through state and should stay loud. The bypass itself did not work end to end: `bypass_package` clears the package on the output graph, but convert_frame checked the package it had been handed and then asserted on the missing guards state. It now checks the output graph's. A bypassed entry also drops the backend ids it already registered and accepts no new ones, since it is never installed and its backends would otherwise be serialized for nothing. A non-strict caching_precompile test compiles a frame whose guarded default refuses to pickle and asserts it runs with a bypass, saves with no backend, and installs nothing on reload. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py ``` Each behavior above was also checked by blunting one aspect of the fix at a time and confirming a named test fails: cells or function attributes carried as reduce arguments again, a cell's contents as bare state, an empty cell read unguarded, `__module__` not restored, convert_frame checking the package it was handed, and a bypassed entry keeping its backend ids. Authored with an AI assistant. ghstack-source-id: f4a0551 Pull-Request: #195353
[ghstack-poisoned]
…at them One of the enabler fixes the precompile PR at the top of this stack needs. That PR serializes a Dynamo guard tree per captured variant and rebuilds it at load; this is what stops the rebuild from failing on ordinary library code. A serialized guard set cannot be loaded if any guard's source walks through a function whose qualname does not resolve back to it. `GuardsStatePickler` looks the function up by `__module__` and `__qualname__` and substitutes a `_Missing` sentinel when that finds something else. For a function nothing depends on that is correct. For one a guard is rooted at, evaluating the source against the sentinel raises while the guard manager is still being built, and the whole load fails. Any `functools.wraps` decorator produces the mismatch, since the wrapper copies the wrapped function's `__module__` and `__qualname__` while living in the decorator's file. That makes this ordinary rather than exotic: it is why a transformers model cannot be loaded from a compile package at all today. The sentinel stays for a module-level function no guard needs. A function in `guard_tree_values` is pickled by value instead, rebuilt from its code object the way the `<locals>` branch already did; both branches now share one reconstruction, so a `<locals>` function also gets the fixes below and is pruned the same way (it used to carry its defaults and closure verbatim, so one unpicklable neighbour failed the package). Most of the diff is what that reconstruction turned out to require, and the reason it is so much is that it is directly observable: `load_guard_manager` re-runs guard construction against the deserialized scope, so an EQUALS_MATCH constant is rebaked by reading the rebuilt function. Any attribute the reconstruction gets wrong does not fail the load, it produces a guard that never passes again. `__name__` (the old code passed `__qualname__` there), `__module__` (`FunctionType` derives it from the globals it is handed, which for the snapshot branch is empty), `__kwdefaults__`, `__dict__`, and the length and keys of the signature containers are all load-bearing for that reason. Each of `__name__`, `__module__`, a `__dict__` attribute, a default's value and the defaults' length, a kwdefault's value and the presence of its key, a global's value and the globals' length has a capture-driven test that mutates the live function and asserts the loaded guard rejects it; an empty and a None-valued closure cell round-trip through a capture as well. Rebuilding drags along whatever the function holds, and carrying all of it would let an unpicklable neighbour fail a package that never needed it. So the policy is to carry only what some guard tree node references and to prune the rest to sentinels -- the inverse of pickling the function wholesale, which is simpler but regresses the failure mode this PR exists to remove. Pruning is shape-preserving for the signature (a rebaked guard reads the container's length and keys) but not for `__dict__`, which holds whatever a decorator happened to stash. Pruned values share one `_Missing` per reason, so a snapshot of a large module costs one sentinel rather than thousands, and the module scope is snapshotted once per module dict, so N functions from one module cost one copy of the scope rather than N. A rebuilt function whose `__globals__` no guard reads is instead given `import_module(__module__).__dict__`, which for a `functools.wraps` wrapper is the wrapped function's module; only a guard that walks `__globals__` forces the snapshot. Everything a rebuilt function holds beyond what `FunctionType()` needs -- its defaults, kwdefaults, attributes and the module scope -- travels as pickle state rather than as a reduce argument, and so do a cell's contents. pickle memoizes an object only after saving its reduce arguments, so a value that reaches back to the function being reduced recurses until RecursionError. That is not a corner case: `wrapped = deco(base)` at module level puts the wrapper in its own globals, a wrapper that reads `wrapper.flag` closes over itself, and a caching decorator stashes `wrapper` in its own `__dict__`. State is applied after memoization, so all of these resolve to the pickle already built. A cell's contents are wrapped in a 1-tuple on the way: pickle skips the state step when the state object is None, and `scale = None` is an ordinary closure variable that must not come back as an empty cell. An empty cell -- a free variable only assigned on a path that did not run -- has no contents to read, and reading them raised `ValueError` out of the pickler. Such a cell is now rebuilt empty. `AOTCompilePickler` in aot_compile.py was a copy of the same reducers and had the same bugs (`__qualname__` as `__name__`, the empty cell, and it dropped `__kwdefaults__` and `__dict__` outright). Rather than fix each twice, the shared pieces -- how a code object, cell, module, bound method and function are rebuilt -- now live in `FunctionPicklerBase` in package.py, which both picklers already depend on for `SerializedCode`. Each pickler keeps its own dispatch and decides what a function carries: the guard pickler prunes to what a guard reads, the AOT one prunes nothing because the runtime env has to run the function. The pickle targets `_unpickle_nested_function` and `_unpickle_cell` are gone and the AOT `_unpickle_module` is renamed `_unpickle_python_module`. Precompile artifacts are gated on an exact `torch.__version__` match before any guard bytes are unpickled, and an `aot_compile` artifact from another version was never loadable (its version check runs after the outer unpickle, as before), so no loadable artifact references the old names; such an artifact whose runtime env holds a cell or nested function now fails inside that unpickle with an AttributeError on the old name rather than with the version error. Carrying a nested function's `__dict__` also means a helper holding an unpicklable attribute, a lock say, now fails `aot_compile` at save where it used to serialize with the attribute silently dropped. `pickle_guards_state` turned only AttributeError into `PackageError`; anything else `dump` raised -- TypeError for an unpicklable value, PicklingError -- escaped as InternalTorchDynamoError. Every such failure means some guarded value cannot be serialized, which is exactly what `PackageError` is for: a bypass for non-strict callers and an error under `strict_precompile`, with the cause chained. So `dump` now maps any Exception to `PackageError`, except RecursionError, which means a cycle the reducers did not route through state and should stay loud. The bypass itself did not work end to end: `bypass_package` clears the package on the output graph, but convert_frame checked the package it had been handed and then asserted on the missing guards state. It now checks the output graph's. A bypassed entry also drops the backend ids and guarded codes it already registered and accepts no new backends, since it is never installed and they would otherwise be serialized for nothing. A non-strict caching_precompile test compiles a frame whose guarded default refuses to pickle and asserts it runs with a bypass, saves an entry with no backend, and installs nothing when the cache is reloaded. Test Plan: ``` python test/dynamo/test_guard_serialization.py python test/dynamo/test_aot_compile.py python test/dynamo/test_package.py ``` Each behavior above was also checked by blunting one aspect of the fix at a time and confirming a named test fails: cells or function attributes carried as reduce arguments again, a cell's contents as bare state, an empty cell read unguarded, `__module__` not restored, convert_frame checking the package it was handed, and a bypassed entry keeping its backend ids. Authored with an AI assistant. ghstack-source-id: f14e3ee Pull-Request: #195353
|
@claude /pr-review |
PR Review: #195353
|
[ghstack-poisoned]
|
@claude /pr-review |
|
Claude finished @bobrenjc93's task in 51m 48s —— View job PR Review: #195353Re-review at head Full review details
What changed since
|
[ghstack-poisoned]
|
@claude /pr-review |
PR Review: #195353
|
[ghstack-poisoned]
|
@claude please re-review: round-39 fixes are in (all inline threads addressed; FAQ updated in the description). |
|
Claude finished @bobrenjc93's task in 6m 43s —— View job PR Review: #195353Re-review at head Full review details
What changed since
|
[ghstack-poisoned]
|
@claude please re-review: round-40 fixes are in (every finding from the last review is fixed or answered in the description's FAQ). |
|
Claude finished @bobrenjc93's task in 46m 22s —— View job PR Review: #195353Re-review at head Full review details
What changed since
|

Stack from ghstack (oldest at bottom):
Enabler for the precompile PR at the top of this stack.
GuardsStatePicklerlooks a function up by__module__and__qualname__andsubstitutes a
_Missingsentinel when that resolves elsewhere; everyfunctools.wrapswrapper and module-level lambda is such a mismatch. For afunction a guard is rooted at,
load_guard_managerthen evaluates the sourceagainst the sentinel and the load fails.
A function in
guard_tree_valuesis now pickled by value and rebuilt from itscode object, sharing one reconstruction with the
<locals>branch in thenew
FunctionPicklerBase(package.py); the AOT pickler is rebuilt on thatsame base in the follow-up commit above this one.
The rebuilt function restores
__name__,__module__,__doc__,__kwdefaults__,__dict__and the signature containers' shape, since a rebaked EQUALS_MATCHreads them. Only values a guard references are carried; the rest become shared
_Missingsentinels, and a function whose__globals__no guard reads getsimport_module(__module__).__dict__at load. Everything beyond theFunctionType()arguments travels as pickle state so self-referential valuesdo not recurse; an empty cell is rebuilt empty; a bound method whose function
does not resolve back is carried explicitly.
pickle_guards_statemaps any exception -- including a RecursionErrorfrom a deep or non-memoizing guard value -- to
PackageError, and the bypassnow works: convert_frame checks the output
graph's package, which
bypass_packageclears, and a bypassed entry drops itsbackend ids and guarded codes.
Test Plan:
The new tests mutate each restored attribute on the live function and assert
the loaded guard rejects it, and pin empty and None-valued cells, lambda and
bound-method roots, a module gone at load, the recursion-overflow-to-PackageError conversion, and
a non-strict bypass.
Authored with an AI assistant.
FAQ
Q: The bound-method branch in reducer_override emits a value that reduces back
to the same branch on a second pass; it reads like a no-op that could be
dropped. Why keep it?
A: It is load-bearing. The guard policy serializes guard state twice, and by
the second pass a method's receiver has already been degraded to the _Missing
sentinel. Emitting the binding unconditionally makes the branch a fixed point:
its own output reduces to itself, so the second pass is stable. Dropping it
would let the method degrade to _Missing on the second pass, re-pinning that
method's TYPE_MATCH to the sentinel, and the loaded artifact would then never
match a live receiver. The branch fires for every method reached during the
dump, so it is exercised, not dead.
Q: The delta ships some testing nits: a bare
assertRaises(RecursionError)where the file's convention is
assertRaisesRegex; noassertIsNotpinning theper-call
{}identity split; no guard-side round-trip for__type_params__;and the bound-method seeding loop is never exercised. Why not close these?
A: Triaged individually. The
RecursionErrorcase is the one place a regex addsnothing:
RecursionErrorcarries CPython's "maximum recursion depth exceeded"boilerplate, not a message this code authors, so
assertRaisesRegexwould pininterpreter text rather than our contract; the sibling PackageError test regexes
precisely because it has an authored message. The
{}-identity split isdeliberate and, as the comment at
_unpickle_fn_from_snapshotnow records,unobservable -- no serialized guard reads
__globals__identity -- so anassertIsNotwould lock in behavior nothing depends on. The__annotations__round-trip WAS reachable here -- a guard reading an annotationvalue rebakes a TYPE_MATCH on the
__annotations__dict plus an ID_MATCH on thevalue type, both of which the by-value reconstruction must restore -- so it is
now folded in as the
annotationssubtest oftest_guard_rooted_at_fqn_mismatched_function, which mutates the restored__annotations__and asserts the loaded guard rejects it. The earlier claimthat annotations are "a verbatim assignment the runtime never evaluates" was an
AOT-path argument that does not hold on the guard path.
__type_params__remains genuine test debt. Every 3.12+ function already exercises the branch
with the empty tuple; a non-empty value needs PEP 695 syntax (3.12+), which this
test file cannot contain while it must parse on 3.10/3.11, so the test needs an
exec'd source and is deferred for the 2000-line gate. The pruned case matters: a
def f[T]TypeVar is not picklable by reference. The pre-dump bound-method seeding loop wasredundant for every reachable case and is now removed: get_guard_manager_from_source
seeds func where every guarded method is known, and the in-reducer write stays
as the belt-and-suspenders no-op described below.
Q: The bound-method seed gates on
id(leaf) in guard_tree_values, which isid-based; bound methods are ephemeral, so when the registered instance differs
from the pytree leaf the seed silently does not happen. And the in-reducer write
at guards.py is dead for every case the pre-dump loop covers. Fix both?
A: The id-based gate is correct for every case with coverage today; the failure
mode it misses (a fresh
MethodTypematerialized bybuilder.getdifferingfrom the pytree leaf) is a latent gap, and an equality fallback on
(__func__, __self__)is the right hardening but is not exercised by anycurrent test, so it is deferred rather than added blind. The in-reducer write is
a deliberate belt-and-suspenders no-op: it cannot fire for the covered cases and
is harmless for the rest; it is annotated as such rather than deleted so the two
registration sites stay symmetric.
Q: The Note's claim that "a guard never calls the rebuilt function" is not
strictly true --
WeakRefCallSource._name_templateis"{0}()", sobuilder.getwould call the value. Shouldn't the claim be softened?
A: Latent and not currently reachable: no guard reconstructed on this path is
rooted at a
WeakRefCallSourceover a reconstructed function. The comment on theshared
_unpickle_fn_from_modulealready scopes the "reads attributes withoutcalling it" claim to the guard-serialization path and spells out that the shared
AOT path does call it (surfacing an empty scope as a call-time
NameError); theWeakRefCallSourcecorner is the same "if a future guard shape calls it" caveatand is noted here rather than complicating the inline comment.
Q: Now that a guard-serialization bypass actually saves a package, a bypassed
frame that also graph-breaks saves a live resume-function entry beside the
bypassed parent. Does the next process die on load with "Name '_resume_at..'
already exists in scope" once the bypassed parent recompiles?
A: Not at the stack head. #195911 renames every installed resume function to a
per-install token-suffixed name, so the name the package owns
(_resume_at) is disjoint from the plain
_resume_at_ a recompiling bypassed parent regenerates. The
install-owned global and the regenerated one no longer share a name, so
install() binding entry.function_names above the
if entry.bypassed: continuecannot collide with CleanupHook.create. The underlying "install()-owned global
vs. a later recompile" overlap is pre-existing -- the named-parameters bypass at
output_graph.py reaches it too -- and is orthogonal to this commit.
Q: bypass_current_entry clears the bypassed entry's backend_ids and
guarded_codes, but never removes the inlined-source contribution that same
entry made to the package-global _source_info during an earlier successful
compile of the same code object (the entry is keyed by code object and reused
across recompiles). cache_entry() serializes _source_info whole, so at load
initialize() raises "Source code changes detected" for a helper only the now-
empty bypassed entry ever inlined, and eval_frame discards the ENTIRE package.
Shouldn't a bypassed entry stop contributing checksummed sources?
A: The _cached_backends half of this is fixed here: bypass now pops the entry's
compiled backends from the package-global cache before clearing backend_ids, so
a dead GraphModule is no longer stranded under an id no entry references. The
_source_info half is a real but narrower gap and is deferred deliberately.
_source_info has no per-entry attribution -- it is a package-global set that
add_inlined_source accumulates across every non-bypassed compile, and a loaded
artifact carries only that flattened blob with no per-entry breakdown, so
recomputing it from the live non-bypassed entries at cache_entry() time would
silently drop the sources a load-then-resave package legitimately inherited. The
honest fix is per-entry inlined-source attribution carried in the artifact
format, so a bypassed entry's uniquely-owned sources drop out while sources a
live entry still shares stay -- a serialization-format change, tracked
separately. Its only observable consequence is a SAFE over-invalidation: a
package whose sole referencer of an edited helper was bypassed is discarded and
recompiled cold, never a wrong result or a crash, which is why the format change
is deferred rather than rushed in here.
Q: _unpickle_fn_from_module swallows any import failure into f_globals = {} for
both the guard-serialization and AOT paths, so an AOT load succeeds and then
NameErrors from arbitrary call depth at first call, instead of failing cleanly
at load time with a ModuleNotFoundError. Why not stash the failed module name,
or have the AOT subclass re-raise?
A: The reducer is shared with the guard-serialization path, which reads
attributes off the rebuilt function without ever calling it and must tolerate an
exec-created or transformers_modules.* module that only existed in sys.modules
at save time. A single swallow keeps that path robust; the AOT path documents
the residual first-call NameError as a known limitation. Re-raising on the AOT
subclass would break the guard path's tolerance, so it is not done here.
Stashing the unresolved module name in the reduce state so the eventual
NameError can be attributed to the missing module is a cheap future improvement
and is tracked separately.
Q: The new
hasattr(cls, "__getattr__")clause in the bound-method reducer(package.py) makes the explicit
(func, self)reduce fire for EVERY nn.Modulemethod -- nn.Module defines getattr -- not just the getattr proxy the
comment describes. Isn't that far wider than documented, and shouldn't it use
inspect.getattr_static(cls, name) to narrow it?
A: Revised: the reducer now asks the class MRO first.
inspect.getattr_static(cls, name) is func-- which never runs a user__getattr__-- means the name isclass-served, so the method returns to pickle's default
getattr(self, name)atload and its
__func__stays the class attribute; any other name on an INSTANCEreceiver (an instance-dict monkeypatch, a slot, a
__getattr__proxy, a property)is carried as
(func, self)explicitly and never probed -- probing runs usercode, can recurse, and a property hands back the bare function (the reducer used
to probe there and reloaded such a method as a plain function). Only a type
receiver (a classmethod) is still probed. The earlier coarse
hasattr(cls, "__getattr__")gate was correct for the guard path but, once the AOT pickler adopted the shared
reducer (#196454), it rebuilt every
<locals>nn.Module method by value -- anunpicklable default then failed the save and the reloaded
__func__was nolonger the class attribute -- so the MRO check is a correctness fix there, not
an optimization. A decorated
forward(the MRO serves the wrapper, not__wrapped__) still takes the explicit path. (The sibling guards.py edge runs no user__getattr__either: it readsdict through object.getattribute -- a type-level
__dict__propertyis still invoked (pickle itself stopped doing so in 3.11, where
object.__getstate__reads the slot directly) and only its AttributeError isabsorbed; a class that makes
__dict__a raising property is out of scope, asit is for
vars()-- and no longer touchesannotations at all, so the two halves of the commit do not take opposite positions on
running user code.)
Q: pr-sanity-checks is red -- this commit is 2228 LOC, over the 2000-line gate.
Shouldn't it be split?
A: Done. The AOT-pickler half -- rebuilding
AOTCompilePickleron the sharedFunctionPicklerBase, the_dumps_cleanlyprune, and the__doc__/__kwdefaults__split -- moved to the follow-up commit above this one, bringing this commit under
the gate. The two halves split cleanly along a file seam (aot_compile.py and its
test move out; package.py's shared base, guards.py, convert_frame.py and the guard
tests stay), and the combined tree is unchanged. What remains here is one cohesive
unit: the fqn-mismatch guard reconstruction plus the guard-tree pruning that makes
the reconstructed guards serializable, with their tests. The bulk of the remaining
delta is new guard-serialization test cases, not new control flow.
Q:
isinstance(source, AttrSource)missesGenericAttrSource, whose member alsolives in
obj.__dict__. Is that a third whole-container shape the edge repairshould cover?
A: Not a reachable one.
GenericAttrSourceis produced only bySuperVariablehandling
object.__getattribute__(variables/misc.py), and the verbatim-__dict__hazard exists only for a receiver that is itself a function -- the only object
_reduce_functionprunes. Dynamo cannot traceobject.__getattribute__(fn, name)or
super(FunctionType, fn).__getattribute__(name)on a function receiver: bothraise an observed exception during tracing and the frame is skipped, so no guard
is ever rooted through such a source on a function. Adding the type would be dead
code; the test-pinned
AttrSourceshape is the one that exists.Q:
getattr(base_example_value, "__dict__", None)runs a user__getattr__on a__slots__receiver, and a non-AttributeError raised there escapes guardcreation as an InternalTorchDynamoError -- outside the
pickle_guards_statebypass. Real bug?
A: Yes -- fixed. The mapping edge now reads
__dict__throughobject.__getattribute__and treats AttributeError as "no instance dict", so nouser
__getattr__or__getattribute__runs on that path (a class-level__dict__property is still invoked, and only its AttributeError absorbed;pickle itself stopped reading
__dict__through the attribute protocol in 3.11). The read is package.py's_instance_dict, sharedwith the bound-method reducer's receiver probe here and with #195912's
whole-object pruner, whose
hasattr(obj, "__dict__")gate had the same hole;test_attribute_guard_on_a_slotted_receiver_runs_no_user_getattrcompiles thereviewer's slotted receiver end to end under caching_precompile. Reproduced with a slotted class whose
__getattr__raises RuntimeError under
caching_precompile: before, the compile failed with aninternal error; after, the frame compiles and the guard state serializes.
Q: The
__annotations__append in the same block should be deleted: reading itdirectly forces PEP 649 evaluation on 3.14 (NameError for a TYPE_CHECKING-only
name), on <3.14
getattr(cls, "__annotations__", None)materializes an empty dictINTO the class/module
__dict__, and the edge it records is keyed on theannotation dict while pointing at the attribute VALUE, which is not an element of
that dict. And the annotations subtest is already covered.
A: All correct -- the append is gone. A guard that reads an annotation value is
rooted at
DictGetItemSource(AttrSource(fn, "__annotations__"), name), whosebase_example_valueIS the annotations dict, so the generic edge at the top ofthe block already records exactly the right container->element edge; the
annotationssubtest oftest_guard_rooted_at_fqn_mismatched_functionexercisesthat path and still passes with the append removed. Only the
__dict__half ofthe repair remains, and the comments and the
_keep_container_verbatimdocstringno longer name
__annotations__as a repaired shape.Q: FunctionPicklerBase's docstring says the reducers are "shared by
GuardsStatePickler and AOTCompilePickler" and a comment describes what "the
shared AOT path" does, but at this commit the base has one subclass and the
resolve=Truebranch of_read_raw_annotationshas no caller.A: Fixed by moving the AOT-only parts up. The docstring and the
_build_functioncomment now describe the one subclass this commit has and say the AOT pickler is
rebuilt on the base in the commit above (#196454), which also rewords them back
to the shared form; the
resolve=keyword and itsFormat.VALUEbranch moved to#196454 with their only caller. The combined tree is unchanged.
Q:
_reduce_bound_methodprobesgetattr(method.__self__, "__dict__", None)BEFORE the
hasattr(cls, "__getattr__")exemption, so a slotted receiver whose__getattr__recurses raises RecursionError out of the probe -- landing in thebypass instead of the
(func, self)reduce the comment promises.A: Fixed. The receiver probe reads
__dict__throughobject.__getattribute__(AttributeError -> no instance dict) so a user
__getattr__never runs there, andthe slotted
__getattr__proxy now takes the intended explicit-binding reduce.Q: The description says a bypassed entry drops its compiled backends from
_cached_backends, but at this commitbypass_current_entryonly clearsbackend_idsandguarded_codes; the pop lives in #195913.A: Fixed by moving those lines down into this commit (they were byte-identical to
#195913's, whose diff shrinks by the same lines).
add_backend_idruns duringcall_user_compiler, beforebuild_guardscan trigger the bypass, so the entry'sbackend is already cached when it is bypassed and the pop is needed here.
Q:
test_fqn_mismatched_function_prunes_an_unpicklable_called_defaultand..._a_verbatim_dict_readcompile a module and assert nothing; a bypass wouldpass them.
A: Fixed. Both now clear PrecompileContext, compile, and assert the single dynamo
entry
save_to_dynamo_cache()reports carries a non-emptybackend_ids-- abypassed frame has none -- so a regression to carrying the container verbatim
(a PackageError bypass under non-strict precompile) fails the test.
Q: The RecursionError bypass message ("guard state exceeded the recursion limit
while pickling") names no frame; shouldn't it say WHERE?
A: Deliberately not by walking the object graph -- that recurses again on an
already-exhausted stack, as the comment says. The frame is still identifiable:
the PackageError is turned into a bypass by
bypass_package, whose"Detected a package bypass" log record is emitted inside that frame's compile and
carries its CompileId prefix, so the log context names the frame. (The
strict_precompileraise on that path had a pre-existing uninterpolated%s;this commit fixes that one-liner while touching the area.)
Q: The Note in GuardsStatePickler says "a registered CONTAINER is carried
verbatim rather than pruned per element", contradicting
_keep_container_verbatim,and the convert_frame comment says the bypass fires when guards "could not be
serialized" although
output_graph.py's named-parameters bypass reaches it too.A: Both comments corrected: the Note now says a registered plain container is
carried verbatim UNLESS a guard is rooted at one of its elements through it, and
the convert_frame comment names both bypass producers.
Q: Per-value pruning can silently and permanently kill a whole-container value
guard, and the shape is ordinary code:
if self.fn.__defaults__ == (2.0, 1.0)(EQUALS_MATCH on the tuple, no per-element source) plus
self.fn(x, b=5.0)(aDefaultsSource edge for
a) makes_keep_container_verbatimprunebto_Missing, the EQUALS_MATCH is rebaked from the pruned tuple at load, and everycall recompiles forever with a healthy-looking package. The docstring's "coexist by
construction" claim does not hold.
A: Confirmed (reproduced: reloaded
__defaults__ == (2.0, _Missing(...)),fail_on_recompile trips) and fixed by tracking the missing fact rather than
documenting it:
EQUALS_MATCHrecords the id of the value it bakes(
GuardBuilder.guard_tree_verbatim, save path only;CONSTANT_MATCHdelegatesthere for tuples -- a dict is never value-baked, its comparison decomposes into
per-key guards whose values register in
guard_tree_values-- whileSEQUENCE_LENGTH/DICT_KEYS/TYPE_MATCH/ID_MATCH bake no contents and need nothing), and
_keep_container_verbatimkeeps such acontainer verbatim before consulting the child edges. The two cases now really are
disjoint: a container some guard bakes whole is carried verbatim (an unpicklable
sibling there is a loud bypass, and cannot occur for a literal tuple anyway), and
only a container nothing reads by value prunes per value. The
__dict__per-valuepath is unaffected because a whole-
__dict__read installs no EQUALS_MATCH. Theregression is pinned at zero cost:
GuardedDefaultsTupleModule.forwardnow alsocalls
self.fn(x, b=5.0), sotest_nested_function_preserves_a_guarded_defaults_tuplefails without the fix and passes with it.
Q: The pre-dump loop in
pickle_guards_statethat seeds a guarded boundmethod's
__func__looks like a no-op: the only writer that puts a bound methodinto
guard_tree_valuesisget_guard_manager_from_source, which seeds__func__in the same statement under the same
save_guardsgate.A: Correct, and measured (across the whole serialization suite the loop would
have seeded zero functions), so it is deleted; the source-site seed is the
load-bearing one and the in-reducer write remains as the belt-and-suspenders
no-op an earlier FAQ describes.
Q: The two full-compile container-edge tests assert only that the frame was
captured (
backend_idsnon-empty), which cannot distinguish "serialized fine" from"serialized fine but the guard never matches again" -- exactly the silent failure
mode the Note warns about.
A: Both now capture, save, reset, reload through the transparent cache and serve
under
fail_on_recompile(_assert_reloads_and_still_matches), so a rebakedguard that no longer matches fails the test; the blocker shape above is pinned by
the defaults-tuple test the same way.
Q:
__doc__is pruned unconditionally, so a plain-strdocstring is dropped anda docstring-less function comes back with a truthy
_Missinginstead ofNone.A: Fixed: a
strorNone__doc__is kept (it always pickles); only areassigned non-str object is pruned. Nothing on the guard path reads
__doc__unless a guard is rooted there, in which case
_keepalready kept it, so this isfidelity, not correctness.
Q:
guard_tree_verbatimis aset[int]whileguard_tree_valuesis a dict thatpins the objects its ids came from; an EQUALS_MATCH
id(val)of a freshly builtvalue could dangle and be recycled onto an unrelated container.
A: Made a
dict[int, Any]for uniformity (zero cost). The hazard was latentrather than live:
GuardBuilder.getmemoizes every source's value insrc_get_value_cache, so thevalEQUALS_MATCH records is the same objectget_guard_manager_from_sourcestores inguard_tree_values, pinned for the wholepickle_guards_statecall (measured over both suites: all 61 recorded ids resolveto live, identical objects). Pinning it directly removes the reliance on that
invariant.
Q:
bypass_current_entry()in the bypass test runs before any backend isregistered, so the new
_cached_backendspop loop iterates zero times and nothingpins it.
A: The test now registers a backend id under the code context first, bypasses,
and asserts
cached_backendsis empty.Q: "A dict/tuple SUBCLASS is always verbatim" reads unconditional, but the
_keepgate above it means an unkept subclass prunes per value and comes back asa plain dict/tuple.
A: Docstring corrected to "a KEPT dict/tuple subclass is always verbatim"; an
unkept container has no guard rooted at it (edges are keyed on values that
_keepholds), so its type is nobody's business.Q: The fqn-resolution walk (module + qualname, rebuild by value when it does not
round back) lives only in the guard pickler; the AOT pickler dispatches on the
<locals>marker alone, so afunctools.wrapswrapper of a module-level functiondiverges between the two.
A: Lifted into
FunctionPicklerBase._fqn_resolveshere and used by the guardpickler; #196454 switches the AOT dispatch to it, which is the "shared so a fix
cannot be missed" promise of the base class. (
pickle_guards_statealso gained theguard_tree_verbatimargument this round; #195912's hand-built builder namespacein its path test is updated to carry it.)
Q: For an instance receiver whose class serves the name through a property (or
any descriptor that is not the function itself), the reducer's
getattr(self, name)probe runs the descriptor and can return the bare function, sofunc is innersays "class-served" and the method reloads as a plain function.A: Real; fixed. The reducer no longer probes an instance receiver at all: an
instance-dict entry is carried explicitly, a
getattr_statichit on the class isclass-served, and anything else on an instance (slot,
__getattr__proxy,property, other descriptor) is carried as
(func, self)explicitly. Only a typereceiver (a classmethod bound to its class) is still probed.
test_bound_method_on_an_instance_served_name_is_not_probedcovers the threereceiver kinds in one subTest loop and asserts the property was never read.
Q:
_globals_snapshotprunes__builtins__to the sentinel, so a function therebuilt function creates at call time cannot resolve builtins through
__globals__.A: The affected shape is narrow -- only a guard-pickler function whose
__globals__a guard reads AND which is later called takes the snapshot path;the AOT pickler passes no snapshot and loads its functions through the real
module dict -- but the hardening is free, so the snapshot now carries the
builtinsmodule for__builtins__instead of pruning it.Q:
third_party/kinetois bumped in this commit.A: A stale gitlink from rebasing across main's kineto bump (#196015 -> #196325),
not an intended change; reset to the base's commit here, which is the only commit
in the stack that touched it.
Q:
BUILTIN_MATCHnow checksisinstance(source.index, str); is that thiscommit's change?
A: No. That line is on origin/main, on this commit's parent and on the PR base
branch (introduced by #196370, "Type source keys and region hashes as object");
git diff <parent> <this commit> -- torch/_dynamo/guards.pyhas no hunk touchingused_builtin_vars. The comparison was against a stale base.Q:
test_a_whole_tuple_guard_keeps_defaults_verbatimpasses noguard_tree_verbatim, so it exercises the absent-edge branch, not the record thename promises.
A: Fixed: the fixture now passes a child edge (which alone would prune the
sibling) together with the verbatim record, so the test fails without
_keep_container_verbatim's record check.Q:
_unpickle_fn_from_moduleimportsfn.__module__for the rebuilt function'sscope, but
functools.wrapscopies__module__from the wrappee, so a wrapperdefined in another module is rebuilt against the wrong globals.
A: Fixed here (the base class owns the reducer): the no-snapshot reduce now
carries both
fn.__module__(for the rebuilt function's__module__) and thecompile scope,
fn.__globals__["__name__"], which is what gets imported for__globals__. A function whose__module__is None still has a scope. Theguard path never calls a rebuilt function, so the AOT pickler (#196454, which
does) carries the test:
test_aot_compile_rebuilt_wrapper_keeps_its_own_module_scope.Q:
snapshot["__builtins__"] = builtinsinserts the key unconditionally, so asnapshot can be one entry longer than the dict it mirrors.
A: Fixed: the insert is gated on the key being present in the live dict. A
function built with
types.FunctionType(code, {})has no__builtins__andCPython resolves its nested functions' builtins from the interpreter, so an
absent key needs no replacement, and a
DICT_KEYS_MATCH/SEQUENCE_LENGTHguard on such a
__globals__sees the live shape.test_snapshot_globals_function_preserves_modulenow asserts the reloaded__globals__["__builtins__"]is the module.Q:
_instance_dict's docstring claims more than the read guarantees, and thebound-method seeding "loop-only shape" (a raw function as a separate unguarded
leaf) has no test.
A: Docstring corrected (a user
__getattr__/__getattribute__never runs; atype-level
__dict__property does, and only its AttributeError is absorbed).test_guard_rooted_at_fqn_mismatched_bound_methodnow also passes the rawfunction as an unguarded leaf, which the pre-dump
missing_valuespass wouldprune if the source-site seed did not keep it whole.