Skip to content

[precompile] Start torch/_dynamo/precompile_package.py with the default guard filter - #197261

Closed
bobrenjc93 wants to merge 16 commits into
gh/bobrenjc93/1217/basefrom
gh/bobrenjc93/1217/head
Closed

bobrenjc93 wants to merge 16 commits into
gh/bobrenjc93/1217/basefrom
gh/bobrenjc93/1217/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem. Precompile needs a guard filter that drops exactly the guards CheckFunctionManager.serialize_guards refuses, and applying the serializer's type set naively gets two cases wrong: a BUILTIN_MATCH the serializer accepts is dropped, and a DICT_KEYS_MATCH the pre-filter build promotes to DICT_VERSION is dropped.

Fix. Start torch/_dynamo/precompile_package.py with default_guard_filter_fn, which reads entries the way the serializer's pre-check does, keeps TYPE_MATCH and BUILTIN_MATCH whatever they derive, and ignores the DICT_KEYS_MATCH-derived DICT_VERSION.

Summary. This creates torch/_dynamo/precompile_package.py, the internal module behind the multi-graph precompile capture, and lands its first function, default_guard_filter_fn, the guard filter a capture's serialized guards are written under. It drops every guard CheckFunctionManager.serialize_guards would refuse for its type or a derived type -- the types in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES: ID_MATCH, FUNCTION_MATCH, MODULE_MATCH, NN_MODULE and CLASS_MATCH, which check the guarded object's identity, CLOSURE_MATCH, which checks a function by its __code__ id, plus DICT_VERSION and WEAKREF_ALIVE -- and keeps everything else, reading an entry the way the serializer's pre-check does, with one departure. As in the pre-check, TYPE_MATCH and BUILTIN_MATCH are kept whatever they derive, which keeps BUILTIN_MATCH, an id_match_unchecked deriving ID_MATCH that a plain derived-type check drops although the serializer accepts it and the loaded artifact still checks the builtin against the loading process's builtins. The departure is a DICT_VERSION derived by a DICT_KEYS_MATCH, which the filter ignores because the pre-filter build CheckFunctionManager.__init__ runs with save_guards=False promotes the DICT_KEYS_MATCH on torch.utils._pytree.SUPPORTED_NODES to DICT_VERSION while the save build keeps the DICT_KEYS_MATCH the serializer accepts -- a CheckFunctionManager artifact, not a property of the serializer, whose proper fix is a separate guards.py PR. Nothing under torch/ calls the filter in this stack (its production caller is the capture session in the follow-up stack), nothing in the file is public, and passing the filter does not mean the artifact serializes: the pre-check also refuses a kept TYPE_MATCH on a local-scope type, which the filter keeps on purpose so the refusal is loud.

The filter

from torch._dynamo.precompile_package import default_guard_filter_fn

default_guard_filter_fn(guard_entries)
# [keep_0, keep_1, ...]: False for an entry of a refused guard_type or deriving one;
# True otherwise, always for TYPE_MATCH and BUILTIN_MATCH, and for a DICT_KEYS_MATCH
# whose only refused derived type is DICT_VERSION

The whole rule is the loop body:

unsupported = CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES
for g in guard_entries:
    derived = g.derived_guard_types
    if g.guard_type == "DICT_KEYS_MATCH":
        derived = tuple(d for d in derived if d != "DICT_VERSION")   # the one departure
    keep.append(
        g.guard_type in ("TYPE_MATCH", "BUILTIN_MATCH")              # the pre-check's accepted-by-type pair
        or (g.guard_type not in unsupported and not any(d in unsupported for d in derived))
    )

default_guard_filter_fn names its parameter guard_entries as the guard filters in torch/compiler/__init__.py and aot_compile's default do.

The accepted-by-type pair

As in the pre-check, TYPE_MATCH and BUILTIN_MATCH are kept whatever they derive; that keeps BUILTIN_MATCH, an id_match_unchecked deriving ID_MATCH, which a plain derived-type check drops although the serializer accepts it and the loaded artifact still checks the builtin against the loading process's builtins.

The pair ("TYPE_MATCH", "BUILTIN_MATCH") is a literal in four places -- serialize_guards' pre-check, the filter, keep_builtin_guards and _pre_check_accepts -- and the comment at the filter's literal names the other three: a type added to the pre-check's tuple is not seen by the filter, and no test can detect it while the value is copied, since every control here is written on _pre_check_accepts, which drops such a guard just as the filter does; hoisting the pair to a CheckFunctionManager constant is a guards.py change outside this stack. What a test can pin is the filter's side of the pair, which the first test's TENSOR_MATCH row does.

The DICT_KEYS_MATCH exemption

# what the filter sees, from the pre-filter build (save_guards=False):
("DICT_KEYS_MATCH", "SUPPORTED_NODES", derived=("DICT_VERSION",))   # kept
# what the save build serializes for the same guard:
"DICT_KEYS_MATCH"                                                    # which the pre-check accepts

A DICT_VERSION derived by a DICT_KEYS_MATCH is ignored. That compensates for a CheckFunctionManager artifact rather than encoding a property of the serializer: the entries a filter sees carry the derived types of the build CheckFunctionManager.__init__ runs before filtering, with save_guards=False, where a DICT_KEYS_MATCH on torch.utils._pytree.SUPPORTED_NODES (which a tree_flatten in a compiled region produces) is promoted to DICT_VERSION, while the save build keeps the DICT_KEYS_MATCH the serializer accepts. The caching_precompile wrapper trips over the same artifact and drops that keys-match, with a warning naming DICT_KEYS_MATCH. The fix belongs in guards.py, where the pre-filter build would agree with the save build, and would delete the two lines of the exemption; that is a separate PR, since this stack does not edit guards.py, so the filter's docstring says what the exemption compensates for. That pair only: a DICT_KEYS_MATCH deriving any other refused type, and any other type deriving DICT_VERSION, are dropped as the serializer would refuse them.

A local-scope TYPE_MATCH is kept so the refusal is loud

Passing the filter does not mean the artifact serializes: the pre-check also refuses a kept TYPE_MATCH on a local-scope type, and the filter keeps such guards on purpose so the refusal is loud, since dropping the TYPE_MATCH on an nn.Module of a local class ships an artifact that serves a module of another class.

class LocalModule(torch.nn.Module): ...      # defined inside a function
class Other(torch.nn.Module): ...            # forward returns x - 1

_aot_compile(fn3, x, LocalModule())          # default filter: PackageError "LocalModule'> cannot be saved ... defined in local scope"
# control that drops only the pre-check-refused TYPE_MATCHes:
loaded.guard_check(x, Other())               # True
loaded(x, Other())                           # x + 1: LocalModule's graph served to a module of another class

Callers, neighbours and the module docstring

Nothing under torch/ calls default_guard_filter_fn in this stack; its production caller is the capture session in the follow-up stack, and a later test in this stack passes it as the guard_filter_fn of a torch._dynamo.optimize(..., package=...) call. test/dynamo/test_aot_compile.py keeps its own keep_builtin_guards: that file is unchanged base code pinning aot_compile's contract. The filter and that predicate differ only on a DICT_KEYS_MATCH deriving DICT_VERSION, which no call site of that one produces (none traces a tree_flatten inside the compiled region), so the divergence is contractual rather than observable there.

The module docstring says in one sentence, naming no symbol, that the rest of the module, added by the following commits of this stack, is the guard tooling reporting what the filter dropped and the configuration a capture runs under, since at this commit it holds the filter alone and a reader arriving from PrecompileSummary's docstring in the base should not find a schedule of unlanded names, and that the multi-graph Dynamo capture session driving it is a follow-up stack. It names the two neighbours a reader may confuse it with:

  • the ahead-of-time torch.compiler.precompile this repository already has, which does not call into this module;
  • torch._dynamo.config.caching_precompile, which when set wraps every guard filter and drops, with a warning, any guard of type ID_MATCH, CLOSURE_MATCH, WEAKREF_ALIVE or DICT_VERSION and any guard deriving ID_MATCH or DICT_VERSION (CheckFunctionManager.__init__), so neither the filter's accepted-by-type branch (a TYPE_MATCH or BUILTIN_MATCH deriving ID_MATCH) nor its DICT_KEYS_MATCH keep holds under it, which the filter's docstring says too.

It also says why the filter lives here rather than beside the serializer's pre-check (it is the capture's policy over that pre-check) and why it is the module's one unprefixed name (the capture session passes it as the default a caller may name). Nothing in this file is public.

Tests

The test file is new because the module is new: test/dynamo/test_precompile_package.py grows with the module through this stack, one test file per Dynamo module as test/dynamo/test_aot_compile.py is to aot_compile.py. The test module imports the module under its own name, precompile_package.

