Skip to content

[precompile] Name the guard bindings that cannot be repointed by configuration (#197263) - #197962

Closed
bobrenjc93 wants to merge 1 commit into
gh/bobrenjc93/1376/basefrom
gh/bobrenjc93/1376/head
Closed

bobrenjc93 wants to merge 1 commit into
gh/bobrenjc93/1376/basefrom
gh/bobrenjc93/1376/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

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 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

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

# 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

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

_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

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

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__:

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.

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

Co-Authored-By: Claude Fable 5.1 [email protected]

Reverted in 0dbac14 as a dependent of #197262 and back in the stack unchanged.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98

[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 21, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

⏳ 56 Pending, 2 Unrelated Failures

As of commit 061ebd3 with merge base d78bbf2 (image):

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

  • Dead-code addition
    • _reads_a_builtin, _defined_where_read, _is_dynamo_synthesized and _dynamo_alias_module are new in torch/_dynamo/precompile_package.py with no caller: a grep for all five names across ./pytorch hits only that file and its test, the torch/fx/graph.py matches being an unrelated Graph._owning_module attribute.
    • Nothing under torch/ imports precompile_package (torch/compiler/_precompile_types.py names it only in a docstring), so the new from .aot_compile import ... adds no load-time cycle.
  • Constant refactor is value-preserving
    • torch/_dynamo/aot_compile.py lines 94-100 name _IMPORT_ALIAS_PREFIX/_BUILTINS_DICT_PREFIX and rebuild _MINTED_GLOBAL_PREFIXES from them with the same three strings in the same order; its only consumer, the startswith at line 124, is untouched.
    • Both literals match what Dynamo mints: output_graph.py:1154 installs __builtins_dict__ and symbolic_convert.py:2433 builds f"__import_{...}".
  • Predicates fail closed and match the sources they read
    • _defined_where_read gates on os.path.isabs for both the frame filename and each co_filename, and wraps _norm in except ValueError, so a <string> pseudo-name, a relative spelling or an embedded NUL returns False rather than raising.
    • _is_dynamo_synthesized covers only __nested_resume_fns, the first resume-function parameter at resume_execution.py:383, and leaves its sibling __nested_frame_values (same line) judged normally.
  • Test coverage tracks the logic
    • Nine new tests in test/dynamo/test_precompile_package.py pin each predicate on hand-built sources, including the property/fget and staticmethod/__func__ unwrap arms and the torch.classes proxy whose __getattr__ raises (torch/_classes.py:12-15).
    • test_minted_global_names_match_dynamo pins both prefixes and both nested-resume locals against a real torch.compile, and its nested_graph_breaks=True premise holds via torch/_dynamo/test_case.py:154.

reason: clean
Reviewed commit: 061ebd3

Inference job

🐛 Report a wrong verdict

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

This was referenced Sep 21, 2026
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…y its resolved path (#197428) (#197963)

**Problem.** Given the roots from #197262, the lint still has to turn one module into a verdict (shipped with torch or the stdlib, shipped elsewhere, or no evidence), and a naive `__file__` read runs user code and misclassifies relative, driveless or NUL-bearing paths and frozen apps.

**Fix.** Add `_classify_file`, which resolves a path against the roots behind explicit None gates and a cache, and `_located`, which reads `__file__`, `__loader__` and `__spec__` out of the module dict without triggering `__getattr__` and trusts the builtin and frozen importers by identity.

**Summary.** The risky-drop lint that later commits add waives a dropped identity guard when the value it guarded is owned by torch or the standard library, and the root finders added two commits earlier (`_stdlib_roots`, `_install_roots`, `_torch_roots`) say where each of those lives; this commit adds the two helpers that turn a module into a verdict against those roots, and the consumer, `_is_library_module`, follows in the next commit. `_classify_file(file, stdlib)` answers for one `__file__` -- shipped here (True), shipped elsewhere (False), or no evidence (None) -- judging the path `_norm` resolves against the torch roots (`stdlib=False`) or the stdlib roots minus the install roots (`stdlib=True`), with None reserved for a path that cannot be resolved (relative, driveless on Windows, or carrying a NUL) and for any stdlib question in a frozen app, where the bundle root holds the stdlib and every third party alike. `_located(module, name, stdlib)` answers the same three ways for a `sys.modules` entry, reading `__file__`, `__loader__` and `__spec__` out of the module DICT through `object.__getattribute__` so that no PEP 562 `__getattr__`, `_LazyModule` body or user `__eq__` runs, letting a placed `__file__` decide first and only then trusting `BuiltinImporter` or `FrozenImporter` by identity under the caller's full dotted `name`. Every read that remains user code is inside one `try` that answers None, so nothing escapes a lint, and `_classify_file` is `functools.cache`d on the (file, flag) pair because everything else it reads is fixed for the process while the module a name resolves to is not. Two tests pin every arm, gate and ordering, each row against a named mutation, on paths spelled so they cannot pre-exist and with the Windows path module replayed so the driveless and NUL gates hold on every platform.

## The two helpers

```python
@functools.cache
def _classify_file(file: str, stdlib: bool) -> bool | None:
    # True: shipped here; False: shipped elsewhere; None: no evidence

def _located(module: object, name: str, stdlib: bool) -> bool | None:
    # the same three answers for a sys.modules entry, which need not be a module
```

`_is_library_module` refuses None for a top-level name and keeps the package's waiver for an inner one, so an unplaceable inner `__file__` counts as no evidence there.

## `_classify_file`: the gates

```python
driveless = sys.platform == "win32" and not os.path.splitdrive(file)[0]
if driveless or not os.path.isabs(file):
    return None                                   # would resolve against the wrong cwd
if "\x00" in file:
    return None                                   # no file has one; see gh-106242
path = _norm(file)
```

A relative path is None, because `realpath` would resolve it against the process cwd rather than the one it was recorded under (on Windows before 3.13 `ntpath.isabs` accepts a driveless `\Lib\x.py`, the stdlib's own LEGACY BUG comment, so the gate also asks `splitdrive` for a drive there). So is a path with an embedded NUL, which no file has: `posixpath.realpath` raises `ValueError` on one from `os.lstat`, but from 3.11.5/3.12 on (gh-106242) `ntpath.realpath` swallows that and returns the path unresolved, NUL intact, and `_within` would then match the prefix before the NUL and waive the file, so the gate is an explicit check ahead of `realpath` rather than a catch around it. None comes from those two gates and from the frozen-app gate below. Every arm judges the path `_norm` returns, never the string as recorded: a venv or symlink-farm `__file__` must be placed by where the file is, not by where its link sits.

## `_classify_file`: the torch arm

```python
if not stdlib:
    return _within(path, _torch_roots())          # never None past the gates
```

With `stdlib=False` the verdict is whether the path lies under a torch root and is never None: with no torch root (a frozen torch) every path is elsewhere, which `_is_library_module` never reaches because it waives torch names before asking. The install-root exclusion below is the stdlib arm's alone: torch ships platform wheels, `Root-Is-Purelib: false`, so a pip-installed torch lies under platlib. The torch arm is not gated on `sys.frozen` either: its root is torch's own package directory, taken from where this file sits (`_torch_roots`), so in a bundle nothing outside torch lies under it, where the stdlib root is the bundle root itself.

## `_classify_file`: the stdlib arm

```python
_INSTALL_DIR_NAMES = frozenset({"site-packages", "dist-packages"})

if getattr(sys, "frozen", False):
    return None
if _within(path, _install_roots()):
    return False
for root in _stdlib_roots():                      # sorted: the first match is the outermost
    if _within(path, (root,)):
        below = path[len(root) + 1 :].lower().split(os.sep)
        return _INSTALL_DIR_NAMES.isdisjoint(below)
return False
```

With `stdlib=True` the path must be under a stdlib root and NOT under an install root, since `purelib` nests inside `stdlib` in a conda layout and inside `platstdlib` in a venv, so the exclusion is what does the work. A `site-packages` or `dist-packages` component (`_INSTALL_DIR_NAMES`, compared case folded: `normcase` is the identity on posix and a macOS filesystem is case-insensitive, so a mis-cased `Site-Packages` entry on `sys.path` would otherwise slip past both the install roots and this check) BELOW the stdlib root the file was found under also refuses, a cheap belt-and-braces check for an install directory none of the roots name, matched at any depth below the root rather than on the whole path, so that an interpreter bundled inside another environment's site-packages keeps its own stdlib (the roots are sorted, so of nested roots the outermost is matched, the part below it is the longest and the check the strictest). The match is on `os.sep`, not `/`, since `_norm` yields the platform's separator.

## Frozen apps

In a frozen app (`sys.frozen` truthy, as `multiprocessing.spawn` reads it: PyInstaller and cx_Freeze set the flag to True, py2exe to a string, `"console_exe"`, `"windows_exe"` or `"dll"`) the stdlib arm answers None instead: such a bundle holds the stdlib and every third party under one root with no `site-packages` component between them, and PyInstaller's `_fixup_frozen_stdlib` names that root in `sys._stdlib_dir` and in the `__file__` it gives the CPython-frozen modules, so every bundled file would lie under a stdlib root and a bundled module named after a stdlib module (a `graphlib` or `dataclasses` backport, an app module that shadows one) would be waived as interpreter-owned, the wrong-True direction. None rather than False so that `_located` still reads the loader: the modules CPython itself freezes or links in keep their waiver through the `FrozenImporter` and `BuiltinImporter` arms, and the rest of the stdlib is merely unwaived, lint noise and not a wrong drop.

## The cache

The function is `functools.cache`d on the (file, flag) pair rather than on a module name: everything else it reads, the roots and `sys.frozen`, is fixed once the process is running, so the answer for a path never changes, while the module a name resolves to can (a test that patches either clears the cache on both sides of the patch).

## `_located`: reading the module dict

```python
try:
    attrs = object.__getattribute__(module, "__dict__")   # not getattr, not module.__dict__
    file = attrs.get("__file__")
    if isinstance(file, str):
        verdict = _classify_file(file, stdlib)
        if verdict is not None:
            return verdict                                # a placed file decides
    loader = attrs.get("__loader__")
    if loader is None:
        loader = getattr(attrs.get("__spec__"), "loader", None)
    if loader is importlib.machinery.BuiltinImporter:
        return name in sys.builtin_module_names
    if loader is importlib.machinery.FrozenImporter:
        return importlib.machinery.FrozenImporter.find_spec(name) is not None
except Exception:
    return None
return None
```

`_located` is typed on `object` because a `sys.modules` entry need not be a module. None covers no `__file__` and no known loader, a `__file__` that `_classify_file` cannot place (relative, non-string, NUL, or any stdlib path in a frozen app) with no known loader, and a read that raised.

It reads `__file__` out of the module DICT, not through `getattr`: a class attribute is not evidence about where the module came from (torch.ops is a `ModuleType` subclass carrying the class's relative `"_ops.py"` as its `__file__`, which a dict read does not see), and on an entry whose dict is missing one of the three dunders read here `getattr` would fall through to a PEP 562 module `__getattr__`, user code a lint must not run (a raise would be caught, but not its side effects). The dict itself is read with `object.__getattribute__`, not the module's: `importlib.util.LazyLoader` leaves a `_LazyModule` in `sys.modules` whose `__getattribute__` executes the module body on ANY attribute read, `__dict__` included, so a plain `getattr(module, "__dict__")` would import the module the lint was only inspecting (and if the body raised, or the name was rebound in `sys.modules` meanwhile, leave it half-initialised behind the catch); the lazy module's dict already carries the seeded `__file__`, `__spec__` and `__loader__`, so the read through `object` loses nothing.

`sys.modules` can hold any object, so the reads that remain user code, a `__dict__` descriptor defined on the type and the spec's `loader` on a hand-rolled spec, are caught, answering None, as is the `AttributeError` that `object`'s read itself raises for a slotted entry with no `__dict__` (a `__getattr__` on it is never consulted), and since the `try` also spans the `_classify_file` call and the loader arms, a raise out of the classifier's own gates or out of `FrozenImporter.find_spec` (an `ImportError` on an excluded or invalid frozen table entry) lands there as None too rather than escaping a lint. A `__file__` that is not a string (a namespace package sets None) is skipped by an `isinstance` gate, and like a relative one it is evidence in neither direction, so the loader is still read (`isabs` accepts `bytes` and a `PathLike`, so the gate is what keeps them out; unguarded they would raise from the NUL check into the same catch).

## `_located`: the file decides before the loader is read

A located file decides, and only then is the loader read, an order that matters: with importlib on disk, `importlib._bootstrap` carries a stdlib `__file__` (importlib/__init__.py assigns it, inside a `try/except NameError` that a frozen importlib skips) next to a `FrozenImporter` whose table knows the module only as `_frozen_importlib`, so with the arms swapped it would lose its waiver; with importlib frozen too there is no `__file__`, the frozen arm answers False under the dotted name and the waiver is lost either way, a fail-closed corner that costs lint noise, not a wrong drop.

```python
bootstrap = types.ModuleType("importlib._bootstrap")
bootstrap.__file__ = os.path.join(stdlib_root, "importlib", "_bootstrap.py")
bootstrap.__loader__ = importlib.machinery.FrozenImporter   # find_spec("importlib._bootstrap") is None
pp._located(bootstrap, "importlib._bootstrap", True)        # True: the file decides; loader-first would answer False
```

## `_located`: the loader arms

The loader (`__loader__` in the dict, else the spec's: a `__loader__` in the dict skips the `spec.loader` read, the only user-code half of this, and is compared with None rather than for truth, so no `__bool__` of user code runs; a hand-made `ModuleType` carries the `None` that `ModuleType.__init__` seeds and falls through, where an imported module's dict carries `spec.loader`, copied in by `_init_module_attrs`) is read, not `spec.origin`: `BuiltinImporter.find_spec` and `FrozenImporter.find_spec` both call `spec_from_loader(fullname, cls, origin=cls._ORIGIN)` (the frozen one adds `is_package`, then fills in `loader_state` and the package's search path) and `_init_module_attrs` copies `spec.loader` into `__loader__`, so the origin string never says anything the loader class does not, and the class is the stronger signal.

Both tables are looked up under the caller's `name`, the `sys.modules` key `_is_library_module` was asked about, not the module's own `__name__` (the entry for `os.path` is `posixpath`). Both arms match the loader class by identity, not equality, for the same reason the dict is read through `object`: under `==` a `__loader__` whose `__eq__` answers true for anything would take the waiver. `BuiltinImporter` is trusted only if the FULL dotted `name` is in `sys.builtin_module_names` (the inittab is keyed on it, so a fabricated `sys.sub` is refused), `FrozenImporter` only if the frozen table has the name (`zipimport`, not `zipimport.sub`), and a module with neither (namespace package, exec'd in memory with no loader) is None; a REPL, `-c` or stdin `__main__` is not one of these, since the interpreter seeds `BuiltinImporter` as its `__loader__`, so it is False, `__main__` not being in the inittab.

Both arms answer on the name alone whichever roots `stdlib` selects: built-in and frozen precede the path finder on `sys.meta_path`, so on import no file on `sys.path` is reachable under such a name, and a module compiled into the interpreter has its code fixed by the interpreter binary, which is what either waiver needs. The `stdlib=False` case is not the stdlib's `sys` asked under the wrong flag (`_is_library_module` routes a name to a flag by its top component) but an embedding that registers `torch._C` through `PyImport_AppendInittab` while torch's Python files stay on disk, so `_torch_roots` is non-empty and torch is not waived on its name; in an ordinary build `torch._C` is an extension module and not in `sys.builtin_module_names`. A spec assigned straight into `sys.modules` is taken at its word.

## Behaviour pinned by the tests

```python
from torch._dynamo import precompile_package as pp

stdlib_root = sysconfig.get_paths()["stdlib"]
pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)                  # True
pp._classify_file(torch.__file__, False)                                           # True: the torch arm reads the torch roots
pp._classify_file(torch.__file__, True)                                            # False: torch lies under no stdlib root, or under an install root
pp._classify_file(os.path.join(stdlib_root, "torch", "__init__.py"), False)        # False: the stdlib dir itself is never a pip target, so no torch root holds it
pp._classify_file("graphlib.py", True)                                             # None: relative
pp._classify_file("graphlib.py", False)                                            # None: the gates precede the flag split
pp._classify_file(os.path.join(stdlib_root, "graph\x00lib.py"), True)              # None: embedded NUL, on every platform
platlib_torch = os.path.join(sysconfig.get_paths()["platlib"], "torch")
pp._classify_file.cache_clear()                                                    # in a wheel install the next file IS torch.__file__, judged above
with mock.patch.object(pp, "_torch_roots", return_value=(pp._norm(platlib_torch),)):
    pp._classify_file(os.path.join(platlib_torch, "__init__.py"), False)            # True: the torch arm is exempt from the install-root exclusion
for flag in (True, "console_exe"):                                                 # a frozen app: PyInstaller and cx_Freeze set True, py2exe a string
    pp._classify_file.cache_clear()
    with mock.patch.object(sys, "frozen", flag, create=True):
        pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)          # None: the bundle root holds the stdlib and third parties alike
        pp._classify_file(torch.__file__, False)                                   # True: the torch arm keeps torch's own package directory
        pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), False)         # False: and that root holds nothing outside torch
pp._classify_file.cache_clear()
pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True)                  # True again: the answer changed with sys.frozen, hence the clear
import ntpath
with mock.patch.object(sys, "platform", "win32"), mock.patch.object(os, "path", ntpath), mock.patch.object(os, "sep", "\\"), mock.patch.object(pp, "_stdlib_roots", return_value=(r"c:\python312\lib",)), mock.patch.object(pp, "_install_roots", return_value=()):
    pp._classify_file(r"\Lib\graphlib.py", True)                                   # None: driveless, so resolved against the current drive
    pp._classify_file("C:\\Python312\\Lib\\graphlib.py\x00C:\\evil\\evil.py", True)   # None: without the gate ntpath.realpath returns it unresolved and it lies under the root
    pp._classify_file(r"c:\python312\lib\vendored\site-packages\graphlib.py", True)  # False: the part below the root is split on os.sep, so the name is seen
with mock.patch.object(pp, "_install_roots", return_value=()):
    pp._classify_file(os.path.join(stdlib_root, "vendored", "site-packages", "g.py"), True)   # False: _INSTALL_DIR_NAMES alone, two components below the root
    pp._classify_file(os.path.join(stdlib_root, "vendored", "dist-packages", "g.py"), True)   # False: same
    pp._classify_file(os.path.join(stdlib_root, "vendored", "Site-Packages", "g.py"), True)   # False: case folded
    pp._classify_file(os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py"), True)  # True: nothing installed there
    with mock.patch.object(pp, "_stdlib_roots", return_value=()):
        pp._classify_file(os.path.join(stdlib_root, "os.py"), True)                    # False: under no stdlib root at all
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=(pp._norm(os.path.join(stdlib_root, "vendored")),)):
    pp._classify_file(os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py"), True)  # False: the install-root exclusion alone
tmp = tempfile.mkdtemp()                                                           # a tree of its own: a real <stdlib>/site-packages is a symlink out of the stdlib on some layouts
bundled = os.path.join(tmp, "site-packages", "runtime", "lib")                     # a stdlib that itself sits under site-packages
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(bundled),)):
    pp._classify_file(os.path.join(bundled, "graphlib.py"), True)                  # True: site-packages ABOVE the stdlib root does not count
    pp._classify_file(os.path.join(bundled, "site-packages", "graphlib.py"), True) # False: below it does
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(tmp), pp._norm(bundled))):
    pp._classify_file(os.path.join(bundled, "graphlib.py"), True)                  # False: of nested roots the outermost is matched
pp._classify_file.cache_clear()
with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(tmp),)):
    pp._classify_file(os.path.join(tmp, "site-packages", os.pardir, "g.py"), True) # True: judged after _norm resolves it, not as recorded
```

```python
module = types.ModuleType("graphlib")
module.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
pp._located(module, "graphlib", True)              # False: a placed file decides either way
module.__file__ = os.path.join(stdlib_root, "graphlib.py")
pp._located(module, "graphlib", True)              # True
on_disk = types.ModuleType("torch")
on_disk.__file__ = torch.__file__
pp._located(on_disk, "torch", False)               # True: the flag reaches the file arm (the production torch shape)
pp._located(on_disk, "torch", True)                # False
class Shadow(types.ModuleType):
    __file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
pp._located(Shadow("graphlib"), "graphlib", True)  # None: a class attribute is not in the module dict
pp._located(torch.ops, "torch.ops", False)         # None: same shape, the real one (a canary: a getattr read would answer None too)
raising = types.ModuleType("graphlib")
raising.__getattr__ = mock.Mock(side_effect=RuntimeError)
del raising.__spec__, raising.__loader__            # ModuleType seeds both into the dict
pp._located(raising, "graphlib", True)             # None, and __getattr__ was not called for __file__, __spec__ or __loader__
eager = mock.Mock(**{"create_module.return_value": None})
wrapped = importlib.util.LazyLoader(eager)
lazy_spec = importlib.util.spec_from_file_location("graphlib", os.path.join(stdlib_root, "site-packages", "graphlib.py"), loader=wrapped)
lazy = importlib.util.module_from_spec(lazy_spec)
wrapped.exec_module(lazy)                      # now a _LazyModule: any attribute read runs eager.exec_module
pp._located(lazy, "graphlib", True)                # False, and eager.exec_module was not called
pp._located(types.ModuleType("graphlib"), "graphlib", True)   # None: no file, no spec
odd = types.ModuleType("graphlib")
odd.__file__ = 42
pp._located(odd, "graphlib", True)                 # None: not a path
class Proxy:                                       # a non-module sys.modules entry
    __slots__ = ()
    def __getattr__(self, attr): raise RuntimeError(attr)
pp._located(Proxy(), "graphlib", True)             # None: object's __dict__ read raises AttributeError on a slotted entry; caught, __getattr__ never consulted
odd.__spec__ = Proxy()
pp._located(odd, "graphlib", True)                 # None: so is spec.loader
odd.__file__ = os.path.join(stdlib_root, "graphlib.py")
pp._located(odd, "graphlib", True)                 # True: a placed file decides, the loader is never read
spec_poisoned = types.ModuleType("sys")
spec_poisoned.__spec__ = Proxy()
spec_poisoned.__loader__ = importlib.machinery.BuiltinImporter
pp._located(spec_poisoned, "sys", True)            # True: __loader__ is read first, so the spec never is
bootstrap = types.ModuleType("importlib._bootstrap")
bootstrap.__file__ = os.path.join(stdlib_root, "importlib", "_bootstrap.py")
bootstrap.__loader__ = importlib.machinery.FrozenImporter   # the real module's shape; FrozenImporter.find_spec("importlib._bootstrap") is None
pp._located(bootstrap, "importlib._bootstrap", True)        # True: the file decides before the loader is read
shadow_sys = types.ModuleType("sys")
shadow_sys.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py")
shadow_sys.__loader__ = importlib.machinery.BuiltinImporter
pp._located(shadow_sys, "sys", True)               # False: the converse, an installed file under a built-in name
odd_sys = types.ModuleType("sys")
odd_sys.__file__ = 42
odd_sys.__loader__ = importlib.machinery.BuiltinImporter
pp._located(odd_sys, "sys", True)                  # True: a __file__ that cannot be placed is no evidence, so the loader is read
relative = types.ModuleType("zipimport")
relative.__file__ = "zipimport.py"
relative.__loader__ = importlib.machinery.FrozenImporter
pp._located(relative, "zipimport", True)           # True: same for a relative one
frozen_zip = types.ModuleType("zipimport")                  # frozen on every version; os only from 3.11 on (gh-45020)
frozen_zip.__file__ = os.path.join(stdlib_root, "zipimport.py")
frozen_zip.__loader__ = importlib.machinery.FrozenImporter
with mock.patch.object(sys, "frozen", True, create=True):
    pp._located(frozen_zip, "zipimport", True)     # True: in a frozen app the file arm is no evidence, so the loader decides
pp._located(sys, "sys", True)                      # True: built in
pp._located(sys, "sys.sub", True)                  # False: the caller's name is looked up, not the module's __name__
zipimport_by_name = types.ModuleType("zipimport")
zipimport_by_name.__loader__ = importlib.machinery.FrozenImporter
pp._located(zipimport_by_name, "zipimport.sub", True)  # False: same in the frozen arm
sub = types.ModuleType("sys.sub")
sub.__spec__ = importlib.machinery.ModuleSpec("sys.sub", importlib.machinery.BuiltinImporter, origin="built-in")
pp._located(sub, "sys.sub", True)                  # False: the inittab is keyed on the full dotted name
frozen = importlib.machinery.FrozenImporter
zipimport_frozen = types.ModuleType("zipimport")
zipimport_frozen.__spec__ = importlib.machinery.ModuleSpec("zipimport", frozen, origin="frozen")
pp._located(zipimport_frozen, "zipimport", True)   # True: the frozen table has zipimport
zipimport_sub = types.ModuleType("zipimport.sub")
zipimport_sub.__spec__ = importlib.machinery.ModuleSpec("zipimport.sub", frozen, origin="frozen")
pp._located(zipimport_sub, "zipimport.sub", True)  # False: keyed on the full dotted name, not its top component
graphlib_frozen = types.ModuleType("graphlib")
graphlib_frozen.__spec__ = importlib.machinery.ModuleSpec("graphlib", frozen, origin="frozen")
pp._located(graphlib_frozen, "graphlib", True)     # False: a frozen spec under a name the frozen table does not have
with mock.patch.object(frozen, "find_spec", side_effect=ImportError):
    pp._located(zipimport_by_name, "zipimport", True)  # None: find_spec raises on an excluded or invalid frozen table entry, and nothing escapes _located
lying_eq = types.ModuleType("sys")
lying_eq.__loader__ = mock.ANY                     # a stdlib object whose __eq__ answers true for anything
pp._located(lying_eq, "sys", True)                 # None: the arms match the loader class by identity
by_loader = types.ModuleType("sys")
by_loader.__loader__ = importlib.machinery.BuiltinImporter
pp._located(by_loader, "sys", True)                # True: __loader__ alone in the dict, no spec
by_loader = types.ModuleType("zipimport")
by_loader.__loader__ = frozen
pp._located(by_loader, "zipimport", True)          # True: same, frozen
pp._located(by_loader, "zipimport", False)         # True: both arms answer under either flag
by_loader = types.ModuleType("sys")
by_loader.__loader__ = importlib.machinery.BuiltinImporter
pp._located(by_loader, "sys", False)               # True: same, built in
with mock.patch.object(sys, "builtin_module_names", (*sys.builtin_module_names, "torch._C")):
    embedded = types.ModuleType("torch._C")
    embedded.__loader__ = importlib.machinery.BuiltinImporter
    pp._located(embedded, "torch._C", False)       # True: the torch shape, an embedded torch._C with torch's Python files on disk
```

## Tests

Both tests call `_clear_root_caches` first, like every other root test, and clear the `_classify_file` cache on entry and on cleanup: its keys are stdlib-rooted paths that other tests judge under patched roots.

**`test_classify_file_places_a_path_by_the_roots_it_lies_under`** pins every arm of `_classify_file` on paths spelled relative to sysconfig's `stdlib` (the stdlib dir itself is never a pip target, so no torch root holds the fake torch path):

- the stdlib True, and the torch arm reading the torch roots and not the stdlib ones;
- the torch arm exempt from the install-root exclusion: with `_torch_roots` patched to `<platlib>/torch`, after asserting that `<platlib>/torch/__init__.py` lies under a real install root and clearing the cache, that file is True. A checkout's `torch.__file__` is under no install root, so the plain torch row cannot see this, while in a wheel install that file IS `torch.__file__`, and without the clear the row would only re-read the torch-arm row's cached verdict;
- the frozen-app None: with `sys.frozen` patched to True and then to py2exe's `"console_exe"`, a stdlib-rooted file under `stdlib=True` is None while `torch.__file__` under `stdlib=False` stays True and that stdlib file under `stdlib=False` is False, the torch arm still telling torch from the rest of a bundle. The cache is cleared before each flag and after the block, and the stdlib file is then re-read as True, the row that shows the answer for a path changing with `sys.frozen` and so what the clears are for;
- the relative None under both flags (the gates precede the flag split) and the embedded-NUL None on every platform;
- the driveless Windows spelling, the NUL path under a Windows stdlib root and an installed file two components below one, with `sys.platform`, `os.path` and `os.sep` patched to `win32`, `ntpath` and a backslash and the root finders patched to `c:\python312\lib` and `()`, so the rows run on every platform. The second replays what gh-106242 does: without the gate `ntpath.realpath` returns the path unresolved, `_within` matches the prefix before the NUL, and the file is waived. The third is the only row that reaches `_INSTALL_DIR_NAMES` with a non-posix separator, which is what splitting the part below the root on `os.sep` rather than `/` is for;
- both `_INSTALL_DIR_NAMES` refusing with `_install_roots` patched to `()`, and a mis-cased `Site-Packages` refusing on every platform (case folded, since `normcase` only folds on Windows);
- a stdlib-rooted file under no stdlib root at all (both root finders patched to `()`) refused, which pins the terminal False without depending on where torch is installed (in a wheel or conda install `torch.__file__` lies under an install root and returns from the exclusion instead);
- one file under a nested `vendored` directory judged twice, with the cache cleared in between: stdlib with nothing installed there, third party once that directory is an install root;
- `_INSTALL_DIR_NAMES` scoped below the root: with `_stdlib_roots` patched to a root that itself sits under `site-packages`, a file directly under it is stdlib and one under a further `site-packages` is not, and with both that root and the one above it patched in, the same file is refused, since the outermost root is the one matched;
- that judging happens after `_norm`: a path naming `site-packages` and then `os.pardir` is stdlib, since it resolves to a plain file directly under the root.

The rows that turn on where an install directory sits relative to a root are spelled on paths that cannot pre-exist -- a `vendored` component under sysconfig's `stdlib`, and a `TemporaryDirectory` for the bundled-interpreter fixture -- because a real `<stdlib>/site-packages` is a symlink out of the stdlib on some layouts (a relocated site-packages, a Windows junction), which resolves such a path out of the root it is meant to be judged under, and then those rows either assert the wrong verdict or pass through the terminal False.

Each row fails under the matching mutation: the `_INSTALL_DIR_NAMES` check or the install-root exclusion removed; `_INSTALL_DIR_NAMES` matched on the whole path, case-sensitively, on `/` in place of `os.sep` or on the first component below the root alone; `_norm` weakened to `normcase` so the recorded path is judged unresolved; the roots walked innermost first; the terminal False turned into None; the `isabs` gate, the driveless gate or the NUL gate removed; the install-root exclusion hoisted above the flag split; the torch arm reading the stdlib roots; the `stdlib` flag ignored; the frozen-app gate removed, answering False, hoisted above the flag split, or asking `is True` of the flag, which the string row alone fails.

**`test_located_reads_the_file_from_the_module_dict`** starts with a placed `__file__` deciding either way (an installed one False, a stdlib one True) and the production torch shape, a module carrying `torch.__file__` asked under `stdlib=False` (True) and `stdlib=True` (False), the only rows on which the flag is not a constant of the file arm. It then pins:

- the module-dict read, with a `ModuleType` subclass whose class attribute `__file__` would classify False if seen (the row that fails under a `getattr` read of `__file__`), the real `torch.ops` as a canary for that shape (asserting first that its dict has no `__file__`; a `getattr` read of its relative `"_ops.py"` would answer the same None, so this row documents rather than pins), and a module whose PEP 562 `__getattr__` raises, with `__spec__` and `__loader__` deleted from its dict, since `ModuleType.__init__` seeds both and a `getattr` read of either would otherwise never reach `__getattr__`;
- a module built through `importlib.util.LazyLoader` over a mock loader, carrying the installed `__file__` (False, and the loader's `exec_module` was not called: under a `getattr` read of `__dict__` the `_LazyModule` runs it, and since the real `graphlib` is in `sys.modules` under that name then raises inside the catch, answering None);
- no file and no spec; a non-string `__file__`; a slotted proxy whose `__getattr__` raises (standing in for a non-module `sys.modules` entry) both as the module and as its `__spec__`; that module again once it has a placeable `__file__`; a `sys` with that proxy as `__spec__` next to a `BuiltinImporter` `__loader__` (True: the dict's `__loader__` is read first, so the spec never is);
- the two rows that pin the arm order: the `importlib._bootstrap` shape, a stdlib `__file__` plus `FrozenImporter`, asserting first that the frozen table does not know the name, is True; an installed `__file__` plus `BuiltinImporter` under `sys` is False;
- the two that cross unusable file evidence with a loader: a non-string `__file__` under `sys` with `BuiltinImporter`, a relative one under `zipimport` with `FrozenImporter`, both True;
- the frozen-app shape: a `zipimport` carrying a stdlib `__file__` and `FrozenImporter` is True with `sys.frozen` patched in, the file arm being no evidence there, so the loader decides. `zipimport` rather than `os` because CPython freezes `os` only from 3.11 on, gh-45020, and the row must hold on 3.10;
- the real `sys` under its own name and under `sys.sub`, and a fabricated `zipimport` with `FrozenImporter` asked under `zipimport.sub` (False: in both arms the caller's name is looked up, not the module's `__name__`); the fabricated `sys.sub`; a frozen spec under a frozen name, under a dotted name whose top component is frozen (`zipimport.sub`) and under a non-frozen name;
- `FrozenImporter.find_spec` patched to raise `ImportError` (None: the loader arms are inside the `try`); a `__loader__` that is `mock.ANY`, a stdlib object whose `__eq__` answers true for anything (None: the arms match by identity, so nothing of its runs);
- each importer as a bare `__loader__` with no spec asked under both flags, and the torch shape, `torch._C` with `BuiltinImporter` under `stdlib=False` with the inittab patched to list it (asserting first that the real one does not).

Each of these mutations fails a row: a `getattr` read of `__file__`, of `__spec__` or of `__loader__` (the first fails the `Shadow` row, the other two the `assert_not_called`); a `getattr` read of `__dict__` (the LazyLoader row); the `stdlib` flag hardcoded on the file arm; the `try/except` removed; the arms swapped or the loader read before the file arm; the `__loader__` read dropped for the spec's loader alone or read after it; either arm's identity comparison loosened to `==`; an inittab or frozen-table lookup on the top component; the name taken from the module's `__name__`; an unconditional frozen True; a False for no evidence; `stdlib and` in front of either loader arm; the `isinstance(file, str)` gate loosened to truthiness; and the fall-through from a None `_classify_file` to the loader replaced by a return. The last two are killed only by rows that cross an unplaceable file with a loader: the loosened gate by the non-string crossing row alone (the catch covers the `TypeError` that `os.path.isabs` raises on a non-string, so it answers the same None as the real one until the module also carries a loader that should have decided), the return by the relative crossing row and the frozen-app row, where `_classify_file` answers None and the loader was to decide.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_classify_file_places_a_path_by_the_roots_it_lies_under -k test_located_reads_the_file_from_the_module_dict
lintrunner torch/_dynamo/precompile_package.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 7d01447 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197963
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…a capture (#197260) (#197964)

**Problem.** The multi-graph precompile capture needs a report type that tells a caller what it captured and what it dropped, and nothing in the tree defines one.

**Fix.** Add `PrecompileSummary`, a frozen keyword-only dataclass with documented fields, a coverage-only `complete` flag, per-type guard tallies and a one-line digest. It is data only; the producer that fills it comes later in the stack.

**Summary.** `PrecompileSummary` is the frozen, keyword-only dataclass a multi-graph capture will hand back to describe what it observed: how many frames, graph-break continuations, guarded codes and backend graphs were captured, which frames were bypassed, truncated or left uncovered, and which guards were dropped, kept, dropped riskily, or dropped by the invariance policy. Nothing in this commit produces one -- the builder (`_summarize`), the guard filter and the lints it names live later in this stack -- so every `Attributes:` entry says what the field means to a consumer of the report and names the producer for how it is populated instead of repeating its rules, after two earlier drafts that restated the guard-filter rule went stale against it. The relations between the fields (`bypassed` and `uncovered_frames` never share a frame, `kept_guards` and `dropped_guards` are disjoint per frame variant but aggregate across frames, `policy_dropped_guards` is drawn from slots the filter kept) are stated in the docstrings and not enforced, because a `__post_init__` that raised on a bookkeeping collision would lose the whole report, which `capture_errors` exists to avoid. `complete` is the one piece of logic, a coverage-only flag with six terms (nothing bypassed, truncated or uncovered, no capture error, at least one guarded code and at least one backend graph), and `dropped_guard_types`, `kept_guard_types` and `__str__` derive the per-type tallies and a one-line digest that names risky drops and shouts the frame failures last. It is keyword-only because its four required fields are all `int`, so `PrecompileSummary(3, 0, 1, 1)` would be legal and unreadable, and the positional order would become part of a public contract once the type is exported from `torch.compiler.precompile` later in this stack.

## The fields

```python
@dataclasses.dataclass(frozen=True, kw_only=True)
class PrecompileSummary:
    frames: int                       # every frame the package holds an entry for
    resume_functions: int             # of those, the graph-break continuations
    guarded_codes: int
    backend_graphs: int
    bypassed: tuple[str, ...] = ()             # co_name per frame
    truncated: tuple[str, ...] = ()            # "co_name (filename:firstlineno)" per code object
    uncovered_frames: tuple[str, ...] = ()     # co_name per frame
    wont_generalize: tuple[str, ...] = ()      # guard sources, not frame names
    dropped_guards: tuple[tuple[str, str], ...] = ()          # (guard_type, source) slots
    kept_guards: tuple[tuple[str, str], ...] = ()
    risky_dropped_guards: tuple[tuple[str, str], ...] = ()
    policy_dropped_guards: tuple[tuple[str, str], ...] = ()
    dropped_guard_code: tuple[tuple[str, str, str], ...] = () # (guard_type, source, rendered_check)
    capture_errors: tuple[str, ...] = ()                      # "ExceptionType: message", one per distinct exception
```

## The frame fields

`frames` counts every frame the package holds an entry for, the bypassed, truncated and uncovered ones included, and the docstring says so, because `bypassed` as "frames the package refused to record" otherwise reads as frames outside the count and `8 frames, ... 7 UNCOVERED` as fifteen frames; the builder later in this stack (`_summarize`) takes `frames` from `len(entry.codes)` and both `bypassed` and `uncovered_frames` from the same list, so both are subsets by construction, and the digest's frame clauses cut into the count rather than add to it.

`bypassed` is documented as what `_DynamoCodeCacheEntry.bypassed` records: the package holds nothing installable for the frame because no compile of it recorded a guarded code and one was bypassed (either `OutputGraph.bypass_package` cause, guards that could not be serialized or a graph that held parameters by static address), or a backend artifact was missing at save; the frame still ran compiled during capture, the package kept no variant of it a load can serve, and an install re-traces it; it is not an eager fallback. Not "every compile was bypassed": `bypass_current_compile` sets the flag as `not guarded_codes` and `add_guarded_code` clears it, so a compile that raised before recording anything is neither a bypass nor a record and leaves the flag free for a later bypassed compile of the same frame. How each cause gets there (a save-time bypass leaves the stale guarded codes in the artifact for `CompilePackage.initialize` to drop, while a `bypass_package` compile never recorded them) is the package's business, so the field says what the consumer gets and leaves that to the producer.

`uncovered_frames` is the frames the capture ran that ended with no guarded code and were not bypassed, a different cause and remedy from `bypassed` (an install `skip_code`s an uncovered frame, so only a re-capture recovers it, where it re-traces a bypassed one) and never the same frame (which is why the predicate excludes bypassed frames rather than leaning on their guarded codes, which a save-time bypass leaves in place). The docstring names three causes: a thin wrapper whose graphs landed in an inner frame, a frame Dynamo gave up on, and a frame whose compile raised, since `code_context` sets `has_compile_id` in its `finally`, for a compile attempted whether or not it finished, so one failure shows in the digest as both a CAPTURE ERROR and an UNCOVERED clause; and it states the one overlap, a frame that hit the recompile limit before it recorded a guarded code (the limit check runs inside `code_context` and reads the code object's pre-existing cache size, so a warm process gets there with no guarded code), which is in `truncated` too. The docstring says it is explicitly not a remainder, because which frames count as a gap is the producer's call and a frame the package holds an entry for but never ran is not one, so a consumer cannot recompute it as `frames` minus `bypassed` minus the frames that hold guarded code. An earlier draft had `uncovered_frames` arrive as a set of bare names, which the builder now reads off the entry instead (a frame that entered Dynamo, holds no guarded code and was not bypassed), so `2 UNCOVERED` is two frames and not two names; `install()` `skip_code()`s a superset of those frames (`if len(entry.guarded_codes) == 0`, with no `has_compile_id` test), which is why the docstring describes the field rather than equating it with the skip.

The frame lists differ in what an entry is, and the docstring says so:

```python
bypassed=("forward", "forward")                    # two frames, not a repeat: every nn.Module has a forward
uncovered_frames=("helper",)                       # bare co_name; len() counts frames
truncated=("forward (model.py:12)", "forward (model.py:40)")   # once per code object; identifies a frame
```

`bypassed` and `uncovered_frames` hold one bare `co_name` per frame, so a name can repeat and their lengths count frames, while `truncated` holds `co_name (filename:firstlineno)`, recorded once per code object by the compile path that sees a frame hit the limit (the only producer of that set, in the follow-up stack, spells it that way, and a set of bare names would merge two `forward`s into one), so its entries do identify a frame. A bare name identifies none, which is why the `bypassed`/`uncovered_frames` relation is stated and not enforced.

`truncated` is documented as a lower bound, which is why the digest prints it as `>=`: from a limit hit on, that frame and the frames it calls run without tracing (`FrameExecStrategy(RUN_ONLY, RUN_ONLY)` in `convert_frame.py`, whose second component is the action for callees), so a limit hit that would follow it there is never recorded; by the same mechanism every count and frame list is a lower bound once `truncated` is non-empty, and the class docstring says so. A callee the traced compiles reached is in the entry and counted; one first reached after the hit never enters Dynamo (under `RUN_ONLY` the nested callback is `Py_False`, `eval_frame_cpp.cpp`), so it gets no entry and is missing from `frames` and `uncovered_frames` alike, while sibling frames keep tracing and keep being recorded.

## The guard slot lists

The four guard lists hold `(guard_type, source)` slots, the source spelled as `GuardFilterEntry.name`, the `Guard.name` with local scope stripped (`self.act`, not `L['self'].act`; `G['CFG'].width` unchanged).

`dropped_guards` is every slot the serialized copy's guard filter rejected, the guards the serializer refuses plus whatever a caller-supplied filter dropped, not only the unserializable ones; that matches the `default_guard_filter_fn` docstring the next commit of this stack adds to `torch/_dynamo/precompile_package.py` ("Every dropped slot is reported in `PrecompileSummary.dropped_guards`, once however many variants dropped it") and is what the `dropped_guard_code` entry below relies on. Which guards a filter rejects is not restated here at all: the docstring names `default_guard_filter_fn` as the default (one sentence above the `Attributes:` block says the three rules it names live in `torch._dynamo.precompile_package`, whose filter this stack adds alongside this type and whose other two rules come later in the stack, so a reader of landed `main` knows where the targets are), defers the whole rule and every exemption to that filter's docstring, and says a caller-supplied filter decides its own set. Two earlier drafts did restate the rule and both went stale as the filter changed shape underneath them -- the first repeated two of its three by-type exemptions, the second characterized the exemptions as by-type when the filter now has two by-type exemptions plus one derived type it ignores -- and each time the stale rule predicted a drop on the pytree-registry guard essentially every capture keeps. That is the shape every `Attributes:` entry now follows: say what the field means to a consumer of the report, and name the producer for how it is populated instead of repeating its rules. A slot keeps its own type, so a `TENSOR_MATCH` that checked identity (`match_on_id_for_tensor` routes it through `ID_MATCH`) is listed as a dropped `TENSOR_MATCH`, the same type the tests use as the canonical kept guard.

The class docstring states how the lists relate and why nothing enforces it. Within one frame variant `kept_guards` and `dropped_guards` are disjoint (the filter gives a slot one verdict, keep or reject), `risky_dropped_guards` is drawn from `dropped_guards` and `policy_dropped_guards` is disjoint from both it and `kept_guards` (the policy re-serializes each variant's guards from the pickle the filters already passed, so a policy drop is a slot the filter kept, taken out once it held identically across every captured variant, and is not checked either, so `(N kept)` never counts one; `policy_dropped_guards` is documented as those kept-then-dropped slots, with `_INVARIANT_DROPPABLE_GUARD_TYPES` named as the bound on what the policy may drop, rather than as "serializable slots", since that set also lists the identity types the default filter drops first). But the lists aggregate every captured frame:

```python
# test_summary_guard_lists_aggregate_over_frames: two frames' guards on the builtin
# len are one slot. One frame's caller filter rejected it and the drop told that
# frame's variants apart (risky); the other frame's invariance policy dropped it.
act = ("BUILTIN_MATCH", "G['__builtins_dict___<n>']['len']")
summary = PrecompileSummary(frames=2, resume_functions=0, guarded_codes=2, backend_graphs=2,
                            dropped_guards=(act,), risky_dropped_guards=(act,), policy_dropped_guards=(act,),
                            dropped_guard_code=(act + (check,),))
summary.dropped_guard_types   # {'BUILTIN_MATCH': 1}: distinct slots, not occurrences
str(summary)
# "2 frames (0 from graph breaks), 2 guarded codes, 2 backend graphs, dropped guards {'BUILTIN_MATCH': 1} (0 kept), RISKY drops [\"BUILTIN_MATCH G['__builtins_dict___<n>']['len']\"], 1 policy-dropped guard"
```

Each slot appears once however many frames or variants carried it (so `dropped_guard_types` counts distinct slots, not occurrences), and a slot names no frame, so two frames' `self.act` are one slot, a slot one frame kept and another dropped is in both `kept_guards` and `dropped_guards` (which is why the digest's `(N kept)` is the kept count beside the drops, not the other half of a total), and a slot one frame's filter rejected and another frame's invariance policy dropped is legitimately in both drop lists. The relations are therefore stated, not checked, the way the frame lists already are; a `__post_init__` that raised on them would turn a bookkeeping collision into the loss of the whole report, which `capture_errors` exists to avoid. The same holds for `dropped_guard_code`, whose slots come from the two drop lists, and for `wont_generalize`, whose every source is the source half of a `kept_guards` slot.

## `dropped_guard_code`

`dropped_guard_code` carries the rendered check next to each dropped slot, because a slot such as `('HASATTR', "counts['pixel']")` can be either the benign companion of a kept `TENSOR_MATCH` or the only guard on an optional attribute, and only the rendered text tells them apart; it is for programmatic consumers, not the digest.

A slot is absent from it when its guard rendered no check, i.e. its `GuardBuilder` method never set `Guard.code_list` (the only writer is `Guard.set_export_info`, reached through the builder's `_set_guard_export_info`, and `CheckFunctionManager` resets `code_list` before every build, so this is a statement about the pre-filter build the entries come from, not about the guard in general). That is not predictable from how the check is installed, and the docstring states the predicate and says so instead of offering a rule or enumerating guard types (an enumeration in a docstring would rot against `guards.py` unchecked); the evidence is recorded here instead:

| guard type | installed through | renders a check |
| --- | --- | --- |
| `AUTOGRAD_SAVED_TENSORS_HOOKS` | a lambda | yes |
| `DEFAULT_DEVICE` | a C++ leaf | yes |
| `GLOBAL_STATE`, `TORCH_FUNCTION_STATE`, `DISPATCH_KEY_SET_MATCH`, `TENSOR_SUBCLASS_METADATA_MATCH` | | no |
| `CLOSURE_MATCH` on a plain function | guards `__code__` through a separate guard | no |
| `CLOSURE_MATCH` on any other callable | falls through to `FUNCTION_MATCH` -> `ID_MATCH` | yes |

The entry holds one rendering however many variants dropped the slot, and the docstring says what that means for a check that embeds the guarded value (`EQUALS_MATCH` renders `L['n'] == 3`): variants that differ in the value render differently, the entry shows one variant's rendering, the producer's pick rather than a merge, so it tells the form of the check and not the value; that the slot varied at all is what `risky_dropped_guards` records. The alternative, several entries per slot sharing a `(guard_type, source)` prefix, would make the field grow with variants rather than with slots and would answer a question (`which values`) the field is not for.

## `wont_generalize`

`wont_generalize` is documented as observed, not proven: a source is listed when a kept value-equality guard on a bare argument name pins it in some variant (`_pins_a_value` in `torch/_dynamo/precompile_package.py` is the rule, named rather than restated, so a kept `EQUALS_MATCH` on `self.eps` or `G['CFG'].width` is deliberately not one; `kept_guards` stays the authoritative list) and no other variant of the same frame guards it without pinning it, which is what the builder computes frame by frame (a variant that never guarded the source does not cancel the pin, and a frame that cancels its own pin does not cancel another frame's), rather than as a claim that every variant pins it.

## Keyword-only

```python
PrecompileSummary(frames=3, resume_functions=0, guarded_codes=1, backend_graphs=1)   # ok
PrecompileSummary(3, 0, 1, 1)   # TypeError: takes 1 positional argument but 5 were given
```

Its four required fields are all `int`, so the positional form would be legal and unreadable, and the positional order would become part of a public contract (the type is exported from `torch.compiler.precompile` later in this stack); the builder later in this stack (`_summarize`) and every test already construct it by keyword.

## complete

Its `complete` property is the one piece of logic: a capture counts as complete only if nothing was bypassed, truncated or uncovered, no capture call raised, and it produced at least one guarded code and at least one backend graph. It is a coverage flag only. `risky_dropped_guards` is a lint finding, not a proof, and `wont_generalize` follows from any value the capture pinned, so neither enters `complete`; both describe how far a complete capture generalizes, and the digest reports them on their own. The `backend_graphs > 0` term matters because `allow_empty_graphs` lets a frame that compiled nothing still count as a guarded code, so `guarded_codes` alone cannot tell a real capture from an empty one (a model whose every graph sits behind a recursive `torch._dynamo.disable`).

```python
def summary(**kw):
    base = dict(frames=1, resume_functions=0, guarded_codes=1, backend_graphs=1)
    base.update(kw)
    return PrecompileSummary(**base)

summary().complete                             # True
summary(backend_graphs=0).complete             # False: nothing was compiled
summary(guarded_codes=0).complete              # False
summary(capture_errors=("boom",)).complete     # False
summary(bypassed=("f",)).complete              # False, likewise truncated / uncovered_frames
risky = (("ID_MATCH", "self.act"),)
summary(dropped_guards=risky, risky_dropped_guards=risky).complete  # True: coverage only
```

`complete`, `dropped_guard_types` and `kept_guard_types` are all properties: each is an argument-free derivation of the fields, and one convention keeps `if summary.dropped_guard_types:` from silently passing on a bound method.

## The one-line digest

```python
s = PrecompileSummary(frames=2, resume_functions=1, guarded_codes=3, backend_graphs=2,
                      dropped_guards=(("ID_MATCH", "G['fn']"),),
                      kept_guards=(("EQUALS_MATCH", "scale"), ("TENSOR_MATCH", "x")),
                      wont_generalize=("scale",))
str(s)
# "2 frames (1 from graph breaks), 3 guarded codes, 2 backend graphs, dropped guards {'ID_MATCH': 1} (2 kept), 1 value-pinned source"
s.dropped_guard_types     # {'ID_MATCH': 1}

risky = (("HASATTR", "self.act"), ("ID_MATCH", "self.act"))
wide = PrecompileSummary(frames=8, resume_functions=0, guarded_codes=1, backend_graphs=1,
                         uncovered_frames=tuple(f"f{i}" for i in range(7)),
                         dropped_guards=risky, risky_dropped_guards=risky,
                         capture_errors=("RuntimeError: boom", "TypeError: bad", "ValueError: no"))
str(wide)
# "8 frames (0 from graph breaks), 1 guarded code, 1 backend graph, dropped guards {'HASATTR': 1, 'ID_MATCH': 1} (0 kept), RISKY drops ['HASATTR self.act', 'ID_MATCH self.act'], 7 UNCOVERED: ['f0', 'f1', 'f2', 'f3', 'f4'] +2 more, 3 CAPTURE ERRORS: 'RuntimeError: boom' +2 more"
```

Ordinary drops are counted by type with the kept count beside them for scale (a count, not a denominator: the two lists are disjoint per frame variant, not across frames), since every model drops the identity guards precompile cannot serialize. RISKY drops are few and actionable, so the digest names them, both halves of the slot, because two risky slots can share a source (a dropped `ID_MATCH` on `self.act` and a `HASATTR` checked on that object; a `HASATTR` slot's source is the object checked, the attribute is only in its rendering) and `['self.act', 'self.act']` would read as a duplicate. Policy drops and value-pinned sources are counted.

The digest stays one line whatever the model: the four list clauses (RISKY, UNCOVERED, TRUNCATED, BYPASSED) show their first five entries and then `+N more`, and the CAPTURE ERROR clause, the one place the report carries prose a reader can act on, shows the first non-empty line of the first message (repr'd, so a multi-line Dynamo message cannot break the line; non-empty so a message that opens with a newline does not render as `''`) and `+N more` for the rest. `capture_errors` is documented as `ExceptionType: message` strings, one per distinct exception rather than per failed call (the producer collapses repeats of the same type and message, so ten inputs failing the same way render `1 CAPTURE ERROR`), the type name first, so a bare `assert` (whose `str()` is empty) still leaves the clause something to show. The count in front of the three frame clauses and the CAPTURE ERROR clause is still the full count (the RISKY clause carries no count, so its total is the entries shown plus `+N more`). Every counted noun agrees with its count (`1 guarded code`, `2 backend graphs`, `1 CAPTURE ERROR`); the shouted frame clauses (`1 UNCOVERED: ['helper']`) carry a list, not a noun. The guard clauses come first and the shouted frame failures (UNCOVERED, TRUNCATED, BYPASSED, CAPTURE ERROR) last, so a failure never sits between two notes.

## Tests

All in `test/test_precompile.py`, next to the module's other tests.

- `test_summary_complete_requires_every_term` pins all six terms of `complete` and that the guard fields never enter it.
- `test_summary_digest_and_guard_type_counts` feeds every guard list sorted, as `_summarize` emits them, so the tally orderings its goldens pin are ones real output produces. It pins the digest for a capture with three dropped guards, a policy drop and a value-pinned source (which carries a `dropped_guard_code` entry the digest must not mention); for a clean capture with kept guards and no optional clause at all (`1 frame (0 from graph breaks), 1 guarded code, 1 backend graph`: kept guards appear only beside the drops); for a failing one whose two risky slots share a source and whose single capture error is a three-line message opening with a blank line (only its first non-empty line is shown); and for a wide one with seven uncovered frames and three errors (`['f0', 'f1', 'f2', 'f3', 'f4'] +2 more`, `'RuntimeError: boom' +2 more`), with singular and plural counts, plus the `dropped_guard_types` / `kept_guard_types` properties.
- `test_summary_pickle_and_hash` round-trips a fully populated summary (every field set, including `dropped_guard_code` and `capture_errors`) through `pickle`, checks that the copy compares and hashes equal, pins that summary's digest (the only golden with all eight clauses: `bad` already pinned notes before the shouted UNCOVERED, TRUNCATED, BYPASSED, CAPTURE ERROR order, and this one adds `1 policy-dropped guard` and `1 value-pinned source` between the RISKY clause and UNCOVERED, which no other fixture places), and checks that positional construction raises the keyword-only `TypeError`. Only `PrecompileSummary` is round-tripped here: `GuardFact` gets its own round-trip with its keyword-only change two commits up, which also deletes `FrameInvariants` as unused.
- `test_summary_guard_lists_aggregate_over_frames` pins the multi-frame case: one slot listed as dropped, risky and policy-dropped at once constructs, is counted once by `dropped_guard_types`, and renders once in each digest clause. Its comment credits the risky classification to the slot telling its frame's variants apart, not to the risky-drop lint, which waives a builtin read the ordinary way (`_reads_a_builtin`).

Every policy-dropped fixture slot is a `BUILTIN_MATCH` on `G['__builtins_dict___<n>']['len']`, one of the four serializable types the default filter keeps and `_INVARIANT_DROPPABLE_GUARD_TYPES` lets the policy drop, and the only one of them with a source (`DUAL_LEVEL`, `FUNCTORCH_STACK_MATCH` and `AUTOGRAD_SAVED_TENSORS_HOOKS` are global-state guards); a `CONSTANT_MATCH` or `HASATTR` is `_SHAPE_BEARING_GUARD_TYPES`, never policy-dropped, so a fixture placing one on the policy side would pin a state the producer cannot emit. Likewise every fixture that lists a `wont_generalize` source keeps an `EQUALS_MATCH` on that bare name, since `_wont_generalize` returns nothing unless a kept slot passes `_pins_a_value`.

Test Plan:

```
python test/test_precompile.py -k summary
lintrunner torch/compiler/_precompile_types.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]>

Reverted in 94990b8 as a dependent of #197262 and back in the stack unchanged.
Pull Request resolved: #197964
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
… by its name (#197264) (#197965)

**Summary.** `_is_library_module(name)` answers whether torch or the standard library owns a module, which is the waiver the risky-drop lint (added two commits later) applies to a dropped identity guard on a library-owned value. A name is not an identity: `graphlib`, `queue`, `code` and `distutils` are all stdlib names a third party ships, and `import distutils` in a default setuptools install actually resolves to `site-packages/setuptools/_distutils`, selected by `SETUPTOOLS_USE_DISTUTILS`, which is exactly the config-chooses-the-implementation shape the lint exists to catch. So the top-level module must RESOLVE to code shipped with the interpreter, judged by the previous commit's `_located` (a placed `__file__`, else the inittab or the frozen table). Every imported dotted ancestor of the name is checked the same way, but an inner name only has to not be located ELSEWHERE: `pyexpat.errors` (registered by pyexpat's C init with neither `__file__` nor `__spec__`) and `torch.ops` (a `ModuleType` subclass whose `__file__` is a class attribute the module dict never sees) keep their waiver because their packages are located, while a shadowed submodule (a `collections.abc` under `site-packages`, a `torch.foo` outside the torch roots) loses it. A top-level name that is not imported or carries no location evidence (a namespace package, an exec'd module) and `None` are all untrusted. The torch arm alone has an escape hatch, and the docstring says so: a frozen torch gives `_torch_roots` nothing to anchor to, and then every torch name is waived on its name with no location evidence.

## Behaviour pinned by the tests

```python
from torch._dynamo import precompile_package as pp

stdlib_root = sysconfig.get_paths()["stdlib"]
shadowed = types.ModuleType("graphlib")
shadowed.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib", "__init__.py")
with mock.patch.dict(sys.modules, {"graphlib": shadowed}), mock.patch.object(pp, "_install_roots", return_value=()):
    pp._is_library_module("graphlib")      # False: under an install dir, even though under the stdlib root and no install root is known

vendored = types.ModuleType("graphlib")    # no site-packages component in the path
vendored.__file__ = os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py")
with mock.patch.dict(sys.modules, {"graphlib": vendored}), mock.patch.object(pp, "_install_roots", return_value=(pp._norm(os.path.join(stdlib_root, "vendored")),)):
    pp._is_library_module("graphlib")      # False: only the install-root exclusion catches this one
pp._classify_file.cache_clear()            # the verdict is cached per __file__
with mock.patch.dict(sys.modules, {"graphlib": vendored}), mock.patch.object(pp, "_install_roots", return_value=()):
    pp._is_library_module("graphlib")      # True: the same file is stdlib once nothing is installed there

with mock.patch.dict(sys.modules, {"graphlib": types.ModuleType("graphlib")}):
    pp._is_library_module("graphlib")      # False: no __file__, no __spec__ -- no evidence

fake_torch = types.ModuleType("torch")
fake_torch.__file__ = os.path.join(stdlib_root, "torch", "__init__.py")   # the stdlib dir itself is never a pip target
with mock.patch.dict(sys.modules, {"torch": fake_torch}):
    pp._is_library_module("torch")         # False: the top-level check, torch resolving outside the torch roots
foo = types.ModuleType("torch.foo")
foo.__file__ = os.path.join(stdlib_root, "torch", "foo.py")
with mock.patch.dict(sys.modules, {"torch.foo": foo}):
    pp._is_library_module("torch.foo")     # False: the ancestor loop, a located torch does not vouch for it
foo.__file__ = "foo.py"
with mock.patch.dict(sys.modules, {"torch.foo": foo}):
    pp._is_library_module("torch.foo")     # True: a relative __file__ is no evidence, and an inner name needs none
pp._is_library_module("collections.never_imported")   # True: an inner name that is not imported has nothing to check
with mock.patch.object(pp, "_torch_roots", return_value=()):
    pp._is_library_module("torch.never_imported")   # True: frozen torch, waived on the name alone

sub = types.ModuleType("sys.sub")
sub.__spec__ = importlib.machinery.ModuleSpec("sys.sub", importlib.machinery.BuiltinImporter, origin="built-in")
with mock.patch.dict(sys.modules, {"sys.sub": sub}):
    pp._is_library_module("sys.sub")       # False: "sys.sub" is not in sys.builtin_module_names, "sys" is

# On 3.11+ every frozen stdlib module also carries an absolute __file__ (whenever sys._stdlib_dir is
# known), so the real zipimport is decided by its path; a module dict without one reaches the frozen table.
frozen = importlib.machinery.FrozenImporter
zipimport_frozen = types.ModuleType("zipimport")
zipimport_frozen.__spec__ = importlib.machinery.ModuleSpec("zipimport", frozen, origin="frozen")
with mock.patch.dict(sys.modules, {"zipimport": zipimport_frozen}):
    pp._is_library_module("zipimport")     # True: the frozen table has zipimport
graphlib_frozen = types.ModuleType("graphlib")
graphlib_frozen.__spec__ = importlib.machinery.ModuleSpec("graphlib", frozen, origin="frozen")
with mock.patch.dict(sys.modules, {"graphlib": graphlib_frozen}):
    pp._is_library_module("graphlib")      # False: a frozen spec under a name the frozen table does not have

pp._is_library_module("torch._C._nn")      # True: located parent torch._C; _nn (no __file__, no __spec__) carries no evidence of its own
pp._is_library_module("pyexpat.errors")    # True: located parent, submodule (no __file__, no __spec__) not located elsewhere
pp._is_library_module("collections.abc")   # True, unless sys.modules["collections.abc"] resolves to site-packages
pp._is_library_module("not_a_stdlib_name") # False: not a stdlib name
with mock.patch.dict(sys.modules):
    sys.modules.pop("graphlib", None)
    pp._is_library_module("graphlib")      # False: a stdlib name that is not imported
pp._is_library_module(None)                # False
```

## The tests

Two module-level fixtures carry the rows. `_STDLIB_ROOT` is sysconfig's `stdlib`, the path every shadow row with an absolute `__file__` is spelled under and the directory the relative row is judged from (the stdlib dir itself is never a pip target, so no torch root holds the torch rows, while `site-packages/torch` IS one wherever purelib nests under stdlib). `_NOT_LIBRARY_MODULES` is a table of shadow modules, one row per refused shape, each labelled by the check that refuses it: under an install dir with `_install_roots` patched to `()` (only `_INSTALL_DIR_NAMES` refuses it), under a nested install root with no `site-packages` component (only the `_install_roots` exclusion does), no file and no spec, a relative file (judged with the cwd at `_STDLIB_ROOT`, where the real `graphlib.py` sits, so that without the `isabs` gate the name would resolve to stdlib and be waived), `torch` itself and `torch.foo` outside the torch roots (the top-level check and the ancestor loop), a dotted name under a built-in top (by spec; the `__loader__` leg is `_located`'s and pinned by its own tests), a frozen spec under a non-frozen name and a shadowed `collections.abc`; a `__file__` with an embedded NUL has no row, because `_is_library_module` refuses it whether `_classify_file`'s NUL gate answers None or `_norm` raises out of `_located` (the gate is pinned by `_classify_file`'s own tests).

`test_library_module_requires_the_name_to_resolve_to_the_library` is parametrized over `_NOT_LIBRARY_MODULES` so a regression names its row; the rows are built from `types.ModuleType` objects patched into `sys.modules` with `_install_roots` patched per row, so nothing touches the real interpreter layout, and the test clears `_classify_file`'s cache first, because that verdict is cached per `__file__` while `_install_roots` is patched per row, so a verdict another test left for a row's file would be read back under the wrong roots. Every row here is a refusal: no `True` path is exercised by this commit's test, so on its own it cannot tell the function from `return False`. The waiver side (the real torch and stdlib names, the evidence-only-at-the-top rule, and the location-free refusals: not a stdlib name, not imported, `None`) is pinned by the next commit's tests, which is where the code block above is exercised in full.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_library_module
lintrunner torch/_dynamo/precompile_package.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 01ab03e as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197965
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…nd the evidence-only-at-the-top rule (#197595) (#197966)

**Summary.** Tests only, for `_is_library_module` from the previous commit. That commit pins every shape the predicate refuses; this one pins what it must keep waiving: the real torch and stdlib names as they are laid out in the running interpreter, and the rule that location evidence is demanded only of the top-level name of a dotted module, never of its inner names. It is a separate commit so each half stays small enough to review in one sitting; the code is unchanged.

## Behaviour pinned by the tests

```python
from torch._dynamo import precompile_package as pp

pp._is_library_module("torch._C._nn")      # True: located parent torch._C; _nn (no __file__, no __spec__) carries no evidence of its own
pp._is_library_module("pyexpat.errors")    # True: located parent, submodule (no __file__, no __spec__) not located elsewhere
pp._is_library_module("collections.abc")   # True, unless sys.modules["collections.abc"] resolves to site-packages
pp._is_library_module("collections.never_imported")   # True: an inner name that is not imported has nothing to check
with mock.patch.object(pp, "_torch_roots", return_value=()):
    pp._is_library_module("torch.never_imported")   # True: frozen torch, waived on the name alone
foo = types.ModuleType("torch.foo")
foo.__file__ = "foo.py"
with mock.patch.dict(sys.modules, {"torch.foo": foo}):
    pp._is_library_module("torch.foo")     # True: a relative __file__ is no evidence, and an inner name needs none
with mock.patch.dict(sys.modules):
    sys.modules.pop("graphlib", None)
    pp._is_library_module("graphlib")      # False: a stdlib name that is not imported
pp._is_library_module("not_a_stdlib_name") # False: not a stdlib name
pp._is_library_module(None)                # False
```

## The tests

`_LIBRARY_NAMES` lists the torch and stdlib names that must keep their waiver, including the evidence-free inner names `torch._C._nn`, `torch.ops`, `pyexpat.errors` and `xml.parsers.expat.model`; the header's `import xml.parsers.expat` keeps the last one's top-level name in `sys.modules`, which a waiver requires. `test_library_module_keeps_the_waiver_for_the_real_library` is parametrized over it and clears `_classify_file`'s cache first, so it reads the real layout rather than a verdict a sibling interned under patched roots.

`test_library_module_needs_location_evidence_only_at_the_top` pins an unimported stdlib name, a non-stdlib name and `None` as untrusted, a relative `__file__` on an inner name keeping the waiver, an inner name that is not imported keeping it too (nothing under the name to check, and the package is located), the `under_a_nested_install_root` row's own file being stdlib once nothing is installed there, the frozen table's True on a fabricated file-less `zipimport`, and the frozen-torch early True.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_library_module
lintrunner 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 c654400 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197966
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…rd hangs off (#197265) (#197967)

**Summary.** Dynamo guards every module it walks through, so the path down to `F.gelu` is guarded module by module, and that is what lets a dropped identity guard on an attribute be recognised as a read off a namespace rather than off an object a config could have swapped. `_module_namespaces(entries)` collects the module-valued guard entries rooted at a `GlobalSource` and returns the TRUSTED ones, mapped from source name to module. `_source_root(source)`, a one-line walk down `ChainedSource.base` to the root, is added here as the helper that finds that `GlobalSource`. A module is trusted if torch or the stdlib owns it (`_is_library_module`), if it is bound under its own name (`import mypkg`, or the `__import_x` alias Dynamo installs to reach an inlined function's globals, recognised through `_dynamo_alias_module`), or if it is an attribute of a trusted module under a name that module already owns: its own `__name__` (a plain `import own_sub` inside the parent) or the parent's name plus the attribute (`from . import sub`, and `import mypkg.layers`, which Dynamo guards as `G['mypkg'].layers`). An ALIASED user module is none of those: `if flag: import impl_b as impl` picks what `impl.op` resolves to per machine, and so does `from . import impl_b as impl` in a package `__init__`; inheriting the parent's trust without checking the name is what let that shape through in an earlier round. Library ownership is trusted under any binding, `import torch.nn.functional as F` included; the price, taken deliberately because flagging `F` would flag every model, is that an alias config picks between two torch modules is waived too, which `_is_risky_drop`'s KNOWN GAP records. Dynamo never guards a bare `__import_torch` alias, only the attributes read off it, so aliases with no module-valued entry are recovered from their name rather than treating `torch.Tensor` as a config-swappable slot. A config module (`torch.utils._config_module.ConfigModule`, e.g. `torch._dynamo.config`) is the one namespace whose bindings config chooses by definition, so it is never trusted, whoever owns it and however it is reached: the check is a trust verdict inside `is_trusted`, not a filter on what is collected, so a config module recovered from an `__import_x` alias (`from torch._dynamo.config import verbose` in an inlined function) is refused the same way as one bound under a plain name.

## Which namespaces are trusted

```python
import mypkg                 # G['mypkg']: trusted, bound under its own name
import mypkg.layers          # G['mypkg'].layers: trusted, mypkg is and owns the name mypkg.layers
import torch.nn.functional as F   # trusted: torch owns it, whatever the alias
import impl_b as impl        # NOT trusted: the alias is a slot the import picked
impl.deep                    # NOT trusted: a name impl owns, but impl itself is not trusted
config = torch._dynamo.config     # NOT trusted: a config module, whoever owns it
from torch._dynamo.config import verbose  # NOT trusted either: G['__import_torch_dot__dynamo_dot_config'] is recovered, then refused

# inside a trusted package __init__:
from . import sub            # trusted: module.__name__ == "mypkg.sub" == f"{parent}.sub"
from . import impl_b as impl # NOT trusted: "mypkg.impl_b" is neither "impl" nor "mypkg.impl"
```

The result feeds `_is_risky_drop` (next commit): a dropped guard whose source is in the returned dict, or whose `source.base.name` is one of its keys (an exact lookup, never a prefix match), is judged by the namespace's owner rather than flagged outright. `test_module_namespaces_trust_only_bindings_config_cannot_repoint` builds each shape above from hand-made `GuardFilterEntry` values and asserts the exact trusted set.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_module_namespaces_trust_only_bindings_config_cannot_repoint
lintrunner torch/_dynamo/precompile_package.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 fde4ed9 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197967
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…r compared (#197267) (#197968)

**Summary.** A later invariance policy may leave a guard out of the serialized artifact when it held identically across every captured variant, and this commit names the two classes of guard that must never take part in that. Each set states two independent properties, never dropped and never compared. `_SHAPE_BEARING_GUARD_TYPES` are the guard types that pin an input's shape, value or kind; the report compares them across variants and a policy never drops one, because with a single captured example nothing can discriminate, and what would disappear is the check that the runtime input looks like the captured one at all. `_UNMODELLED_GUARD_TYPES` are the guard types on ambient or process state that the guard leaf checks for itself and that nothing in this module fingerprints; calling two of them equal would assert a precondition the report cannot see, so they are reported as undetermined rather than compared, and they are never dropped because a policy may drop only what its droppable set names. Both sets are plain sorted literals with a header stating the criterion; membership was settled over the review rounds of this PR, and the four-set partition of `GuardBuilder`'s methods (these two plus the identity and no-op sets) is pinned by the totality test in the next commit, so a guard type added to Dynamo is kept unconditionally until someone classifies it.

## Membership

```python
from torch._dynamo.precompile_package import _SHAPE_BEARING_GUARD_TYPES, _UNMODELLED_GUARD_TYPES

len(_SHAPE_BEARING_GUARD_TYPES), len(_UNMODELLED_GUARD_TYPES)  # (24, 12)
_SHAPE_BEARING_GUARD_TYPES & _UNMODELLED_GUARD_TYPES           # frozenset()
"TENSOR_MATCH" in _SHAPE_BEARING_GUARD_TYPES                   # True: compared, never dropped
"SHAPE_ENV" in _UNMODELLED_GUARD_TYPES                         # True: never compared, never dropped
"ID_MATCH" in _SHAPE_BEARING_GUARD_TYPES | _UNMODELLED_GUARD_TYPES   # False: classified next commit
```

Test Plan:

```
python -c "import torch._dynamo.precompile_package"
lintrunner torch/_dynamo/precompile_package.py
```

The classification tests land with the next commit, which adds the other two sets; run there:

```
python test/dynamo/test_precompile_package.py -k test_guard_policy_classification_is_total
python test/dynamo/test_precompile_package.py -k guard_type
```

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 c51118f as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197968
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
… totality test (#197268) (#197969)

**Summary.** With the shape-bearing and unmodelled sets in place, this commit adds the other two and the test that makes the classification enforceable. `_IDENTITY_GUARD_TYPES` freezes `CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, both for the fingerprinting code that follows and as the base of `_INVARIANT_DROPPABLE_GUARD_TYPES`, the ONLY guard types an invariance policy may drop, and only when proven invariant across every captured variant: the identity guards the default filter drops anyway as unserializable, derived from that same set so the two cannot disagree, plus `BUILTIN_MATCH`, an identity match the default filter keeps; the ambient-state guards (`DEFAULT_DEVICE`, `FUNCTORCH_STACK_MATCH`, `DUAL_LEVEL`, `AUTOGRAD_SAVED_TENSORS_HOOKS`) are unmodelled per the previous commit, so nothing outside identity is droppable. `_NOOP_GUARD_TYPES` (`DETERMINISTIC_ALGORITHMS`, `GRAD_MODE`) are markers whose `GuardBuilder` method is `pass` and whose check is made by `GLOBAL_STATE`'s leaf, so nothing about them is ever serialized or dropped, and `_is_noop_guard_type` adds `EMPTY_NN_MODULE_HOOKS_DICT` under the default `skip_nnmodule_hook_guards`, where the builder emits nothing for it; with the skip off it emits a real `SEQUENCE_LENGTH`, which is why the previous commit classified it shape-bearing rather than droppable. `test_guard_policy_classification_is_total` enumerates every uppercase callable on `GuardBuilder` (through `dir`, so a method added on `GuardBuilderBase` or a mixin counts) and asserts the four sets cover all of them, contain nothing else, are pairwise disjoint, and that the identity set is inside the droppable one, so a guard type added to Dynamo fails this test until someone triages it and is KEPT unconditionally until then. Guards installed outside `GuardBuilder` -- the root manager's `DuplicateInputs` and `StorageOverlap` exprs and the dimension-marking lambda -- never reach the guard filter and are outside the policy as well. `test_noop_guard_type_follows_the_hook_guard_config` pins the config-dependent answer.

## The test

```python
guard_types = {name for name in dir(GuardBuilder) if name.isupper() and callable(getattr(GuardBuilder, name))}
sets = {
    "_SHAPE_BEARING_GUARD_TYPES": _SHAPE_BEARING_GUARD_TYPES,
    "_UNMODELLED_GUARD_TYPES": _UNMODELLED_GUARD_TYPES,
    "_INVARIANT_DROPPABLE_GUARD_TYPES": _INVARIANT_DROPPABLE_GUARD_TYPES,
    "_NOOP_GUARD_TYPES": _NOOP_GUARD_TYPES,
}
classified = frozenset().union(*sets.values())
assert guard_types - classified == set()   # "unclassified GuardBuilder guard type(s): add each to exactly one policy set"
assert classified - guard_types == set()   # "phantom entries: no GuardBuilder method by these names"
for (a_name, a), (b_name, b) in itertools.combinations(sets.items(), 2):
    assert not (a & b)
assert _IDENTITY_GUARD_TYPES <= _INVARIANT_DROPPABLE_GUARD_TYPES
```

```python
_is_noop_guard_type("GRAD_MODE")                     # True
_is_noop_guard_type("EMPTY_NN_MODULE_HOOKS_DICT")    # True under the default config, False under
                                                     # torch._dynamo.config.patch(skip_nnmodule_hook_guards=False)
```

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_guard_policy_classification_is_total
python test/dynamo/test_precompile_package.py -k test_noop_guard_type_follows_the_hook_guard_config
lintrunner torch/_dynamo/precompile_package.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 ca5b700 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197969
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…ered guard code (#197269) (#197970)

**Summary.** The invariants report a later commit writes is meant to be committed to a repository and diffed across runs, so anything in a rendered guard that differs run to run has to be scrubbed first. `_normalize` replaces the object address in `___check_obj_id(..., 140311678493200), type=` renderings, the `(id, id)` tuple in `top_saved_tensors_hooks ids == (...)`, the per-process counter Dynamo appends to the builtins dict it installs (`__builtins_dict___6`), and the `_<id>_c<n>` suffix `OutputGraph.install_global_by_id` bakes into an identifier, where neither of the other patterns can see it (transformers' Qwen2 installs three such globals; torch itself is installed under an empty prefix as `_<id>_c<n>`). Those are exactly the three minted families `aot_compile._MINTED_GLOBAL_PREFIXES` names as able to root a serializable guard; `__compiled_fn_*` and `__resume_at_*` are codegen-only `LOAD_GLOBAL` targets and are deliberately not matched, since a pattern for them would have to guess at a shape (`__resume_at_<offset>_<counter>`, `__compiled_fn_<n>_<uuid>`) no guard ever renders. Each pattern is anchored to the call shape that carries the address, because a bare `\b\d{9,}\b` also eats a user constant such as a dict key or slice bound, and two variants guarding different values would then render the same fact and invent an invariant neither holds; for the `install_global_by_id` shape the digit width is that anchor, since the prefix can be empty and `w_1_c2` is a plausible user identifier. `_render_code` applies the normalization to every part of a guard's `code_list`, and `_hash_text` is the 12-hex-digit sha256 prefix the fingerprints that follow use. `test_normalize_scrubs_addresses_and_counters_but_not_user_constants` is a table over both directions: everything run-varying is erased, and nothing meaningful is.

## Before and after

```python
from torch._dynamo.precompile_package import _normalize

_normalize("___check_obj_id(G['fn'], 140311678493200), type=<class 'function'>")
# "___check_obj_id(G['fn'], <id>), type=<class 'function'>"
_normalize("G['__builtins_dict___6']['len']")
# "G['__builtins_dict___<n>']['len']"
_normalize("G['__import_mod_140311678493200_c1']")
# "G['__import_mod_<id>_c<n>']"
_normalize("G['_140311678493200_c3'] is not None")
# "G['_<id>_c<n>'] is not None"
_normalize("top_saved_tensors_hooks ids == (139, 140)")
# "top_saved_tensors_hooks ids == (<ids>)"
_normalize("L['dims'][0] == 140311678493200")
# unchanged: a bare number is a user constant, not an address
_normalize("L['w_1_c2'] == 3")
# unchanged: a short counter-looking identifier is the user's
```

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_normalize_scrubs_addresses_and_counters_but_not_user_constants
lintrunner torch/_dynamo/precompile_package.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 73422e9 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197970
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…e guard report (#197270) (#197971)

**Summary.** `_normalize` strips the address an identity guard renders, so the report needs another stable name for the object it guarded, or two variants holding different callables at one source collapse into one fact and are reported as an invariant neither holds. `_object_identity(value)` names a module by `__name__`, and a callable by where it is DEFINED plus a digest of its body: `is @<basename>:<firstlineno>#<fingerprint> <module>.<qualname>`, truncated to 160 characters with the discriminating part FIRST, because a qualname alone can exceed the limit on a transformers lambda nested in a long module path, and a digest appended at the end would be cut off exactly where it is needed. The digest comes from `_code_fingerprint`, a sha256 prefix over `co_code`, `co_names`, `co_varnames`, `co_freevars`, `co_cellvars` and the stable constants, which is what tells apart an `ACT2FN`-style table whose lambdas are all written on one source line and so agree on file AND lineno. `_stable_consts` reduces `co_consts` to what reprs the same in every process, recursing into tuples, frozensets (sorted by repr) and nested code objects instead of dropping them, because two lambdas that differ only in `x * (1, 2)` versus `x * (1, 3)`, or only inside an inner lambda, are genuinely different variants and dropping the container is what let them collide. A const of any other type keeps its SLOT as a type marker for the same reason: `x[..., 0]` and `x[0, ...]` fold to one const tuple at the same index, so dropping the unrecognized `Ellipsis` merged them (Ellipsis and NotImplemented repr by name and are kept by value). Only the code object is named, not the data bound to it, and the docstring says so: two closures from one factory, two functions differing only in `__defaults__`, bound methods of two instances and every `functools.partial` render the same. The digest is stable across processes but not across Python versions, since `co_code` is version-specific bytecode.

## The collision the test pins

```python
from torch._dynamo.precompile_package import _code_fingerprint, _object_identity

left, right = (lambda x: x * (1, 2)), (lambda x: x * (1, 3))
left.__code__.co_code == right.__code__.co_code          # True: only co_consts differ
_code_fingerprint(left.__code__) == _code_fingerprint(right.__code__)   # False

# same for a frozenset constant, a nested code object, and an Ellipsis subscript:
(lambda x: x in {1, 2}), (lambda x: x in {1, 3})
(lambda x: (lambda y: y + 1)), (lambda x: (lambda y: y + 2))
(lambda x: x[..., 0]), (lambda x: x[0, ...])

_object_identity(torch.nn.functional)   # "is module torch.nn.functional"
_object_identity(left)                  # "is @test_x.py:12#3f9a... __main__.<lambda>"
_object_identity(object())              # "is a builtins.object"
```

`test_code_fingerprint_recurses_into_container_and_nested_consts` asserts, for each of the four pairs, that `co_code` agrees and the fingerprints differ, that an unrenderable const keeps its slot, and that the same source compiled twice agrees. `test_code_fingerprint_is_stable_across_processes` checks the digest of a fixed snippet against a fresh interpreter, which is the only thing that holds the "committed and diffed" line. `test_object_identity_puts_the_digest_before_the_truncation_point` pins the module and fallback renderings and that, on a qualname longer than the bound, the site and digest survive the cut.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_code_fingerprint_recurses_into_container_and_nested_consts
python test/dynamo/test_precompile_package.py -k test_code_fingerprint_is_stable_across_processes
python test/dynamo/test_precompile_package.py -k test_object_identity_puts_the_digest_before_the_truncation_point
lintrunner torch/_dynamo/precompile_package.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 e4639d6 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197971
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…ization dropped (#197266) (#197972)

**Summary.** Serialization drops every identity guard, so precompiling gives up on noticing that a guarded object was rebound; `_is_risky_drop(entry, namespaces)` is the lint that says which of those drops can plausibly change results on a capture-here / serve-there deployment, where the concern is DIVERGENCE: the serving machine runs the same source but a config, flag or environment variable picks a different object. It intersects the binding SITE with who owns the value, because either test alone is wrong: `self.act = getattr(F, cfg.activation)` and `self.act = cfg.act_fn` are the same swappable slot, so calling the first benign because `F.gelu` is torch-owned waves through capture-gelu-serve-silu, while `if flag: import impl_b as impl` then `impl.op` is a read off a module namespace exactly like `F.gelu` but the module is user code an env var chose. Three bindings are waived: a builtin read the ordinary way, an attribute read off a trusted namespace that torch or the stdlib owns or that owns a def of that same name, and a global bound to a def of the same name when torch or the stdlib owns the def or it lives in the file doing the reading; instance attributes, closure cells, aliased imports, cross-module `from x import op`, registry lookups, reads off a config module and an entry whose value could not be read are all risky. The docstring records the KNOWN GAP: every waiver judges the object capture happened to bind, not the statement that bound it, so a name bound conditionally is waived whenever the branch taken at capture is a waived shape, a third party that rebinds `F.gelu` at import is waived, and so is an alias config picks between two torch modules. `dropped_guards` stays the authoritative list; this is a lint over it, not a proof. `test_risky_drop_decision_table` pins every shape found so far on hand-built entries. One shape's source spelling is Dynamo's own: under `nested_graph_breaks=True` a callee's `act = pick()` crosses the break as `L['__nested_frame_values'][0][k]` rather than `L['act']`, and `test_risky_drop_sees_the_slot_behind_a_nested_resume` drives that layout and the flat one through a real compile, so the slot is flagged and the def read inside `pick()` waived either way. The capture-session corpus that drives real compiles through the same predicate belongs to a later stack.

## The decision, in order

```python
def _is_risky_drop(entry, namespaces):
    source, value = entry.orig_guard.originating_source, entry.value
    if _is_dynamo_synthesized(source):        return False   # Dynamo's own generated resume functions
    if source.name in namespaces:             return False   # the guard IS on a trusted module
    if _reads_a_builtin(source, value):       return False   # len, sorted via __builtins_dict__
    if not entry.has_value:                   return True    # nothing to judge ownership by
    if isinstance(source, AttrSource):
        ns = namespaces.get(source.base.name)
        if ns is not None:                    # F.gelu, own_helpers.call ...
            return not (_is_library_module(ns.__name__)
                        or (_owning_module(value) == ns.__name__ and value.__name__ == source.member))
    if isinstance(source, GlobalSource) and getattr(value, "__name__", None) == source.global_name:
        return not (_is_library_module(_owning_module(value))   # from torch.nn.functional import silu
                    or _defined_where_read(value, source.global_name, entry.orig_guard.user_stack))  # def in this file
    return True
```

```python
F.gelu(x)                      # waived: torch owns torch.nn.functional
own_helpers.call(x)            # waived: own_helpers owns a def named call
own_helpers.act(x)             # RISKY: act is bound to some other def, i.e. a slot
cpkg.op(x)                     # RISKY: re-exported from cpkg.impl_b, chosen by an import elsewhere
self.act(x)                    # RISKY: an instance attribute is a slot
impl.op(x)  # import impl_b as impl   RISKY: the alias is the slot
config.attn_impl(x)            # RISKY: a config module is never a trusted namespace
```

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_risky_drop
lintrunner torch/_dynamo/precompile_package.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 e0ba7af as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197972
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…oes not say (#197271) (#197973)

**Summary.** Most guards render code that names the value they check, but three kinds do not, and comparing their facts across variants by rendered code alone would call different specializations equal. `_value_fingerprint(entry)` supplies the missing discriminator: for a tensor it renders exactly what `TensorCheck` stores, via `get_tensor_guard_code_part` with the TLS-adjusted dispatch key set, because `TENSOR_MATCH`'s `code_list` carries only the `_dynamo_*_indices` checks while dtype, shape, python type and dispatch keys all live in the C++ leaf (a `Parameter` against a `Tensor`, or an inference-mode tensor against a `no_grad` one, splits a compilation exactly as dtype does); for `GRAD_MODE` and `DETERMINISTIC_ALGORITHMS`, which carry no name, code or value, it reads the same process state `GlobalStateGuard` snapshots; for `AUTOGRAD_SAVED_TENSORS_HOOKS` it names the installed hooks through `_saved_hooks_fingerprint` the way the guard compares them, since `_normalize` had to erase their ids: the guard stores `None` for any hooks it cannot inline, so plain-Python hooks and no hooks are one value, and inlineable fx `GraphModule` hooks are named by a digest of their rendered graph (KNOWN TRADEOFF: two distinct `GraphModule`s with identical code read as one hook set while the guard compares ids); and for an identity guard it uses `_object_identity`. Every other guard returns `""`, deliberately: `TYPE_MATCH` on an unspecialized int checks only that it is an int, and stamping `1` on one variant and `2` on the next would demote a real invariant into two identical "varies" lines. Every branch therefore dispatches on `entry.guard_type`, never on the value's type: the `NOT_NONE_MATCH` Dynamo installs on an optimizer's `.grad`, a `COW_TENSOR_MATCH`, or a `TYPE_MATCH` on a tensor attribute holds a tensor whose shape and dtype it never checks, and rendering them would split identical guards. `_fact_order` is the sort key for facts, and it includes the value because once boilerplate code parts are filtered a `TENSOR_MATCH` renders no code, so two shape specializations would otherwise tie and sort unstably. The docstring records the KNOWN GAP that under `dynamic=True` the concrete shape here is narrower than the guard, so a shape-generic `TENSOR_MATCH` reads as varying rather than invariant.

## What each guard type contributes

```python
_value_fingerprint(grad_mode_entry)          # "grad_enabled=True"          (read from torch.is_grad_enabled())
_value_fingerprint(deterministic_entry)      # "deterministic=False, warn_only=False"
_value_fingerprint(saved_hooks_entry)        # "hooks=None", or "hooks=(<sha>, <sha>)" for inlineable fx hooks
_value_fingerprint(tensor_entry)             # "check_tensor(<value>, Parameter, DispatchKeySet(...), torch.float32, ...)"
_value_fingerprint(id_match_entry)           # _object_identity(entry.value)
_value_fingerprint(type_match_on_int_entry)  # "" -- the rendered code already names the check
_value_fingerprint(not_none_on_grad_entry)   # "" -- a tensor value, but the guard checks only presence
```

A tensor whose guard part cannot be rendered (a `__torch_function__` subclass that refuses attribute reads) falls back to `type=..., <unrenderable>` rather than raising out of a lint, and a hooks read that fails renders `hooks=<unreadable>`, distinct from the `""` that means no discriminator is needed.

`test_value_fingerprint_dispatches_on_the_guard_type` pins that five tensors differing in dtype, shape, `Parameter`-ness and inference mode render five distinct `check_tensor(<value>, ...)` strings, that `NOT_NONE_MATCH`, `TYPE_MATCH` and `COW_TENSOR_MATCH` on the same tensor render `""`, the `GRAD_MODE`, identity and unrenderable-subclass renderings, and that `_fact_order` orders by value. `test_saved_hooks_fingerprint_mirrors_what_the_guard_stores` pins `hooks=None` for both no hooks and plain-Python hooks and the per-graph digest for `GraphModule` hooks.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k fingerprint
lintrunner torch/_dynamo/precompile_package.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 602de98 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197973
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
… generalize (#197272) (#197974)

**Summary.** A non-tensor argument, and any value that crosses a graph break, is guarded by equality, so an int, bool or str argument yields an artifact that only serves calls reproducing that exact value; `PrecompileSummary.wont_generalize` is where a capture reports those, and this commit adds the two functions that compute it. `_pins_a_value(guard_type, name)` is true for a value-equality guard on a BARE name (a plain local, or the `___stackN` Dynamo gives a value crossing a break), and never for the empty source of a guard checked against no source. The value-equality guards are `CONSTANT_MATCH` (the front door, which delegates a bool to `BOOL_MATCH`, None to `NONE_MATCH`, a code object to `ID_MATCH` and everything else, ints included, to `EQUALS_MATCH`, and is the only guard method that derives into another one of these, so the slot's top-level type is enough), `EQUALS_MATCH`, `CONSTANT_SUBCLASS_MATCH` (the base value of an int/float/str subclass argument) and the two iterator guards `RANGE_ITERATOR_MATCH` and `COUNT_ITERATOR_MATCH`, which pin an iterator argument's exact position; length and key-set guards pin a container's structure rather than a value and are deliberately not counted; the set keys on guard type alone, so an `EQUALS_MATCH` installed on a container argument itself (a `dict_keys` or a frozenset of torch ops) is counted, its contents being the value the artifact then serves only for. A dotted or subscripted source such as `self.eps` or `G['CFG'].width` is reached through an argument rather than being one, which is where model config lives, and every `LayerNorm` contributes a `CONSTANT_MATCH` there, so counting those would flag every model. `_wont_generalize(kept, guard_sets)` starts from the pinned kept slots and keeps a source only if SOME frame pins it in a variant and no variant of that frame reaches it without pinning (a fact whose guard the filter dropped, `enforced` False, checks nothing and counts as a generic mention, not a pin, the drop itself being what `dropped_guards` reports; a variant's OWN companion guards on a source it pins, the `SEQUENCE_LENGTH` beside a `dict_keys` `EQUALS_MATCH`, are not a generic mention); a frame whose variants both pin a source and guard it generically cancels its own pin and nobody else's, because a source pinned in one variant is not pinned for the artifact: once two examples are captured the ordinary shape is one variant guarding `scale` by equality and another guarding it generically, and the second serves new values fine. Cancellation is per frame, like every comparison in this module, because a bare name means nothing across frames and `___stack0` names whatever crossed the break in EVERY resume frame -- a tensor in one, an `.item()` int in the next -- so a generic mention elsewhere must not erase a real pin. `GuardFact.source` and a kept slot's name share one spelling, the `GuardFilterEntry.name` with local scope stripped. The KNOWN GAPs are a constant inside a container argument, guarded on a subscripted source like `dims[0]` and therefore not counted, and the unspecialized int whose variant carries only a `TYPE_MATCH` on the name: if the trace then specializes the symbol, the `L['scale'] == 3` check is a `SHAPE_ENV` fact with an empty source, so the variant looks generic and cancels a sibling's pin that nothing serves. `test_wont_generalize_cancels_pins_only_within_a_frame` pins the predicate on both kinds of source, the in-frame cancellation, the cross-frame `___stack0` case, that a frame pinning `scale` in its only variant stays reported when the entry frame cancels its own `scale` pin, that a variant whose value guard was dropped cancels its sibling's pin, that a variant holding `EQUALS_MATCH` and `SEQUENCE_LENGTH` on one source keeps its pin (removing the per-variant `- here` subtraction fails it), that a pin with no kept slot is not reported, the empty source and both iterator types, and that every value-equality type is in the never-dropped shape-bearing set.

## Examples

```python
from torch._dynamo.precompile_package import _pins_a_value, _wont_generalize

_pins_a_value("EQUALS_MATCH", "scale")        # True
_pins_a_value("CONSTANT_MATCH", "___stack0")  # True: a value that crossed a graph break
_pins_a_value("CONSTANT_SUBCLASS_MATCH", "n") # True: an int-subclass argument
_pins_a_value("CONSTANT_MATCH", "self.eps")   # False: reached through self
_pins_a_value("EQUALS_MATCH", "dims[0]")      # False: subscripted (the known gap)
_pins_a_value("TENSOR_MATCH", "x")            # False: not a value-equality guard
_pins_a_value("EQUALS_MATCH", "")             # False: a guard checked against no source

kept = {("EQUALS_MATCH", "scale"), ("EQUALS_MATCH", "mode"), ("CONSTANT_MATCH", "___stack0")}
# entry frame: one variant pins scale and mode, another guards scale by TYPE_MATCH only;
# one resume frame has ___stack0 as a tensor, another has it as the .item() int
_wont_generalize(kept, guard_sets)            # ("___stack0", "mode"): scale is served generically
                                              # by the entry's second variant; the tensor ___stack0
                                              # in a different frame does not cancel the int one
```

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_wont_generalize_cancels_pins_only_within_a_frame
lintrunner torch/_dynamo/precompile_package.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 31e7603 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197974
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…er (#197273) (#197975)

**Summary.** `_varying_guard_slots(guard_sets)` finds the guard slots that actually discriminate between the captured variants of a frame, which is what licenses a policy to leave every other slot out of the serialized copy. A slot is `(guard_type, source)`, the source as `GuardFact.source` spells it (the `GuardFilterEntry.name` with local scope stripped, `L['x']` -> `x`), and it varies in two cases: two variants of one frame recorded DIFFERENT facts for it, or it is present in some variants and absent in others, because a guard only one variant carries is what tells that variant apart and comparing values alone would call it invariant and drop it; the present-in-some case is the majority of what is kept, not an edge. A fact is the guard's rendered code and value; `GuardFact.enforced` says whether the serialized copy keeps the guard, not what it checks, so it is deliberately not part of the comparison. One variant can hold several facts on one slot (Dynamo installs a `HASATTR` per attribute name on the parent source, and `DICT_CONTAINS`/`SET_CONTAINS` a guard per key on the container), so the comparison is between each variant's set of facts for the slot, never between two facts inside one variant. Guards from different frames are never compared, since an entry frame guards its arguments while a resume frame guards whatever crossed the break, so the loop runs per frame key. `_summarize` assembles a `PrecompileSummary` from a `_DynamoCacheEntry` (frame, resume-function, guarded-code and backend-graph counts, and the bypassed and uncovered code names, one bare `co_name` per frame: uncovered is the frame that entered Dynamo, holds no guarded code and was not bypassed (`install()` `skip_code()`s a superset, every entry that is not bypassed and has no guarded codes whether or not it entered Dynamo, so a generated-but-never-executed resume entry is skipped there but is not a gap here), so a repeated `forward` is two frames and both lists are subsets of the frame count by construction; `backend_graphs` counts the backend ids of the entries that are not bypassed, the ones `install()` loads, because a save-time bypass in `PrecompileCacheEntry.from_cache_entry` marks the entry and leaves its ids in place) plus the dropped, kept, policy-dropped and risky slot sets, the truncated frame names (the compile path records those as `co_name (filename:firstlineno)`, once per code object, so that set cannot merge two frames), the capture errors, and the rendered check for each dropped slot that has one (`dropped_code`, one rendering per slot, the caller's pick among the variants that dropped it, which is what `PrecompileSummary.dropped_guard_code` documents; a slot without one gets no entry), computing `wont_generalize` on the way. Its slot-set parameters are keyword-only: four of them share one type, and a transposed `dropped`/`kept` pair would swap what the report calls dropped and kept with nothing to catch it (`PrecompileSummary` states its slot relations and checks none of them: the slots aggregate every frame and a slot names no frame, so a slot one frame's filter rejected and another frame's policy dropped is legitimately in both sets; the `dropped_guard_code` union is `dropped | policy_dropped`, which lists such a slot once, and does not name `risky` because a risky slot is a dropped slot). Both are private, like every other helper in the module that is not a filter a caller passes to CompilePackage; the session that consumes them is a later stack.

## Two variants of one frame

```python
from torch.compiler._precompile_types import GuardFact
from torch._dynamo.precompile_package import _varying_guard_slots

x_f32 = GuardFact("TENSOR_MATCH", "x", (), "dtype=torch.float32, size=[4, 8]", True)
x_f16 = GuardFact("TENSOR_MATCH", "x", (), "dtype=torch.float16, size=[4, 8]", True)
flag  = GuardFact("CONSTANT_MATCH", "flag", ("L['flag'] == True",), "", True)
fn_id = GuardFact("ID_MATCH", "G['fn']", (), "is @m.py:3#abc mod.fn", False)
has_w = GuardFact("HASATTR", "mod", ("hasattr(L['mod'], 'weight')",), "", True)
has_b = GuardFact("HASATTR", "mod", ("hasattr(L['mod'], 'bias')",), "", True)

guard_sets = {("forward", "m.py", 12): [frozenset({x_f32, fn_id, has_w, has_b}), frozenset({x_f16, flag, fn_id, has_w, has_b})]}
_varying_guard_slots(guard_sets)
# frozenset({("TENSOR_MATCH", "x"),      # different facts in the two variants
#            ("CONSTANT_MATCH", "flag")})  # present in only one variant
# ("ID_MATCH", "G['fn']") is NOT varying: identical in both, so a policy may drop it
# ("HASATTR", "mod") is NOT varying either: two facts on one slot, the same set in both variants
```

Test Plan:

```
python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_varying_guard_slots_are_the_differing_and_present_in_some_ones
python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_summarize_reads_the_frame_lists_off_the_entry
lintrunner torch/_dynamo/precompile_package.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 1150b36 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197975
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…e runs under (#197274) (#197976)

**Summary.** A multi-graph capture needs three configuration changes for as long as one of the caller's calls runs, and `_capture_config(training)` is the context manager that applies them. It patches `torch._functorch.config` with `bundled_autograd_cache=True`, so backends serialize into the artifact rather than the process-local inductor cache, and `bypass_autograd_cache_key=True`, because `AOTAutogradCache` refuses to KEY a graph that calls anything outside its allowlist and a refusal means it never saves, leaving the capture with nothing to serialize; a precompile artifact is addressed by backend id and pinned to one torch build, so a nonce key is fine, as `torch._dynamo.aot_compile` already does. With `training=True` it also sets `force_non_lazy_backward_lowering`, since AOTAutograd otherwise defers the backward to the first `.backward()` and a training capture that never makes one would record no backend. Under `torch._dynamo.config.strict_precompile` it sets `strict_autograd_cache` too: `AOTAutogradCache.try_load` honours `strict_precompile`, but the save side only checks `strict_autograd_cache`, so without it a bundled entry that fails to pickle is dropped with a warning and the capture is short one backend, which only surfaces as a missing backend when the artifact is written. It patches `torch._dynamo.config.allow_empty_graphs=True` so an empty graph still counts as a compiled frame whose guards reach the artifact; the docstring records that this also extends the lifetime of objects the frame holds (see `ReproTests.test_weakref_callback`). Entering with `torch.compiler.config.force_disable_caches` set raises `PackageError` up front: compiled backends reach the artifact through the AOTAutograd cache path, which that setting turns off, so the capture would record no graphs and only fail at write time, as missing backends. This mirrors the check `torch.compile(...).aot_compile` already makes.

## Nesting

`ConfigModule.patch` is re-entrant and per-thread (each patch keeps its saved values on a `ContextVar` stack), so every scope simply patches and restores for itself: nested scopes unwind in order, an inner `training=True` lowers the backward while it is open even inside a `training=False` scope, and a worker thread entering the scope patches only itself.

```python
from torch._dynamo.precompile_package import _capture_config

with _capture_config(training=False):        # patches applied
    with _capture_config(training=True):     # force_non_lazy_backward_lowering on
        ...
    ...                                      # back to the outer scope's values
# everything restored, even if the body raised
```

Test Plan:

```
python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_capture_config_is_scoped_per_entry_and_per_thread TestPrecompilePackage.test_capture_config_refuses_disabled_caches_and_honours_strict
lintrunner torch/_dynamo/precompile_package.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 743d735 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197976
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…h allow_empty_graphs (#197275) (#197977)

**Summary.** `_AllowEmptyGraphsConvertFrame` is the `ConvertFrame` subclass a precompile capture will install beneath the `CatchErrorsWrapper` that `torch._dynamo.optimize` builds: it wraps every frame compilation in an `allow_empty_graphs=True` patch and reverts it afterwards. The reason is coverage: an uncovered no-op branch must become a guarded variant rather than Dynamo's ordinary eager-only `SkipFrame`, whose skip applies to the code object, so one fallback call permanently skips that frame and no later call can capture its other variants. `_capture_config` patches the same flag for the duration of the caller's calls, and the converter patches it again so the package's frames get it whenever this converter compiles them, including recompiles of a loaded artifact, which run outside any capture-config scope. It sits beneath `CatchErrorsWrapper` rather than replacing it for two reasons: the wrapper's skipfile, `config.disable` and namedtuple checks reject most intercepted frames before any compile, and patching there would make each of them pay a patch and a revert (and two config-hash invalidations) for nothing; and `log_dynamo_start` builds the `dynamo_start` user stack that tlparse shows by cutting at the first `convert_frame.py` frame, so a subclass frame outside the wrapper would survive as a bogus leaf, while a frame beneath it is cut. The converter passes `skip + 1` down so the traceback arithmetic accounts for its own frame. A frame under `DistributedDataParallel` with `optimize_ddp="ddp_optimizer"` reaches the converter through `CatchErrorsWrapper`'s `_clone_with_backend` hook, which the next commit in this stack overrides; the docstring says so. `_ALLOW_EMPTY_GRAPHS` is built once with `torch._dynamo.config._make_closure_patcher`, because `config.patch()` allocates a class and a `ContextVar` on every call and this runs on every frame Dynamo compiles for a package. The `OptimizeContext` wiring that installs the converter belongs to the capture session and is not part of this stack; nothing constructs the class here except its tests, which install it beneath the wrapper exactly that way and check end to end that a function whose first call traces an empty graph still gets its later variant compiled (a plain `ConvertFrame` compiles nothing after the no-op call) and that the flag is back off afterwards; and that the `finally` revert runs when the wrapped compile raises, with the flag on and `skip` incremented by one for the inner call, so the process-wide `ContextVar` behind `allow_empty_graphs` does not leak and the traceback arithmetic accounts for the converter's frame.

## Shape of the converter

```python
class _AllowEmptyGraphsConvertFrame(ConvertFrame):
    def __call__(self, frame, cache_entry, hooks, frame_state, skip=0):
        revert = _ALLOW_EMPTY_GRAPHS()        # allow_empty_graphs=True for this frame
        try:
            return super().__call__(frame, cache_entry, hooks, frame_state, skip=skip + 1)
        finally:
            revert()

# how a session will use it, replacing the converter torch._dynamo.optimize built:
# optimize_ctx.callback._torchdynamo_orig_backend = _AllowEmptyGraphsConvertFrame(
#     backend, optimize_ctx.callback.hooks, package=package, recompile_limit=recompile_limit
# )
```

Test Plan:

```
python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_allow_empty_graphs_convert_frame_keeps_a_no_op_frame_compilable
python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_allow_empty_graphs_convert_frame_reverts_the_flag_when_the_compile_raises
lintrunner torch/_dynamo/precompile_package.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 5574388 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197977
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…onverter is asked to clone (#197721) (#197978)

**Summary.** DDP plus a package is not supported, and the converter refuses it by name: `_clone_with_backend` is the hook `CatchErrorsWrapper` calls only for a frame under an active `DistributedDataParallel` module in `optimize_ddp="ddp_optimizer"` mode (the default, `optimize_ddp=True`), and when a package is attached the converter's override returns a callable that raises `PackageError` in place of the clone, naming `torch._dynamo.config.optimize_ddp`, the `"no_optimization"` setting that does work, and the `"python_reducer"` and `"python_reducer_without_compiled_forward"` modes, which bypass DDPOptimizer as well (`CatchErrorsWrapper` takes its DDPOptimizer branch only when `get_optimize_ddp_mode()` is `"ddp_optimizer"`). The raise sits in the returned callable rather than the property getter because `CatchErrorsWrapper` first reads the attribute through `hasattr` as a capability probe and only then calls it; `hasattr` swallows only `AttributeError`, so a getter that raised would raise `PackageError` out of the probe itself, before the wrapper reaches the call it means to make (its own `AssertionError` is reachable only for converters that lack the attribute, which this subclass never does). Without a package the override returns a clone of the same subclass built with the same hooks and recompile limit, so the flag survives a DDP clone the way it survives an ordinary compile; the base clone would have rebuilt a plain `ConvertFrame` and silently dropped the patch, and there is no artifact to protect, so refusing would describe an id the object never records. A package-less converter is what the tests build, and what a capture session may build before it attaches a package. Refusing is the only honest answer: DDPOptimizer splits the Dynamo graph into per-bucket submodules and compiles each one separately, `propagate_metadata` copies only `meta` and `_param_name_to_source` onto them, so no bucket carries the `_backend_id` the outer graph was given and the package's `backend_ids` names an id under which no AOTAutograd artifact is ever recorded; the base `ConvertFrame` clone, which silently drops the package, would have turned that into an uncovered frame, and the previous round's package-preserving clone would have turned it into a save-time `Backend ... is not found` error that never mentions DDP. Construction is not the place for the check, because `optimize_ddp` is `True` by default and the branch also needs an active DDP module, which exists only inside a DDP forward. The other site that rebuilds a plain `ConvertFrame`, `eval_frame._create_wrapped_callback` behind the process-wide `set_stance(backend=...)` and the `eager_then_compile` stances, is deliberately left alone: a stance replaces the whole callback with an unpackaged one and is outside what a capture session promises. The base `ConvertFrame._clone_with_backend`, which the `caching_precompile` callback (`eval_frame._optimize`) still takes under DDP and which drops its package the same silent way, is base code this stack does not touch and is deferred. The DDP rationale lives in a comment on the override; the class docstring keeps two sentences pointing at it. Nothing constructs `_AllowEmptyGraphsConvertFrame` here except its tests, which take the wrapper down its DDPOptimizer branch with a stub active DDP module and check that a converter holding a package still answers the wrapper's `hasattr` probe and refuses the frame with a `PackageError` naming the `DistributedDataParallel` forward and the `optimize_ddp="no_optimization"` remedy under both `True` and `"ddp_optimizer"` while `"no_optimization"` compiles it normally, and that a package-less converter built from a fresh `CompileCounter` and `Hooks` clones to the same subclass with the same hooks and recompile limit.

## Shape of the override

```python
class _AllowEmptyGraphsConvertFrame(ConvertFrame):
    def _clone_with_backend(self):            # property; asked for only by CatchErrorsWrapper's DDPOptimizer branch
        if self._inner_convert._package is None:   # no artifact to protect: keep the subclass
            return lambda backend: type(self)(backend, self._hooks, recompile_limit=self._recompile_limit)
        def refuse(backend) -> NoReturn:
            raise PackageError(f"Cannot precompile a DistributedDataParallel forward with torch._dynamo.config.optimize_ddp={...!r}: ... Set torch._dynamo.config.optimize_ddp=\"no_optimization\" ...; the \"python_reducer\" ... modes bypass DDPOptimizer as well")
        return refuse
```

Test Plan:

```
python test/dynamo/test_precompile_package.py TestPrecompilePackage.test_allow_empty_graphs_convert_frame_refuses_a_ddp_optimizer_frame
lintrunner torch/_dynamo/precompile_package.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 71397e1 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197978
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
#197276) (#197979)

**Summary.** When a computation needs to guard on a dim the caller marked with `mark_unbacked`, `_capture` catches make_fx's `GuardOnDataDependentSymNode` and raises a `PrecompileError` explaining that an unbacked dim cannot be guarded and how to restructure. That message was built inline inside `_capture`, and the dynamo tracer that later commits add hits the same condition through Dynamo, so the construction moves into `_unbacked_guard_error(e)` and `_capture` raises what it returns. The text is unchanged; the one behavioural difference is that an exception with an empty message no longer trips `str(e).splitlines()[0]` on an empty list, since the helper takes `(str(e).splitlines() or [""])[0]`. The existing unbacked tests in `test/test_precompile.py` cover the path.

## Before and after

```python
# parent, inside _capture:
except GuardOnDataDependentSymNode as e:
    raise PrecompileError(
        "precompile: fn needs to guard on a dim marked with mark_unbacked ..."
        f"{str(e).splitlines()[0]}"
    ) from e

# now:
except GuardOnDataDependentSymNode as e:
    raise _unbacked_guard_error(e) from e

_unbacked_guard_error(RuntimeError("")).args[0].endswith("Underlying: ")   # True: no IndexError on an empty message
```

Test Plan:

```
python test/test_precompile.py -k unbacked -k guard_required
lintrunner torch/_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]>

Reverted in 2b8b6df as a dependent of #197262 and back in the stack unchanged.
Pull Request resolved: #197979
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
…97980)

**Summary.** `load` recovers the calling convention of an artifact by parsing `python_code` with `ast` and reading the top-level `NAME = <literal>` assignments, and until now it required one fixed set of names: the make_fx driver's `PARAM_NAMES`, `OUT_SPEC`, `USER_INPUT_SHAPES` and so on. A dynamo-tracer artifact carries a different set, because its multi-graph driver rehydrates frames from opaque blobs rather than reading a parameter list, so the required set is now chosen by the `TRACER` literal: absent (every artifact written before this) or anything but `"dynamo"` keeps the make_fx set unchanged, while `"dynamo"` requires `BACKEND`, `FN_NAME`, `FRAMES`, `DROPPED_GUARDS`, `RISKY_DROPPED_GUARDS`, `WONT_GENERALIZE`, `_FRAMES`, `_BACKENDS`, `_ENTRY_BINDING` and the two versions that lock the blobs to the build that wrote them, `_DYNAMO_PYTHON_VERSION` for the marshalled bytecode and `TORCH_VERSION` for the pickled guard state (the multi-graph driver refuses to unpickle it under another torch build; a make_fx artifact inlines neither, so it needs no such lock), and a `SERVING_MODE == "installed"` artifact swaps `_FRAMES`/`_BACKENDS` for `_PACKAGE` and `UNREACHABLE_WITHOUT_INSTALL`. The parser collects the top-level assignments in one pass, last assignment winning as it would under `exec`, so the literal that selects the required set and the value reported for it are the same assignment. A consumed name whose value is not a Python literal, `TRACER` and `SERVING_MODE` included, raises `PrecompileError` naming the constant instead of a raw `ValueError` (or, for a set or dict literal with an unhashable member, `TypeError`) out of `ast.literal_eval`; an unconsumed top-level assignment is still skipped with a debug log. Four names are parsed when present but never required, so an auditor gets them back as data and older artifacts load unchanged: `TRACER` and `SERVING_MODE`, which select the required set and so would check nothing as members of it (`SERVING_MODE` defaults to `"standalone"` in the result), and the guard-audit sections `POLICY_DROPPED_GUARDS` and `DROPPED_GUARD_CODE`. The emitter of the dynamo set lives further up the stack; this commit lands the reader first so those artifacts load the moment they are produced.

## Before and after

```python
from torch._precompile import _parse_artifact_metadata

_parse_artifact_metadata('TRACER = "dynamo"\nBACKEND = "eager"\n')
# parent: PrecompileError: python_code is missing calling-convention metadata ['BUFFER_NAMES', ...]
#         (the make_fx names were always required)
# now:    PrecompileError: python_code is missing calling-convention metadata
#         ['DROPPED_GUARDS', 'FN_NAME', 'FRAMES', 'RISKY_DROPPED_GUARDS', ...]  -- the dynamo set

_parse_artifact_metadata("BACKEND = object()\n...")
# parent: ValueError: malformed node or string ...   (out of ast.literal_eval)
# now:    PrecompileError: python_code 'BACKEND' calling-convention metadata is malformed; it must be a Python literal.

meta = _parse_artifact_metadata(make_fx_python_code)
meta["SERVING_MODE"]     # "standalone": filled in for artifacts that predate the field
```

`test_parse_artifact_metadata_required_set_follows_tracer` pins the three required sets from hand-written sources (make_fx both with `TRACER` absent and with `TRACER = 'other'`), and `test_parse_artifact_metadata_literals` parses a complete standalone and a complete installed dynamo source and covers the optional sections, the `SERVING_MODE` default, last-assignment-wins and the malformed-literal error on both a call and an unhashable set member. The existing load tests (`test_load_invalid_python_code_rejected`, `test_missing_calling_convention_metadata_rejected`, the export/reload round trips) keep passing.

Test Plan:

```
python test/test_precompile.py -k parse_artifact_metadata
python test/test_precompile.py
lintrunner torch/_precompile.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]>

Reverted in bc6503f as a dependent of #197262 and back in the stack unchanged.
Pull Request resolved: #197980
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979
pytorchmergebot pushed a commit that referenced this pull request Sep 21, 2026
) (#197981)

**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]>

Reverted in 70f4f9b as a dependent of #197262 and back in the stack unchanged.
Pull Request resolved: #197981
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…pes (#197982)

**Summary.** These are the three public-facing types of the caller-driven precompile API that later commits build on, added here as plain classes in `torch/_precompile.py` with no public export yet. `MakeFxTracer` is a frozen dataclass holding the one make_fx-specific knob, `decompositions`, and is what a caller will pass as `tracer=` to select the single-trace front-end. `PrecompiledRunnable` is the base type `load` will return: a callable with the captured `fn`'s calling convention that can also be entered as a context manager and unloaded, with `installed = False` and no-op `__enter__`/`__exit__`/`unload` for a standalone artifact. `Capture` is the base type the capture entry point will return, whose three methods all raise `NotImplementedError` until a concrete capture fills them in. `PrecompiledModule`, the existing make_fx runnable, now subclasses `PrecompiledRunnable` and forwards keyword arguments from `__call__` to the loaded forward; the make_fx drivers take positional arguments only, so a keyword argument fails there with the usual `TypeError` at the call, and the multi-graph driver will bind them. The three types keep their truthful `__module__` (`torch._precompile`) here: nothing exports them yet, and the commit that makes `torch.compiler.precompile` a module re-homes `MakeFxTracer` and `Capture` under it together with the other re-exports. `MakeFxTracer` has no consumer yet either: the callable API's string `tracer=` and its separate `decompositions=` parameter are retired together with that API later in this stack, where `tracer=MakeFxTracer(...)` takes over. The new `Self` annotation import lives in the `TYPE_CHECKING` block, next to the `Callable`/`Mapping` one the module already had.

```python
@dataclasses.dataclass(frozen=True)
class MakeFxTracer:
    decompositions: dict | None = None      # forwarded to make_fx as decomposition_table

class PrecompiledRunnable:
    installed: bool = False                  # True for the installing shape, added later
    def __call__(self, *args, **kwargs): raise NotImplementedError
    def __enter__(self): return self
    def __exit__(self, *exc): self.unload()
    def unload(self) -> None: ...            # no-op: a standalone artifact installed nothing

class Capture:
    def __enter__(self): raise NotImplementedError
    def __exit__(self, *exc): raise NotImplementedError
    def __call__(self, *args, **kwargs): raise NotImplementedError

class PrecompiledModule(PrecompiledRunnable):          # was: class PrecompiledModule:
    def __call__(self, *args, **kwargs):
        ...
        return self._loaded_forward(*args, **kwargs)   # was: (*args)
```

```python
f = PrecompiledModule._from_loaded(forward, backend="eager")   # what load() builds
isinstance(f, PrecompiledRunnable)   # True now
with f:                              # enters and exits as a no-op
    f(model, x)
```

`test_precompiled_module_is_a_standalone_runnable` pins the reparenting: `isinstance`, `installed == False`, the no-op `with`/`unload`, keyword forwarding, and the not-runnable refusal of a bare `PrecompiledModule`.

Test Plan:

```
python test/test_precompile.py -k test_precompiled_module_is_a_standalone_runnable
python test/test_precompile.py
lintrunner torch/_precompile.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: #197982
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
… optional (#197983)

**Summary.** `_make_inlined_forward(python_code)` is the no-cache path of `load`: it `exec`s the self-contained artifact and hands back its `forward`, logging a warning first because `python_code` is untrusted executable input. It gains a keyword-only `warn=True`. Every `load` keeps warning exactly as before; the one caller that will pass `warn=False` is the capture itself, which in the caller-driven design renders the artifact in-process and immediately self-loads it to run the caller's call -- that source was just produced by this process, is not untrusted input, and warning on every capture would drown the real warning. The comment above the warning says the same: a load is never silent, only the capture-time self-load passes `warn=False`. The `options` dict handed to `compile_to_python` is annotated `dict[str, object]` instead of `dict[str, Any]`; no runtime change. The existing export/reload tests in `test/test_precompile.py` cover the warning path, which is unchanged for them, and `test_inlined_forward_warns_unless_told_not_to` pins both settings directly: one warning per `_make_inlined_forward(code)` and none for `warn=False`.

## Before and after

```python
_make_inlined_forward(python_code)              # parent and now: warns
# WARNING torch.compiler.precompile.load is about to EXEC python_code, which is untrusted
# executable input (it runs inlined kernels / graph code). Only exec python_code you produced
# or otherwise trust (Note [precompile programming model], invariant 7).

_make_inlined_forward(python_code, warn=False)  # new: silent, for the capture-time self-load only
```

Test Plan:

```
python test/test_precompile.py -k test_inlined_forward_warns_unless_told_not_to
python test/test_precompile.py
lintrunner torch/_precompile.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: #197983
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…frame (#197984)

**Summary.** A capture with graph breaks or several guarded variants is not one graph, so its artifact cannot inline a single `call`; it has to carry every frame Dynamo compiled and dispatch among them. `_multigraph_frames(entry)` turns a `_DynamoCacheEntry` into the list of plain dicts the driver rebuilds from, one per code: `is_entry` for `codes[0]`, which is where `CompilePackage` records the captured callable and reads it back from (`main, *codes`), so no name heuristic is involved and neither a bypassed entry nor a same-named submodule frame can move it; `bypassed`, the code's flag; the serialized `code`; its `python_module`; the `import_sources` aliases its bytecode reads; the `resume_names` a continuation is bound under; and one `variants` record per guarded code holding `guards_state` and `dynamo_code`. A bypassed code keeps its record, flagged and without variants, the way `install()` keeps its global binding but none of its guarded codes: the frame ahead of a bypassed continuation still does `LOAD_GLOBAL` on its resume name, so dropping the record would leave a dangling global, and a bypassed code's guarded codes are dead (they name a backend that was missing at save time). `_MULTIGRAPH_GENERATED_HEADER` is the banner of that artifact and `_SERVING_NOTES` the two paragraphs, keyed by serving mode, that say what loading the artifact does to the process (a standalone artifact mutates nothing and refuses uncovered calls; an installed one mutates code objects and compiles fresh on a miss). `_b64` is the base64-of-pickle encoding the opaque sections use. Nothing renders these yet; the source builder that does is part of the capture session. `test_multigraph_frames_record_every_dynamo_frame` in `test/test_precompile.py` builds a real `_DynamoCacheEntry` (bypassed entry, same-named helper, healthy and bypassed continuations) and checks the records.

```python
_multigraph_frames(entry)
```

Test Plan:

```
python test/test_precompile.py -k test_multigraph_frames_record_every_dynamo_frame
lintrunner torch/_precompile.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: #197984
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…dispatch (#197985)

**Summary.** A standalone multi-graph artifact dispatches explicitly: the caller invokes the entry frame, and a continuation is reached only because the frame ahead of it does `LOAD_GLOBAL` on the resume name capture minted. A frame Dynamo compiled that is entered by an ordinary Python call -- an inner `nn.Module.__call__` wrapper, an un-inlinable helper -- is reachable only through the frame evaluator, which a source artifact does not use, so it would run eager when served. `_reachable_frames(frames)` computes the set that IS reachable as a worklist fixpoint: start from the entry, and each time a frame becomes reachable add the `co_names` of its variant bytecode (recursing into nested code constants) to the names seen, then admit every frame one of whose `resume_names` is among them. Each frame's bytecode is walked once. Asking merely whether a frame carries a resume name is not the same question, because a continuation whose parent is itself unreachable is just as dead, and counting it as covered under-reports how much of the artifact will run eager. `_serving_mode(frames)` reduces that to the artifact's mode: `"standalone"` when the reachable frames are exactly the frames with variants, `"installed"` otherwise. Either mismatch defeats a source artifact: an unreachable frame with variants would silently give up its compiled variant and run eager, and a reachable frame WITHOUT variants -- a bypassed continuation -- would raise on the very path capture exercised, since a standalone artifact has no compiler behind it. Installing has one, so such captures are served that way. `test_reachable_frames_follow_resume_names` in `test/test_precompile.py` covers the multi-hop chain (one hop through a nested code object), the unreachable helper, a continuation named only by that helper, an unreferenced resume name, and the bypassed-continuation case.

```python
frames = [entry, cont_a, cont_b, helper]

_reachable_frames(frames)   # {0, 1, 2}
_serving_mode(frames)       # "installed": helper has variants but is unreachable
_serving_mode(frames[:3])   # "standalone"
_serving_mode([entry, bypassed_cont_a, cont_b])   # "installed": reachable, but nothing to serve
```

Test Plan:

```
python test/test_precompile.py -k test_reachable_frames_follow_resume_names
lintrunner torch/_precompile.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: #197985
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
… and name the cause (#197986)

**Summary.** The multi-graph driver rebuilds the entry function from its code object, and a code object carries no closure: a closure entry cannot be built at all. That is a capture-time fact, so `_reject_uninstallable_entry(frames, entry)` refuses it at capture rather than at load on the serving machine. (Defaults, which a code object does not carry either, are recorded into the artifact by a later commit rather than refused.) It also handles the entry with no dispatchable graph, which has two very different causes that call for different advice. If Dynamo BYPASSED the entry frame -- its guards could not be serialized, or a backend artifact was missing when the package was saved -- the frame record carries the `bypassed` flag `_multigraph_frames` copied from the code, and the error says so and points at where Dynamo logged the reason (the package-bypass warning; the `precompile_cache_bypass` / `dynamo_cache_bypass` artifacts under tlparse), because the thin-wrapper advice would then send the caller restructuring code that was never the problem. If the entry compiled but produced no guarded code, the caller handed precompile a thin wrapper -- an `nn.Module`, or a forward that immediately delegates -- so Dynamo compiled the wrapper's inner frame instead, and the error says to capture the function that calls the model. Only the ENTRY record is consulted, so a bypassed helper or continuation beside a healthy entry refuses nothing, and a capture with no frames at all says nothing rather than guess. `test_no_dispatchable_graph_names_the_cause` in `test/test_precompile.py` builds real `_DynamoCacheEntry` / `_DynamoCodeCacheEntry` values and feeds them through `_multigraph_frames`, so it exercises the records the function actually receives; it walks the bypassed entry, the thin wrapper beside a bypassed helper, the healthy entry beside a bypassed continuation, the empty capture and the closure entry.

## The diagnostics

```python
_reject_uninstallable_entry(_multigraph_frames(entry_whose_codes0_is_bypassed), entry)
# PrecompileError: precompile captured no dispatchable graph for 'fwd_loss_bwd': the entry
# frame was BYPASSED during capture (its guards could not be serialized, or a backend
# artifact was missing when the package was saved), so no variant of it can be served.
# Dynamo logged the reason: look for the package-bypass warning, or the
# precompile_cache_bypass / dynamo_cache_bypass artifacts under tlparse. Fix that rather
# than restructuring the captured callable.

_reject_uninstallable_entry([{"is_entry": True, "bypassed": False, "variants": [], ...}], entry)
# PrecompileError: ... The entry frame produced no guarded code, so the artifact would serve
# nothing. This happens when the captured callable is a thin wrapper ... Capture the function
# that CALLS the model, e.g. precompile.capture(lambda m, x: m(x), ...) and calling cap(model, x).

_reject_uninstallable_entry([healthy_entry, bypassed_continuation], entry)   # returns
_reject_uninstallable_entry([], entry)                                       # returns

_reject_uninstallable_entry([{"is_entry": True, "variants": [v], "code": code_with_freevars, ...}], entry)
# PrecompileError: precompile cannot build a self-contained artifact for 'step': it closes over
# ['scale'], and this capture has to rebuild the entry from its code object ...
```

Test Plan:

```
python test/test_precompile.py -k test_no_dispatchable_graph_names_the_cause
lintrunner torch/_precompile.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: #197986
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…7987)

**Summary.** `_build_multigraph_forward` is the driver a multi-graph artifact inlines: where the single-graph drivers call one `call`, this one rebuilds the captured ENTRY frame from its `_FRAMES` record and returns a `forward` that DISPATCHES among that frame's variants at call time. It is deliberately standalone -- nothing is installed onto the running program's code objects and no frame evaluator is involved -- so an artifact serves exactly what it captured and writes nothing into the captured module but names Dynamo minted while tracing; a call no variant's guards accept RAISES a `PrecompileError` rather than compiling, because there is no compiler behind a source artifact. That error names both ways a call can miss -- a guard on the arguments or on a module global the graph baked in no longer holds (restore the environment), or a call shape capture never exercised (add an example and recapture) -- since only the second is a coverage gap that recapturing fixes. It rebuilds one `GuardManager` per variant through `load_guards_state`/`load_guard_manager`, re-minting the `__builtins_dict___N` key Dynamo guards builtins through (the tracing process had it in its globals; a loading process never traced, and `CompilePackage.install` re-mints it the same way), wraps each variant's transformed bytecode in a `types.FunctionType` over the live globals of the module the frame was compiled in, and dispatches by rebuilding the frame's `f_locals` from the call: the arguments bound with `inspect.Signature` through `torch._dynamo.aot_compile.bind_locals`, so keyword-only parameters, `*args`, `**kwargs` and the entry's recorded defaults land under their names exactly as Python binds them. The first variant whose `manager.check(f_locals)` passes runs; the managers are checked in two passes, as `AOTCompiledModel.__call__` does, because a tag-safe root's no-tensor-aliasing fast path (`GuardManager::check_nopybind`) can refuse without running its tree and disarms itself, so only a second `check` evaluates the tree it skipped. An entry with free variables is refused (capture already refuses one, so its arrival is a malformed artifact, not something to rebuild over empty cells); that refusal and the recorded defaults are gated on the record's `is_entry` flag, so neither reaches a continuation once one is built. Those globals are the LIVE module dict, as `CompilePackage.install` has it, for the rebuilt bytecode and the guards alike: a module-level global the graph baked in as a constant is guarded by EQUALS_MATCH, which the default filter keeps, and only a live dict lets a rebinding after load fail that guard instead of passing against a stale copy, and lets a global the frame writes (side-effect replay emits `STORE_GLOBAL` into the transformed bytecode) land where the module reads it. The driver binds none of its own names there -- not the metadata constants, not `forward` -- only names Dynamo minted while tracing: that module's import aliases, re-imported; its builtins dict key; and the artifact's compiled subgraphs under their backend ids behind `torch._dynamo.disable` (every backend id is seeded into each module the driver opens, where `install` binds a code entry's own ids only; the ids are uuid-suffixed dunders, so no user name is shadowed). The standalone note in `_SERVING_NOTES` is narrowed to match: nothing is installed onto code objects and no frame evaluator is involved, and the only global state loading touches is the captured module, where those minted names are re-seeded and stay. Each is bound the way `install` binds it, `CleanupHook.disown` first so a pre-reset compile's hook cannot delete the binding once its code object is collected, and the builtins key is refused if it is already bound to anything but the module's builtins dict, as `install` refuses it. A module that does not import here -- the defining module or an alias alike -- surfaces as the documented torch-build lock `PrecompileError`, and a frame captured from a script's `__main__` is refused outright, because `importlib.import_module("__main__")` succeeds in every process and would hand the serving script's globals to the guards silently. An entry with no variant -- BYPASSED at capture, or trivial and run eager by Dynamo -- is diagnosed by cause at build rather than as a coverage gap at the call. Before any of that, `_DYNAMO_PYTHON_VERSION` is checked against the running interpreter, because `SerializedCode.to_code_object` feeds the recorded `co_*` fields to `types.CodeType` in the running interpreter's `get_code_keys()` order, so a foreign artifact either raises a bare `TypeError` on a changed field set or builds a code object whose bytecode is foreign and crashes when a variant runs, and `TORCH_VERSION` against `torch.__version__`, because `_FRAMES` carries pickled Dynamo guard state that no other build promises to unpickle and the import check cannot see a build whose modules all still import. Both names, like `_FRAMES`, `_BACKENDS` and `_ENTRY_BINDING`, are read bare: `_parse_artifact_metadata` already refuses a dynamo artifact that lacks them. Only the entry frame is rebuilt here. A graph-break continuation is reached by `LOAD_GLOBAL` on the resume name Dynamo minted, so serving one means binding its dispatcher in the module under that name, with the closure factory a continuation that closes over locals is emitted as, and a zero-variant continuation's refusal deferred to the call that reaches it; that is #197286. Nothing emits this driver into an artifact yet, so no artifact with a graph break exists in between. The function is a single `def` with nested helpers, with its `TYPE_CHECKING` placeholders; keeping it one unit is what lets the source builder emit it with one `inspect.getsource`.

## Dispatch

```python
# emitted into the artifact after the metadata and the subgraph sources
forward = _build_multigraph_forward()

forward(model, x)              # f_locals = {"model": model, "x": x, "rest": (), "scale": 2.0}
                               # (Signature.bind + the recorded defaults); the first
                               # variant whose guard manager accepts them runs
forward(model, x, scale=3.0)   # no variant matches:
# PrecompileError: precompile: no captured variant of 'step' matches this call (2 captured).
# Either a guard on the call's arguments or on a module global the graph baked in no longer
# holds (restore that environment), or this call shape was never captured: the artifact serves
# only what capture exercised, so add an example covering it and recapture.
```

```python
# on a different Python
# PrecompileError: precompile: this artifact was produced on Python 3.12 and cannot load on 3.13:
# it inlines serialized code objects whose bytecode and field layout are Python-version-locked.
# Regenerate the artifact under the serving Python.
```

Nothing emits this driver into an artifact yet; the source builder that does is part of the capture session. The test builds the records the driver reads from a real `CompilePackage` capture of a function with no graph break (two calls, the second passing a `*args` tensor: `len(rest)` is a constant in the graph, so the entry recompiles and carries two variants whose outputs differ by one, and dispatch has to pick rather than just run; a keyword-only default the call omits; a module global the entry reads), asserts `_serving_mode` calls it standalone with one frame of two variants, `exec`s the driver's source into a bare namespace with the Dynamo-minted globals scrubbed from the test module, and checks that each captured call dispatches to the variant that produced its answer, that rebinding the module global the entry reads fails its guard and refuses rather than serving the stale graph (and serves again once restored), that an uncovered call refuses, that the builtins key is minted into the captured module and a foreign binding of it is refused, and that every build-time refusal is diagnosed by its own cause: both version locks, a `__main__` frame, an unimportable module, a BYPASSED and a trivial entry, a closure entry, and a record set with no entry.

Test Plan:

```
python test/test_precompile.py -k test_multigraph_driver_dispatches_entry_frame
python test/test_precompile.py
lintrunner --take RUFF,PYFMT,FLAKE8,CODESPELL,PYREFLY 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: #197987
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985, #197986
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…eal Dynamo backend graph (#197988)

**Summary.** This is a follow-up to the `_graph_has_dynamic_shapes` fix that made the probe read `"example_value"` as well as `"val"`: it adds the end-to-end regression test that fix was missing and tightens the surrounding prose. `test_dynamo_dynamic_graph_runs_at_multiple_shapes` compiles a module with `torch.compile(dynamic=True)` through a recording backend, lowers the captured graph with `compile_to_python`, and runs the artifact at three batch sizes; on the parent of the original fix the artifact specialized to the example size and failed `assert_size_stride` at every other size. The helper's docstring and the two unit tests now say precisely which graphs carry which key: make_fx writes only `"val"`, the graph Dynamo hands a torch.compile backend carries only `"example_value"`, and Dynamo's export paths stamp `"val"` as well, so `"val"` alone does not identify a make_fx graph. The unit test also covers the union in the other direction (a symbolic `"val"` beside a static `"example_value"`).

The code change is prose only; the behaviour under test is the `_graph_has_dynamic_shapes` change in #197258 (the second commit of this stack), which is kept byte-identical because it is already approved.

## Test Plan

```
python test/functorch/test_compile_to_python.py -k dynamic_graph_runs_at_multiple_shapes
python test/functorch/test_compile_to_python.py -k graph_has_dynamic_shapes
python test/functorch/test_compile_to_python.py
```

Authored with an AI assistant (Claude Code).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Pull Request resolved: #197988
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…iver (#197989)

**Summary.** The entry-only `_build_multigraph_forward` from #197743 rebuilds and dispatches the entry frame only; this one makes it rebuild every captured frame from the `_FRAMES` records, so a capture with graph breaks serves standalone. A continuation is reached the way Dynamo emits it -- the frame ahead of it does `LOAD_GLOBAL` on the resume name Dynamo minted in the module both were compiled in (a continuation is recorded under its parent's module; under `config.nested_graph_breaks`, default False, an inlined frame's continuation is recorded under the inlined function's module while the root frame's bytecode does the `LOAD_GLOBAL`) -- so the driver now builds a dispatcher per frame and binds each continuation's dispatcher in that module under its resume names, `CleanupHook.disown` first like the other minted names. A continuation that closes over locals is bound as a FACTORY taking the closure tuple, the way Dynamo emits it and the frame ahead of it calls it, and its `f_locals` are rebuilt the way `AOTCompiledFunction.prepare_f_locals` does: the closure cells' contents first (a cell unbound at the graph break is absent, as it is from a real frame's `f_locals`), then the arguments bound through `bind_locals`, with a comprehension iterator argument that Dynamo spells `.N` in the resume code's `co_varnames` renamed back from the `implicitN` that `inspect.signature` gives it, since the guards are rooted at the bytecode name; the `inspect.Signature` is taken over a throwaway function with empty cells since a code object with free variables cannot be wrapped without them. A module is opened only for a frame with variants: a zero-variant record is dead, never imports its module, and binds its refusal only into a module a live frame already opened (an unopened module means no frame is left to name it), so a dead record naming a module the serving process cannot import neither refuses the load nor binds anything. Resume names are minted by a per-process counter (`unique_id_unbound_in`; backend ids carry a uuid4 and cannot collide), so two standalone artifacts of the same module captured in different processes can mint the same resume name and, loaded into one process, would silently overwrite each other's continuations (the entry bytecode's `LOAD_GLOBAL` cannot be renamed at load); every continuation dispatcher the driver binds under a resume name therefore carries its artifact's tag (the first 16 hex digits of the sha256 of `_FRAMES` and `_BACKENDS` together, so two artifacts emitted from one capture with different backends get different tags) in `__precompile_artifact__` -- the entry dispatcher handed back as `forward` carries nothing -- and, before anything is seeded, a pre-pass over the frames checks every resume name a frame would bind (in a module some frame with variants opens; the check imports the module and seeds nothing): the name must be unbound or hold this artifact's own dispatcher (rebuilding rebinds), otherwise the load is refused with a `PrecompileError` naming the module and the resume name and, for a holder carrying another artifact's tag, both tags and "only one standalone artifact per captured module can serve continuations in a process", or, for an untagged holder, "this process already holds it (a live compile of the same function, or a user binding); load the artifact in a fresh process". There is deliberately no same-continuation permit: a live compile of the same function holds its resume name for entry bytecode Dynamo already emitted, and rebinding it would point that `LOAD_GLOBAL` at a dispatcher that cannot recompile, so the capturing process itself is refused when it loads the artifact it just emitted, and a fresh process serves it. Because the check precedes the dispatcher loop, a refused load mutates nothing in the module; in particular a second artifact of one capture (the same backend ids, other `_BACKENDS`) cannot rebind the live artifact's subgraphs before it is refused. `_seed` itself stays the plain disown-and-overwrite of the previous commit, so the untagged values (import aliases, the builtins dict, the compiled subgraphs) overwrite as before. An artifact with no entry frame is now refused before any module is opened. A load the driver refuses for another reason partway through (a later frame's unimportable alias, a foreign builtins key) leaves the names it had already seeded in the captured module; there is no unwind, and the docstring says so. A frame with no variant -- BYPASSED at capture, or trivial and run eager by Dynamo -- is still diagnosed by cause rather than as a coverage gap, but where the entry raises at build, a continuation's refusal is deferred to the call that reaches it, since by `_serving_mode`'s contract a standalone artifact's zero-variant continuation is unreachable yet must still bind its resume names. Everything else -- the version locks, the `__main__` and import refusals, the live module dict, the builtins key re-mint, the coverage-gap `PrecompileError` -- is unchanged from the previous commit. The edits are interior to the one function, which stays a single `def` with nested helpers so the source builder can still emit it with one `inspect.getsource`.

## Dispatch

```python
# emitted into the artifact after the metadata and the subgraph sources
forward = _build_multigraph_forward()

forward(model, x)              # entry f_locals = {"model": model, "x": x, "rest": (), "scale": 2.0};
                               # the entry's bytecode reaches the continuation by LOAD_GLOBAL on
                               # __resume_at_N, bound in the captured module by this driver
forward(model, x, torch.ones(1), torch.ones(1))   # entry matches, no continuation variant does:
# PrecompileError: precompile: no captured variant of 'torch_dynamo_resume_in_step_at_N' matches
# this call (2 captured). Either a guard on the call's arguments or on a module global the graph
# baked in no longer holds (restore that environment), or this call shape was never captured: the
# artifact serves only what capture exercised, so add an example covering it and recapture.
```

Nothing emits this driver into an artifact yet; the source builder that does is part of the capture session. The test builds the records the driver reads from a real `CompilePackage` capture (two calls, so the continuation carries two variants whose outputs differ; a keyword-only default the call omits, `*args`, and a continuation closing over a cell of the entry frame), asserts `_serving_mode` calls it standalone and the continuation carries more than one variant, `exec`s the driver's source into a bare namespace that also binds `torch` to `None` (the collision the captured module's binding has to win), builds once in the capturing process before the Dynamo-minted globals are scrubbed from the test module (the live compile still holds the continuation's resume name, so the load is refused with the fresh-process message), then with those globals scrubbed checks that every captured call dispatches to the variant that produced its answer, that rebinding a module global the entry reads fails its guard and refuses rather than serving the stale graph (and serves again once restored), that an uncovered call refuses at the entry and at the continuation, that rebuilding the same artifact succeeds, that a foreign function bound under one of its resume names refuses the build, as does an artifact with the same `_FRAMES` and backend ids but other `_BACKENDS` (a second artifact of one capture, its subgraphs rotated across the ids), after which the live artifact still serves its own answer -- the refusal preceded any rebinding of the shared backend ids -- and one with other `_FRAMES` and renamed backend ids (another process's capture), each refused on the resume name it shares with the live one (the later rows scrub the live artifact first), that a zero-variant continuation, trivial or BYPASSED, is diagnosed by cause at the call that reaches it (the BYPASSED build succeeds), and that a dead record naming an unimportable module neither refuses the load nor binds anything. The build-time refusals (the version locks, `__main__`, the builtins key, a zero-variant or closure entry, no entry) stay covered by the previous commit's entry-only test, which keeps passing unchanged.

Test Plan:

```
python test/test_precompile.py -k test_multigraph_driver_dispatches_captured_frames
python test/test_precompile.py -k multigraph
python test/test_precompile.py
lintrunner --take RUFF,PYFMT,FLAKE8,CODESPELL,PYREFLY 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: #197989
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987, #197988
pytorchmergebot pushed a commit that referenced this pull request Sep 22, 2026
…197990)

**Summary.** Two small pieces complete the multi-graph artifact plumbing in `torch/_precompile.py`. `_entry_binding(fn)` records the entry's `__defaults__` and `__kwdefaults__`, which a code object does not carry; without them a defaulted parameter is absent from the served call's `f_locals` and every guard misses. Closure cells are deliberately not recorded: a closure entry is refused earlier (a rebuilt cell would be a new object Dynamo's identity guard misses anyway), and the driver refuses one that arrives regardless rather than rebuilding it over empty cells. `_emit_multigraph_driver_source()` renders `_build_multigraph_forward` into the artifact with `inspect.getsource`, the same path the other drivers use, followed by `forward = _build_multigraph_forward()` and the same `if __name__ == "__main__"` hint block the single-graph artifacts end in. `import inspect` moves to module scope, replacing the function-local import `_emit_driver_source` had. Because that section ends in a top-level assignment, `_parse_artifact_metadata` no longer describes one as hypothetical and skips `forward` without the "unrecognized assignment" debug line, which stays a signal for a malformed artifact.

## Examples

```python
def step(model, x, scale=2.0, *, mode="sum"):
    ...
_entry_binding(step)
# {"defaults": (2.0,), "kwdefaults": {"mode": "sum"}}

_emit_multigraph_driver_source()
# "\ndef _build_multigraph_forward():\n ...\n\n\nforward = _build_multigraph_forward()\n\n\nif __name__ == \"__main__\":\n ..."
```

Test Plan:

```
python test/test_precompile.py -k test_entry_binding_records_defaults -k test_emit_multigraph_driver_source_is_a_complete_section
python test/test_precompile.py
lintrunner torch/_precompile.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: #197990
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987, #197988, #197989
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1376/head branch November 26, 2026 01:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants