Repository navigation
[precompile] Name the guard bindings that cannot be repointed by configuration - #197263
Closed
bobrenjc93 wants to merge 17 commits into
Closed
bobrenjc93 wants to merge 17 commits into
bobrenjc93 wants to merge 17 commits into
Conversation
[ghstack-poisoned]
This was referenced Sep 16, 2026
Closed
Closed
pytorchgreenlight
Bot
dismissed
their stale review
September 21, 2026 15:27
This pull request was reverted; greenlight's approval no longer applies.
[ghstack-poisoned]
This was referenced Sep 21, 2026
Closed
Closed
Closed
Closed
Closed
Closed
Closed
Closed
bobrenjc93
added a commit
that referenced
this pull request
Sep 21, 2026
) **Summary.** Whatever autocast state the capture ran under is already baked into the artifact -- ATen casts for the eager backend, generated kernels for inductor -- but the artifact still re-dispatches at serve time (the eager graph's ATen calls, and on the inductor path every fallback op, which is emitted at its `.default` overload -- e.g. `aten.addbmm.default`, which AutocastCPU registers), so a serving process with autocast enabled would cast a second time. Both inlined drivers now run the graph under `torch._C._DisableAutocast()`, the `c10::impl::ExcludeDispatchKeyGuard` over `autocast_dispatch_keyset` (`torch/csrc/autograd/init.cpp`) that AOTAutograd already emits into its own generated wrappers as `_DisableAutocast_` when a compile ran under autocast (`torch/_functorch/_aot_autograd/runtime_wrappers.py`). It is one RAII exclusion of the autocast keys for every device: no per-device list, no nesting counter, and no `clear_autocast_cache()` on exit, so it is safe to enter unconditionally on every call and leaves the caller's autocast state exactly as it found it. This pins autocast off for the duration of the call regardless of capture-time or serve-time state, exactly like the eager driver's pre-existing unconditional `no_grad`; the programming-model docstring gets the same sentence in the later commit that rewrites it (E2). AOTAutograd's guard is conditional on the capture having run under autocast; precompile's is unconditional because the leak it closes runs the other way too (a capture made without autocast, served under it), which is the case the test exhibits. An earlier draft of this commit recorded a `GRAPH_DEVICES` metadata field and entered `torch.amp.autocast(dev, enabled=False)` per device; that reimplemented the primitive with a narrower cache-clear hazard (any exit that returns autocast's nesting count to zero wipes the process-wide cast cache), so the field, its emitter and its parser entry are gone and the artifact format is unchanged from the parent. ## Before and after ```python compiled = PrecompiledModule(lambda m, x: m(x), backend="eager") compiled._compile((model, x)) ns = {"__name__": "artifact"} exec(compiled.to_python_code(), ns) with torch.autocast("cpu", dtype=torch.bfloat16): out = ns["forward"](model, x) # parent: the captured graph re-dispatched under autocast and cast its inputs a second time (bf16 out) # now: the driver runs call(...) under torch._C._DisableAutocast() (fp32 out, equal to the # no-autocast call), and the caller's autocast state is as it was afterwards ``` ## The driver change ```python # _eager_forward: with _torch._C._DisableAutocast(), _torch.no_grad(): out = list(call([...])) # _inductor_forward: with _torch._C._DisableAutocast(): out = list(call([...])) ``` `test_artifact_neutralizes_ambient_autocast` (parametrized over both backends, CPU bf16 autocast) captures a `torch.addbmm` model and checks that a call under ambient autocast returns the fp32 result of eager `model(x)` computed outside any autocast, that the ambient region is still live and bf16 after the call, and that autocast is off again after the region. `addbmm` is the op that makes the inductor case load-bearing on CPU: `KERNEL_CPU(addbmm, lower_precision_fp)` registers it for AutocastCPU, `make_fallback(aten.addbmm)` leaves it undecomposed, and `FallbackKernel` keeps builtin aten ops at their functional overload, so the inductor artifact calls `torch.ops.aten.addbmm.default` (the `Linear`/`addmm` graph cannot show this: `extern_kernels.addmm` binds `addmm.out`, which autocast never registers). Deleting either guard fails its case: eager with `bfloat16 != float32`, inductor with `assert_tensor_metadata` raising `expected dtype torch.float32 but got torch.bfloat16`. Test Plan: ``` python test/test_precompile.py -k autocast python test/test_precompile.py lintrunner torch/_precompile.py torch/_precompile_driver.py test/test_precompile.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197279 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721, #197276, #197278 Re-land of #197279, reverted in 70f4f9b as a dependent of #197262 (whose test the re-land below fixes). ghstack-source-id: bf1865a
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…iguration (#197263) (#197962) **Problem.** The risky-drop lint needs to recognise dropped identity guards whose value cannot resolve to a different object on the serving machine, and the simple checks (`__module__ == "builtins"`, a bare `type` test) are fooled by shims and `functools.wraps`. **Fix.** Add `_reads_a_builtin` (a CPython-built builtin read under its own name through Dynamo's builtins dict), `_defined_where_read` (a def or class bound under its own name in the file that read it, compared by code object), `_is_dynamo_synthesized` and `_dynamo_alias_module`. Nothing calls them yet. **Summary.** The risky-drop lint asks, for each identity guard that serialization dropped, whether the value it guarded could resolve to a different object on the serving machine, and this commit adds the small predicates that recognise bindings where that cannot happen. `_reads_a_builtin` is true for `len` or `sorted` reached the ordinary way, through the `__builtins_dict__*` global Dynamo installs, but only under the builtin's own name, only for a value `builtins` itself owns, and only for one CPython built (a builtin function or a static type carrying `Py_TPFLAGS_IMMUTABLETYPE`), because that dict is the frame's live `builtins.__dict__` and a shim can install anything into it under any name. `_defined_where_read(value, global_name, user_stack)` is true for a def, or through its own methods a class statement, bound under its own name whose code lives in the file that read it -- the one binding the inlined-source checksum of that file covers -- comparing `__qualname__` against the code object's own name and the code object's `co_filename` (never `__module__`, which `functools.wraps` copies) against the OUTERMOST frame of the guard's `user_stack`, with only absolute filenames on both sides admitted. `_is_dynamo_synthesized` recognises the `__nested_resume_fns` local every generated resume function takes and an entry read straight off it, and `_dynamo_alias_module` maps an `__import_a_dot_b` global back to the module it aliases, both leaning on prefixes this commit names individually in `torch/_dynamo/aot_compile.py` (`_IMPORT_ALIAS_PREFIX`, `_BUILTINS_DICT_PREFIX`) rather than restating the strings. Nothing calls these yet; `_module_namespaces` and `_is_risky_drop`, which do, follow once the library-module classifier is in. ## Examples ```python import torch from torch._dynamo import precompile_package as pp from torch._dynamo.source import ( AttrSource, CellContentsSource, ClosureSource, GetItemSource, GlobalSource, LocalSource, TypeSource, ) pp._dynamo_alias_module("__import_torch_dot_nn_dot_functional") # sys.modules["torch.nn.functional"] pp._dynamo_alias_module("F") # None: not a Dynamo alias pp._owning_module(torch.nn.functional) # "torch.nn.functional" (a module names itself) pp._owning_module(torch.nn.functional.gelu) # "torch._C._nn": the extension module that defines gelu pp._owning_module(3) # None: an int has no __module__ entry = GetItemSource(LocalSource("__nested_resume_fns"), 0) pp._is_dynamo_synthesized(entry) # True cell = CellContentsSource(GetItemSource(ClosureSource(entry), 0), "cell_contents") pp._is_dynamo_synthesized(AttrSource(TypeSource(cell), "__call__")) # False: a value the resume function closes over pp._is_dynamo_synthesized(GetItemSource(LocalSource("__nested_frame_values"), 0)) # False: a nested frame's stack and locals pp._is_dynamo_synthesized(GlobalSource("__nested_resume_fns")) # False: a user global spelled like it ``` ## The prefixes, named in `aot_compile.py` ```python # torch/_dynamo/aot_compile.py, parent _MINTED_GLOBAL_PREFIXES = ("__import_", "__builtins_dict__", _UNNAMED_SCOPE_PREFIX) # now _IMPORT_ALIAS_PREFIX = "__import_" _BUILTINS_DICT_PREFIX = "__builtins_dict__" _MINTED_GLOBAL_PREFIXES = (_IMPORT_ALIAS_PREFIX, _BUILTINS_DICT_PREFIX, _UNNAMED_SCOPE_PREFIX) ``` The `__import_` and `__builtins_dict__` prefixes are two of the three `_MINTED_GLOBAL_PREFIXES` torch/_dynamo/aot_compile.py already keeps; this commit names them there individually and `precompile_package.py` imports them rather than restating the strings, which are minted as bare literals in `OutputGraph.install_builtins_dict_in_fglobals` and `symbolic_convert.import_source` and pinned against a real compile by `test_minted_global_names_match_dynamo`. ## `_owning_module` and `_dynamo_alias_module` ```python def _owning_module(value): if isinstance(value, types.ModuleType): return value.__name__ owner = getattr(value, "__module__", None) return owner if isinstance(owner, str) else None def _dynamo_alias_module(global_name): if not global_name.startswith(_IMPORT_ALIAS_PREFIX): return None tail = global_name[len(_IMPORT_ALIAS_PREFIX):] return sys.modules.get(tail.replace("_dot_", ".")) ``` `_owning_module` has one caller here, `_reads_a_builtin`; `_module_namespaces` and `_is_risky_drop` reuse it once they arrive. `_dynamo_alias_module` maps an `__import_a_dot_b` global back to the module it aliases: the OutputGraph's `import_sources` table is authoritative, but a guard entry does not carry it, and the unmangling collides only for a module whose name contains `_dot_` (`pkg.sub_dot_mod` is aliased as `__import_pkg_dot_sub_dot_mod`, which comes back as `pkg.sub.mod` when that module is loaded too); that collision fails open, since the callers judge the module returned. A torch_package module is aliased without the prefix and comes back None, which fails closed. ## `_is_dynamo_synthesized` ```python _DYNAMO_SYNTHESIZED = ("__nested_resume_fns",) def _is_dynamo_synthesized(source): if isinstance(source, GetItemSource) and isinstance(source.index, int): source = source.base return isinstance(source, LocalSource) and source.local_name in _DYNAMO_SYNTHESIZED ``` It recognises the `__nested_resume_fns` local Dynamo passes into every generated resume function as its first parameter, a list of generated resume functions rather than a slot any config chooses, and an entry read straight off it (`__nested_resume_fns[0]`), nothing deeper: a resume function's closure cells carry the resumed frame's cell variables, so `type(__nested_resume_fns[0].__closure__[0].cell_contents).__call__`, which Dynamo mints for a callable an inner def captured, is the user's and is judged like any other value (an earlier revision walked to the source root and waived it). Its sibling `__nested_frame_values` is deliberately not covered, because it carries the live stack and locals of the frames nested INSIDE the one resuming, which pops the last entry off it for the callee it resumes (under `nested_graph_breaks=True` a callee's `act = pick()` reaches its caller's resume frame as `L['__nested_frame_values'][0][2]`, `[0]` selecting the frame and the tail a position in its values, not a key), so a guard rooted there must be judged like the local or intermediate it stands for. ## `_reads_a_builtin` ```python def _reads_a_builtin(source, value): return ( isinstance(source, DictGetItemSource) and isinstance(source.base, GlobalSource) and source.base.global_name.startswith(_BUILTINS_DICT_PREFIX) and ( isinstance(value, types.BuiltinFunctionType) or (isinstance(value, type) and bool(vars(type)["__flags__"].__get__(value) & (1 << 8))) # Py_TPFLAGS_IMMUTABLETYPE ) and _owning_module(value) == "builtins" and getattr(value, "__name__", None) == source.index ) ``` It requires the guard's source to be a `DictGetItemSource` whose base is a `GlobalSource` named `__builtins_dict__...` AND the value to be a `types.BuiltinFunctionType` or a `type` carrying `Py_TPFLAGS_IMMUTABLETYPE` AND its `__module__` to be `builtins` AND its `__name__` to equal the dict key; `_reads_a_builtin` reads `source.base` itself. A builtin parked in `self.act = abs` is a slot like any other, so the test keys on where the read comes FROM, not on who owns the value. That dict is the frame's live `builtins.__dict__`, not a table of the real builtins, so a shim's `builtins.py2_sum = sum` is a binding under it that another machine's shim can point elsewhere; the read is waived only under the builtin's own name (`IOError` and `EnvironmentError`, CPython's aliases of `OSError`, fail closed), and only for a value CPython built: `functools.wraps` copies `__module__` and `__name__` onto a Python shim installed as `builtins.sum = wraps(sum)(logged_sum)`, whose `CLOSURE_MATCH` the serializer drops, and a class statement exec'd with the builtins namespace as its globals (or handed `__module__ = "builtins"`) claims the module outright, which a bare `type` test waived; a class statement or `type()` call does not carry the flag. The flag is read through `type`'s own descriptor, so a metaclass can neither shadow it nor make the read raise, and a static type's `__module__` is derived from its C name; a builtin function's `__module__` is a writable member, though, so `builtins.getcwd = os.getcwd` plus `os.getcwd.__module__ = "builtins"` is waived, evidence rather than proof on that branch, which an advisory lint over a dropped-guard set does not defend against. Every callable in `builtins.__dict__` is one of those two kinds apart from the `_sitebuiltins` objects, instances of neither, and beside the aliases (`WindowsError` is a third on Windows) three of them fail closed: | key | why it fails closed | | --- | --- | | `IOError`, `EnvironmentError` (`WindowsError` on Windows) | aliases: `__name__` is `OSError`, not the key | | `open` | the one builtin function `builtins` does not own: `__module__` is `_io`, `io` before 3.12, so a dropped guard on one of the most mainstream builtins here is reported | | `ExceptionGroup` (3.11+) | a heap type, no `Py_TPFLAGS_IMMUTABLETYPE` | | `__loader__` | a heap type, and read under a name that is not its own as well | The exposure is narrow either way, since a registered builtin is id-matched into a `BUILTIN_MATCH` the serializer keeps and only a deregistered, polyfilled one (`sum`, `enumerate`, `all`, `any`) or such a shim reaches the dropped set the lint examines. ## `_defined_where_read` ```python def _defined_where_read(value, global_name, user_stack): if not user_stack or not isinstance(value, (type, types.FunctionType)): return False # a bound method or proxy is refused before any read if value.__qualname__ != global_name: return False # act = _impl_a if ... else _impl_b, op = Ops.op, a factory's def def compiled_as(fn, qualname): # wraps copies __qualname__ but not the code object's own name if sys.version_info >= (3, 11): return fn.__code__.co_qualname == qualname return fn.__code__.co_name == qualname.rpartition(".")[2] if isinstance(value, type): skip = ("__annotate__", "__annotate_func__") files = [] for key, attr in vars(value).items(): # unwrap staticmethod/classmethod via __func__, property via fget ... if attr.__qualname__ == f"{global_name}.{key}" and compiled_as(attr, ...): files.append(attr.__code__.co_filename) else: files = [value.__code__.co_filename] if compiled_as(value, global_name) else [] read = user_stack[0].filename # the OUTERMOST frame if not os.path.isabs(read): return False try: here = _norm(read) return any(os.path.isabs(f) and _norm(f) == here for f in files) except ValueError: # an embedded NUL, which posixpath.realpath lets through return False ``` **The name rule.** `_defined_where_read(value, global_name, user_stack)` takes the read's `GlobalSource.global_name` (not the `G['op']` spelling `GuardFilterEntry.name` keeps) and is true for a def, or through its own methods a class statement, bound under its own name whose code lives in the file that read it, the one binding the inlined-source checksum of that file covers, unlike `from impl_a import op`, which only takes a conditional import the checksum never sees; it checks the name itself rather than leaving that to the caller, and compares `__qualname__`, so `act = _impl_a if cfg.fast else _impl_b` in the reading file is a slot and so are `op = Ops.op` and a def returned by a factory, and the paths are compared normalized. The `__qualname__` is backed by the code object's own name, which `functools.wraps` copies onto a wrapper's `__qualname__` but cannot forge (`co_qualname`; before 3.11 only `co_name`, so a wrapper def named after what it wraps slips through there), so a same-file `wraps` decorator a flag turns on is a slot in both arms. Only a plain function or a class is judged: a bound method or any other object forwarding `__qualname__` and `__code__` is refused before an attribute is read, which also keeps a proxy that answers reads by raising, such as `torch.classes.<ns>`, out of the value slot. **The file comes off the code object.** The file is read off the value's code object rather than off `__module__`, because `functools.wraps` copies `__module__` along with `__name__` and `__qualname__`: ```python op = torch.compile(op) # behind a flag: claims the reader's module, code lives in eval_frame.py -> not waived @torch.no_grad() # an unconditional cross-file decorator on a same-file def -> not waived either def op(x): ... cached = functools.lru_cache(op) # no code object at all -> not waived ``` The object does not tell the flag shape from an unconditional cross-file decorator, so a same-file def under `@torch.no_grad()` is not waived either and the risky-drop lint reports it. Anything else without a code object, such as a `functools.lru_cache` wrapper, which claims the reader's module the same way, is not waived. **A class is judged by its own methods.** A class has no code object, and its `__module__` is no better: `namedtuple` and `type()` stamp it from the calling frame (`make_dataclass` does so from Python 3.12) under a BARE `__qualname__` (a def or class statement inside the factory would carry `factory.<locals>.`), so a `Point = namedtuple("Point", "x y")` in the reader looks exactly like a class statement; the frame stamped is the caller's, so the collision needs a factory called from the reading file, `lib.make_point()` coming back stamped `lib`. Its methods can tell: a class statement compiles its defs in its own file under its own `__qualname__` prefix, so a class is waived when at least one function in its own `__dict__`, stored under key `k` with `__qualname__` `Cls.k` (a staticmethod or classmethod unwrapped through `__func__` and a property through `fget`, by type rather than by `getattr`, since a class attribute can be a proxy such as `torch.classes.<ns>` that answers any attribute read by raising; a `cached_property` keeps its function under `.func` and does not count), was compiled in the reading file. ```python class Ops: # waived: op compiled here under Ops.op @staticmethod def op(x): return x class Marker: pass # fails closed: no def of its own Point = collections.namedtuple("Point", "x") # bare __qualname__ "Point", methods compiled in collections -> not waived type("Point", (), {"area": _area}) # a factory fed a same-file def: qualname "_area", not "Point.area" -> not waived from mypkg.impl import Point; Point.extra = _extra # attached afterwards keeps its bare qualname -> not waived Point.norm = functools.wraps(Point.norm)(_norm) # forges "Point.norm", code object still named "_norm" -> not waived ``` A function attached afterwards keeps its bare qualname, and one attached through `functools.wraps` keeps its code object's own name, so a class imported from another file that the reader extends or patches is refused, as is a factory fed same-file methods (`type(name, bases, {"area": _area})`, `make_dataclass(name, cfg.fields, namespace={"area": _area})`), and `class Marker: pass` fails closed; so does a class statement whose only functions are generated: a fields-only `@dataclass`'s and a `NamedTuple`'s are defs of a factory (dataclasses' `__create_fn__`, `namedtuple`), so their code objects' own qualname carries the factory's `<locals>.` prefix (on 3.10, where only `co_name` exists, the `<string>` or stdlib file they compile in refuses them instead), and an `Enum`'s arrive in the subclass `__dict__` under `Enum.` qualnames the key rule refuses, so a plain config dataclass read as a global is reported. The one function the compiler itself puts in a class `__dict__`, the PEP 649 annotate function Python 3.14 stores for an annotated class body, compiles in the reading file, but under key `__annotate_func__` with `__qualname__` `Cls.__annotate__`, so the key rule refuses it and the verdict on a config dataclass is the same on every version; the scan also skips both annotate keys outright, against a version that stores the function under its own name. **Only absolute filenames compare.** A `co_filename` is not always a path: an `exec` records `<string>` and a REPL `<stdin>`, and `realpath` resolves either against the cwd, so an ungated comparison made every `<string>` compilation one file and waived a def exec'd under it the moment the reading frame was exec-generated too (on 3.10 a fields-only dataclass as well, whose `__init__` compiles in `<string>` under a `co_name` that cannot tell it from a class statement's def). Only absolute filenames on both sides are compared (the gate `_norm` documents and `_classify_file` applies to a recorded `__file__`); a pseudo-filename, a relative spelling and an embedded NUL, which makes `posixpath.realpath` raise, fail closed. **The frame read.** The filename compared is that of the OUTERMOST frame in the guard's `user_stack`. That frame is the one being compiled, whose globals a bare `GlobalSource` denotes (`InliningInstructionTranslator._load_global` mints one only when the inlined frame's globals are the root's, and otherwise reads through an `__import_` alias or an `___unnamed_scope` dict entry); the stack itself is stamped in `GuardsSet.add` with the inlining stack at the moment the guard is installed, which for a lazily realized global is the point of first use, so the innermost frame can be a helper inlined from another file, and reading the file off it would waive `from b import op` whenever `op` is first used inside a helper inlined from `b`. **The known gap.** What the predicate cannot see, and its docstring says so, is a same-name fork inside the reading file (`try: from x import impl as op` / `except ImportError: def op`, or a class statement under the same `if`), which binds a different def per machine under one checksum; that is the conditional-bind KNOWN GAP `_is_risky_drop` records. ## Tests Each predicate is pinned on hand-built sources by a test of its own, except `_defined_where_read`, which gets six `test_defined_where_read_*` methods, one per shape family so a premise that holds only on some CPython versions cannot mask another family's rows. - `test_reads_a_builtin_keys_on_where_the_read_comes_from` pins `len` read through the builtins dict as waived, a builtin in a slot, a user table keyed `len`, the same table read off a slot (`self.act_fns["len"]`, the unnarrowed source the lint hands over, refused rather than read as a global) and user code injected into builtins as not, and a `functools.wraps(sum)` shim under the `sum` key as not (the test asserts `(__module__, __name__) == ("builtins", "sum")` first) while `sum` under its own key is and so is `int`, a type passing the CPython-built conjunct. The remaining conjuncts each get rows of their own: `IOError` and `EnvironmentError` under their own keys (CPython-built, but named `OSError`), `open` under its own key (a builtin function named `open`, but owned by `io` or `_io` depending on the version and never by `builtins`, so the `__module__` conjunct is what refuses it; the test asserts those two facts first), a user exception class installed into builtins under its own name and a class exec'd with the builtins namespace as its globals (the test asserts it claims `__module__ == "builtins"` first; both are heap types, so the flag is what refuses them), a class whose metaclass shadows `__flags__` with the immutable bit while claiming `builtins` (refused, since the flag is read through `type`'s descriptor) and one whose metaclass makes the `__flags__` read raise (refused without raising), all not waived, and every type in `builtins.__dict__` read under its own name waived except `ExceptionGroup`, the one heap type there read under its own name (`__loader__` is a heap type too, and the test pins that its `__name__` is not the key). - `test_dynamo_synthesized_covers_only_the_resume_function_list` pins the list and its entry as synthesized and, past the entry, the resume function's `__closure__`, a cell's contents and `type(...).__call__` off it as not, beside `__nested_frame_values`, a same-named global and an ordinary local. - `test_alias_module_and_owning_module` pins `__import_torch_dot_nn_dot_functional` to `torch.nn.functional` and as None a user global whose tail past the prefix length names a module (`imported_torch`), an unknown tail and a torch_package alias, which `import_source` mints without the prefix, and the `_dot_` collision, `__import_mypkg_dot_sub_dot_mod` (the alias of `mypkg.sub_dot_mod` as much as of `mypkg.sub.mod`) coming back as the loaded `mypkg.sub.mod`; `_owning_module` answers None for an int and for a `__module__` that is not a string. - `test_defined_where_read_needs_the_name_and_the_file` pins the name and file rules: a same-file def under its own name is waived, also through another spelling of the path and on a two-frame stack whose inner frame is torch/nn/functional.py (where `F.silu` is not), and not under another name, from another file, with no stack, or for `F.silu` and an int; a staticmethod extracted under its own name and a def returned by a factory are not waived (`__qualname__` tells); a module-level def exec'd under this file's name is waived, as the documented gap. - `test_defined_where_read_takes_the_file_off_the_code_object` pins the `torch.compile` wrapper (the test asserts it claims this module first), a `functools.lru_cache` wrapper and a `@torch.no_grad()`-decorated def as not waived, a same-file conditional `functools.wraps` decorator as waived with the flag off (the def itself comes back) and not with it on (the wrapper forges `__qualname__`; its code object is named `wrapper`), and a bound method of the same-file def and a namespace forwarding its `__qualname__` and `__code__` as refused by type before either is read. - `test_defined_where_read_judges_a_class_by_its_own_methods` pins the test class itself as waived when read from this file and not from another, and `torch.nn.Linear` as not; a same-file class with one staticmethod is waived, so is one with one classmethod (both the `__func__` arm) and one whose only def is a `@property` (the `fget` arm), while one whose only def is a `functools.cached_property` is not, nor is a same-file class with no method of its own, a fields-only `@dataclass` or a `NamedTuple` (their generated defs carry the factory's `<locals>.` in `co_qualname`; on 3.10 the `<string>` or stdlib file they compile in refuses them) or an `Enum` (its functions carry `Enum.` qualnames the key rule refuses); and an `nn.Module` subclass holding `torch.classes.<ns>` as a class attribute, which the test first shows raises `RuntimeError` on an attribute read (`Model.ns.__func__`), is judged like any other class (waived from this file, not from another) instead of raising out of the predicate, the proxy itself handed over as the value is refused by type, and the namespace `torch.classes` fabricated for that read is removed from it again in a cleanup. - `test_defined_where_read_refuses_a_class_minted_for_the_file` pins a `namedtuple` (the test asserts it claims this module under a bare `__qualname__` first), a `make_dataclass` (bare `__qualname__` asserted; the module is stamped only from 3.12) and a `type()` class as not waived, nor a `type()` class handed a same-file def in its namespace, under another key or under the def's own name (a bare qualname either way, so the class half of the rule, the missing `Point.` prefix, is what refuses both); the key half gets its own pair, a same-file class statement's method handed to a `type()` class of the same `__qualname__`, waived under its own key `m` and not borrowed under `other`; nor is a class compiled under torch/nn/functional.py's name (the imported-class shape) waived with a same-file function attached afterwards or with a method replaced through `functools.wraps` (the test asserts the forged `Point.norm` qualname beside the code object's own `_norm` name first). - `test_defined_where_read_skips_the_compiler_annotate_function` pins the fields-only `@dataclass` as not waived and, on 3.14, first asserts what the compiler stored beside its generated methods: key `__annotate_func__`, qualname `Cfg.__annotate__` on the function and on its code object, compiled in this file; that is replayed on every version through a `type()` class handed a same-file function under that key, the qualname stamped on the function and on its code object as a class statement's def carries it (not waived), beside a control row with the same function under an ordinary key and matching qualname (waived, so the replay is the shape a class statement produces) and the two rows that pin the `skip`, the function under `__annotate__` or `__annotate_func__` with a `Cfg.<key>` qualname (not waived). - `test_defined_where_read_refuses_a_pseudo_filename` reads a def exec'd under `<string>` (the test asserts its `co_filename` first) from a `<string>` frame, the row that pins the gate on every version (a fields-only `@dataclass` collides only on 3.10, where `co_name` cannot refuse it first), and a same-file def from a relative frame filename (`os.path.relpath(__file__)`, which the test asserts resolves to this file), the same def with that relative spelling as its own `co_filename` read from an absolute frame, from a frame filename with an embedded NUL and with a NUL in its own `co_filename`, all not waived and none raising. - `test_minted_global_names_match_dynamo` pins the names the predicates lean on (the two prefixes, spelled in aot_compile.py, and the two nested-resume locals) against the code that mints them, through a real compile: a `__builtins_dict__` read, an `__import_` alias, and, under `nested_graph_breaks=True` (the harness runs every test with it on; the config default is off), the two locals every generated resume function takes and roots a guard at, judged on the sources Dynamo actually minted: off `__nested_resume_fns` exactly the list and its `[0]` entry are synthesized, while `type(__nested_resume_fns[0].__closure__[0].cell_contents).__call__`, the guard on a callable the resumed frame's inner def captured, is present and is not; nothing rooted at `__nested_frame_values` is. ## What comes next Nothing calls these yet; `_module_namespaces` and `_is_risky_drop`, which do, follow once the library-module classifier is in. Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_reads_a_builtin -k test_dynamo_synthesized -k test_alias_module -k test_defined_where_read -k test_minted_global_names python test/dynamo/test_precompile_package.py lintrunner torch/_dynamo/precompile_package.py torch/_dynamo/aot_compile.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in 0dbac14 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197962 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Problem. The risky-drop lint needs to recognise dropped identity guards whose value cannot resolve to a different object on the serving machine, and the simple checks (
__module__ == "builtins", a baretypetest) are fooled by shims andfunctools.wraps.Fix. Add
_reads_a_builtin(a CPython-built builtin read under its own name through Dynamo's builtins dict),_defined_where_read(a def or class bound under its own name in the file that read it, compared by code object),_is_dynamo_synthesizedand_dynamo_alias_module. Nothing calls them yet.Summary. The risky-drop lint asks, for each identity guard that serialization dropped, whether the value it guarded could resolve to a different object on the serving machine, and this commit adds the small predicates that recognise bindings where that cannot happen.
_reads_a_builtinis true forlenorsortedreached the ordinary way, through the__builtins_dict__*global Dynamo installs, but only under the builtin's own name, only for a valuebuiltinsitself owns, and only for one CPython built (a builtin function or a static type carryingPy_TPFLAGS_IMMUTABLETYPE), because that dict is the frame's livebuiltins.__dict__and a shim can install anything into it under any name._defined_where_read(value, global_name, user_stack)is true for a def, or through its own methods a class statement, bound under its own name whose code lives in the file that read it -- the one binding the inlined-source checksum of that file covers -- comparing__qualname__against the code object's own name and the code object'sco_filename(never__module__, whichfunctools.wrapscopies) against the OUTERMOST frame of the guard'suser_stack, with only absolute filenames on both sides admitted._is_dynamo_synthesizedrecognises the__nested_resume_fnslocal every generated resume function takes and an entry read straight off it, and_dynamo_alias_modulemaps an__import_a_dot_bglobal back to the module it aliases, both leaning on prefixes this commit names individually intorch/_dynamo/aot_compile.py(_IMPORT_ALIAS_PREFIX,_BUILTINS_DICT_PREFIX) rather than restating the strings. Nothing calls these yet;_module_namespacesand_is_risky_drop, which do, follow once the library-module classifier is in.Examples
The prefixes, named in
aot_compile.pyThe
__import_and__builtins_dict__prefixes are two of the three_MINTED_GLOBAL_PREFIXEStorch/_dynamo/aot_compile.py already keeps; this commit names them there individually andprecompile_package.pyimports them rather than restating the strings, which are minted as bare literals inOutputGraph.install_builtins_dict_in_fglobalsandsymbolic_convert.import_sourceand pinned against a real compile bytest_minted_global_names_match_dynamo._owning_moduleand_dynamo_alias_module_owning_modulehas one caller here,_reads_a_builtin;_module_namespacesand_is_risky_dropreuse it once they arrive._dynamo_alias_modulemaps an__import_a_dot_bglobal back to the module it aliases: the OutputGraph'simport_sourcestable is authoritative, but a guard entry does not carry it, and the unmangling collides only for a module whose name contains_dot_(pkg.sub_dot_modis aliased as__import_pkg_dot_sub_dot_mod, which comes back aspkg.sub.modwhen that module is loaded too); that collision fails open, since the callers judge the module returned. A torch_package module is aliased without the prefix and comes back None, which fails closed._is_dynamo_synthesizedIt recognises the
__nested_resume_fnslocal Dynamo passes into every generated resume function as its first parameter, a list of generated resume functions rather than a slot any config chooses, and an entry read straight off it (__nested_resume_fns[0]), nothing deeper: a resume function's closure cells carry the resumed frame's cell variables, sotype(__nested_resume_fns[0].__closure__[0].cell_contents).__call__, which Dynamo mints for a callable an inner def captured, is the user's and is judged like any other value (an earlier revision walked to the source root and waived it). Its sibling__nested_frame_valuesis deliberately not covered, because it carries the live stack and locals of the frames nested INSIDE the one resuming, which pops the last entry off it for the callee it resumes (undernested_graph_breaks=Truea callee'sact = pick()reaches its caller's resume frame asL['__nested_frame_values'][0][2],[0]selecting the frame and the tail a position in its values, not a key), so a guard rooted there must be judged like the local or intermediate it stands for._reads_a_builtinIt requires the guard's source to be a
DictGetItemSourcewhose base is aGlobalSourcenamed__builtins_dict__...AND the value to be atypes.BuiltinFunctionTypeor atypecarryingPy_TPFLAGS_IMMUTABLETYPEAND its__module__to bebuiltinsAND its__name__to equal the dict key;_reads_a_builtinreadssource.baseitself. A builtin parked inself.act = absis a slot like any other, so the test keys on where the read comes FROM, not on who owns the value.That dict is the frame's live
builtins.__dict__, not a table of the real builtins, so a shim'sbuiltins.py2_sum = sumis a binding under it that another machine's shim can point elsewhere; the read is waived only under the builtin's own name (IOErrorandEnvironmentError, CPython's aliases ofOSError, fail closed), and only for a value CPython built:functools.wrapscopies__module__and__name__onto a Python shim installed asbuiltins.sum = wraps(sum)(logged_sum), whoseCLOSURE_MATCHthe serializer drops, and a class statement exec'd with the builtins namespace as its globals (or handed__module__ = "builtins") claims the module outright, which a baretypetest waived; a class statement ortype()call does not carry the flag. The flag is read throughtype's own descriptor, so a metaclass can neither shadow it nor make the read raise, and a static type's__module__is derived from its C name; a builtin function's__module__is a writable member, though, sobuiltins.getcwd = os.getcwdplusos.getcwd.__module__ = "builtins"is waived, evidence rather than proof on that branch, which an advisory lint over a dropped-guard set does not defend against.Every callable in
builtins.__dict__is one of those two kinds apart from the_sitebuiltinsobjects, instances of neither, and beside the aliases (WindowsErroris a third on Windows) three of them fail closed:IOError,EnvironmentError(WindowsErroron Windows)__name__isOSError, not the keyopenbuiltinsdoes not own:__module__is_io,iobefore 3.12, so a dropped guard on one of the most mainstream builtins here is reportedExceptionGroup(3.11+)Py_TPFLAGS_IMMUTABLETYPE__loader__The exposure is narrow either way, since a registered builtin is id-matched into a
BUILTIN_MATCHthe serializer keeps and only a deregistered, polyfilled one (sum,enumerate,all,any) or such a shim reaches the dropped set the lint examines._defined_where_readThe name rule.
_defined_where_read(value, global_name, user_stack)takes the read'sGlobalSource.global_name(not theG['op']spellingGuardFilterEntry.namekeeps) and is true for a def, or through its own methods a class statement, bound under its own name whose code lives in the file that read it, the one binding the inlined-source checksum of that file covers, unlikefrom impl_a import op, which only takes a conditional import the checksum never sees; it checks the name itself rather than leaving that to the caller, and compares__qualname__, soact = _impl_a if cfg.fast else _impl_bin the reading file is a slot and so areop = Ops.opand a def returned by a factory, and the paths are compared normalized. The__qualname__is backed by the code object's own name, whichfunctools.wrapscopies onto a wrapper's__qualname__but cannot forge (co_qualname; before 3.11 onlyco_name, so a wrapper def named after what it wraps slips through there), so a same-filewrapsdecorator a flag turns on is a slot in both arms. Only a plain function or a class is judged: a bound method or any other object forwarding__qualname__and__code__is refused before an attribute is read, which also keeps a proxy that answers reads by raising, such astorch.classes.<ns>, out of the value slot.The file comes off the code object. The file is read off the value's code object rather than off
__module__, becausefunctools.wrapscopies__module__along with__name__and__qualname__:The object does not tell the flag shape from an unconditional cross-file decorator, so a same-file def under
@torch.no_grad()is not waived either and the risky-drop lint reports it. Anything else without a code object, such as afunctools.lru_cachewrapper, which claims the reader's module the same way, is not waived.A class is judged by its own methods. A class has no code object, and its
__module__is no better:namedtupleandtype()stamp it from the calling frame (make_dataclassdoes so from Python 3.12) under a BARE__qualname__(a def or class statement inside the factory would carryfactory.<locals>.), so aPoint = namedtuple("Point", "x y")in the reader looks exactly like a class statement; the frame stamped is the caller's, so the collision needs a factory called from the reading file,lib.make_point()coming back stampedlib. Its methods can tell: a class statement compiles its defs in its own file under its own__qualname__prefix, so a class is waived when at least one function in its own__dict__, stored under keykwith__qualname__Cls.k(a staticmethod or classmethod unwrapped through__func__and a property throughfget, by type rather than bygetattr, since a class attribute can be a proxy such astorch.classes.<ns>that answers any attribute read by raising; acached_propertykeeps its function under.funcand does not count), was compiled in the reading file.A function attached afterwards keeps its bare qualname, and one attached through
functools.wrapskeeps its code object's own name, so a class imported from another file that the reader extends or patches is refused, as is a factory fed same-file methods (type(name, bases, {"area": _area}),make_dataclass(name, cfg.fields, namespace={"area": _area})), andclass Marker: passfails closed; so does a class statement whose only functions are generated: a fields-only@dataclass's and aNamedTuple's are defs of a factory (dataclasses'__create_fn__,namedtuple), so their code objects' own qualname carries the factory's<locals>.prefix (on 3.10, where onlyco_nameexists, the<string>or stdlib file they compile in refuses them instead), and anEnum's arrive in the subclass__dict__underEnum.qualnames the key rule refuses, so a plain config dataclass read as a global is reported. The one function the compiler itself puts in a class__dict__, the PEP 649 annotate function Python 3.14 stores for an annotated class body, compiles in the reading file, but under key__annotate_func__with__qualname__Cls.__annotate__, so the key rule refuses it and the verdict on a config dataclass is the same on every version; the scan also skips both annotate keys outright, against a version that stores the function under its own name.Only absolute filenames compare. A
co_filenameis not always a path: anexecrecords<string>and a REPL<stdin>, andrealpathresolves either against the cwd, so an ungated comparison made every<string>compilation one file and waived a def exec'd under it the moment the reading frame was exec-generated too (on 3.10 a fields-only dataclass as well, whose__init__compiles in<string>under aco_namethat cannot tell it from a class statement's def). Only absolute filenames on both sides are compared (the gate_normdocuments and_classify_fileapplies to a recorded__file__); a pseudo-filename, a relative spelling and an embedded NUL, which makesposixpath.realpathraise, fail closed.The frame read. The filename compared is that of the OUTERMOST frame in the guard's
user_stack. That frame is the one being compiled, whose globals a bareGlobalSourcedenotes (InliningInstructionTranslator._load_globalmints one only when the inlined frame's globals are the root's, and otherwise reads through an__import_alias or an___unnamed_scopedict entry); the stack itself is stamped inGuardsSet.addwith the inlining stack at the moment the guard is installed, which for a lazily realized global is the point of first use, so the innermost frame can be a helper inlined from another file, and reading the file off it would waivefrom b import opwheneveropis first used inside a helper inlined fromb.The known gap. What the predicate cannot see, and its docstring says so, is a same-name fork inside the reading file (
try: from x import impl as op/except ImportError: def op, or a class statement under the sameif), which binds a different def per machine under one checksum; that is the conditional-bind KNOWN GAP_is_risky_droprecords.Tests
Each predicate is pinned on hand-built sources by a test of its own, except
_defined_where_read, which gets sixtest_defined_where_read_*methods, one per shape family so a premise that holds only on some CPython versions cannot mask another family's rows.test_reads_a_builtin_keys_on_where_the_read_comes_frompinslenread through the builtins dict as waived, a builtin in a slot, a user table keyedlen, the same table read off a slot (self.act_fns["len"], the unnarrowed source the lint hands over, refused rather than read as a global) and user code injected into builtins as not, and afunctools.wraps(sum)shim under thesumkey as not (the test asserts(__module__, __name__) == ("builtins", "sum")first) whilesumunder its own key is and so isint, a type passing the CPython-built conjunct. The remaining conjuncts each get rows of their own:IOErrorandEnvironmentErrorunder their own keys (CPython-built, but namedOSError),openunder its own key (a builtin function namedopen, but owned byioor_iodepending on the version and never bybuiltins, so the__module__conjunct is what refuses it; the test asserts those two facts first), a user exception class installed into builtins under its own name and a class exec'd with the builtins namespace as its globals (the test asserts it claims__module__ == "builtins"first; both are heap types, so the flag is what refuses them), a class whose metaclass shadows__flags__with the immutable bit while claimingbuiltins(refused, since the flag is read throughtype's descriptor) and one whose metaclass makes the__flags__read raise (refused without raising), all not waived, and every type inbuiltins.__dict__read under its own name waived exceptExceptionGroup, the one heap type there read under its own name (__loader__is a heap type too, and the test pins that its__name__is not the key).test_dynamo_synthesized_covers_only_the_resume_function_listpins the list and its entry as synthesized and, past the entry, the resume function's__closure__, a cell's contents andtype(...).__call__off it as not, beside__nested_frame_values, a same-named global and an ordinary local.test_alias_module_and_owning_modulepins__import_torch_dot_nn_dot_functionaltotorch.nn.functionaland as None a user global whose tail past the prefix length names a module (imported_torch), an unknown tail and a torch_package alias, whichimport_sourcemints without the prefix, and the_dot_collision,__import_mypkg_dot_sub_dot_mod(the alias ofmypkg.sub_dot_modas much as ofmypkg.sub.mod) coming back as the loadedmypkg.sub.mod;_owning_moduleanswers None for an int and for a__module__that is not a string.test_defined_where_read_needs_the_name_and_the_filepins the name and file rules: a same-file def under its own name is waived, also through another spelling of the path and on a two-frame stack whose inner frame is torch/nn/functional.py (whereF.siluis not), and not under another name, from another file, with no stack, or forF.siluand an int; a staticmethod extracted under its own name and a def returned by a factory are not waived (__qualname__tells); a module-level def exec'd under this file's name is waived, as the documented gap.test_defined_where_read_takes_the_file_off_the_code_objectpins thetorch.compilewrapper (the test asserts it claims this module first), afunctools.lru_cachewrapper and a@torch.no_grad()-decorated def as not waived, a same-file conditionalfunctools.wrapsdecorator as waived with the flag off (the def itself comes back) and not with it on (the wrapper forges__qualname__; its code object is namedwrapper), and a bound method of the same-file def and a namespace forwarding its__qualname__and__code__as refused by type before either is read.test_defined_where_read_judges_a_class_by_its_own_methodspins the test class itself as waived when read from this file and not from another, andtorch.nn.Linearas not; a same-file class with one staticmethod is waived, so is one with one classmethod (both the__func__arm) and one whose only def is a@property(thefgetarm), while one whose only def is afunctools.cached_propertyis not, nor is a same-file class with no method of its own, a fields-only@dataclassor aNamedTuple(their generated defs carry the factory's<locals>.inco_qualname; on 3.10 the<string>or stdlib file they compile in refuses them) or anEnum(its functions carryEnum.qualnames the key rule refuses); and annn.Modulesubclass holdingtorch.classes.<ns>as a class attribute, which the test first shows raisesRuntimeErroron an attribute read (Model.ns.__func__), is judged like any other class (waived from this file, not from another) instead of raising out of the predicate, the proxy itself handed over as the value is refused by type, and the namespacetorch.classesfabricated for that read is removed from it again in a cleanup.test_defined_where_read_refuses_a_class_minted_for_the_filepins anamedtuple(the test asserts it claims this module under a bare__qualname__first), amake_dataclass(bare__qualname__asserted; the module is stamped only from 3.12) and atype()class as not waived, nor atype()class handed a same-file def in its namespace, under another key or under the def's own name (a bare qualname either way, so the class half of the rule, the missingPoint.prefix, is what refuses both); the key half gets its own pair, a same-file class statement's method handed to atype()class of the same__qualname__, waived under its own keymand not borrowed underother; nor is a class compiled under torch/nn/functional.py's name (the imported-class shape) waived with a same-file function attached afterwards or with a method replaced throughfunctools.wraps(the test asserts the forgedPoint.normqualname beside the code object's own_normname first).test_defined_where_read_skips_the_compiler_annotate_functionpins the fields-only@dataclassas not waived and, on 3.14, first asserts what the compiler stored beside its generated methods: key__annotate_func__, qualnameCfg.__annotate__on the function and on its code object, compiled in this file; that is replayed on every version through atype()class handed a same-file function under that key, the qualname stamped on the function and on its code object as a class statement's def carries it (not waived), beside a control row with the same function under an ordinary key and matching qualname (waived, so the replay is the shape a class statement produces) and the two rows that pin theskip, the function under__annotate__or__annotate_func__with aCfg.<key>qualname (not waived).test_defined_where_read_refuses_a_pseudo_filenamereads a def exec'd under<string>(the test asserts itsco_filenamefirst) from a<string>frame, the row that pins the gate on every version (a fields-only@dataclasscollides only on 3.10, whereco_namecannot refuse it first), and a same-file def from a relative frame filename (os.path.relpath(__file__), which the test asserts resolves to this file), the same def with that relative spelling as its ownco_filenameread from an absolute frame, from a frame filename with an embedded NUL and with a NUL in its ownco_filename, all not waived and none raising.test_minted_global_names_match_dynamopins the names the predicates lean on (the two prefixes, spelled in aot_compile.py, and the two nested-resume locals) against the code that mints them, through a real compile: a__builtins_dict__read, an__import_alias, and, undernested_graph_breaks=True(the harness runs every test with it on; the config default is off), the two locals every generated resume function takes and roots a guard at, judged on the sources Dynamo actually minted: off__nested_resume_fnsexactly the list and its[0]entry are synthesized, whiletype(__nested_resume_fns[0].__closure__[0].cell_contents).__call__, the guard on a callable the resumed frame's inner def captured, is present and is not; nothing rooted at__nested_frame_valuesis.What comes next
Nothing calls these yet;
_module_namespacesand_is_risky_drop, which do, follow once the library-module classifier is in.Test Plan:
Authored with an AI assistant.
🤖 Generated with Claude Code
Co-Authored-By: Claude Fable 5.1 [email protected]
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98