Controls. The behavioural controls are written over the entries' guard_type and derived_guard_types through _pre_check_accepts (a second implementation of the pre-check's type tests, without the _unserializable refusal of a local-scope TYPE_MATCH that the last test is for), not over the filter under test. _pre_check_accepts is keep_builtin_guards' predicate verbatim modulo the loop, a hand-written control rather than an import from another test file so that this file's controls do not depend on test_aot_compile.py's fixtures. dropping and drop_type_match read nothing else, and drop_local_type_match, the control that has to ship an artifact, also reads the type of the entry's value (t.__qualname__ != t.__name__), so it is written over production entries only.

  • test_default_guard_filter_drops_the_unserializable_types builds GuardFilterEntry values by hand (the _entry helper fills is_global as make_guard_filter_entry does, and sets orig_guard.guard_types, which that function only reads, so the entry and its guard agree) and pins that every type in UNSUPPORTED_SERIALIZATION_GUARD_TYPES is dropped, comparing the verdicts by type name, on bare entries (the builder gives most of these a derived ID_MATCH, which the derived-type rule drops too, so the verdicts are the same either way), with the eight refused names spelled out and asserted to still be in that constant so a shrunk constant cannot pass it. A second table pins the derived-type rule, the exact membership of the accepted-by-type pair and both halves of the exemption's condition, as mixed verdicts in one call, since a table of one verdict cannot tell a misordered verdict list from a right one and the base applies them positionally:
rows = [
    ("CONSTANT_MATCH", ("ID_MATCH",), False),       # a CONSTANT_MATCH on a code object runs through ID_MATCH
    ("TENSOR_MATCH", ("ID_MATCH",), False),         # match_on_id_for_tensor; the row a TENSOR_MATCH added to the pair would fail
    ("DICT_KEYS_MATCH", ("ID_MATCH",), False),      # the exemption is for DICT_VERSION only
    ("DICT_CONTAINS", ("DICT_VERSION",), False),    # and for a DICT_KEYS_MATCH only
    ("DICT_KEYS_MATCH", ("DICT_VERSION",), True),
    ("CONSTANT_MATCH", (), True),
]
  • test_default_guard_filter_keeps_what_the_serializer_accepts pins TENSOR_MATCH, a plain TYPE_MATCH and a BUILTIN_MATCH deriving ID_MATCH kept, by row (no GuardBuilder path gives a TYPE_MATCH a refused derived type -- id_match_unchecked on a TypeSource runs TYPE_MATCH on a fresh guard -- so that half of the accepted-by-type branch has no row), on a local source (the helper strips the L[...] scope as make_guard_filter_entry does; the filter reads neither name nor scope, which is what keeps the TYPE_MATCH on L['obj'] the last test's refusal needs). The DICT_KEYS_MATCH deriving DICT_VERSION is not in that table, since the pre-check refuses it and the departure is pinned where it is explained, in the first test's mixed-verdict rows.

Three tests drive the filter through a real aot_compile (the module-level _aot_compile records every verdict when passed seen=).

  • test_default_guard_filter_through_serialize_guards: a function calling a module-level helper and len has its CLOSURE_MATCH on G['_user_op'] dropped and its BUILTIN_MATCH on the builtins dict's len slot kept, with the serialized guard types asserted equal to the types of the entries the filter kept (that the refused guard is merely absent from the serialized set cannot fail on its own, since serialize_guards raises on a refused type in the guards it pickles). The deserialized function runs; rebinding _user_op leaves the loaded artifact passing its guards and serving the old graph (what the dropped guard would have noticed); swapping builtins.len afterwards fails the loaded call on that guard's len slot of the builtins dict by name, and the guard passes again once the builtin is restored.
with mock.patch.object(sys.modules[__name__], "_user_op", lambda x: x - 1):
    fn(x)                    # x       (eager follows the rebind)
    loaded.guard_check(x)    # True    (the CLOSURE_MATCH was dropped)
    loaded(x)                # x + 2   (the old graph)
with mock.patch.object(builtins, "len", lambda *args: real_len(*args)):
    loaded(x)                # RuntimeError matching ___check_obj_id(G['__builtins_dict___N']['len']
  • test_default_guard_filter_keeps_the_pytree_registry_keys_match: a tree_flatten of a dict reaches the filter as a DICT_KEYS_MATCH on SUPPORTED_NODES deriving DICT_VERSION, is kept, serializes as DICT_KEYS_MATCH, and is compared against a control artifact of the same function built under the pre-check's verdicts, whose serialized guard types differ from the kept artifact's by exactly DICT_KEYS_MATCH and whose guard count is one lower (the count as well, because a set of type names hides a second divergence in a type that still has another instance). A node registered between serialize and load is baked into both loads (guard_check passes); a node registered after load fails both artifacts -- the control on the length check of the DictGuardManager the other kept guards build, the kept artifact on that or on its keys-match, and the test pins only that both fail; the kept artifact passes again once that node is deregistered, so a failed check is not latched; and a same-count key swap (the node registered before capture deregistered, another registered) fails only the artifact that kept the keys-match.

  • test_default_guard_filter_keeps_local_type_guards_for_a_loud_refusal: a function reading an attribute of a local-scope class instance is refused with the local-scope PackageError naming that class, from serialize_guards' pre-check under the default filter and from GuardsStatePickler.reducer_override under a control that also drops TYPE_MATCH (both paths raise through the one raise_local_type_error, so the messages are identical by construction and the traceback's frame names are what pin the path); a function calling an nn.Module of a local class is refused from the pre-check naming the module class; and a control that drops only the TYPE_MATCHes the pre-check refuses -- those on a type whose qualname is not its name, guards.py's own test -- lets that module case serialize so that the loaded artifact's guard_check passes a module of another local class and its call returns the first class's result, which is what keeping the guard prevents. The control is narrowed to that type so the module's own type guard is the only candidate cause.

Test Plan:

python test/dynamo/test_precompile_package.py -k default_guard_filter
lintrunner torch/_dynamo/precompile_package.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]

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 commented Sep 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ You can merge normally! (2 Unrelated Failures), 1 Unclassified Failure

As of commit 09235e9 with merge base 26c0213 (image):

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

  • Correctness
    • default_guard_filter_fn mirrors serialize_guards' if/elif at guards.py:5127-5147, where the TYPE_MATCH/BUILTIN_MATCH branch short-circuits before the derived-type check
    • The DICT_KEYS_MATCH exemption matches the save_guards=False promotion of the SUPPORTED_NODES keys-match to DICT_VERSION at guards.py:3348-3363
    • The eight refused names the docstring lists are exactly UNSUPPORTED_SERIALIZATION_GUARD_TYPES at guards.py:5104-5113
  • Testing
    • test/dynamo/test_precompile_package.py adds five tests: two table-driven over guard_type/derived_guard_types, three driving the filter through a real aot_compile and a deserialize round-trip
    • The pytree test's register adds self.addCleanup(deregister, cls) and deregister is guarded on SUPPORTED_NODES membership, so the global registry is restored
  • Scope
    • Two new files only; no existing file is modified and nothing under torch/ calls default_guard_filter_fn yet, so the 12-line filter cannot regress a live path
    • No workflow, .github/ or CI-gate file appears in the diff, and the filter reads no external input

reason: clean
Reviewed commit: 09235e9

Inference job

🐛 Report a wrong verdict

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

  • .github/workflows/trunk.yml (gh) (this job did not run on the merge base, so DrCI cannot tell whether the failure is pre-existing)

    AI verdict: AI verdict: inconclusive

    The partition data contains zero events — no failure logs, no success baselines, and no trunk observations. Without any completed evidence to examine, it is impossible to determine whether this commit caused the trunk workflow failure or not.

    Full reasoning on HUD →

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.

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 16, 2026
This was referenced Sep 16, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #197260

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

/easycla

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #197260

pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…e-ownership lint (#197262)

**Problem.** The upcoming risky-drop lint must decide whether a module belongs to torch, the standard library or a third party by where its file lives, and Python offers no single reliable answer: stdlib and site-packages nest inside each other, Windows lists the bare prefix as a site directory, and torch can be reached through symlink farms.

**Fix.** Add three cached root finders (`_stdlib_roots`, `_install_roots`, `_torch_roots`) and the realpath-normalized `_within` prefix test they are consulted through, with an install root outranking a stdlib root. Nothing calls them yet.

**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 that ownership has to be decided by where a module's file lives rather than by its name. This commit adds the three cached root finders the decision rests on -- `_stdlib_roots`, `_install_roots` and `_torch_roots` -- plus `_norm`/`_within`, the realpath-normalized prefix test the consumers apply, and `_norm_absolute`, the gate every root candidate passes through. `_install_roots` is the load-bearing exclusion: `purelib` nests inside `stdlib` in a conda layout and inside `platstdlib` in a venv (on a `--with-platlibdir=lib64` build it is `platlib` that nests), so the two sets overlap by construction and the consumer must apply the rule `_stdlib_roots`' docstring records, a path under both is third party, an install root wins over a stdlib root. Every root candidate from every source keeps only absolute strings, because `realpath` resolves a relative path against the process cwd, and a relative venv `home` or `PYTHONHOME` leaves the interpreter's own metadata relative on an unpatched 3.12; only this module's own `__file__` is taken as read. Nothing calls these yet: the next commit is the first caller of `_norm`, the roots and `_within` are first consulted by `_classify_file` two commits up, and `_is_library_module`, the ownership verdict the lint applies, arrives three commits up.

## What the roots look like

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

pp._stdlib_roots()    # e.g. ('/usr/lib/python3.12',)
pp._install_roots()   # e.g. ('/usr/lib/python3.12/site-packages',)  -- nested under the stdlib root
pp._torch_roots()     # e.g. ('/repo/torch', '/venv/lib/python3.12/site-packages/torch') for an editable build
pp._within("/usr/lib/python3.12/site-packages/numpy/__init__.py", pp._stdlib_roots())   # True, which is why
pp._within("/usr/lib/python3.12/site-packages/numpy/__init__.py", pp._install_roots())  # True must be checked too
```

## `_stdlib_roots`

```python
roots.append(os.path.dirname(_norm(os_file)))        # only when os.__file__ is an absolute str
roots.append(getattr(sys, "_stdlib_dir", None))      # 3.11+
roots += [paths["stdlib"], paths["platstdlib"]]      # sysconfig
if sys.platform == "win32":
    roots.append(os.path.join(sys.base_prefix, "DLLs"))
return tuple(sorted(_norm_absolute(roots)))
```

The sources are the directory `os.__file__` resolves into, taken only when that path is absolute, `sys._stdlib_dir` on 3.11+, sysconfig's `stdlib`/`platstdlib`, and `<base_prefix>\DLLs` on Windows, where the stdlib's C extensions live beside `Lib` rather than under it -- `base_prefix` and not `prefix`, since a Windows venv has no `DLLs` directory of its own and reading `prefix` would leave the stdlib's C extensions under no stdlib root at all. When the stdlib is a zip the first of these is the whole archive, so a third party bundled into it is waived with the stdlib, which the docstring records. It is the directory the file RESOLVES into, not the one it was imported from: in a venv over a symlink-farm prefix (a Nix, Guix or Spack profile) `os.py` is a per-file link into the store, sysconfig and `sys._stdlib_dir` already name the farm, and every consumer normalizes the file it asks about. All three tuples are sorted, and `_stdlib_roots`' docstring makes that a contract, because `_classify_file` takes the first stdlib root a path lies under as the outermost.

## `_install_roots`

```python
roots: list[object] = [paths["purelib"], paths["platlib"]]
for name in ("getsitepackages", "getusersitepackages"):
    try:
        got = getattr(site, name)()
        roots += [got] if isinstance(got, str) else list(got)
    except Exception:
        continue  # an old-virtualenv site.py lacks it, or it cannot answer
stdlib = _stdlib_roots()
normed = _norm_absolute(roots)
above = {r for r in normed for s in stdlib if s.startswith(r + os.sep)}   # strictly under, not equal
return tuple(sorted(normed - above))
```

The roots are sysconfig's `purelib`/`platlib` plus whatever `site.getsitepackages`/`getusersitepackages` answer, minus any directory a stdlib root lies strictly under: on Windows `getsitepackages()` lists the bare prefix, which would otherwise put `Lib` and `DLLs` inside an install root and classify the whole stdlib as third-party. The `site` accessors are reached through `getattr` inside a `try` that also covers consuming their answer, because the old-virtualenv `site.py` this guards against does not define them, and a lint must not abort the capture it was asked to check.

This is the load-bearing exclusion. `purelib` is nested inside `stdlib` in a conda layout and inside `platstdlib` in a venv, and on a `--with-platlibdir=lib64` build (Fedora, RHEL, openSUSE) it is `platlib` that nests instead, since sysconfig's prefix and venv schemes hard-code `lib` in `purelib` but interpolate `platlibdir` into `platlib` and both stdlib keys; without the exclusion every pip-installed package would count as stdlib. The two sets therefore overlap by construction, and `_stdlib_roots`' docstring records the rule the consumer must apply: a path under both is third party, an install root wins over a stdlib root.

The exclusion drops only a directory a stdlib root lies strictly under; a candidate that equals a stdlib root stays an install root, so a layout that put third parties into the stdlib directory itself would read the stdlib as third party, a refused artifact rather than a silent waiver, and no scheme `sysconfig.get_paths()` returns has that shape (`posix_home` is the only one with `purelib` at `stdlib`, and it is reachable only by naming it). `test_install_roots_keep_a_directory_that_is_a_stdlib_root` fabricates the shape and pins that asymmetry: restoring the equality clause fails that test and no other.

## `_torch_roots`

```python
own_file = globals().get("__file__")
if not own_file:
    return ()                                          # frozen torch: no directory to anchor to
own = os.path.dirname(os.path.dirname(own_file))       # the torch package directory, two levels up
roots = {_norm(own)}                                   # spelling 1: resolved as a directory
resolved = _norm(own_file)
tail = os.path.join("_dynamo", "precompile_package.py")
if resolved.endswith(os.sep + os.path.normcase(tail)):
    roots.add(os.path.dirname(os.path.dirname(resolved)))   # spelling 2: two levels up from the resolved FILE
listed = _norm_absolute(getattr(sys.modules.get("torch"), "__path__", None) or ())
if roots & listed:
    roots |= listed                                    # trust torch.__path__ only once either spelling is in it
return tuple(sorted(roots))
```

The roots are the `torch` package directory this file sits under, in both of its spellings -- resolved as a directory, and two levels up from where the file itself resolves, which differ only in a per-file symlink farm. The second is taken only while the resolved file still ends in `_dynamo/<file>`, since a link that flattened the depth would make an ancestor of unrelated code a torch root and waive every dropped guard over that code, whereas skipping it only leaves the patched file under no torch root. To those are added every absolute entry of `torch.__path__`, adopted once either spelling is among them; the gate rules out a substituted `sys.modules['torch']`, not an entry a third party appended to the real one's `__path__`, and a relative entry is dropped rather than resolved, since `realpath` would place it in the process cwd and make the caller's own project read as torch-owned.

## `_norm`, `_norm_absolute` and `_within`

```python
def _norm(path):            return os.path.normcase(os.path.realpath(path))
def _norm_absolute(paths):  return {_norm(p) for p in paths if isinstance(p, str) and os.path.isabs(p)}
def _within(path, roots):   return any(path == r or path.startswith(r + os.sep) for r in roots)
```

`_norm`/`_within` do the realpath-normalized prefix test; the caller normalizes both sides. Every root candidate from every source -- `os.__file__`, `sys._stdlib_dir`, the four sysconfig paths, the `DLLs` join, both `site` accessors and the `__path__` entries -- passes through `_norm_absolute`, which keeps only absolute strings, since `realpath` resolves a relative path against the process cwd. That is not hypothetical: a venv whose `pyvenv.cfg` `home` is relative, or a relative `PYTHONHOME`, leaves `sys.base_prefix`, `sys._stdlib_dir` and every sysconfig path relative on an unpatched 3.12 (`os.__file__` alone comes out absolute, `site.abs_paths()` having re-anchored it at startup, which `-S` skips), and a relative `PYTHONUSERBASE` leaves the user site relative; resolved, such a root would sit wherever the cwd was at the first call and stay cached there, so a writer and a reader on one interpreter could classify differently.

Only this module's own `__file__` is taken as read, because it is always the path finder's spelling, absolute since bpo-43105 (3.10+): the finder that keeps a relative `__file__`, zipimport, cannot load torch, whose `torch._C` is an extension module, and a frozen torch has no `__file__` and returns early; `os` is the exception that motivates the gate on its side, being frozen since 3.11 with a `__file__` spelled from `sys._stdlib_dir`. `_norm`'s docstring says so.

## What calls these

Nothing yet. The next commit is the first caller of `_norm`, comparing code filenames in `_defined_where_read`; the roots and `_within` are first consulted by `_classify_file` two commits up, and `_is_library_module`, the ownership verdict the lint applies, arrives three commits up.

## Tests

Every test that reads the roots goes through `_clear_root_caches`, which clears the three caches on the spot and again at exit, so a test sees its own interpreter or its own patches rather than what a sibling left cached, and a patched answer outlives no test. Every fabricated root in these tests is spelled through `os.path.abspath`: `os.path.join(os.sep, ...)` is a bare leading separator, which `ntpath.isabs` stopped accepting in 3.13, so on a Windows runner `_norm_absolute` would drop the fabricated roots and six tests would fail against code behaving as designed (today's x86 Windows jobs pin 3.10 and the ARM64 job does not run `test/dynamo/`, so CI would not have said so).

- **`test_roots_locate_the_stdlib_install_and_torch_dirs`** pins the properties of the running interpreter the classifier will depend on: the three tuples are non-empty, the nesting runs one way only (sysconfig's `purelib` survives the exclusion while no stdlib root is under or equal to an install root -- a containment check both because the Windows prefix shape would pass an equality one and because the code permits the equal case on purpose, a shape no `sysconfig`/`site` layout produces), `os.__file__` is under a stdlib root, `torch.__file__`'s directory is a torch root, and `_within` treats `/a/bc` as outside `/a/b`. The pins are on sysconfig's own answers rather than on where pip happened to put a third-party package, so they hold in a Buck/PAR run too.
- **`test_install_roots_drop_a_directory_the_stdlib_sits_under`** replays the Windows prefix shape on every platform, since the containment check above can only fail on a Windows runner: with `site.getsitepackages` patched to list the parent of a stdlib root, that directory is not an install root, no stdlib root lies under one, and `purelib` still is. It lists the parent of a root rather than `sys.prefix` because that is a strict ancestor whatever the host's layout is, while `sys.prefix` is the host's shape: a `configure --prefix=/` build or a Windows embeddable unpacked at a drive root leaves it at a filesystem root, which this exclusion cannot drop, `r + os.sep` being a doubled separator no root starts with -- harmless in the code, since a root that swallows everything is one `_within` matches nothing against, but an assertion on `sys.prefix` would fail there. It replaces `getsitepackages`' answer rather than extending it for the reason the code reads it through `getattr` in a `try`: the old-virtualenv `site.py` this survives does not define it. Removing the exclusion fails this test on every layout and so does inverting it (dropping the roots that lie under a stdlib root instead); the inversion additionally fails `test_roots_locate_the_stdlib_install_and_torch_dirs` wherever `purelib` nests under a stdlib root, which a venv or conda layout does and a Debian or Fedora `dist-packages` one does not.
- **`test_install_roots_keep_a_directory_that_is_a_stdlib_root`** fabricates the equal-root shape (every stdlib source and every install source naming one directory) and pins the strict-ancestor asymmetry: the directory is both a stdlib root and an install root, and a `third_party.py` in it is within the install roots.
- **`test_install_roots_skip_a_site_accessor_that_raises`** pins the `try` with `getsitepackages` raising, after which sysconfig's `purelib` and the other accessor's answer are still roots.
- **`test_install_roots_take_only_the_strings_a_site_accessor_lists`** pins the consuming side: a non-string entry in a list is dropped rather than handed to `realpath`, and the `None` that `getusersitepackages` returns where there is no home directory (WASI) is skipped the same way as a raise.
- **`test_torch_roots_trust_torch_path_only_when_this_file_is_in_it`** exercises the trust gate with `sys.modules['torch']` replaced by a stub: a `__path__` that does not list the `torch` package directory this file sits under is ignored and the result is exactly that directory, appending it makes the stub's absolute string entries count (a `None` among them is dropped rather than handed to `realpath`, and so are `""` and a relative entry, which `realpath` would have placed in the process cwd), a `__path__` that is `None` is ignored as well, and with no `__file__` (a frozen torch) the result is empty.
- **`test_stdlib_roots_take_the_windows_dlls_dir`** replays the win32 branch with `sys.platform` patched, since nothing else reaches it off a Windows runner; it primes `sysconfig` before patching, because sysconfig's first initialization imports a `_sysconfigdata_*_{sys.platform}_*` module that does not exist for the patched platform. `sys.base_prefix` is patched to a fabricated directory in the same block, so the root is pinned to `base_prefix` and reading `sys.prefix` instead fails the test rather than passing on every interpreter CI runs, where the two coincide. `sys.prefix` itself is left alone deliberately: sysconfig re-initializes its config vars whenever `sys.prefix` moves away from the value it cached (GH-126789), and that re-init would import the `_sysconfigdata` module for the patched platform however early the test primed it.
- **`test_stdlib_roots_take_each_source_in_a_venv_layout`**: on a conda or system interpreter all four stdlib sources name the same directory, so deleting any one of them changes nothing a test on the real interpreter can see. This test patches `sysconfig.get_paths` to a venv shape (`stdlib` at the base prefix, `platstdlib` the venv's own lib directory with `purelib` nested under it) and `sys._stdlib_dir` to a third directory, so that each source is the only one naming its root and deleting any one fails the test, and it runs the nesting the exclusion exists for: `purelib` is under a stdlib root and an install root all the same. With `os.__file__` then patched to `None`, the shape of a frozen os, and `sys.platform` patched off `win32`, the result is exactly the three remaining roots in sorted order, which pins the other branch of the `os.__file__` guard and the ordering `_classify_file` reads; a relative `os.__file__` gives the same three, which pins the `isabs` half of that guard, since resolving one would make the process cwd a stdlib root and waive a local module whose name shadows a stdlib one; the platform is the one input `_stdlib_roots` reads that is not a path, and a Windows runner would add its `DLLs` root to that tuple.
- **`test_install_roots_take_purelib_and_platlib_on_a_lib64_build`**: in that venv `purelib` and `platlib` coincide, as they do in every layout where `platlibdir` is `lib`, so this test replays the system-interpreter shape where they do not (`stdlib` and `platlib` under `lib64`, `purelib` under `lib`), with every stdlib source (`os.__file__`, `sys._stdlib_dir`, sysconfig's two keys) patched onto a made-up prefix and `sys.platform` patched off `win32`: a Debian or Ubuntu python3.12 has the real `os.py` at `/usr/lib/python3.12`, the parent of a `/usr/lib` purelib, and a merged-lib host resolves `/usr/lib64` onto `/usr/lib`, so a fixture that leaves any source on the host holds only where the host happens to match it. The fabricated stdlib directory is then the only stdlib root on every runner (a Windows one would otherwise add `<base_prefix>\DLLs`, the branch `test_stdlib_roots_take_the_windows_dlls_dir` pins in the other direction), `platlib` is under it and `purelib` is not, both are install roots, and reading either key alone fails it. The same fixture has `site` list a directory that is a string prefix of the stdlib directory without being its parent (`python3` beside `python3.12`) and pins that the exclusion keeps it: `_within` already pins that `/a/bc` is outside `/a/b`, and this is the mirror-image separator in `_install_roots`.
- **`test_norm_resolves_a_symlinked_prefix_into_its_root`** builds a real symlink in a temporary directory (skipping where symlinks cannot be created) and pins the `realpath` in `_norm`: a file reached through a linked directory normalizes to a path under the resolved root, which `abspath` would not give.
- **`test_stdlib_roots_follow_a_symlink_farm_into_the_store`** pins the other shape, a real directory whose entries are links into a per-package store, which is what `python -m venv` makes of a Nix, Guix or Spack profile: venv records the unresolved `sys._base_executable` as `home`, so the child's `base_prefix`, sysconfig's `stdlib` and `sys._stdlib_dir` all stay on the farm (measured on a venv built over such a farm), while `realpath` of any file in it lands in the store, which none of those sources name; since every consumer normalizes the file it asks about, `_stdlib_roots` takes the directory `os.__file__` resolves into rather than the one it was imported from. The test patches all three sources onto the farm and asserts that the farm and the store are both roots and that the normalized `os.__file__` is within them, which fails without the resolved directory.
- **`test_torch_roots_follow_a_symlink_farm_into_the_store`** is its mirror for `_torch_roots`: a farm `torch` directory whose `_dynamo` and `nn` subdirectories are real and whose two modules are links into a store, with this module's `__file__` patched onto the farm and a stub torch whose `__path__` names it; the roots are exactly the farm and the store, and the normalized `nn/functional.py` is within them, which fails when the directory alone is resolved, since then no root names where any torch module resolves and `_classify_file` would answer False for all of torch.
- **`test_torch_roots_drop_a_link_that_flattens_this_files_depth`** is the shape that spelling must not follow: the same farm, but this module's link points at a flat `patchdir/precompile_package.py` two levels below a directory that also holds a `my_project/mymod.py`; the roots are exactly the farm, and neither `mymod.py` nor the resolved module itself is within them, where chopping two components off the resolved file unconditionally reports the shared ancestor as a torch root and `mymod.py` as torch-owned.
- **`test_roots_drop_a_relative_interpreter_path`** pins the absolute-only gate on the sources no other test touches: sysconfig's four paths, `sys._stdlib_dir`, `sys.base_prefix` (with `sys.platform` patched onto `win32` so the `DLLs` join runs) and both `site` accessors are patched to the relative shapes a relative `PYTHONHOME` and `PYTHONUSERBASE` produce, and the stdlib roots are then exactly the directory the real `os.__file__` resolves into while the install roots are empty; resolving any one of them fails the test.
- **`test_stdlib_roots_take_the_archive_a_zipped_os_comes_from`** pins the zip shape the summary describes: with `os.__file__` patched to `<archive>/os.py` over a real zip, the archive itself, a file, is a stdlib root and a `queue.py` bundled beside it is within the stdlib roots, which an `isdir` gate on that root would silently break.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_roots_locate_the_stdlib_install_and_torch_dirs -k test_norm_resolves_a_symlinked_prefix_into_its_root -k test_stdlib_roots_follow_a_symlink_farm_into_the_store -k test_torch_roots_follow_a_symlink_farm_into_the_store -k test_torch_roots_drop_a_link_that_flattens_this_files_depth -k test_roots_drop_a_relative_interpreter_path -k test_stdlib_roots_take_the_archive_a_zipped_os_comes_from -k test_stdlib_roots_take_the_windows_dlls_dir -k test_stdlib_roots_take_each_source_in_a_venv_layout -k test_install_roots_take_purelib_and_platlib_on_a_lib64_build -k test_install_roots_drop_a_directory_the_stdlib_sits_under -k test_install_roots_keep_a_directory_that_is_a_stdlib_root -k test_install_roots_skip_a_site_accessor_that_raises -k test_install_roots_take_only_the_strings_a_site_accessor_lists -k test_torch_roots_trust_torch_path_only_when_this_file_is_in_it
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]>

Pull Request resolved: #197262
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…iguration (#197263)

**Problem.** The risky-drop lint needs to recognise dropped identity guards whose value cannot resolve to a different object on the serving machine, and the simple checks (`__module__ == "builtins"`, a bare `type` test) are fooled by shims and `functools.wraps`.

**Fix.** Add `_reads_a_builtin` (a CPython-built builtin read under its own name through Dynamo's builtins dict), `_defined_where_read` (a def or class bound under its own name in the file that read it, compared by code object), `_is_dynamo_synthesized` and `_dynamo_alias_module`. Nothing calls them yet.

**Summary.** The risky-drop lint asks, for each identity guard that serialization dropped, whether the value it guarded could resolve to a different object on the serving machine, and this commit adds the small predicates that recognise bindings where that cannot happen. `_reads_a_builtin` is true for `len` or `sorted` reached the ordinary way, through the `__builtins_dict__*` global Dynamo installs, but only under the builtin's own name, only for a value `builtins` itself owns, and only for one CPython built (a builtin function or a static type carrying `Py_TPFLAGS_IMMUTABLETYPE`), because that dict is the frame's live `builtins.__dict__` and a shim can install anything into it under any name. `_defined_where_read(value, global_name, user_stack)` is true for a def, or through its own methods a class statement, bound under its own name whose code lives in the file that read it -- the one binding the inlined-source checksum of that file covers -- comparing `__qualname__` against the code object's own name and the code object's `co_filename` (never `__module__`, which `functools.wraps` copies) against the OUTERMOST frame of the guard's `user_stack`, with only absolute filenames on both sides admitted. `_is_dynamo_synthesized` recognises the `__nested_resume_fns` local every generated resume function takes and an entry read straight off it, and `_dynamo_alias_module` maps an `__import_a_dot_b` global back to the module it aliases, both leaning on prefixes this commit names individually in `torch/_dynamo/aot_compile.py` (`_IMPORT_ALIAS_PREFIX`, `_BUILTINS_DICT_PREFIX`) rather than restating the strings. Nothing calls these yet; `_module_namespaces` and `_is_risky_drop`, which do, follow once the library-module classifier is in.

## Examples

```python
import torch
from torch._dynamo import precompile_package as pp
from torch._dynamo.source import (
    AttrSource, CellContentsSource, ClosureSource, GetItemSource, GlobalSource, LocalSource, TypeSource,
)

pp._dynamo_alias_module("__import_torch_dot_nn_dot_functional")   # sys.modules["torch.nn.functional"]
pp._dynamo_alias_module("F")                                       # None: not a Dynamo alias

pp._owning_module(torch.nn.functional)   # "torch.nn.functional"  (a module names itself)
pp._owning_module(torch.nn.functional.gelu)   # "torch._C._nn": the extension module that defines gelu
pp._owning_module(3)                     # None: an int has no __module__

entry = GetItemSource(LocalSource("__nested_resume_fns"), 0)
pp._is_dynamo_synthesized(entry)                                                    # True
cell = CellContentsSource(GetItemSource(ClosureSource(entry), 0), "cell_contents")
pp._is_dynamo_synthesized(AttrSource(TypeSource(cell), "__call__"))                 # False: a value the resume function closes over
pp._is_dynamo_synthesized(GetItemSource(LocalSource("__nested_frame_values"), 0))   # False: a nested frame's stack and locals
pp._is_dynamo_synthesized(GlobalSource("__nested_resume_fns"))                      # False: a user global spelled like it
```

## The prefixes, named in `aot_compile.py`

```python
# torch/_dynamo/aot_compile.py, parent
_MINTED_GLOBAL_PREFIXES = ("__import_", "__builtins_dict__", _UNNAMED_SCOPE_PREFIX)

# now
_IMPORT_ALIAS_PREFIX = "__import_"
_BUILTINS_DICT_PREFIX = "__builtins_dict__"
_MINTED_GLOBAL_PREFIXES = (_IMPORT_ALIAS_PREFIX, _BUILTINS_DICT_PREFIX, _UNNAMED_SCOPE_PREFIX)
```

The `__import_` and `__builtins_dict__` prefixes are two of the three `_MINTED_GLOBAL_PREFIXES` torch/_dynamo/aot_compile.py already keeps; this commit names them there individually and `precompile_package.py` imports them rather than restating the strings, which are minted as bare literals in `OutputGraph.install_builtins_dict_in_fglobals` and `symbolic_convert.import_source` and pinned against a real compile by `test_minted_global_names_match_dynamo`.

## `_owning_module` and `_dynamo_alias_module`

```python
def _owning_module(value):
    if isinstance(value, types.ModuleType):
        return value.__name__
    owner = getattr(value, "__module__", None)
    return owner if isinstance(owner, str) else None

def _dynamo_alias_module(global_name):
    if not global_name.startswith(_IMPORT_ALIAS_PREFIX):
        return None
    tail = global_name[len(_IMPORT_ALIAS_PREFIX):]
    return sys.modules.get(tail.replace("_dot_", "."))
```

`_owning_module` has one caller here, `_reads_a_builtin`; `_module_namespaces` and `_is_risky_drop` reuse it once they arrive. `_dynamo_alias_module` maps an `__import_a_dot_b` global back to the module it aliases: the OutputGraph's `import_sources` table is authoritative, but a guard entry does not carry it, and the unmangling collides only for a module whose name contains `_dot_` (`pkg.sub_dot_mod` is aliased as `__import_pkg_dot_sub_dot_mod`, which comes back as `pkg.sub.mod` when that module is loaded too); that collision fails open, since the callers judge the module returned. A torch_package module is aliased without the prefix and comes back None, which fails closed.

## `_is_dynamo_synthesized`

```python
_DYNAMO_SYNTHESIZED = ("__nested_resume_fns",)

def _is_dynamo_synthesized(source):
    if isinstance(source, GetItemSource) and isinstance(source.index, int):
        source = source.base
    return isinstance(source, LocalSource) and source.local_name in _DYNAMO_SYNTHESIZED
```

It recognises the `__nested_resume_fns` local Dynamo passes into every generated resume function as its first parameter, a list of generated resume functions rather than a slot any config chooses, and an entry read straight off it (`__nested_resume_fns[0]`), nothing deeper: a resume function's closure cells carry the resumed frame's cell variables, so `type(__nested_resume_fns[0].__closure__[0].cell_contents).__call__`, which Dynamo mints for a callable an inner def captured, is the user's and is judged like any other value (an earlier revision walked to the source root and waived it). Its sibling `__nested_frame_values` is deliberately not covered, because it carries the live stack and locals of the frames nested INSIDE the one resuming, which pops the last entry off it for the callee it resumes (under `nested_graph_breaks=True` a callee's `act = pick()` reaches its caller's resume frame as `L['__nested_frame_values'][0][2]`, `[0]` selecting the frame and the tail a position in its values, not a key), so a guard rooted there must be judged like the local or intermediate it stands for.

## `_reads_a_builtin`

```python
def _reads_a_builtin(source, value):
    return (
        isinstance(source, DictGetItemSource)
        and isinstance(source.base, GlobalSource)
        and source.base.global_name.startswith(_BUILTINS_DICT_PREFIX)
        and (
            isinstance(value, types.BuiltinFunctionType)
            or (isinstance(value, type) and bool(vars(type)["__flags__"].__get__(value) & (1 << 8)))  # Py_TPFLAGS_IMMUTABLETYPE
        )
        and _owning_module(value) == "builtins"
        and getattr(value, "__name__", None) == source.index
    )
```

It requires the guard's source to be a `DictGetItemSource` whose base is a `GlobalSource` named `__builtins_dict__...` AND the value to be a `types.BuiltinFunctionType` or a `type` carrying `Py_TPFLAGS_IMMUTABLETYPE` AND its `__module__` to be `builtins` AND its `__name__` to equal the dict key; `_reads_a_builtin` reads `source.base` itself. A builtin parked in `self.act = abs` is a slot like any other, so the test keys on where the read comes FROM, not on who owns the value.

That dict is the frame's live `builtins.__dict__`, not a table of the real builtins, so a shim's `builtins.py2_sum = sum` is a binding under it that another machine's shim can point elsewhere; the read is waived only under the builtin's own name (`IOError` and `EnvironmentError`, CPython's aliases of `OSError`, fail closed), and only for a value CPython built: `functools.wraps` copies `__module__` and `__name__` onto a Python shim installed as `builtins.sum = wraps(sum)(logged_sum)`, whose `CLOSURE_MATCH` the serializer drops, and a class statement exec'd with the builtins namespace as its globals (or handed `__module__ = "builtins"`) claims the module outright, which a bare `type` test waived; a class statement or `type()` call does not carry the flag. The flag is read through `type`'s own descriptor, so a metaclass can neither shadow it nor make the read raise, and a static type's `__module__` is derived from its C name; a builtin function's `__module__` is a writable member, though, so `builtins.getcwd = os.getcwd` plus `os.getcwd.__module__ = "builtins"` is waived, evidence rather than proof on that branch, which an advisory lint over a dropped-guard set does not defend against.

Every callable in `builtins.__dict__` is one of those two kinds apart from the `_sitebuiltins` objects, instances of neither, and beside the aliases (`WindowsError` is a third on Windows) three of them fail closed:

| key | why it fails closed |
| --- | --- |
| `IOError`, `EnvironmentError` (`WindowsError` on Windows) | aliases: `__name__` is `OSError`, not the key |
| `open` | the one builtin function `builtins` does not own: `__module__` is `_io`, `io` before 3.12, so a dropped guard on one of the most mainstream builtins here is reported |
| `ExceptionGroup` (3.11+) | a heap type, no `Py_TPFLAGS_IMMUTABLETYPE` |
| `__loader__` | a heap type, and read under a name that is not its own as well |

The exposure is narrow either way, since a registered builtin is id-matched into a `BUILTIN_MATCH` the serializer keeps and only a deregistered, polyfilled one (`sum`, `enumerate`, `all`, `any`) or such a shim reaches the dropped set the lint examines.

## `_defined_where_read`

```python
def _defined_where_read(value, global_name, user_stack):
    if not user_stack or not isinstance(value, (type, types.FunctionType)):
        return False                                   # a bound method or proxy is refused before any read
    if value.__qualname__ != global_name:
        return False                                   # act = _impl_a if ... else _impl_b, op = Ops.op, a factory's def
    def compiled_as(fn, qualname):                     # wraps copies __qualname__ but not the code object's own name
        if sys.version_info >= (3, 11):
            return fn.__code__.co_qualname == qualname
        return fn.__code__.co_name == qualname.rpartition(".")[2]
    if isinstance(value, type):
        skip = ("__annotate__", "__annotate_func__")
        files = []
        for key, attr in vars(value).items():          # unwrap staticmethod/classmethod via __func__, property via fget
            ...
            if attr.__qualname__ == f"{global_name}.{key}" and compiled_as(attr, ...):
                files.append(attr.__code__.co_filename)
    else:
        files = [value.__code__.co_filename] if compiled_as(value, global_name) else []
    read = user_stack[0].filename                      # the OUTERMOST frame
    if not os.path.isabs(read):
        return False
    try:
        here = _norm(read)
        return any(os.path.isabs(f) and _norm(f) == here for f in files)
    except ValueError:                                 # an embedded NUL, which posixpath.realpath lets through
        return False
```

**The name rule.** `_defined_where_read(value, global_name, user_stack)` takes the read's `GlobalSource.global_name` (not the `G['op']` spelling `GuardFilterEntry.name` keeps) and is true for a def, or through its own methods a class statement, bound under its own name whose code lives in the file that read it, the one binding the inlined-source checksum of that file covers, unlike `from impl_a import op`, which only takes a conditional import the checksum never sees; it checks the name itself rather than leaving that to the caller, and compares `__qualname__`, so `act = _impl_a if cfg.fast else _impl_b` in the reading file is a slot and so are `op = Ops.op` and a def returned by a factory, and the paths are compared normalized. The `__qualname__` is backed by the code object's own name, which `functools.wraps` copies onto a wrapper's `__qualname__` but cannot forge (`co_qualname`; before 3.11 only `co_name`, so a wrapper def named after what it wraps slips through there), so a same-file `wraps` decorator a flag turns on is a slot in both arms. Only a plain function or a class is judged: a bound method or any other object forwarding `__qualname__` and `__code__` is refused before an attribute is read, which also keeps a proxy that answers reads by raising, such as `torch.classes.<ns>`, out of the value slot.

**The file comes off the code object.** The file is read off the value's code object rather than off `__module__`, because `functools.wraps` copies `__module__` along with `__name__` and `__qualname__`:

```python
op = torch.compile(op)          # behind a flag: claims the reader's module, code lives in eval_frame.py -> not waived
@torch.no_grad()                # an unconditional cross-file decorator on a same-file def -> not waived either
def op(x): ...
cached = functools.lru_cache(op)   # no code object at all -> not waived
```

The object does not tell the flag shape from an unconditional cross-file decorator, so a same-file def under `@torch.no_grad()` is not waived either and the risky-drop lint reports it. Anything else without a code object, such as a `functools.lru_cache` wrapper, which claims the reader's module the same way, is not waived.

**A class is judged by its own methods.** A class has no code object, and its `__module__` is no better: `namedtuple` and `type()` stamp it from the calling frame (`make_dataclass` does so from Python 3.12) under a BARE `__qualname__` (a def or class statement inside the factory would carry `factory.<locals>.`), so a `Point = namedtuple("Point", "x y")` in the reader looks exactly like a class statement; the frame stamped is the caller's, so the collision needs a factory called from the reading file, `lib.make_point()` coming back stamped `lib`. Its methods can tell: a class statement compiles its defs in its own file under its own `__qualname__` prefix, so a class is waived when at least one function in its own `__dict__`, stored under key `k` with `__qualname__` `Cls.k` (a staticmethod or classmethod unwrapped through `__func__` and a property through `fget`, by type rather than by `getattr`, since a class attribute can be a proxy such as `torch.classes.<ns>` that answers any attribute read by raising; a `cached_property` keeps its function under `.func` and does not count), was compiled in the reading file.

```python
class Ops:                                  # waived: op compiled here under Ops.op
    @staticmethod
    def op(x): return x
class Marker: pass                          # fails closed: no def of its own
Point = collections.namedtuple("Point", "x")          # bare __qualname__ "Point", methods compiled in collections -> not waived
type("Point", (), {"area": _area})                    # a factory fed a same-file def: qualname "_area", not "Point.area" -> not waived
from mypkg.impl import Point; Point.extra = _extra    # attached afterwards keeps its bare qualname -> not waived
Point.norm = functools.wraps(Point.norm)(_norm)       # forges "Point.norm", code object still named "_norm" -> not waived
```

A function attached afterwards keeps its bare qualname, and one attached through `functools.wraps` keeps its code object's own name, so a class imported from another file that the reader extends or patches is refused, as is a factory fed same-file methods (`type(name, bases, {"area": _area})`, `make_dataclass(name, cfg.fields, namespace={"area": _area})`), and `class Marker: pass` fails closed; so does a class statement whose only functions are generated: a fields-only `@dataclass`'s and a `NamedTuple`'s are defs of a factory (dataclasses' `__create_fn__`, `namedtuple`), so their code objects' own qualname carries the factory's `<locals>.` prefix (on 3.10, where only `co_name` exists, the `<string>` or stdlib file they compile in refuses them instead), and an `Enum`'s arrive in the subclass `__dict__` under `Enum.` qualnames the key rule refuses, so a plain config dataclass read as a global is reported. The one function the compiler itself puts in a class `__dict__`, the PEP 649 annotate function Python 3.14 stores for an annotated class body, compiles in the reading file, but under key `__annotate_func__` with `__qualname__` `Cls.__annotate__`, so the key rule refuses it and the verdict on a config dataclass is the same on every version; the scan also skips both annotate keys outright, against a version that stores the function under its own name.

**Only absolute filenames compare.** A `co_filename` is not always a path: an `exec` records `<string>` and a REPL `<stdin>`, and `realpath` resolves either against the cwd, so an ungated comparison made every `<string>` compilation one file and waived a def exec'd under it the moment the reading frame was exec-generated too (on 3.10 a fields-only dataclass as well, whose `__init__` compiles in `<string>` under a `co_name` that cannot tell it from a class statement's def). Only absolute filenames on both sides are compared (the gate `_norm` documents and `_classify_file` applies to a recorded `__file__`); a pseudo-filename, a relative spelling and an embedded NUL, which makes `posixpath.realpath` raise, fail closed.

**The frame read.** The filename compared is that of the OUTERMOST frame in the guard's `user_stack`. That frame is the one being compiled, whose globals a bare `GlobalSource` denotes (`InliningInstructionTranslator._load_global` mints one only when the inlined frame's globals are the root's, and otherwise reads through an `__import_` alias or an `___unnamed_scope` dict entry); the stack itself is stamped in `GuardsSet.add` with the inlining stack at the moment the guard is installed, which for a lazily realized global is the point of first use, so the innermost frame can be a helper inlined from another file, and reading the file off it would waive `from b import op` whenever `op` is first used inside a helper inlined from `b`.

**The known gap.** What the predicate cannot see, and its docstring says so, is a same-name fork inside the reading file (`try: from x import impl as op` / `except ImportError: def op`, or a class statement under the same `if`), which binds a different def per machine under one checksum; that is the conditional-bind KNOWN GAP `_is_risky_drop` records.

## Tests

Each predicate is pinned on hand-built sources by a test of its own, except `_defined_where_read`, which gets six `test_defined_where_read_*` methods, one per shape family so a premise that holds only on some CPython versions cannot mask another family's rows.

- `test_reads_a_builtin_keys_on_where_the_read_comes_from` pins `len` read through the builtins dict as waived, a builtin in a slot, a user table keyed `len`, the same table read off a slot (`self.act_fns["len"]`, the unnarrowed source the lint hands over, refused rather than read as a global) and user code injected into builtins as not, and a `functools.wraps(sum)` shim under the `sum` key as not (the test asserts `(__module__, __name__) == ("builtins", "sum")` first) while `sum` under its own key is and so is `int`, a type passing the CPython-built conjunct. The remaining conjuncts each get rows of their own: `IOError` and `EnvironmentError` under their own keys (CPython-built, but named `OSError`), `open` under its own key (a builtin function named `open`, but owned by `io` or `_io` depending on the version and never by `builtins`, so the `__module__` conjunct is what refuses it; the test asserts those two facts first), a user exception class installed into builtins under its own name and a class exec'd with the builtins namespace as its globals (the test asserts it claims `__module__ == "builtins"` first; both are heap types, so the flag is what refuses them), a class whose metaclass shadows `__flags__` with the immutable bit while claiming `builtins` (refused, since the flag is read through `type`'s descriptor) and one whose metaclass makes the `__flags__` read raise (refused without raising), all not waived, and every type in `builtins.__dict__` read under its own name waived except `ExceptionGroup`, the one heap type there read under its own name (`__loader__` is a heap type too, and the test pins that its `__name__` is not the key).
- `test_dynamo_synthesized_covers_only_the_resume_function_list` pins the list and its entry as synthesized and, past the entry, the resume function's `__closure__`, a cell's contents and `type(...).__call__` off it as not, beside `__nested_frame_values`, a same-named global and an ordinary local.
- `test_alias_module_and_owning_module` pins `__import_torch_dot_nn_dot_functional` to `torch.nn.functional` and as None a user global whose tail past the prefix length names a module (`imported_torch`), an unknown tail and a torch_package alias, which `import_source` mints without the prefix, and the `_dot_` collision, `__import_mypkg_dot_sub_dot_mod` (the alias of `mypkg.sub_dot_mod` as much as of `mypkg.sub.mod`) coming back as the loaded `mypkg.sub.mod`; `_owning_module` answers None for an int and for a `__module__` that is not a string.
- `test_defined_where_read_needs_the_name_and_the_file` pins the name and file rules: a same-file def under its own name is waived, also through another spelling of the path and on a two-frame stack whose inner frame is torch/nn/functional.py (where `F.silu` is not), and not under another name, from another file, with no stack, or for `F.silu` and an int; a staticmethod extracted under its own name and a def returned by a factory are not waived (`__qualname__` tells); a module-level def exec'd under this file's name is waived, as the documented gap.
- `test_defined_where_read_takes_the_file_off_the_code_object` pins the `torch.compile` wrapper (the test asserts it claims this module first), a `functools.lru_cache` wrapper and a `@torch.no_grad()`-decorated def as not waived, a same-file conditional `functools.wraps` decorator as waived with the flag off (the def itself comes back) and not with it on (the wrapper forges `__qualname__`; its code object is named `wrapper`), and a bound method of the same-file def and a namespace forwarding its `__qualname__` and `__code__` as refused by type before either is read.
- `test_defined_where_read_judges_a_class_by_its_own_methods` pins the test class itself as waived when read from this file and not from another, and `torch.nn.Linear` as not; a same-file class with one staticmethod is waived, so is one with one classmethod (both the `__func__` arm) and one whose only def is a `@property` (the `fget` arm), while one whose only def is a `functools.cached_property` is not, nor is a same-file class with no method of its own, a fields-only `@dataclass` or a `NamedTuple` (their generated defs carry the factory's `<locals>.` in `co_qualname`; on 3.10 the `<string>` or stdlib file they compile in refuses them) or an `Enum` (its functions carry `Enum.` qualnames the key rule refuses); and an `nn.Module` subclass holding `torch.classes.<ns>` as a class attribute, which the test first shows raises `RuntimeError` on an attribute read (`Model.ns.__func__`), is judged like any other class (waived from this file, not from another) instead of raising out of the predicate, the proxy itself handed over as the value is refused by type, and the namespace `torch.classes` fabricated for that read is removed from it again in a cleanup.
- `test_defined_where_read_refuses_a_class_minted_for_the_file` pins a `namedtuple` (the test asserts it claims this module under a bare `__qualname__` first), a `make_dataclass` (bare `__qualname__` asserted; the module is stamped only from 3.12) and a `type()` class as not waived, nor a `type()` class handed a same-file def in its namespace, under another key or under the def's own name (a bare qualname either way, so the class half of the rule, the missing `Point.` prefix, is what refuses both); the key half gets its own pair, a same-file class statement's method handed to a `type()` class of the same `__qualname__`, waived under its own key `m` and not borrowed under `other`; nor is a class compiled under torch/nn/functional.py's name (the imported-class shape) waived with a same-file function attached afterwards or with a method replaced through `functools.wraps` (the test asserts the forged `Point.norm` qualname beside the code object's own `_norm` name first).
- `test_defined_where_read_skips_the_compiler_annotate_function` pins the fields-only `@dataclass` as not waived and, on 3.14, first asserts what the compiler stored beside its generated methods: key `__annotate_func__`, qualname `Cfg.__annotate__` on the function and on its code object, compiled in this file; that is replayed on every version through a `type()` class handed a same-file function under that key, the qualname stamped on the function and on its code object as a class statement's def carries it (not waived), beside a control row with the same function under an ordinary key and matching qualname (waived, so the replay is the shape a class statement produces) and the two rows that pin the `skip`, the function under `__annotate__` or `__annotate_func__` with a `Cfg.<key>` qualname (not waived).
- `test_defined_where_read_refuses_a_pseudo_filename` reads a def exec'd under `<string>` (the test asserts its `co_filename` first) from a `<string>` frame, the row that pins the gate on every version (a fields-only `@dataclass` collides only on 3.10, where `co_name` cannot refuse it first), and a same-file def from a relative frame filename (`os.path.relpath(__file__)`, which the test asserts resolves to this file), the same def with that relative spelling as its own `co_filename` read from an absolute frame, from a frame filename with an embedded NUL and with a NUL in its own `co_filename`, all not waived and none raising.
- `test_minted_global_names_match_dynamo` pins the names the predicates lean on (the two prefixes, spelled in aot_compile.py, and the two nested-resume locals) against the code that mints them, through a real compile: a `__builtins_dict__` read, an `__import_` alias, and, under `nested_graph_breaks=True` (the harness runs every test with it on; the config default is off), the two locals every generated resume function takes and roots a guard at, judged on the sources Dynamo actually minted: off `__nested_resume_fns` exactly the list and its `[0]` entry are synthesized, while `type(__nested_resume_fns[0].__closure__[0].cell_contents).__call__`, the guard on a callable the resumed frame's inner def captured, is present and is not; nothing rooted at `__nested_frame_values` is.

## What comes next

Nothing calls these yet; `_module_namespaces` and `_is_risky_drop`, which do, follow once the library-module classifier is in.

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_reads_a_builtin -k test_dynamo_synthesized -k test_alias_module -k test_defined_where_read -k test_minted_global_names
python test/dynamo/test_precompile_package.py
lintrunner torch/_dynamo/precompile_package.py torch/_dynamo/aot_compile.py test/dynamo/test_precompile_package.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

Pull Request resolved: #197263
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…y its resolved path (#197428)

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

Pull Request resolved: #197428
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…a capture (#197260)

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

Pull Request resolved: #197260
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
… by its name (#197264)

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

Pull Request resolved: #197264
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…nd the evidence-only-at-the-top rule (#197595)

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

Pull Request resolved: #197595
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…rd hangs off (#197265)

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

Pull Request resolved: #197265
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…r compared (#197267)

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

Pull Request resolved: #197267
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
… totality test (#197268)

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

Pull Request resolved: #197268
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…ered guard code (#197269)

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

Pull Request resolved: #197269
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…e guard report (#197270)

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

Pull Request resolved: #197270
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…ization dropped (#197266)

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

Pull Request resolved: #197266
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…oes not say (#197271)

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

Pull Request resolved: #197271
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
… generalize (#197272)

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

Pull Request resolved: #197272
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…er (#197273)

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

Pull Request resolved: #197273
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…e runs under (#197274)

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

Pull Request resolved: #197274
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…h allow_empty_graphs (#197275)

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

Pull Request resolved: #197275
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
…onverter is asked to clone (#197721)

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

Pull Request resolved: #197721
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
#197276)

**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]>
Pull Request resolved: #197276
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
**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]>

Pull Request resolved: #197278
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721, #197276
pytorchmergebot pushed a commit that referenced this pull request Sep 20, 2026
)

**Summary.** Whatever autocast state the capture ran under is already baked into the artifact -- ATen casts for the eager backend, generated kernels for inductor -- but the artifact still re-dispatches at serve time (the eager graph's ATen calls, and on the inductor path every fallback op, which is emitted at its `.default` overload -- e.g. `aten.addbmm.default`, which AutocastCPU registers), so a serving process with autocast enabled would cast a second time. Both inlined drivers now run the graph under `torch._C._DisableAutocast()`, the `c10::impl::ExcludeDispatchKeyGuard` over `autocast_dispatch_keyset` (`torch/csrc/autograd/init.cpp`) that AOTAutograd already emits into its own generated wrappers as `_DisableAutocast_` when a compile ran under autocast (`torch/_functorch/_aot_autograd/runtime_wrappers.py`). It is one RAII exclusion of the autocast keys for every device: no per-device list, no nesting counter, and no `clear_autocast_cache()` on exit, so it is safe to enter unconditionally on every call and leaves the caller's autocast state exactly as it found it. This pins autocast off for the duration of the call regardless of capture-time or serve-time state, exactly like the eager driver's pre-existing unconditional `no_grad`; the programming-model docstring gets the same sentence in the later commit that rewrites it (E2). AOTAutograd's guard is conditional on the capture having run under autocast; precompile's is unconditional because the leak it closes runs the other way too (a capture made without autocast, served under it), which is the case the test exhibits. An earlier draft of this commit recorded a `GRAPH_DEVICES` metadata field and entered `torch.amp.autocast(dev, enabled=False)` per device; that reimplemented the primitive with a narrower cache-clear hazard (any exit that returns autocast's nesting count to zero wipes the process-wide cast cache), so the field, its emitter and its parser entry are gone and the artifact format is unchanged from the parent.

## Before and after

```python
compiled = PrecompiledModule(lambda m, x: m(x), backend="eager")
compiled._compile((model, x))
ns = {"__name__": "artifact"}
exec(compiled.to_python_code(), ns)

with torch.autocast("cpu", dtype=torch.bfloat16):
    out = ns["forward"](model, x)
# parent: the captured graph re-dispatched under autocast and cast its inputs a second time (bf16 out)
# now:    the driver runs call(...) under torch._C._DisableAutocast() (fp32 out, equal to the
#         no-autocast call), and the caller's autocast state is as it was afterwards
```

## The driver change

```python
# _eager_forward:     with _torch._C._DisableAutocast(), _torch.no_grad(): out = list(call([...]))
# _inductor_forward:  with _torch._C._DisableAutocast(): out = list(call([...]))
```

`test_artifact_neutralizes_ambient_autocast` (parametrized over both backends, CPU bf16 autocast) captures a `torch.addbmm` model and checks that a call under ambient autocast returns the fp32 result of eager `model(x)` computed outside any autocast, that the ambient region is still live and bf16 after the call, and that autocast is off again after the region. `addbmm` is the op that makes the inductor case load-bearing on CPU: `KERNEL_CPU(addbmm, lower_precision_fp)` registers it for AutocastCPU, `make_fallback(aten.addbmm)` leaves it undecomposed, and `FallbackKernel` keeps builtin aten ops at their functional overload, so the inductor artifact calls `torch.ops.aten.addbmm.default` (the `Linear`/`addmm` graph cannot show this: `extern_kernels.addmm` binds `addmm.out`, which autocast never registers). Deleting either guard fails its case: eager with `bfloat16 != float32`, inductor with `assert_tensor_metadata` raising `expected dtype torch.float32 but got torch.bfloat16`.

Test Plan:

```
python test/test_precompile.py -k autocast
python test/test_precompile.py
lintrunner torch/_precompile.py torch/_precompile_driver.py test/test_precompile.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

Pull Request resolved: #197279
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721, #197276, #197278
bobrenjc93 added a commit that referenced this pull request Sep 21, 2026
)

**Summary.** Whatever autocast state the capture ran under is already baked into the artifact -- ATen casts for the eager backend, generated kernels for inductor -- but the artifact still re-dispatches at serve time (the eager graph's ATen calls, and on the inductor path every fallback op, which is emitted at its `.default` overload -- e.g. `aten.addbmm.default`, which AutocastCPU registers), so a serving process with autocast enabled would cast a second time. Both inlined drivers now run the graph under `torch._C._DisableAutocast()`, the `c10::impl::ExcludeDispatchKeyGuard` over `autocast_dispatch_keyset` (`torch/csrc/autograd/init.cpp`) that AOTAutograd already emits into its own generated wrappers as `_DisableAutocast_` when a compile ran under autocast (`torch/_functorch/_aot_autograd/runtime_wrappers.py`). It is one RAII exclusion of the autocast keys for every device: no per-device list, no nesting counter, and no `clear_autocast_cache()` on exit, so it is safe to enter unconditionally on every call and leaves the caller's autocast state exactly as it found it. This pins autocast off for the duration of the call regardless of capture-time or serve-time state, exactly like the eager driver's pre-existing unconditional `no_grad`; the programming-model docstring gets the same sentence in the later commit that rewrites it (E2). AOTAutograd's guard is conditional on the capture having run under autocast; precompile's is unconditional because the leak it closes runs the other way too (a capture made without autocast, served under it), which is the case the test exhibits. An earlier draft of this commit recorded a `GRAPH_DEVICES` metadata field and entered `torch.amp.autocast(dev, enabled=False)` per device; that reimplemented the primitive with a narrower cache-clear hazard (any exit that returns autocast's nesting count to zero wipes the process-wide cast cache), so the field, its emitter and its parser entry are gone and the artifact format is unchanged from the parent.

## Before and after

```python
compiled = PrecompiledModule(lambda m, x: m(x), backend="eager")
compiled._compile((model, x))
ns = {"__name__": "artifact"}
exec(compiled.to_python_code(), ns)

with torch.autocast("cpu", dtype=torch.bfloat16):
    out = ns["forward"](model, x)
# parent: the captured graph re-dispatched under autocast and cast its inputs a second time (bf16 out)
# now:    the driver runs call(...) under torch._C._DisableAutocast() (fp32 out, equal to the
#         no-autocast call), and the caller's autocast state is as it was afterwards
```

## The driver change

```python
# _eager_forward:     with _torch._C._DisableAutocast(), _torch.no_grad(): out = list(call([...]))
# _inductor_forward:  with _torch._C._DisableAutocast(): out = list(call([...]))
```

`test_artifact_neutralizes_ambient_autocast` (parametrized over both backends, CPU bf16 autocast) captures a `torch.addbmm` model and checks that a call under ambient autocast returns the fp32 result of eager `model(x)` computed outside any autocast, that the ambient region is still live and bf16 after the call, and that autocast is off again after the region. `addbmm` is the op that makes the inductor case load-bearing on CPU: `KERNEL_CPU(addbmm, lower_precision_fp)` registers it for AutocastCPU, `make_fallback(aten.addbmm)` leaves it undecomposed, and `FallbackKernel` keeps builtin aten ops at their functional overload, so the inductor artifact calls `torch.ops.aten.addbmm.default` (the `Linear`/`addmm` graph cannot show this: `extern_kernels.addmm` binds `addmm.out`, which autocast never registers). Deleting either guard fails its case: eager with `bfloat16 != float32`, inductor with `assert_tensor_metadata` raising `expected dtype torch.float32 but got torch.bfloat16`.

Test Plan:

```
python test/test_precompile.py -k autocast
python test/test_precompile.py
lintrunner torch/_precompile.py torch/_precompile_driver.py test/test_precompile.py
```

Authored with an AI assistant.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

Pull Request resolved: #197279
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721, #197276, #197278

Re-land of #197279, reverted in 70f4f9b as a dependent of #197262 (whose test the re-land below fixes).
ghstack-source-id: bf1865a
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1217/head branch November 22, 2026 01:43
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