Repository navigation
[precompile] Locate the stdlib, install and torch roots for the module-ownership lint - #197262
Closed
bobrenjc93 wants to merge 17 commits into
Closed
bobrenjc93 wants to merge 17 commits into
bobrenjc93 wants to merge 17 commits into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197262
Note: Links to docs will display an error until the docs builds have been completed. ⏳ No Failures, 51 PendingAs of commit d9e1b95 with merge base d78bbf2 ( 🟡 GREEN LIGHT - PR was reverted - re-landing requires human review:
Green Light will not review this PR again, on this or any later commit; re-landing it needs a human approval. This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Sep 16, 2026
Closed
This was referenced Sep 21, 2026
Closed
Closed
Closed
Closed
Closed
bobrenjc93
added a commit
that referenced
this pull request
Sep 21, 2026
) **Summary.** Whatever autocast state the capture ran under is already baked into the artifact -- ATen casts for the eager backend, generated kernels for inductor -- but the artifact still re-dispatches at serve time (the eager graph's ATen calls, and on the inductor path every fallback op, which is emitted at its `.default` overload -- e.g. `aten.addbmm.default`, which AutocastCPU registers), so a serving process with autocast enabled would cast a second time. Both inlined drivers now run the graph under `torch._C._DisableAutocast()`, the `c10::impl::ExcludeDispatchKeyGuard` over `autocast_dispatch_keyset` (`torch/csrc/autograd/init.cpp`) that AOTAutograd already emits into its own generated wrappers as `_DisableAutocast_` when a compile ran under autocast (`torch/_functorch/_aot_autograd/runtime_wrappers.py`). It is one RAII exclusion of the autocast keys for every device: no per-device list, no nesting counter, and no `clear_autocast_cache()` on exit, so it is safe to enter unconditionally on every call and leaves the caller's autocast state exactly as it found it. This pins autocast off for the duration of the call regardless of capture-time or serve-time state, exactly like the eager driver's pre-existing unconditional `no_grad`; the programming-model docstring gets the same sentence in the later commit that rewrites it (E2). AOTAutograd's guard is conditional on the capture having run under autocast; precompile's is unconditional because the leak it closes runs the other way too (a capture made without autocast, served under it), which is the case the test exhibits. An earlier draft of this commit recorded a `GRAPH_DEVICES` metadata field and entered `torch.amp.autocast(dev, enabled=False)` per device; that reimplemented the primitive with a narrower cache-clear hazard (any exit that returns autocast's nesting count to zero wipes the process-wide cast cache), so the field, its emitter and its parser entry are gone and the artifact format is unchanged from the parent. ## Before and after ```python compiled = PrecompiledModule(lambda m, x: m(x), backend="eager") compiled._compile((model, x)) ns = {"__name__": "artifact"} exec(compiled.to_python_code(), ns) with torch.autocast("cpu", dtype=torch.bfloat16): out = ns["forward"](model, x) # parent: the captured graph re-dispatched under autocast and cast its inputs a second time (bf16 out) # now: the driver runs call(...) under torch._C._DisableAutocast() (fp32 out, equal to the # no-autocast call), and the caller's autocast state is as it was afterwards ``` ## The driver change ```python # _eager_forward: with _torch._C._DisableAutocast(), _torch.no_grad(): out = list(call([...])) # _inductor_forward: with _torch._C._DisableAutocast(): out = list(call([...])) ``` `test_artifact_neutralizes_ambient_autocast` (parametrized over both backends, CPU bf16 autocast) captures a `torch.addbmm` model and checks that a call under ambient autocast returns the fp32 result of eager `model(x)` computed outside any autocast, that the ambient region is still live and bf16 after the call, and that autocast is off again after the region. `addbmm` is the op that makes the inductor case load-bearing on CPU: `KERNEL_CPU(addbmm, lower_precision_fp)` registers it for AutocastCPU, `make_fallback(aten.addbmm)` leaves it undecomposed, and `FallbackKernel` keeps builtin aten ops at their functional overload, so the inductor artifact calls `torch.ops.aten.addbmm.default` (the `Linear`/`addmm` graph cannot show this: `extern_kernels.addmm` binds `addmm.out`, which autocast never registers). Deleting either guard fails its case: eager with `bfloat16 != float32`, inductor with `assert_tensor_metadata` raising `expected dtype torch.float32 but got torch.bfloat16`. Test Plan: ``` python test/test_precompile.py -k autocast python test/test_precompile.py lintrunner torch/_precompile.py torch/_precompile_driver.py test/test_precompile.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197279 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721, #197276, #197278 Re-land of #197279, reverted in 70f4f9b as a dependent of #197262 (whose test the re-land below fixes). ghstack-source-id: bf1865a
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…e-ownership lint (#197262) (#197961) **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]> Reverted in 588393c (the internal Buck link-tree failure of this commit's test) and back in the stack: under a per-file symlink farm `_torch_roots()` returns the package directory under both of its spellings, as designed, and the test asserted only one; it now expects both. Pull Request resolved: #197961 Approved by: https://github.com/pytorchgreenlight
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…iguration (#197263) (#197962) **Problem.** The risky-drop lint needs to recognise dropped identity guards whose value cannot resolve to a different object on the serving machine, and the simple checks (`__module__ == "builtins"`, a bare `type` test) are fooled by shims and `functools.wraps`. **Fix.** Add `_reads_a_builtin` (a CPython-built builtin read under its own name through Dynamo's builtins dict), `_defined_where_read` (a def or class bound under its own name in the file that read it, compared by code object), `_is_dynamo_synthesized` and `_dynamo_alias_module`. Nothing calls them yet. **Summary.** The risky-drop lint asks, for each identity guard that serialization dropped, whether the value it guarded could resolve to a different object on the serving machine, and this commit adds the small predicates that recognise bindings where that cannot happen. `_reads_a_builtin` is true for `len` or `sorted` reached the ordinary way, through the `__builtins_dict__*` global Dynamo installs, but only under the builtin's own name, only for a value `builtins` itself owns, and only for one CPython built (a builtin function or a static type carrying `Py_TPFLAGS_IMMUTABLETYPE`), because that dict is the frame's live `builtins.__dict__` and a shim can install anything into it under any name. `_defined_where_read(value, global_name, user_stack)` is true for a def, or through its own methods a class statement, bound under its own name whose code lives in the file that read it -- the one binding the inlined-source checksum of that file covers -- comparing `__qualname__` against the code object's own name and the code object's `co_filename` (never `__module__`, which `functools.wraps` copies) against the OUTERMOST frame of the guard's `user_stack`, with only absolute filenames on both sides admitted. `_is_dynamo_synthesized` recognises the `__nested_resume_fns` local every generated resume function takes and an entry read straight off it, and `_dynamo_alias_module` maps an `__import_a_dot_b` global back to the module it aliases, both leaning on prefixes this commit names individually in `torch/_dynamo/aot_compile.py` (`_IMPORT_ALIAS_PREFIX`, `_BUILTINS_DICT_PREFIX`) rather than restating the strings. Nothing calls these yet; `_module_namespaces` and `_is_risky_drop`, which do, follow once the library-module classifier is in. ## Examples ```python import torch from torch._dynamo import precompile_package as pp from torch._dynamo.source import ( AttrSource, CellContentsSource, ClosureSource, GetItemSource, GlobalSource, LocalSource, TypeSource, ) pp._dynamo_alias_module("__import_torch_dot_nn_dot_functional") # sys.modules["torch.nn.functional"] pp._dynamo_alias_module("F") # None: not a Dynamo alias pp._owning_module(torch.nn.functional) # "torch.nn.functional" (a module names itself) pp._owning_module(torch.nn.functional.gelu) # "torch._C._nn": the extension module that defines gelu pp._owning_module(3) # None: an int has no __module__ entry = GetItemSource(LocalSource("__nested_resume_fns"), 0) pp._is_dynamo_synthesized(entry) # True cell = CellContentsSource(GetItemSource(ClosureSource(entry), 0), "cell_contents") pp._is_dynamo_synthesized(AttrSource(TypeSource(cell), "__call__")) # False: a value the resume function closes over pp._is_dynamo_synthesized(GetItemSource(LocalSource("__nested_frame_values"), 0)) # False: a nested frame's stack and locals pp._is_dynamo_synthesized(GlobalSource("__nested_resume_fns")) # False: a user global spelled like it ``` ## The prefixes, named in `aot_compile.py` ```python # torch/_dynamo/aot_compile.py, parent _MINTED_GLOBAL_PREFIXES = ("__import_", "__builtins_dict__", _UNNAMED_SCOPE_PREFIX) # now _IMPORT_ALIAS_PREFIX = "__import_" _BUILTINS_DICT_PREFIX = "__builtins_dict__" _MINTED_GLOBAL_PREFIXES = (_IMPORT_ALIAS_PREFIX, _BUILTINS_DICT_PREFIX, _UNNAMED_SCOPE_PREFIX) ``` The `__import_` and `__builtins_dict__` prefixes are two of the three `_MINTED_GLOBAL_PREFIXES` torch/_dynamo/aot_compile.py already keeps; this commit names them there individually and `precompile_package.py` imports them rather than restating the strings, which are minted as bare literals in `OutputGraph.install_builtins_dict_in_fglobals` and `symbolic_convert.import_source` and pinned against a real compile by `test_minted_global_names_match_dynamo`. ## `_owning_module` and `_dynamo_alias_module` ```python def _owning_module(value): if isinstance(value, types.ModuleType): return value.__name__ owner = getattr(value, "__module__", None) return owner if isinstance(owner, str) else None def _dynamo_alias_module(global_name): if not global_name.startswith(_IMPORT_ALIAS_PREFIX): return None tail = global_name[len(_IMPORT_ALIAS_PREFIX):] return sys.modules.get(tail.replace("_dot_", ".")) ``` `_owning_module` has one caller here, `_reads_a_builtin`; `_module_namespaces` and `_is_risky_drop` reuse it once they arrive. `_dynamo_alias_module` maps an `__import_a_dot_b` global back to the module it aliases: the OutputGraph's `import_sources` table is authoritative, but a guard entry does not carry it, and the unmangling collides only for a module whose name contains `_dot_` (`pkg.sub_dot_mod` is aliased as `__import_pkg_dot_sub_dot_mod`, which comes back as `pkg.sub.mod` when that module is loaded too); that collision fails open, since the callers judge the module returned. A torch_package module is aliased without the prefix and comes back None, which fails closed. ## `_is_dynamo_synthesized` ```python _DYNAMO_SYNTHESIZED = ("__nested_resume_fns",) def _is_dynamo_synthesized(source): if isinstance(source, GetItemSource) and isinstance(source.index, int): source = source.base return isinstance(source, LocalSource) and source.local_name in _DYNAMO_SYNTHESIZED ``` It recognises the `__nested_resume_fns` local Dynamo passes into every generated resume function as its first parameter, a list of generated resume functions rather than a slot any config chooses, and an entry read straight off it (`__nested_resume_fns[0]`), nothing deeper: a resume function's closure cells carry the resumed frame's cell variables, so `type(__nested_resume_fns[0].__closure__[0].cell_contents).__call__`, which Dynamo mints for a callable an inner def captured, is the user's and is judged like any other value (an earlier revision walked to the source root and waived it). Its sibling `__nested_frame_values` is deliberately not covered, because it carries the live stack and locals of the frames nested INSIDE the one resuming, which pops the last entry off it for the callee it resumes (under `nested_graph_breaks=True` a callee's `act = pick()` reaches its caller's resume frame as `L['__nested_frame_values'][0][2]`, `[0]` selecting the frame and the tail a position in its values, not a key), so a guard rooted there must be judged like the local or intermediate it stands for. ## `_reads_a_builtin` ```python def _reads_a_builtin(source, value): return ( isinstance(source, DictGetItemSource) and isinstance(source.base, GlobalSource) and source.base.global_name.startswith(_BUILTINS_DICT_PREFIX) and ( isinstance(value, types.BuiltinFunctionType) or (isinstance(value, type) and bool(vars(type)["__flags__"].__get__(value) & (1 << 8))) # Py_TPFLAGS_IMMUTABLETYPE ) and _owning_module(value) == "builtins" and getattr(value, "__name__", None) == source.index ) ``` It requires the guard's source to be a `DictGetItemSource` whose base is a `GlobalSource` named `__builtins_dict__...` AND the value to be a `types.BuiltinFunctionType` or a `type` carrying `Py_TPFLAGS_IMMUTABLETYPE` AND its `__module__` to be `builtins` AND its `__name__` to equal the dict key; `_reads_a_builtin` reads `source.base` itself. A builtin parked in `self.act = abs` is a slot like any other, so the test keys on where the read comes FROM, not on who owns the value. That dict is the frame's live `builtins.__dict__`, not a table of the real builtins, so a shim's `builtins.py2_sum = sum` is a binding under it that another machine's shim can point elsewhere; the read is waived only under the builtin's own name (`IOError` and `EnvironmentError`, CPython's aliases of `OSError`, fail closed), and only for a value CPython built: `functools.wraps` copies `__module__` and `__name__` onto a Python shim installed as `builtins.sum = wraps(sum)(logged_sum)`, whose `CLOSURE_MATCH` the serializer drops, and a class statement exec'd with the builtins namespace as its globals (or handed `__module__ = "builtins"`) claims the module outright, which a bare `type` test waived; a class statement or `type()` call does not carry the flag. The flag is read through `type`'s own descriptor, so a metaclass can neither shadow it nor make the read raise, and a static type's `__module__` is derived from its C name; a builtin function's `__module__` is a writable member, though, so `builtins.getcwd = os.getcwd` plus `os.getcwd.__module__ = "builtins"` is waived, evidence rather than proof on that branch, which an advisory lint over a dropped-guard set does not defend against. Every callable in `builtins.__dict__` is one of those two kinds apart from the `_sitebuiltins` objects, instances of neither, and beside the aliases (`WindowsError` is a third on Windows) three of them fail closed: | key | why it fails closed | | --- | --- | | `IOError`, `EnvironmentError` (`WindowsError` on Windows) | aliases: `__name__` is `OSError`, not the key | | `open` | the one builtin function `builtins` does not own: `__module__` is `_io`, `io` before 3.12, so a dropped guard on one of the most mainstream builtins here is reported | | `ExceptionGroup` (3.11+) | a heap type, no `Py_TPFLAGS_IMMUTABLETYPE` | | `__loader__` | a heap type, and read under a name that is not its own as well | The exposure is narrow either way, since a registered builtin is id-matched into a `BUILTIN_MATCH` the serializer keeps and only a deregistered, polyfilled one (`sum`, `enumerate`, `all`, `any`) or such a shim reaches the dropped set the lint examines. ## `_defined_where_read` ```python def _defined_where_read(value, global_name, user_stack): if not user_stack or not isinstance(value, (type, types.FunctionType)): return False # a bound method or proxy is refused before any read if value.__qualname__ != global_name: return False # act = _impl_a if ... else _impl_b, op = Ops.op, a factory's def def compiled_as(fn, qualname): # wraps copies __qualname__ but not the code object's own name if sys.version_info >= (3, 11): return fn.__code__.co_qualname == qualname return fn.__code__.co_name == qualname.rpartition(".")[2] if isinstance(value, type): skip = ("__annotate__", "__annotate_func__") files = [] for key, attr in vars(value).items(): # unwrap staticmethod/classmethod via __func__, property via fget ... if attr.__qualname__ == f"{global_name}.{key}" and compiled_as(attr, ...): files.append(attr.__code__.co_filename) else: files = [value.__code__.co_filename] if compiled_as(value, global_name) else [] read = user_stack[0].filename # the OUTERMOST frame if not os.path.isabs(read): return False try: here = _norm(read) return any(os.path.isabs(f) and _norm(f) == here for f in files) except ValueError: # an embedded NUL, which posixpath.realpath lets through return False ``` **The name rule.** `_defined_where_read(value, global_name, user_stack)` takes the read's `GlobalSource.global_name` (not the `G['op']` spelling `GuardFilterEntry.name` keeps) and is true for a def, or through its own methods a class statement, bound under its own name whose code lives in the file that read it, the one binding the inlined-source checksum of that file covers, unlike `from impl_a import op`, which only takes a conditional import the checksum never sees; it checks the name itself rather than leaving that to the caller, and compares `__qualname__`, so `act = _impl_a if cfg.fast else _impl_b` in the reading file is a slot and so are `op = Ops.op` and a def returned by a factory, and the paths are compared normalized. The `__qualname__` is backed by the code object's own name, which `functools.wraps` copies onto a wrapper's `__qualname__` but cannot forge (`co_qualname`; before 3.11 only `co_name`, so a wrapper def named after what it wraps slips through there), so a same-file `wraps` decorator a flag turns on is a slot in both arms. Only a plain function or a class is judged: a bound method or any other object forwarding `__qualname__` and `__code__` is refused before an attribute is read, which also keeps a proxy that answers reads by raising, such as `torch.classes.<ns>`, out of the value slot. **The file comes off the code object.** The file is read off the value's code object rather than off `__module__`, because `functools.wraps` copies `__module__` along with `__name__` and `__qualname__`: ```python op = torch.compile(op) # behind a flag: claims the reader's module, code lives in eval_frame.py -> not waived @torch.no_grad() # an unconditional cross-file decorator on a same-file def -> not waived either def op(x): ... cached = functools.lru_cache(op) # no code object at all -> not waived ``` The object does not tell the flag shape from an unconditional cross-file decorator, so a same-file def under `@torch.no_grad()` is not waived either and the risky-drop lint reports it. Anything else without a code object, such as a `functools.lru_cache` wrapper, which claims the reader's module the same way, is not waived. **A class is judged by its own methods.** A class has no code object, and its `__module__` is no better: `namedtuple` and `type()` stamp it from the calling frame (`make_dataclass` does so from Python 3.12) under a BARE `__qualname__` (a def or class statement inside the factory would carry `factory.<locals>.`), so a `Point = namedtuple("Point", "x y")` in the reader looks exactly like a class statement; the frame stamped is the caller's, so the collision needs a factory called from the reading file, `lib.make_point()` coming back stamped `lib`. Its methods can tell: a class statement compiles its defs in its own file under its own `__qualname__` prefix, so a class is waived when at least one function in its own `__dict__`, stored under key `k` with `__qualname__` `Cls.k` (a staticmethod or classmethod unwrapped through `__func__` and a property through `fget`, by type rather than by `getattr`, since a class attribute can be a proxy such as `torch.classes.<ns>` that answers any attribute read by raising; a `cached_property` keeps its function under `.func` and does not count), was compiled in the reading file. ```python class Ops: # waived: op compiled here under Ops.op @staticmethod def op(x): return x class Marker: pass # fails closed: no def of its own Point = collections.namedtuple("Point", "x") # bare __qualname__ "Point", methods compiled in collections -> not waived type("Point", (), {"area": _area}) # a factory fed a same-file def: qualname "_area", not "Point.area" -> not waived from mypkg.impl import Point; Point.extra = _extra # attached afterwards keeps its bare qualname -> not waived Point.norm = functools.wraps(Point.norm)(_norm) # forges "Point.norm", code object still named "_norm" -> not waived ``` A function attached afterwards keeps its bare qualname, and one attached through `functools.wraps` keeps its code object's own name, so a class imported from another file that the reader extends or patches is refused, as is a factory fed same-file methods (`type(name, bases, {"area": _area})`, `make_dataclass(name, cfg.fields, namespace={"area": _area})`), and `class Marker: pass` fails closed; so does a class statement whose only functions are generated: a fields-only `@dataclass`'s and a `NamedTuple`'s are defs of a factory (dataclasses' `__create_fn__`, `namedtuple`), so their code objects' own qualname carries the factory's `<locals>.` prefix (on 3.10, where only `co_name` exists, the `<string>` or stdlib file they compile in refuses them instead), and an `Enum`'s arrive in the subclass `__dict__` under `Enum.` qualnames the key rule refuses, so a plain config dataclass read as a global is reported. The one function the compiler itself puts in a class `__dict__`, the PEP 649 annotate function Python 3.14 stores for an annotated class body, compiles in the reading file, but under key `__annotate_func__` with `__qualname__` `Cls.__annotate__`, so the key rule refuses it and the verdict on a config dataclass is the same on every version; the scan also skips both annotate keys outright, against a version that stores the function under its own name. **Only absolute filenames compare.** A `co_filename` is not always a path: an `exec` records `<string>` and a REPL `<stdin>`, and `realpath` resolves either against the cwd, so an ungated comparison made every `<string>` compilation one file and waived a def exec'd under it the moment the reading frame was exec-generated too (on 3.10 a fields-only dataclass as well, whose `__init__` compiles in `<string>` under a `co_name` that cannot tell it from a class statement's def). Only absolute filenames on both sides are compared (the gate `_norm` documents and `_classify_file` applies to a recorded `__file__`); a pseudo-filename, a relative spelling and an embedded NUL, which makes `posixpath.realpath` raise, fail closed. **The frame read.** The filename compared is that of the OUTERMOST frame in the guard's `user_stack`. That frame is the one being compiled, whose globals a bare `GlobalSource` denotes (`InliningInstructionTranslator._load_global` mints one only when the inlined frame's globals are the root's, and otherwise reads through an `__import_` alias or an `___unnamed_scope` dict entry); the stack itself is stamped in `GuardsSet.add` with the inlining stack at the moment the guard is installed, which for a lazily realized global is the point of first use, so the innermost frame can be a helper inlined from another file, and reading the file off it would waive `from b import op` whenever `op` is first used inside a helper inlined from `b`. **The known gap.** What the predicate cannot see, and its docstring says so, is a same-name fork inside the reading file (`try: from x import impl as op` / `except ImportError: def op`, or a class statement under the same `if`), which binds a different def per machine under one checksum; that is the conditional-bind KNOWN GAP `_is_risky_drop` records. ## Tests Each predicate is pinned on hand-built sources by a test of its own, except `_defined_where_read`, which gets six `test_defined_where_read_*` methods, one per shape family so a premise that holds only on some CPython versions cannot mask another family's rows. - `test_reads_a_builtin_keys_on_where_the_read_comes_from` pins `len` read through the builtins dict as waived, a builtin in a slot, a user table keyed `len`, the same table read off a slot (`self.act_fns["len"]`, the unnarrowed source the lint hands over, refused rather than read as a global) and user code injected into builtins as not, and a `functools.wraps(sum)` shim under the `sum` key as not (the test asserts `(__module__, __name__) == ("builtins", "sum")` first) while `sum` under its own key is and so is `int`, a type passing the CPython-built conjunct. The remaining conjuncts each get rows of their own: `IOError` and `EnvironmentError` under their own keys (CPython-built, but named `OSError`), `open` under its own key (a builtin function named `open`, but owned by `io` or `_io` depending on the version and never by `builtins`, so the `__module__` conjunct is what refuses it; the test asserts those two facts first), a user exception class installed into builtins under its own name and a class exec'd with the builtins namespace as its globals (the test asserts it claims `__module__ == "builtins"` first; both are heap types, so the flag is what refuses them), a class whose metaclass shadows `__flags__` with the immutable bit while claiming `builtins` (refused, since the flag is read through `type`'s descriptor) and one whose metaclass makes the `__flags__` read raise (refused without raising), all not waived, and every type in `builtins.__dict__` read under its own name waived except `ExceptionGroup`, the one heap type there read under its own name (`__loader__` is a heap type too, and the test pins that its `__name__` is not the key). - `test_dynamo_synthesized_covers_only_the_resume_function_list` pins the list and its entry as synthesized and, past the entry, the resume function's `__closure__`, a cell's contents and `type(...).__call__` off it as not, beside `__nested_frame_values`, a same-named global and an ordinary local. - `test_alias_module_and_owning_module` pins `__import_torch_dot_nn_dot_functional` to `torch.nn.functional` and as None a user global whose tail past the prefix length names a module (`imported_torch`), an unknown tail and a torch_package alias, which `import_source` mints without the prefix, and the `_dot_` collision, `__import_mypkg_dot_sub_dot_mod` (the alias of `mypkg.sub_dot_mod` as much as of `mypkg.sub.mod`) coming back as the loaded `mypkg.sub.mod`; `_owning_module` answers None for an int and for a `__module__` that is not a string. - `test_defined_where_read_needs_the_name_and_the_file` pins the name and file rules: a same-file def under its own name is waived, also through another spelling of the path and on a two-frame stack whose inner frame is torch/nn/functional.py (where `F.silu` is not), and not under another name, from another file, with no stack, or for `F.silu` and an int; a staticmethod extracted under its own name and a def returned by a factory are not waived (`__qualname__` tells); a module-level def exec'd under this file's name is waived, as the documented gap. - `test_defined_where_read_takes_the_file_off_the_code_object` pins the `torch.compile` wrapper (the test asserts it claims this module first), a `functools.lru_cache` wrapper and a `@torch.no_grad()`-decorated def as not waived, a same-file conditional `functools.wraps` decorator as waived with the flag off (the def itself comes back) and not with it on (the wrapper forges `__qualname__`; its code object is named `wrapper`), and a bound method of the same-file def and a namespace forwarding its `__qualname__` and `__code__` as refused by type before either is read. - `test_defined_where_read_judges_a_class_by_its_own_methods` pins the test class itself as waived when read from this file and not from another, and `torch.nn.Linear` as not; a same-file class with one staticmethod is waived, so is one with one classmethod (both the `__func__` arm) and one whose only def is a `@property` (the `fget` arm), while one whose only def is a `functools.cached_property` is not, nor is a same-file class with no method of its own, a fields-only `@dataclass` or a `NamedTuple` (their generated defs carry the factory's `<locals>.` in `co_qualname`; on 3.10 the `<string>` or stdlib file they compile in refuses them) or an `Enum` (its functions carry `Enum.` qualnames the key rule refuses); and an `nn.Module` subclass holding `torch.classes.<ns>` as a class attribute, which the test first shows raises `RuntimeError` on an attribute read (`Model.ns.__func__`), is judged like any other class (waived from this file, not from another) instead of raising out of the predicate, the proxy itself handed over as the value is refused by type, and the namespace `torch.classes` fabricated for that read is removed from it again in a cleanup. - `test_defined_where_read_refuses_a_class_minted_for_the_file` pins a `namedtuple` (the test asserts it claims this module under a bare `__qualname__` first), a `make_dataclass` (bare `__qualname__` asserted; the module is stamped only from 3.12) and a `type()` class as not waived, nor a `type()` class handed a same-file def in its namespace, under another key or under the def's own name (a bare qualname either way, so the class half of the rule, the missing `Point.` prefix, is what refuses both); the key half gets its own pair, a same-file class statement's method handed to a `type()` class of the same `__qualname__`, waived under its own key `m` and not borrowed under `other`; nor is a class compiled under torch/nn/functional.py's name (the imported-class shape) waived with a same-file function attached afterwards or with a method replaced through `functools.wraps` (the test asserts the forged `Point.norm` qualname beside the code object's own `_norm` name first). - `test_defined_where_read_skips_the_compiler_annotate_function` pins the fields-only `@dataclass` as not waived and, on 3.14, first asserts what the compiler stored beside its generated methods: key `__annotate_func__`, qualname `Cfg.__annotate__` on the function and on its code object, compiled in this file; that is replayed on every version through a `type()` class handed a same-file function under that key, the qualname stamped on the function and on its code object as a class statement's def carries it (not waived), beside a control row with the same function under an ordinary key and matching qualname (waived, so the replay is the shape a class statement produces) and the two rows that pin the `skip`, the function under `__annotate__` or `__annotate_func__` with a `Cfg.<key>` qualname (not waived). - `test_defined_where_read_refuses_a_pseudo_filename` reads a def exec'd under `<string>` (the test asserts its `co_filename` first) from a `<string>` frame, the row that pins the gate on every version (a fields-only `@dataclass` collides only on 3.10, where `co_name` cannot refuse it first), and a same-file def from a relative frame filename (`os.path.relpath(__file__)`, which the test asserts resolves to this file), the same def with that relative spelling as its own `co_filename` read from an absolute frame, from a frame filename with an embedded NUL and with a NUL in its own `co_filename`, all not waived and none raising. - `test_minted_global_names_match_dynamo` pins the names the predicates lean on (the two prefixes, spelled in aot_compile.py, and the two nested-resume locals) against the code that mints them, through a real compile: a `__builtins_dict__` read, an `__import_` alias, and, under `nested_graph_breaks=True` (the harness runs every test with it on; the config default is off), the two locals every generated resume function takes and roots a guard at, judged on the sources Dynamo actually minted: off `__nested_resume_fns` exactly the list and its `[0]` entry are synthesized, while `type(__nested_resume_fns[0].__closure__[0].cell_contents).__call__`, the guard on a callable the resumed frame's inner def captured, is present and is not; nothing rooted at `__nested_frame_values` is. ## What comes next Nothing calls these yet; `_module_namespaces` and `_is_risky_drop`, which do, follow once the library-module classifier is in. Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_reads_a_builtin -k test_dynamo_synthesized -k test_alias_module -k test_defined_where_read -k test_minted_global_names python test/dynamo/test_precompile_package.py lintrunner torch/_dynamo/precompile_package.py torch/_dynamo/aot_compile.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in 0dbac14 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197962 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…y its resolved path (#197428) (#197963) **Problem.** Given the roots from #197262, the lint still has to turn one module into a verdict (shipped with torch or the stdlib, shipped elsewhere, or no evidence), and a naive `__file__` read runs user code and misclassifies relative, driveless or NUL-bearing paths and frozen apps. **Fix.** Add `_classify_file`, which resolves a path against the roots behind explicit None gates and a cache, and `_located`, which reads `__file__`, `__loader__` and `__spec__` out of the module dict without triggering `__getattr__` and trusts the builtin and frozen importers by identity. **Summary.** The risky-drop lint that later commits add waives a dropped identity guard when the value it guarded is owned by torch or the standard library, and the root finders added two commits earlier (`_stdlib_roots`, `_install_roots`, `_torch_roots`) say where each of those lives; this commit adds the two helpers that turn a module into a verdict against those roots, and the consumer, `_is_library_module`, follows in the next commit. `_classify_file(file, stdlib)` answers for one `__file__` -- shipped here (True), shipped elsewhere (False), or no evidence (None) -- judging the path `_norm` resolves against the torch roots (`stdlib=False`) or the stdlib roots minus the install roots (`stdlib=True`), with None reserved for a path that cannot be resolved (relative, driveless on Windows, or carrying a NUL) and for any stdlib question in a frozen app, where the bundle root holds the stdlib and every third party alike. `_located(module, name, stdlib)` answers the same three ways for a `sys.modules` entry, reading `__file__`, `__loader__` and `__spec__` out of the module DICT through `object.__getattribute__` so that no PEP 562 `__getattr__`, `_LazyModule` body or user `__eq__` runs, letting a placed `__file__` decide first and only then trusting `BuiltinImporter` or `FrozenImporter` by identity under the caller's full dotted `name`. Every read that remains user code is inside one `try` that answers None, so nothing escapes a lint, and `_classify_file` is `functools.cache`d on the (file, flag) pair because everything else it reads is fixed for the process while the module a name resolves to is not. Two tests pin every arm, gate and ordering, each row against a named mutation, on paths spelled so they cannot pre-exist and with the Windows path module replayed so the driveless and NUL gates hold on every platform. ## The two helpers ```python @functools.cache def _classify_file(file: str, stdlib: bool) -> bool | None: # True: shipped here; False: shipped elsewhere; None: no evidence def _located(module: object, name: str, stdlib: bool) -> bool | None: # the same three answers for a sys.modules entry, which need not be a module ``` `_is_library_module` refuses None for a top-level name and keeps the package's waiver for an inner one, so an unplaceable inner `__file__` counts as no evidence there. ## `_classify_file`: the gates ```python driveless = sys.platform == "win32" and not os.path.splitdrive(file)[0] if driveless or not os.path.isabs(file): return None # would resolve against the wrong cwd if "\x00" in file: return None # no file has one; see gh-106242 path = _norm(file) ``` A relative path is None, because `realpath` would resolve it against the process cwd rather than the one it was recorded under (on Windows before 3.13 `ntpath.isabs` accepts a driveless `\Lib\x.py`, the stdlib's own LEGACY BUG comment, so the gate also asks `splitdrive` for a drive there). So is a path with an embedded NUL, which no file has: `posixpath.realpath` raises `ValueError` on one from `os.lstat`, but from 3.11.5/3.12 on (gh-106242) `ntpath.realpath` swallows that and returns the path unresolved, NUL intact, and `_within` would then match the prefix before the NUL and waive the file, so the gate is an explicit check ahead of `realpath` rather than a catch around it. None comes from those two gates and from the frozen-app gate below. Every arm judges the path `_norm` returns, never the string as recorded: a venv or symlink-farm `__file__` must be placed by where the file is, not by where its link sits. ## `_classify_file`: the torch arm ```python if not stdlib: return _within(path, _torch_roots()) # never None past the gates ``` With `stdlib=False` the verdict is whether the path lies under a torch root and is never None: with no torch root (a frozen torch) every path is elsewhere, which `_is_library_module` never reaches because it waives torch names before asking. The install-root exclusion below is the stdlib arm's alone: torch ships platform wheels, `Root-Is-Purelib: false`, so a pip-installed torch lies under platlib. The torch arm is not gated on `sys.frozen` either: its root is torch's own package directory, taken from where this file sits (`_torch_roots`), so in a bundle nothing outside torch lies under it, where the stdlib root is the bundle root itself. ## `_classify_file`: the stdlib arm ```python _INSTALL_DIR_NAMES = frozenset({"site-packages", "dist-packages"}) if getattr(sys, "frozen", False): return None if _within(path, _install_roots()): return False for root in _stdlib_roots(): # sorted: the first match is the outermost if _within(path, (root,)): below = path[len(root) + 1 :].lower().split(os.sep) return _INSTALL_DIR_NAMES.isdisjoint(below) return False ``` With `stdlib=True` the path must be under a stdlib root and NOT under an install root, since `purelib` nests inside `stdlib` in a conda layout and inside `platstdlib` in a venv, so the exclusion is what does the work. A `site-packages` or `dist-packages` component (`_INSTALL_DIR_NAMES`, compared case folded: `normcase` is the identity on posix and a macOS filesystem is case-insensitive, so a mis-cased `Site-Packages` entry on `sys.path` would otherwise slip past both the install roots and this check) BELOW the stdlib root the file was found under also refuses, a cheap belt-and-braces check for an install directory none of the roots name, matched at any depth below the root rather than on the whole path, so that an interpreter bundled inside another environment's site-packages keeps its own stdlib (the roots are sorted, so of nested roots the outermost is matched, the part below it is the longest and the check the strictest). The match is on `os.sep`, not `/`, since `_norm` yields the platform's separator. ## Frozen apps In a frozen app (`sys.frozen` truthy, as `multiprocessing.spawn` reads it: PyInstaller and cx_Freeze set the flag to True, py2exe to a string, `"console_exe"`, `"windows_exe"` or `"dll"`) the stdlib arm answers None instead: such a bundle holds the stdlib and every third party under one root with no `site-packages` component between them, and PyInstaller's `_fixup_frozen_stdlib` names that root in `sys._stdlib_dir` and in the `__file__` it gives the CPython-frozen modules, so every bundled file would lie under a stdlib root and a bundled module named after a stdlib module (a `graphlib` or `dataclasses` backport, an app module that shadows one) would be waived as interpreter-owned, the wrong-True direction. None rather than False so that `_located` still reads the loader: the modules CPython itself freezes or links in keep their waiver through the `FrozenImporter` and `BuiltinImporter` arms, and the rest of the stdlib is merely unwaived, lint noise and not a wrong drop. ## The cache The function is `functools.cache`d on the (file, flag) pair rather than on a module name: everything else it reads, the roots and `sys.frozen`, is fixed once the process is running, so the answer for a path never changes, while the module a name resolves to can (a test that patches either clears the cache on both sides of the patch). ## `_located`: reading the module dict ```python try: attrs = object.__getattribute__(module, "__dict__") # not getattr, not module.__dict__ file = attrs.get("__file__") if isinstance(file, str): verdict = _classify_file(file, stdlib) if verdict is not None: return verdict # a placed file decides loader = attrs.get("__loader__") if loader is None: loader = getattr(attrs.get("__spec__"), "loader", None) if loader is importlib.machinery.BuiltinImporter: return name in sys.builtin_module_names if loader is importlib.machinery.FrozenImporter: return importlib.machinery.FrozenImporter.find_spec(name) is not None except Exception: return None return None ``` `_located` is typed on `object` because a `sys.modules` entry need not be a module. None covers no `__file__` and no known loader, a `__file__` that `_classify_file` cannot place (relative, non-string, NUL, or any stdlib path in a frozen app) with no known loader, and a read that raised. It reads `__file__` out of the module DICT, not through `getattr`: a class attribute is not evidence about where the module came from (torch.ops is a `ModuleType` subclass carrying the class's relative `"_ops.py"` as its `__file__`, which a dict read does not see), and on an entry whose dict is missing one of the three dunders read here `getattr` would fall through to a PEP 562 module `__getattr__`, user code a lint must not run (a raise would be caught, but not its side effects). The dict itself is read with `object.__getattribute__`, not the module's: `importlib.util.LazyLoader` leaves a `_LazyModule` in `sys.modules` whose `__getattribute__` executes the module body on ANY attribute read, `__dict__` included, so a plain `getattr(module, "__dict__")` would import the module the lint was only inspecting (and if the body raised, or the name was rebound in `sys.modules` meanwhile, leave it half-initialised behind the catch); the lazy module's dict already carries the seeded `__file__`, `__spec__` and `__loader__`, so the read through `object` loses nothing. `sys.modules` can hold any object, so the reads that remain user code, a `__dict__` descriptor defined on the type and the spec's `loader` on a hand-rolled spec, are caught, answering None, as is the `AttributeError` that `object`'s read itself raises for a slotted entry with no `__dict__` (a `__getattr__` on it is never consulted), and since the `try` also spans the `_classify_file` call and the loader arms, a raise out of the classifier's own gates or out of `FrozenImporter.find_spec` (an `ImportError` on an excluded or invalid frozen table entry) lands there as None too rather than escaping a lint. A `__file__` that is not a string (a namespace package sets None) is skipped by an `isinstance` gate, and like a relative one it is evidence in neither direction, so the loader is still read (`isabs` accepts `bytes` and a `PathLike`, so the gate is what keeps them out; unguarded they would raise from the NUL check into the same catch). ## `_located`: the file decides before the loader is read A located file decides, and only then is the loader read, an order that matters: with importlib on disk, `importlib._bootstrap` carries a stdlib `__file__` (importlib/__init__.py assigns it, inside a `try/except NameError` that a frozen importlib skips) next to a `FrozenImporter` whose table knows the module only as `_frozen_importlib`, so with the arms swapped it would lose its waiver; with importlib frozen too there is no `__file__`, the frozen arm answers False under the dotted name and the waiver is lost either way, a fail-closed corner that costs lint noise, not a wrong drop. ```python bootstrap = types.ModuleType("importlib._bootstrap") bootstrap.__file__ = os.path.join(stdlib_root, "importlib", "_bootstrap.py") bootstrap.__loader__ = importlib.machinery.FrozenImporter # find_spec("importlib._bootstrap") is None pp._located(bootstrap, "importlib._bootstrap", True) # True: the file decides; loader-first would answer False ``` ## `_located`: the loader arms The loader (`__loader__` in the dict, else the spec's: a `__loader__` in the dict skips the `spec.loader` read, the only user-code half of this, and is compared with None rather than for truth, so no `__bool__` of user code runs; a hand-made `ModuleType` carries the `None` that `ModuleType.__init__` seeds and falls through, where an imported module's dict carries `spec.loader`, copied in by `_init_module_attrs`) is read, not `spec.origin`: `BuiltinImporter.find_spec` and `FrozenImporter.find_spec` both call `spec_from_loader(fullname, cls, origin=cls._ORIGIN)` (the frozen one adds `is_package`, then fills in `loader_state` and the package's search path) and `_init_module_attrs` copies `spec.loader` into `__loader__`, so the origin string never says anything the loader class does not, and the class is the stronger signal. Both tables are looked up under the caller's `name`, the `sys.modules` key `_is_library_module` was asked about, not the module's own `__name__` (the entry for `os.path` is `posixpath`). Both arms match the loader class by identity, not equality, for the same reason the dict is read through `object`: under `==` a `__loader__` whose `__eq__` answers true for anything would take the waiver. `BuiltinImporter` is trusted only if the FULL dotted `name` is in `sys.builtin_module_names` (the inittab is keyed on it, so a fabricated `sys.sub` is refused), `FrozenImporter` only if the frozen table has the name (`zipimport`, not `zipimport.sub`), and a module with neither (namespace package, exec'd in memory with no loader) is None; a REPL, `-c` or stdin `__main__` is not one of these, since the interpreter seeds `BuiltinImporter` as its `__loader__`, so it is False, `__main__` not being in the inittab. Both arms answer on the name alone whichever roots `stdlib` selects: built-in and frozen precede the path finder on `sys.meta_path`, so on import no file on `sys.path` is reachable under such a name, and a module compiled into the interpreter has its code fixed by the interpreter binary, which is what either waiver needs. The `stdlib=False` case is not the stdlib's `sys` asked under the wrong flag (`_is_library_module` routes a name to a flag by its top component) but an embedding that registers `torch._C` through `PyImport_AppendInittab` while torch's Python files stay on disk, so `_torch_roots` is non-empty and torch is not waived on its name; in an ordinary build `torch._C` is an extension module and not in `sys.builtin_module_names`. A spec assigned straight into `sys.modules` is taken at its word. ## Behaviour pinned by the tests ```python from torch._dynamo import precompile_package as pp stdlib_root = sysconfig.get_paths()["stdlib"] pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True) # True pp._classify_file(torch.__file__, False) # True: the torch arm reads the torch roots pp._classify_file(torch.__file__, True) # False: torch lies under no stdlib root, or under an install root pp._classify_file(os.path.join(stdlib_root, "torch", "__init__.py"), False) # False: the stdlib dir itself is never a pip target, so no torch root holds it pp._classify_file("graphlib.py", True) # None: relative pp._classify_file("graphlib.py", False) # None: the gates precede the flag split pp._classify_file(os.path.join(stdlib_root, "graph\x00lib.py"), True) # None: embedded NUL, on every platform platlib_torch = os.path.join(sysconfig.get_paths()["platlib"], "torch") pp._classify_file.cache_clear() # in a wheel install the next file IS torch.__file__, judged above with mock.patch.object(pp, "_torch_roots", return_value=(pp._norm(platlib_torch),)): pp._classify_file(os.path.join(platlib_torch, "__init__.py"), False) # True: the torch arm is exempt from the install-root exclusion for flag in (True, "console_exe"): # a frozen app: PyInstaller and cx_Freeze set True, py2exe a string pp._classify_file.cache_clear() with mock.patch.object(sys, "frozen", flag, create=True): pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True) # None: the bundle root holds the stdlib and third parties alike pp._classify_file(torch.__file__, False) # True: the torch arm keeps torch's own package directory pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), False) # False: and that root holds nothing outside torch pp._classify_file.cache_clear() pp._classify_file(os.path.join(stdlib_root, "graphlib.py"), True) # True again: the answer changed with sys.frozen, hence the clear import ntpath with mock.patch.object(sys, "platform", "win32"), mock.patch.object(os, "path", ntpath), mock.patch.object(os, "sep", "\\"), mock.patch.object(pp, "_stdlib_roots", return_value=(r"c:\python312\lib",)), mock.patch.object(pp, "_install_roots", return_value=()): pp._classify_file(r"\Lib\graphlib.py", True) # None: driveless, so resolved against the current drive pp._classify_file("C:\\Python312\\Lib\\graphlib.py\x00C:\\evil\\evil.py", True) # None: without the gate ntpath.realpath returns it unresolved and it lies under the root pp._classify_file(r"c:\python312\lib\vendored\site-packages\graphlib.py", True) # False: the part below the root is split on os.sep, so the name is seen with mock.patch.object(pp, "_install_roots", return_value=()): pp._classify_file(os.path.join(stdlib_root, "vendored", "site-packages", "g.py"), True) # False: _INSTALL_DIR_NAMES alone, two components below the root pp._classify_file(os.path.join(stdlib_root, "vendored", "dist-packages", "g.py"), True) # False: same pp._classify_file(os.path.join(stdlib_root, "vendored", "Site-Packages", "g.py"), True) # False: case folded pp._classify_file(os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py"), True) # True: nothing installed there with mock.patch.object(pp, "_stdlib_roots", return_value=()): pp._classify_file(os.path.join(stdlib_root, "os.py"), True) # False: under no stdlib root at all pp._classify_file.cache_clear() with mock.patch.object(pp, "_install_roots", return_value=(pp._norm(os.path.join(stdlib_root, "vendored")),)): pp._classify_file(os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py"), True) # False: the install-root exclusion alone tmp = tempfile.mkdtemp() # a tree of its own: a real <stdlib>/site-packages is a symlink out of the stdlib on some layouts bundled = os.path.join(tmp, "site-packages", "runtime", "lib") # a stdlib that itself sits under site-packages with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(bundled),)): pp._classify_file(os.path.join(bundled, "graphlib.py"), True) # True: site-packages ABOVE the stdlib root does not count pp._classify_file(os.path.join(bundled, "site-packages", "graphlib.py"), True) # False: below it does pp._classify_file.cache_clear() with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(tmp), pp._norm(bundled))): pp._classify_file(os.path.join(bundled, "graphlib.py"), True) # False: of nested roots the outermost is matched pp._classify_file.cache_clear() with mock.patch.object(pp, "_install_roots", return_value=()), mock.patch.object(pp, "_stdlib_roots", return_value=(pp._norm(tmp),)): pp._classify_file(os.path.join(tmp, "site-packages", os.pardir, "g.py"), True) # True: judged after _norm resolves it, not as recorded ``` ```python module = types.ModuleType("graphlib") module.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py") pp._located(module, "graphlib", True) # False: a placed file decides either way module.__file__ = os.path.join(stdlib_root, "graphlib.py") pp._located(module, "graphlib", True) # True on_disk = types.ModuleType("torch") on_disk.__file__ = torch.__file__ pp._located(on_disk, "torch", False) # True: the flag reaches the file arm (the production torch shape) pp._located(on_disk, "torch", True) # False class Shadow(types.ModuleType): __file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py") pp._located(Shadow("graphlib"), "graphlib", True) # None: a class attribute is not in the module dict pp._located(torch.ops, "torch.ops", False) # None: same shape, the real one (a canary: a getattr read would answer None too) raising = types.ModuleType("graphlib") raising.__getattr__ = mock.Mock(side_effect=RuntimeError) del raising.__spec__, raising.__loader__ # ModuleType seeds both into the dict pp._located(raising, "graphlib", True) # None, and __getattr__ was not called for __file__, __spec__ or __loader__ eager = mock.Mock(**{"create_module.return_value": None}) wrapped = importlib.util.LazyLoader(eager) lazy_spec = importlib.util.spec_from_file_location("graphlib", os.path.join(stdlib_root, "site-packages", "graphlib.py"), loader=wrapped) lazy = importlib.util.module_from_spec(lazy_spec) wrapped.exec_module(lazy) # now a _LazyModule: any attribute read runs eager.exec_module pp._located(lazy, "graphlib", True) # False, and eager.exec_module was not called pp._located(types.ModuleType("graphlib"), "graphlib", True) # None: no file, no spec odd = types.ModuleType("graphlib") odd.__file__ = 42 pp._located(odd, "graphlib", True) # None: not a path class Proxy: # a non-module sys.modules entry __slots__ = () def __getattr__(self, attr): raise RuntimeError(attr) pp._located(Proxy(), "graphlib", True) # None: object's __dict__ read raises AttributeError on a slotted entry; caught, __getattr__ never consulted odd.__spec__ = Proxy() pp._located(odd, "graphlib", True) # None: so is spec.loader odd.__file__ = os.path.join(stdlib_root, "graphlib.py") pp._located(odd, "graphlib", True) # True: a placed file decides, the loader is never read spec_poisoned = types.ModuleType("sys") spec_poisoned.__spec__ = Proxy() spec_poisoned.__loader__ = importlib.machinery.BuiltinImporter pp._located(spec_poisoned, "sys", True) # True: __loader__ is read first, so the spec never is bootstrap = types.ModuleType("importlib._bootstrap") bootstrap.__file__ = os.path.join(stdlib_root, "importlib", "_bootstrap.py") bootstrap.__loader__ = importlib.machinery.FrozenImporter # the real module's shape; FrozenImporter.find_spec("importlib._bootstrap") is None pp._located(bootstrap, "importlib._bootstrap", True) # True: the file decides before the loader is read shadow_sys = types.ModuleType("sys") shadow_sys.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib.py") shadow_sys.__loader__ = importlib.machinery.BuiltinImporter pp._located(shadow_sys, "sys", True) # False: the converse, an installed file under a built-in name odd_sys = types.ModuleType("sys") odd_sys.__file__ = 42 odd_sys.__loader__ = importlib.machinery.BuiltinImporter pp._located(odd_sys, "sys", True) # True: a __file__ that cannot be placed is no evidence, so the loader is read relative = types.ModuleType("zipimport") relative.__file__ = "zipimport.py" relative.__loader__ = importlib.machinery.FrozenImporter pp._located(relative, "zipimport", True) # True: same for a relative one frozen_zip = types.ModuleType("zipimport") # frozen on every version; os only from 3.11 on (gh-45020) frozen_zip.__file__ = os.path.join(stdlib_root, "zipimport.py") frozen_zip.__loader__ = importlib.machinery.FrozenImporter with mock.patch.object(sys, "frozen", True, create=True): pp._located(frozen_zip, "zipimport", True) # True: in a frozen app the file arm is no evidence, so the loader decides pp._located(sys, "sys", True) # True: built in pp._located(sys, "sys.sub", True) # False: the caller's name is looked up, not the module's __name__ zipimport_by_name = types.ModuleType("zipimport") zipimport_by_name.__loader__ = importlib.machinery.FrozenImporter pp._located(zipimport_by_name, "zipimport.sub", True) # False: same in the frozen arm sub = types.ModuleType("sys.sub") sub.__spec__ = importlib.machinery.ModuleSpec("sys.sub", importlib.machinery.BuiltinImporter, origin="built-in") pp._located(sub, "sys.sub", True) # False: the inittab is keyed on the full dotted name frozen = importlib.machinery.FrozenImporter zipimport_frozen = types.ModuleType("zipimport") zipimport_frozen.__spec__ = importlib.machinery.ModuleSpec("zipimport", frozen, origin="frozen") pp._located(zipimport_frozen, "zipimport", True) # True: the frozen table has zipimport zipimport_sub = types.ModuleType("zipimport.sub") zipimport_sub.__spec__ = importlib.machinery.ModuleSpec("zipimport.sub", frozen, origin="frozen") pp._located(zipimport_sub, "zipimport.sub", True) # False: keyed on the full dotted name, not its top component graphlib_frozen = types.ModuleType("graphlib") graphlib_frozen.__spec__ = importlib.machinery.ModuleSpec("graphlib", frozen, origin="frozen") pp._located(graphlib_frozen, "graphlib", True) # False: a frozen spec under a name the frozen table does not have with mock.patch.object(frozen, "find_spec", side_effect=ImportError): pp._located(zipimport_by_name, "zipimport", True) # None: find_spec raises on an excluded or invalid frozen table entry, and nothing escapes _located lying_eq = types.ModuleType("sys") lying_eq.__loader__ = mock.ANY # a stdlib object whose __eq__ answers true for anything pp._located(lying_eq, "sys", True) # None: the arms match the loader class by identity by_loader = types.ModuleType("sys") by_loader.__loader__ = importlib.machinery.BuiltinImporter pp._located(by_loader, "sys", True) # True: __loader__ alone in the dict, no spec by_loader = types.ModuleType("zipimport") by_loader.__loader__ = frozen pp._located(by_loader, "zipimport", True) # True: same, frozen pp._located(by_loader, "zipimport", False) # True: both arms answer under either flag by_loader = types.ModuleType("sys") by_loader.__loader__ = importlib.machinery.BuiltinImporter pp._located(by_loader, "sys", False) # True: same, built in with mock.patch.object(sys, "builtin_module_names", (*sys.builtin_module_names, "torch._C")): embedded = types.ModuleType("torch._C") embedded.__loader__ = importlib.machinery.BuiltinImporter pp._located(embedded, "torch._C", False) # True: the torch shape, an embedded torch._C with torch's Python files on disk ``` ## Tests Both tests call `_clear_root_caches` first, like every other root test, and clear the `_classify_file` cache on entry and on cleanup: its keys are stdlib-rooted paths that other tests judge under patched roots. **`test_classify_file_places_a_path_by_the_roots_it_lies_under`** pins every arm of `_classify_file` on paths spelled relative to sysconfig's `stdlib` (the stdlib dir itself is never a pip target, so no torch root holds the fake torch path): - the stdlib True, and the torch arm reading the torch roots and not the stdlib ones; - the torch arm exempt from the install-root exclusion: with `_torch_roots` patched to `<platlib>/torch`, after asserting that `<platlib>/torch/__init__.py` lies under a real install root and clearing the cache, that file is True. A checkout's `torch.__file__` is under no install root, so the plain torch row cannot see this, while in a wheel install that file IS `torch.__file__`, and without the clear the row would only re-read the torch-arm row's cached verdict; - the frozen-app None: with `sys.frozen` patched to True and then to py2exe's `"console_exe"`, a stdlib-rooted file under `stdlib=True` is None while `torch.__file__` under `stdlib=False` stays True and that stdlib file under `stdlib=False` is False, the torch arm still telling torch from the rest of a bundle. The cache is cleared before each flag and after the block, and the stdlib file is then re-read as True, the row that shows the answer for a path changing with `sys.frozen` and so what the clears are for; - the relative None under both flags (the gates precede the flag split) and the embedded-NUL None on every platform; - the driveless Windows spelling, the NUL path under a Windows stdlib root and an installed file two components below one, with `sys.platform`, `os.path` and `os.sep` patched to `win32`, `ntpath` and a backslash and the root finders patched to `c:\python312\lib` and `()`, so the rows run on every platform. The second replays what gh-106242 does: without the gate `ntpath.realpath` returns the path unresolved, `_within` matches the prefix before the NUL, and the file is waived. The third is the only row that reaches `_INSTALL_DIR_NAMES` with a non-posix separator, which is what splitting the part below the root on `os.sep` rather than `/` is for; - both `_INSTALL_DIR_NAMES` refusing with `_install_roots` patched to `()`, and a mis-cased `Site-Packages` refusing on every platform (case folded, since `normcase` only folds on Windows); - a stdlib-rooted file under no stdlib root at all (both root finders patched to `()`) refused, which pins the terminal False without depending on where torch is installed (in a wheel or conda install `torch.__file__` lies under an install root and returns from the exclusion instead); - one file under a nested `vendored` directory judged twice, with the cache cleared in between: stdlib with nothing installed there, third party once that directory is an install root; - `_INSTALL_DIR_NAMES` scoped below the root: with `_stdlib_roots` patched to a root that itself sits under `site-packages`, a file directly under it is stdlib and one under a further `site-packages` is not, and with both that root and the one above it patched in, the same file is refused, since the outermost root is the one matched; - that judging happens after `_norm`: a path naming `site-packages` and then `os.pardir` is stdlib, since it resolves to a plain file directly under the root. The rows that turn on where an install directory sits relative to a root are spelled on paths that cannot pre-exist -- a `vendored` component under sysconfig's `stdlib`, and a `TemporaryDirectory` for the bundled-interpreter fixture -- because a real `<stdlib>/site-packages` is a symlink out of the stdlib on some layouts (a relocated site-packages, a Windows junction), which resolves such a path out of the root it is meant to be judged under, and then those rows either assert the wrong verdict or pass through the terminal False. Each row fails under the matching mutation: the `_INSTALL_DIR_NAMES` check or the install-root exclusion removed; `_INSTALL_DIR_NAMES` matched on the whole path, case-sensitively, on `/` in place of `os.sep` or on the first component below the root alone; `_norm` weakened to `normcase` so the recorded path is judged unresolved; the roots walked innermost first; the terminal False turned into None; the `isabs` gate, the driveless gate or the NUL gate removed; the install-root exclusion hoisted above the flag split; the torch arm reading the stdlib roots; the `stdlib` flag ignored; the frozen-app gate removed, answering False, hoisted above the flag split, or asking `is True` of the flag, which the string row alone fails. **`test_located_reads_the_file_from_the_module_dict`** starts with a placed `__file__` deciding either way (an installed one False, a stdlib one True) and the production torch shape, a module carrying `torch.__file__` asked under `stdlib=False` (True) and `stdlib=True` (False), the only rows on which the flag is not a constant of the file arm. It then pins: - the module-dict read, with a `ModuleType` subclass whose class attribute `__file__` would classify False if seen (the row that fails under a `getattr` read of `__file__`), the real `torch.ops` as a canary for that shape (asserting first that its dict has no `__file__`; a `getattr` read of its relative `"_ops.py"` would answer the same None, so this row documents rather than pins), and a module whose PEP 562 `__getattr__` raises, with `__spec__` and `__loader__` deleted from its dict, since `ModuleType.__init__` seeds both and a `getattr` read of either would otherwise never reach `__getattr__`; - a module built through `importlib.util.LazyLoader` over a mock loader, carrying the installed `__file__` (False, and the loader's `exec_module` was not called: under a `getattr` read of `__dict__` the `_LazyModule` runs it, and since the real `graphlib` is in `sys.modules` under that name then raises inside the catch, answering None); - no file and no spec; a non-string `__file__`; a slotted proxy whose `__getattr__` raises (standing in for a non-module `sys.modules` entry) both as the module and as its `__spec__`; that module again once it has a placeable `__file__`; a `sys` with that proxy as `__spec__` next to a `BuiltinImporter` `__loader__` (True: the dict's `__loader__` is read first, so the spec never is); - the two rows that pin the arm order: the `importlib._bootstrap` shape, a stdlib `__file__` plus `FrozenImporter`, asserting first that the frozen table does not know the name, is True; an installed `__file__` plus `BuiltinImporter` under `sys` is False; - the two that cross unusable file evidence with a loader: a non-string `__file__` under `sys` with `BuiltinImporter`, a relative one under `zipimport` with `FrozenImporter`, both True; - the frozen-app shape: a `zipimport` carrying a stdlib `__file__` and `FrozenImporter` is True with `sys.frozen` patched in, the file arm being no evidence there, so the loader decides. `zipimport` rather than `os` because CPython freezes `os` only from 3.11 on, gh-45020, and the row must hold on 3.10; - the real `sys` under its own name and under `sys.sub`, and a fabricated `zipimport` with `FrozenImporter` asked under `zipimport.sub` (False: in both arms the caller's name is looked up, not the module's `__name__`); the fabricated `sys.sub`; a frozen spec under a frozen name, under a dotted name whose top component is frozen (`zipimport.sub`) and under a non-frozen name; - `FrozenImporter.find_spec` patched to raise `ImportError` (None: the loader arms are inside the `try`); a `__loader__` that is `mock.ANY`, a stdlib object whose `__eq__` answers true for anything (None: the arms match by identity, so nothing of its runs); - each importer as a bare `__loader__` with no spec asked under both flags, and the torch shape, `torch._C` with `BuiltinImporter` under `stdlib=False` with the inittab patched to list it (asserting first that the real one does not). Each of these mutations fails a row: a `getattr` read of `__file__`, of `__spec__` or of `__loader__` (the first fails the `Shadow` row, the other two the `assert_not_called`); a `getattr` read of `__dict__` (the LazyLoader row); the `stdlib` flag hardcoded on the file arm; the `try/except` removed; the arms swapped or the loader read before the file arm; the `__loader__` read dropped for the spec's loader alone or read after it; either arm's identity comparison loosened to `==`; an inittab or frozen-table lookup on the top component; the name taken from the module's `__name__`; an unconditional frozen True; a False for no evidence; `stdlib and` in front of either loader arm; the `isinstance(file, str)` gate loosened to truthiness; and the fall-through from a None `_classify_file` to the loader replaced by a return. The last two are killed only by rows that cross an unplaceable file with a loader: the loosened gate by the non-string crossing row alone (the catch covers the `TypeError` that `os.path.isabs` raises on a non-string, so it answers the same None as the real one until the module also carries a loader that should have decided), the return by the relative crossing row and the frozen-app row, where `_classify_file` answers None and the loader was to decide. Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_classify_file_places_a_path_by_the_roots_it_lies_under -k test_located_reads_the_file_from_the_module_dict lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in 7d01447 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197963 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…a capture (#197260) (#197964) **Problem.** The multi-graph precompile capture needs a report type that tells a caller what it captured and what it dropped, and nothing in the tree defines one. **Fix.** Add `PrecompileSummary`, a frozen keyword-only dataclass with documented fields, a coverage-only `complete` flag, per-type guard tallies and a one-line digest. It is data only; the producer that fills it comes later in the stack. **Summary.** `PrecompileSummary` is the frozen, keyword-only dataclass a multi-graph capture will hand back to describe what it observed: how many frames, graph-break continuations, guarded codes and backend graphs were captured, which frames were bypassed, truncated or left uncovered, and which guards were dropped, kept, dropped riskily, or dropped by the invariance policy. Nothing in this commit produces one -- the builder (`_summarize`), the guard filter and the lints it names live later in this stack -- so every `Attributes:` entry says what the field means to a consumer of the report and names the producer for how it is populated instead of repeating its rules, after two earlier drafts that restated the guard-filter rule went stale against it. The relations between the fields (`bypassed` and `uncovered_frames` never share a frame, `kept_guards` and `dropped_guards` are disjoint per frame variant but aggregate across frames, `policy_dropped_guards` is drawn from slots the filter kept) are stated in the docstrings and not enforced, because a `__post_init__` that raised on a bookkeeping collision would lose the whole report, which `capture_errors` exists to avoid. `complete` is the one piece of logic, a coverage-only flag with six terms (nothing bypassed, truncated or uncovered, no capture error, at least one guarded code and at least one backend graph), and `dropped_guard_types`, `kept_guard_types` and `__str__` derive the per-type tallies and a one-line digest that names risky drops and shouts the frame failures last. It is keyword-only because its four required fields are all `int`, so `PrecompileSummary(3, 0, 1, 1)` would be legal and unreadable, and the positional order would become part of a public contract once the type is exported from `torch.compiler.precompile` later in this stack. ## The fields ```python @dataclasses.dataclass(frozen=True, kw_only=True) class PrecompileSummary: frames: int # every frame the package holds an entry for resume_functions: int # of those, the graph-break continuations guarded_codes: int backend_graphs: int bypassed: tuple[str, ...] = () # co_name per frame truncated: tuple[str, ...] = () # "co_name (filename:firstlineno)" per code object uncovered_frames: tuple[str, ...] = () # co_name per frame wont_generalize: tuple[str, ...] = () # guard sources, not frame names dropped_guards: tuple[tuple[str, str], ...] = () # (guard_type, source) slots kept_guards: tuple[tuple[str, str], ...] = () risky_dropped_guards: tuple[tuple[str, str], ...] = () policy_dropped_guards: tuple[tuple[str, str], ...] = () dropped_guard_code: tuple[tuple[str, str, str], ...] = () # (guard_type, source, rendered_check) capture_errors: tuple[str, ...] = () # "ExceptionType: message", one per distinct exception ``` ## The frame fields `frames` counts every frame the package holds an entry for, the bypassed, truncated and uncovered ones included, and the docstring says so, because `bypassed` as "frames the package refused to record" otherwise reads as frames outside the count and `8 frames, ... 7 UNCOVERED` as fifteen frames; the builder later in this stack (`_summarize`) takes `frames` from `len(entry.codes)` and both `bypassed` and `uncovered_frames` from the same list, so both are subsets by construction, and the digest's frame clauses cut into the count rather than add to it. `bypassed` is documented as what `_DynamoCodeCacheEntry.bypassed` records: the package holds nothing installable for the frame because no compile of it recorded a guarded code and one was bypassed (either `OutputGraph.bypass_package` cause, guards that could not be serialized or a graph that held parameters by static address), or a backend artifact was missing at save; the frame still ran compiled during capture, the package kept no variant of it a load can serve, and an install re-traces it; it is not an eager fallback. Not "every compile was bypassed": `bypass_current_compile` sets the flag as `not guarded_codes` and `add_guarded_code` clears it, so a compile that raised before recording anything is neither a bypass nor a record and leaves the flag free for a later bypassed compile of the same frame. How each cause gets there (a save-time bypass leaves the stale guarded codes in the artifact for `CompilePackage.initialize` to drop, while a `bypass_package` compile never recorded them) is the package's business, so the field says what the consumer gets and leaves that to the producer. `uncovered_frames` is the frames the capture ran that ended with no guarded code and were not bypassed, a different cause and remedy from `bypassed` (an install `skip_code`s an uncovered frame, so only a re-capture recovers it, where it re-traces a bypassed one) and never the same frame (which is why the predicate excludes bypassed frames rather than leaning on their guarded codes, which a save-time bypass leaves in place). The docstring names three causes: a thin wrapper whose graphs landed in an inner frame, a frame Dynamo gave up on, and a frame whose compile raised, since `code_context` sets `has_compile_id` in its `finally`, for a compile attempted whether or not it finished, so one failure shows in the digest as both a CAPTURE ERROR and an UNCOVERED clause; and it states the one overlap, a frame that hit the recompile limit before it recorded a guarded code (the limit check runs inside `code_context` and reads the code object's pre-existing cache size, so a warm process gets there with no guarded code), which is in `truncated` too. The docstring says it is explicitly not a remainder, because which frames count as a gap is the producer's call and a frame the package holds an entry for but never ran is not one, so a consumer cannot recompute it as `frames` minus `bypassed` minus the frames that hold guarded code. An earlier draft had `uncovered_frames` arrive as a set of bare names, which the builder now reads off the entry instead (a frame that entered Dynamo, holds no guarded code and was not bypassed), so `2 UNCOVERED` is two frames and not two names; `install()` `skip_code()`s a superset of those frames (`if len(entry.guarded_codes) == 0`, with no `has_compile_id` test), which is why the docstring describes the field rather than equating it with the skip. The frame lists differ in what an entry is, and the docstring says so: ```python bypassed=("forward", "forward") # two frames, not a repeat: every nn.Module has a forward uncovered_frames=("helper",) # bare co_name; len() counts frames truncated=("forward (model.py:12)", "forward (model.py:40)") # once per code object; identifies a frame ``` `bypassed` and `uncovered_frames` hold one bare `co_name` per frame, so a name can repeat and their lengths count frames, while `truncated` holds `co_name (filename:firstlineno)`, recorded once per code object by the compile path that sees a frame hit the limit (the only producer of that set, in the follow-up stack, spells it that way, and a set of bare names would merge two `forward`s into one), so its entries do identify a frame. A bare name identifies none, which is why the `bypassed`/`uncovered_frames` relation is stated and not enforced. `truncated` is documented as a lower bound, which is why the digest prints it as `>=`: from a limit hit on, that frame and the frames it calls run without tracing (`FrameExecStrategy(RUN_ONLY, RUN_ONLY)` in `convert_frame.py`, whose second component is the action for callees), so a limit hit that would follow it there is never recorded; by the same mechanism every count and frame list is a lower bound once `truncated` is non-empty, and the class docstring says so. A callee the traced compiles reached is in the entry and counted; one first reached after the hit never enters Dynamo (under `RUN_ONLY` the nested callback is `Py_False`, `eval_frame_cpp.cpp`), so it gets no entry and is missing from `frames` and `uncovered_frames` alike, while sibling frames keep tracing and keep being recorded. ## The guard slot lists The four guard lists hold `(guard_type, source)` slots, the source spelled as `GuardFilterEntry.name`, the `Guard.name` with local scope stripped (`self.act`, not `L['self'].act`; `G['CFG'].width` unchanged). `dropped_guards` is every slot the serialized copy's guard filter rejected, the guards the serializer refuses plus whatever a caller-supplied filter dropped, not only the unserializable ones; that matches the `default_guard_filter_fn` docstring the next commit of this stack adds to `torch/_dynamo/precompile_package.py` ("Every dropped slot is reported in `PrecompileSummary.dropped_guards`, once however many variants dropped it") and is what the `dropped_guard_code` entry below relies on. Which guards a filter rejects is not restated here at all: the docstring names `default_guard_filter_fn` as the default (one sentence above the `Attributes:` block says the three rules it names live in `torch._dynamo.precompile_package`, whose filter this stack adds alongside this type and whose other two rules come later in the stack, so a reader of landed `main` knows where the targets are), defers the whole rule and every exemption to that filter's docstring, and says a caller-supplied filter decides its own set. Two earlier drafts did restate the rule and both went stale as the filter changed shape underneath them -- the first repeated two of its three by-type exemptions, the second characterized the exemptions as by-type when the filter now has two by-type exemptions plus one derived type it ignores -- and each time the stale rule predicted a drop on the pytree-registry guard essentially every capture keeps. That is the shape every `Attributes:` entry now follows: say what the field means to a consumer of the report, and name the producer for how it is populated instead of repeating its rules. A slot keeps its own type, so a `TENSOR_MATCH` that checked identity (`match_on_id_for_tensor` routes it through `ID_MATCH`) is listed as a dropped `TENSOR_MATCH`, the same type the tests use as the canonical kept guard. The class docstring states how the lists relate and why nothing enforces it. Within one frame variant `kept_guards` and `dropped_guards` are disjoint (the filter gives a slot one verdict, keep or reject), `risky_dropped_guards` is drawn from `dropped_guards` and `policy_dropped_guards` is disjoint from both it and `kept_guards` (the policy re-serializes each variant's guards from the pickle the filters already passed, so a policy drop is a slot the filter kept, taken out once it held identically across every captured variant, and is not checked either, so `(N kept)` never counts one; `policy_dropped_guards` is documented as those kept-then-dropped slots, with `_INVARIANT_DROPPABLE_GUARD_TYPES` named as the bound on what the policy may drop, rather than as "serializable slots", since that set also lists the identity types the default filter drops first). But the lists aggregate every captured frame: ```python # test_summary_guard_lists_aggregate_over_frames: two frames' guards on the builtin # len are one slot. One frame's caller filter rejected it and the drop told that # frame's variants apart (risky); the other frame's invariance policy dropped it. act = ("BUILTIN_MATCH", "G['__builtins_dict___<n>']['len']") summary = PrecompileSummary(frames=2, resume_functions=0, guarded_codes=2, backend_graphs=2, dropped_guards=(act,), risky_dropped_guards=(act,), policy_dropped_guards=(act,), dropped_guard_code=(act + (check,),)) summary.dropped_guard_types # {'BUILTIN_MATCH': 1}: distinct slots, not occurrences str(summary) # "2 frames (0 from graph breaks), 2 guarded codes, 2 backend graphs, dropped guards {'BUILTIN_MATCH': 1} (0 kept), RISKY drops [\"BUILTIN_MATCH G['__builtins_dict___<n>']['len']\"], 1 policy-dropped guard" ``` Each slot appears once however many frames or variants carried it (so `dropped_guard_types` counts distinct slots, not occurrences), and a slot names no frame, so two frames' `self.act` are one slot, a slot one frame kept and another dropped is in both `kept_guards` and `dropped_guards` (which is why the digest's `(N kept)` is the kept count beside the drops, not the other half of a total), and a slot one frame's filter rejected and another frame's invariance policy dropped is legitimately in both drop lists. The relations are therefore stated, not checked, the way the frame lists already are; a `__post_init__` that raised on them would turn a bookkeeping collision into the loss of the whole report, which `capture_errors` exists to avoid. The same holds for `dropped_guard_code`, whose slots come from the two drop lists, and for `wont_generalize`, whose every source is the source half of a `kept_guards` slot. ## `dropped_guard_code` `dropped_guard_code` carries the rendered check next to each dropped slot, because a slot such as `('HASATTR', "counts['pixel']")` can be either the benign companion of a kept `TENSOR_MATCH` or the only guard on an optional attribute, and only the rendered text tells them apart; it is for programmatic consumers, not the digest. A slot is absent from it when its guard rendered no check, i.e. its `GuardBuilder` method never set `Guard.code_list` (the only writer is `Guard.set_export_info`, reached through the builder's `_set_guard_export_info`, and `CheckFunctionManager` resets `code_list` before every build, so this is a statement about the pre-filter build the entries come from, not about the guard in general). That is not predictable from how the check is installed, and the docstring states the predicate and says so instead of offering a rule or enumerating guard types (an enumeration in a docstring would rot against `guards.py` unchecked); the evidence is recorded here instead: | guard type | installed through | renders a check | | --- | --- | --- | | `AUTOGRAD_SAVED_TENSORS_HOOKS` | a lambda | yes | | `DEFAULT_DEVICE` | a C++ leaf | yes | | `GLOBAL_STATE`, `TORCH_FUNCTION_STATE`, `DISPATCH_KEY_SET_MATCH`, `TENSOR_SUBCLASS_METADATA_MATCH` | | no | | `CLOSURE_MATCH` on a plain function | guards `__code__` through a separate guard | no | | `CLOSURE_MATCH` on any other callable | falls through to `FUNCTION_MATCH` -> `ID_MATCH` | yes | The entry holds one rendering however many variants dropped the slot, and the docstring says what that means for a check that embeds the guarded value (`EQUALS_MATCH` renders `L['n'] == 3`): variants that differ in the value render differently, the entry shows one variant's rendering, the producer's pick rather than a merge, so it tells the form of the check and not the value; that the slot varied at all is what `risky_dropped_guards` records. The alternative, several entries per slot sharing a `(guard_type, source)` prefix, would make the field grow with variants rather than with slots and would answer a question (`which values`) the field is not for. ## `wont_generalize` `wont_generalize` is documented as observed, not proven: a source is listed when a kept value-equality guard on a bare argument name pins it in some variant (`_pins_a_value` in `torch/_dynamo/precompile_package.py` is the rule, named rather than restated, so a kept `EQUALS_MATCH` on `self.eps` or `G['CFG'].width` is deliberately not one; `kept_guards` stays the authoritative list) and no other variant of the same frame guards it without pinning it, which is what the builder computes frame by frame (a variant that never guarded the source does not cancel the pin, and a frame that cancels its own pin does not cancel another frame's), rather than as a claim that every variant pins it. ## Keyword-only ```python PrecompileSummary(frames=3, resume_functions=0, guarded_codes=1, backend_graphs=1) # ok PrecompileSummary(3, 0, 1, 1) # TypeError: takes 1 positional argument but 5 were given ``` Its four required fields are all `int`, so the positional form would be legal and unreadable, and the positional order would become part of a public contract (the type is exported from `torch.compiler.precompile` later in this stack); the builder later in this stack (`_summarize`) and every test already construct it by keyword. ## complete Its `complete` property is the one piece of logic: a capture counts as complete only if nothing was bypassed, truncated or uncovered, no capture call raised, and it produced at least one guarded code and at least one backend graph. It is a coverage flag only. `risky_dropped_guards` is a lint finding, not a proof, and `wont_generalize` follows from any value the capture pinned, so neither enters `complete`; both describe how far a complete capture generalizes, and the digest reports them on their own. The `backend_graphs > 0` term matters because `allow_empty_graphs` lets a frame that compiled nothing still count as a guarded code, so `guarded_codes` alone cannot tell a real capture from an empty one (a model whose every graph sits behind a recursive `torch._dynamo.disable`). ```python def summary(**kw): base = dict(frames=1, resume_functions=0, guarded_codes=1, backend_graphs=1) base.update(kw) return PrecompileSummary(**base) summary().complete # True summary(backend_graphs=0).complete # False: nothing was compiled summary(guarded_codes=0).complete # False summary(capture_errors=("boom",)).complete # False summary(bypassed=("f",)).complete # False, likewise truncated / uncovered_frames risky = (("ID_MATCH", "self.act"),) summary(dropped_guards=risky, risky_dropped_guards=risky).complete # True: coverage only ``` `complete`, `dropped_guard_types` and `kept_guard_types` are all properties: each is an argument-free derivation of the fields, and one convention keeps `if summary.dropped_guard_types:` from silently passing on a bound method. ## The one-line digest ```python s = PrecompileSummary(frames=2, resume_functions=1, guarded_codes=3, backend_graphs=2, dropped_guards=(("ID_MATCH", "G['fn']"),), kept_guards=(("EQUALS_MATCH", "scale"), ("TENSOR_MATCH", "x")), wont_generalize=("scale",)) str(s) # "2 frames (1 from graph breaks), 3 guarded codes, 2 backend graphs, dropped guards {'ID_MATCH': 1} (2 kept), 1 value-pinned source" s.dropped_guard_types # {'ID_MATCH': 1} risky = (("HASATTR", "self.act"), ("ID_MATCH", "self.act")) wide = PrecompileSummary(frames=8, resume_functions=0, guarded_codes=1, backend_graphs=1, uncovered_frames=tuple(f"f{i}" for i in range(7)), dropped_guards=risky, risky_dropped_guards=risky, capture_errors=("RuntimeError: boom", "TypeError: bad", "ValueError: no")) str(wide) # "8 frames (0 from graph breaks), 1 guarded code, 1 backend graph, dropped guards {'HASATTR': 1, 'ID_MATCH': 1} (0 kept), RISKY drops ['HASATTR self.act', 'ID_MATCH self.act'], 7 UNCOVERED: ['f0', 'f1', 'f2', 'f3', 'f4'] +2 more, 3 CAPTURE ERRORS: 'RuntimeError: boom' +2 more" ``` Ordinary drops are counted by type with the kept count beside them for scale (a count, not a denominator: the two lists are disjoint per frame variant, not across frames), since every model drops the identity guards precompile cannot serialize. RISKY drops are few and actionable, so the digest names them, both halves of the slot, because two risky slots can share a source (a dropped `ID_MATCH` on `self.act` and a `HASATTR` checked on that object; a `HASATTR` slot's source is the object checked, the attribute is only in its rendering) and `['self.act', 'self.act']` would read as a duplicate. Policy drops and value-pinned sources are counted. The digest stays one line whatever the model: the four list clauses (RISKY, UNCOVERED, TRUNCATED, BYPASSED) show their first five entries and then `+N more`, and the CAPTURE ERROR clause, the one place the report carries prose a reader can act on, shows the first non-empty line of the first message (repr'd, so a multi-line Dynamo message cannot break the line; non-empty so a message that opens with a newline does not render as `''`) and `+N more` for the rest. `capture_errors` is documented as `ExceptionType: message` strings, one per distinct exception rather than per failed call (the producer collapses repeats of the same type and message, so ten inputs failing the same way render `1 CAPTURE ERROR`), the type name first, so a bare `assert` (whose `str()` is empty) still leaves the clause something to show. The count in front of the three frame clauses and the CAPTURE ERROR clause is still the full count (the RISKY clause carries no count, so its total is the entries shown plus `+N more`). Every counted noun agrees with its count (`1 guarded code`, `2 backend graphs`, `1 CAPTURE ERROR`); the shouted frame clauses (`1 UNCOVERED: ['helper']`) carry a list, not a noun. The guard clauses come first and the shouted frame failures (UNCOVERED, TRUNCATED, BYPASSED, CAPTURE ERROR) last, so a failure never sits between two notes. ## Tests All in `test/test_precompile.py`, next to the module's other tests. - `test_summary_complete_requires_every_term` pins all six terms of `complete` and that the guard fields never enter it. - `test_summary_digest_and_guard_type_counts` feeds every guard list sorted, as `_summarize` emits them, so the tally orderings its goldens pin are ones real output produces. It pins the digest for a capture with three dropped guards, a policy drop and a value-pinned source (which carries a `dropped_guard_code` entry the digest must not mention); for a clean capture with kept guards and no optional clause at all (`1 frame (0 from graph breaks), 1 guarded code, 1 backend graph`: kept guards appear only beside the drops); for a failing one whose two risky slots share a source and whose single capture error is a three-line message opening with a blank line (only its first non-empty line is shown); and for a wide one with seven uncovered frames and three errors (`['f0', 'f1', 'f2', 'f3', 'f4'] +2 more`, `'RuntimeError: boom' +2 more`), with singular and plural counts, plus the `dropped_guard_types` / `kept_guard_types` properties. - `test_summary_pickle_and_hash` round-trips a fully populated summary (every field set, including `dropped_guard_code` and `capture_errors`) through `pickle`, checks that the copy compares and hashes equal, pins that summary's digest (the only golden with all eight clauses: `bad` already pinned notes before the shouted UNCOVERED, TRUNCATED, BYPASSED, CAPTURE ERROR order, and this one adds `1 policy-dropped guard` and `1 value-pinned source` between the RISKY clause and UNCOVERED, which no other fixture places), and checks that positional construction raises the keyword-only `TypeError`. Only `PrecompileSummary` is round-tripped here: `GuardFact` gets its own round-trip with its keyword-only change two commits up, which also deletes `FrameInvariants` as unused. - `test_summary_guard_lists_aggregate_over_frames` pins the multi-frame case: one slot listed as dropped, risky and policy-dropped at once constructs, is counted once by `dropped_guard_types`, and renders once in each digest clause. Its comment credits the risky classification to the slot telling its frame's variants apart, not to the risky-drop lint, which waives a builtin read the ordinary way (`_reads_a_builtin`). Every policy-dropped fixture slot is a `BUILTIN_MATCH` on `G['__builtins_dict___<n>']['len']`, one of the four serializable types the default filter keeps and `_INVARIANT_DROPPABLE_GUARD_TYPES` lets the policy drop, and the only one of them with a source (`DUAL_LEVEL`, `FUNCTORCH_STACK_MATCH` and `AUTOGRAD_SAVED_TENSORS_HOOKS` are global-state guards); a `CONSTANT_MATCH` or `HASATTR` is `_SHAPE_BEARING_GUARD_TYPES`, never policy-dropped, so a fixture placing one on the policy side would pin a state the producer cannot emit. Likewise every fixture that lists a `wont_generalize` source keeps an `EQUALS_MATCH` on that bare name, since `_wont_generalize` returns nothing unless a kept slot passes `_pins_a_value`. Test Plan: ``` python test/test_precompile.py -k summary lintrunner torch/compiler/_precompile_types.py test/test_precompile.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in 94990b8 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197964 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
… by its name (#197264) (#197965) **Summary.** `_is_library_module(name)` answers whether torch or the standard library owns a module, which is the waiver the risky-drop lint (added two commits later) applies to a dropped identity guard on a library-owned value. A name is not an identity: `graphlib`, `queue`, `code` and `distutils` are all stdlib names a third party ships, and `import distutils` in a default setuptools install actually resolves to `site-packages/setuptools/_distutils`, selected by `SETUPTOOLS_USE_DISTUTILS`, which is exactly the config-chooses-the-implementation shape the lint exists to catch. So the top-level module must RESOLVE to code shipped with the interpreter, judged by the previous commit's `_located` (a placed `__file__`, else the inittab or the frozen table). Every imported dotted ancestor of the name is checked the same way, but an inner name only has to not be located ELSEWHERE: `pyexpat.errors` (registered by pyexpat's C init with neither `__file__` nor `__spec__`) and `torch.ops` (a `ModuleType` subclass whose `__file__` is a class attribute the module dict never sees) keep their waiver because their packages are located, while a shadowed submodule (a `collections.abc` under `site-packages`, a `torch.foo` outside the torch roots) loses it. A top-level name that is not imported or carries no location evidence (a namespace package, an exec'd module) and `None` are all untrusted. The torch arm alone has an escape hatch, and the docstring says so: a frozen torch gives `_torch_roots` nothing to anchor to, and then every torch name is waived on its name with no location evidence. ## Behaviour pinned by the tests ```python from torch._dynamo import precompile_package as pp stdlib_root = sysconfig.get_paths()["stdlib"] shadowed = types.ModuleType("graphlib") shadowed.__file__ = os.path.join(stdlib_root, "site-packages", "graphlib", "__init__.py") with mock.patch.dict(sys.modules, {"graphlib": shadowed}), mock.patch.object(pp, "_install_roots", return_value=()): pp._is_library_module("graphlib") # False: under an install dir, even though under the stdlib root and no install root is known vendored = types.ModuleType("graphlib") # no site-packages component in the path vendored.__file__ = os.path.join(stdlib_root, "vendored", "graphlib", "__init__.py") with mock.patch.dict(sys.modules, {"graphlib": vendored}), mock.patch.object(pp, "_install_roots", return_value=(pp._norm(os.path.join(stdlib_root, "vendored")),)): pp._is_library_module("graphlib") # False: only the install-root exclusion catches this one pp._classify_file.cache_clear() # the verdict is cached per __file__ with mock.patch.dict(sys.modules, {"graphlib": vendored}), mock.patch.object(pp, "_install_roots", return_value=()): pp._is_library_module("graphlib") # True: the same file is stdlib once nothing is installed there with mock.patch.dict(sys.modules, {"graphlib": types.ModuleType("graphlib")}): pp._is_library_module("graphlib") # False: no __file__, no __spec__ -- no evidence fake_torch = types.ModuleType("torch") fake_torch.__file__ = os.path.join(stdlib_root, "torch", "__init__.py") # the stdlib dir itself is never a pip target with mock.patch.dict(sys.modules, {"torch": fake_torch}): pp._is_library_module("torch") # False: the top-level check, torch resolving outside the torch roots foo = types.ModuleType("torch.foo") foo.__file__ = os.path.join(stdlib_root, "torch", "foo.py") with mock.patch.dict(sys.modules, {"torch.foo": foo}): pp._is_library_module("torch.foo") # False: the ancestor loop, a located torch does not vouch for it foo.__file__ = "foo.py" with mock.patch.dict(sys.modules, {"torch.foo": foo}): pp._is_library_module("torch.foo") # True: a relative __file__ is no evidence, and an inner name needs none pp._is_library_module("collections.never_imported") # True: an inner name that is not imported has nothing to check with mock.patch.object(pp, "_torch_roots", return_value=()): pp._is_library_module("torch.never_imported") # True: frozen torch, waived on the name alone sub = types.ModuleType("sys.sub") sub.__spec__ = importlib.machinery.ModuleSpec("sys.sub", importlib.machinery.BuiltinImporter, origin="built-in") with mock.patch.dict(sys.modules, {"sys.sub": sub}): pp._is_library_module("sys.sub") # False: "sys.sub" is not in sys.builtin_module_names, "sys" is # On 3.11+ every frozen stdlib module also carries an absolute __file__ (whenever sys._stdlib_dir is # known), so the real zipimport is decided by its path; a module dict without one reaches the frozen table. frozen = importlib.machinery.FrozenImporter zipimport_frozen = types.ModuleType("zipimport") zipimport_frozen.__spec__ = importlib.machinery.ModuleSpec("zipimport", frozen, origin="frozen") with mock.patch.dict(sys.modules, {"zipimport": zipimport_frozen}): pp._is_library_module("zipimport") # True: the frozen table has zipimport graphlib_frozen = types.ModuleType("graphlib") graphlib_frozen.__spec__ = importlib.machinery.ModuleSpec("graphlib", frozen, origin="frozen") with mock.patch.dict(sys.modules, {"graphlib": graphlib_frozen}): pp._is_library_module("graphlib") # False: a frozen spec under a name the frozen table does not have pp._is_library_module("torch._C._nn") # True: located parent torch._C; _nn (no __file__, no __spec__) carries no evidence of its own pp._is_library_module("pyexpat.errors") # True: located parent, submodule (no __file__, no __spec__) not located elsewhere pp._is_library_module("collections.abc") # True, unless sys.modules["collections.abc"] resolves to site-packages pp._is_library_module("not_a_stdlib_name") # False: not a stdlib name with mock.patch.dict(sys.modules): sys.modules.pop("graphlib", None) pp._is_library_module("graphlib") # False: a stdlib name that is not imported pp._is_library_module(None) # False ``` ## The tests Two module-level fixtures carry the rows. `_STDLIB_ROOT` is sysconfig's `stdlib`, the path every shadow row with an absolute `__file__` is spelled under and the directory the relative row is judged from (the stdlib dir itself is never a pip target, so no torch root holds the torch rows, while `site-packages/torch` IS one wherever purelib nests under stdlib). `_NOT_LIBRARY_MODULES` is a table of shadow modules, one row per refused shape, each labelled by the check that refuses it: under an install dir with `_install_roots` patched to `()` (only `_INSTALL_DIR_NAMES` refuses it), under a nested install root with no `site-packages` component (only the `_install_roots` exclusion does), no file and no spec, a relative file (judged with the cwd at `_STDLIB_ROOT`, where the real `graphlib.py` sits, so that without the `isabs` gate the name would resolve to stdlib and be waived), `torch` itself and `torch.foo` outside the torch roots (the top-level check and the ancestor loop), a dotted name under a built-in top (by spec; the `__loader__` leg is `_located`'s and pinned by its own tests), a frozen spec under a non-frozen name and a shadowed `collections.abc`; a `__file__` with an embedded NUL has no row, because `_is_library_module` refuses it whether `_classify_file`'s NUL gate answers None or `_norm` raises out of `_located` (the gate is pinned by `_classify_file`'s own tests). `test_library_module_requires_the_name_to_resolve_to_the_library` is parametrized over `_NOT_LIBRARY_MODULES` so a regression names its row; the rows are built from `types.ModuleType` objects patched into `sys.modules` with `_install_roots` patched per row, so nothing touches the real interpreter layout, and the test clears `_classify_file`'s cache first, because that verdict is cached per `__file__` while `_install_roots` is patched per row, so a verdict another test left for a row's file would be read back under the wrong roots. Every row here is a refusal: no `True` path is exercised by this commit's test, so on its own it cannot tell the function from `return False`. The waiver side (the real torch and stdlib names, the evidence-only-at-the-top rule, and the location-free refusals: not a stdlib name, not imported, `None`) is pinned by the next commit's tests, which is where the code block above is exercised in full. Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_library_module lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in 01ab03e as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197965 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…nd the evidence-only-at-the-top rule (#197595) (#197966) **Summary.** Tests only, for `_is_library_module` from the previous commit. That commit pins every shape the predicate refuses; this one pins what it must keep waiving: the real torch and stdlib names as they are laid out in the running interpreter, and the rule that location evidence is demanded only of the top-level name of a dotted module, never of its inner names. It is a separate commit so each half stays small enough to review in one sitting; the code is unchanged. ## Behaviour pinned by the tests ```python from torch._dynamo import precompile_package as pp pp._is_library_module("torch._C._nn") # True: located parent torch._C; _nn (no __file__, no __spec__) carries no evidence of its own pp._is_library_module("pyexpat.errors") # True: located parent, submodule (no __file__, no __spec__) not located elsewhere pp._is_library_module("collections.abc") # True, unless sys.modules["collections.abc"] resolves to site-packages pp._is_library_module("collections.never_imported") # True: an inner name that is not imported has nothing to check with mock.patch.object(pp, "_torch_roots", return_value=()): pp._is_library_module("torch.never_imported") # True: frozen torch, waived on the name alone foo = types.ModuleType("torch.foo") foo.__file__ = "foo.py" with mock.patch.dict(sys.modules, {"torch.foo": foo}): pp._is_library_module("torch.foo") # True: a relative __file__ is no evidence, and an inner name needs none with mock.patch.dict(sys.modules): sys.modules.pop("graphlib", None) pp._is_library_module("graphlib") # False: a stdlib name that is not imported pp._is_library_module("not_a_stdlib_name") # False: not a stdlib name pp._is_library_module(None) # False ``` ## The tests `_LIBRARY_NAMES` lists the torch and stdlib names that must keep their waiver, including the evidence-free inner names `torch._C._nn`, `torch.ops`, `pyexpat.errors` and `xml.parsers.expat.model`; the header's `import xml.parsers.expat` keeps the last one's top-level name in `sys.modules`, which a waiver requires. `test_library_module_keeps_the_waiver_for_the_real_library` is parametrized over it and clears `_classify_file`'s cache first, so it reads the real layout rather than a verdict a sibling interned under patched roots. `test_library_module_needs_location_evidence_only_at_the_top` pins an unimported stdlib name, a non-stdlib name and `None` as untrusted, a relative `__file__` on an inner name keeping the waiver, an inner name that is not imported keeping it too (nothing under the name to check, and the package is located), the `under_a_nested_install_root` row's own file being stdlib once nothing is installed there, the frozen table's True on a fabricated file-less `zipimport`, and the frozen-torch early True. Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_library_module lintrunner test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in c654400 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197966 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…rd hangs off (#197265) (#197967) **Summary.** Dynamo guards every module it walks through, so the path down to `F.gelu` is guarded module by module, and that is what lets a dropped identity guard on an attribute be recognised as a read off a namespace rather than off an object a config could have swapped. `_module_namespaces(entries)` collects the module-valued guard entries rooted at a `GlobalSource` and returns the TRUSTED ones, mapped from source name to module. `_source_root(source)`, a one-line walk down `ChainedSource.base` to the root, is added here as the helper that finds that `GlobalSource`. A module is trusted if torch or the stdlib owns it (`_is_library_module`), if it is bound under its own name (`import mypkg`, or the `__import_x` alias Dynamo installs to reach an inlined function's globals, recognised through `_dynamo_alias_module`), or if it is an attribute of a trusted module under a name that module already owns: its own `__name__` (a plain `import own_sub` inside the parent) or the parent's name plus the attribute (`from . import sub`, and `import mypkg.layers`, which Dynamo guards as `G['mypkg'].layers`). An ALIASED user module is none of those: `if flag: import impl_b as impl` picks what `impl.op` resolves to per machine, and so does `from . import impl_b as impl` in a package `__init__`; inheriting the parent's trust without checking the name is what let that shape through in an earlier round. Library ownership is trusted under any binding, `import torch.nn.functional as F` included; the price, taken deliberately because flagging `F` would flag every model, is that an alias config picks between two torch modules is waived too, which `_is_risky_drop`'s KNOWN GAP records. Dynamo never guards a bare `__import_torch` alias, only the attributes read off it, so aliases with no module-valued entry are recovered from their name rather than treating `torch.Tensor` as a config-swappable slot. A config module (`torch.utils._config_module.ConfigModule`, e.g. `torch._dynamo.config`) is the one namespace whose bindings config chooses by definition, so it is never trusted, whoever owns it and however it is reached: the check is a trust verdict inside `is_trusted`, not a filter on what is collected, so a config module recovered from an `__import_x` alias (`from torch._dynamo.config import verbose` in an inlined function) is refused the same way as one bound under a plain name. ## Which namespaces are trusted ```python import mypkg # G['mypkg']: trusted, bound under its own name import mypkg.layers # G['mypkg'].layers: trusted, mypkg is and owns the name mypkg.layers import torch.nn.functional as F # trusted: torch owns it, whatever the alias import impl_b as impl # NOT trusted: the alias is a slot the import picked impl.deep # NOT trusted: a name impl owns, but impl itself is not trusted config = torch._dynamo.config # NOT trusted: a config module, whoever owns it from torch._dynamo.config import verbose # NOT trusted either: G['__import_torch_dot__dynamo_dot_config'] is recovered, then refused # inside a trusted package __init__: from . import sub # trusted: module.__name__ == "mypkg.sub" == f"{parent}.sub" from . import impl_b as impl # NOT trusted: "mypkg.impl_b" is neither "impl" nor "mypkg.impl" ``` The result feeds `_is_risky_drop` (next commit): a dropped guard whose source is in the returned dict, or whose `source.base.name` is one of its keys (an exact lookup, never a prefix match), is judged by the namespace's owner rather than flagged outright. `test_module_namespaces_trust_only_bindings_config_cannot_repoint` builds each shape above from hand-made `GuardFilterEntry` values and asserts the exact trusted set. Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_module_namespaces_trust_only_bindings_config_cannot_repoint lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in fde4ed9 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197967 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…r compared (#197267) (#197968) **Summary.** A later invariance policy may leave a guard out of the serialized artifact when it held identically across every captured variant, and this commit names the two classes of guard that must never take part in that. Each set states two independent properties, never dropped and never compared. `_SHAPE_BEARING_GUARD_TYPES` are the guard types that pin an input's shape, value or kind; the report compares them across variants and a policy never drops one, because with a single captured example nothing can discriminate, and what would disappear is the check that the runtime input looks like the captured one at all. `_UNMODELLED_GUARD_TYPES` are the guard types on ambient or process state that the guard leaf checks for itself and that nothing in this module fingerprints; calling two of them equal would assert a precondition the report cannot see, so they are reported as undetermined rather than compared, and they are never dropped because a policy may drop only what its droppable set names. Both sets are plain sorted literals with a header stating the criterion; membership was settled over the review rounds of this PR, and the four-set partition of `GuardBuilder`'s methods (these two plus the identity and no-op sets) is pinned by the totality test in the next commit, so a guard type added to Dynamo is kept unconditionally until someone classifies it. ## Membership ```python from torch._dynamo.precompile_package import _SHAPE_BEARING_GUARD_TYPES, _UNMODELLED_GUARD_TYPES len(_SHAPE_BEARING_GUARD_TYPES), len(_UNMODELLED_GUARD_TYPES) # (24, 12) _SHAPE_BEARING_GUARD_TYPES & _UNMODELLED_GUARD_TYPES # frozenset() "TENSOR_MATCH" in _SHAPE_BEARING_GUARD_TYPES # True: compared, never dropped "SHAPE_ENV" in _UNMODELLED_GUARD_TYPES # True: never compared, never dropped "ID_MATCH" in _SHAPE_BEARING_GUARD_TYPES | _UNMODELLED_GUARD_TYPES # False: classified next commit ``` Test Plan: ``` python -c "import torch._dynamo.precompile_package" lintrunner torch/_dynamo/precompile_package.py ``` The classification tests land with the next commit, which adds the other two sets; run there: ``` python test/dynamo/test_precompile_package.py -k test_guard_policy_classification_is_total python test/dynamo/test_precompile_package.py -k guard_type ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in c51118f as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197968 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
… totality test (#197268) (#197969) **Summary.** With the shape-bearing and unmodelled sets in place, this commit adds the other two and the test that makes the classification enforceable. `_IDENTITY_GUARD_TYPES` freezes `CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, both for the fingerprinting code that follows and as the base of `_INVARIANT_DROPPABLE_GUARD_TYPES`, the ONLY guard types an invariance policy may drop, and only when proven invariant across every captured variant: the identity guards the default filter drops anyway as unserializable, derived from that same set so the two cannot disagree, plus `BUILTIN_MATCH`, an identity match the default filter keeps; the ambient-state guards (`DEFAULT_DEVICE`, `FUNCTORCH_STACK_MATCH`, `DUAL_LEVEL`, `AUTOGRAD_SAVED_TENSORS_HOOKS`) are unmodelled per the previous commit, so nothing outside identity is droppable. `_NOOP_GUARD_TYPES` (`DETERMINISTIC_ALGORITHMS`, `GRAD_MODE`) are markers whose `GuardBuilder` method is `pass` and whose check is made by `GLOBAL_STATE`'s leaf, so nothing about them is ever serialized or dropped, and `_is_noop_guard_type` adds `EMPTY_NN_MODULE_HOOKS_DICT` under the default `skip_nnmodule_hook_guards`, where the builder emits nothing for it; with the skip off it emits a real `SEQUENCE_LENGTH`, which is why the previous commit classified it shape-bearing rather than droppable. `test_guard_policy_classification_is_total` enumerates every uppercase callable on `GuardBuilder` (through `dir`, so a method added on `GuardBuilderBase` or a mixin counts) and asserts the four sets cover all of them, contain nothing else, are pairwise disjoint, and that the identity set is inside the droppable one, so a guard type added to Dynamo fails this test until someone triages it and is KEPT unconditionally until then. Guards installed outside `GuardBuilder` -- the root manager's `DuplicateInputs` and `StorageOverlap` exprs and the dimension-marking lambda -- never reach the guard filter and are outside the policy as well. `test_noop_guard_type_follows_the_hook_guard_config` pins the config-dependent answer. ## The test ```python guard_types = {name for name in dir(GuardBuilder) if name.isupper() and callable(getattr(GuardBuilder, name))} sets = { "_SHAPE_BEARING_GUARD_TYPES": _SHAPE_BEARING_GUARD_TYPES, "_UNMODELLED_GUARD_TYPES": _UNMODELLED_GUARD_TYPES, "_INVARIANT_DROPPABLE_GUARD_TYPES": _INVARIANT_DROPPABLE_GUARD_TYPES, "_NOOP_GUARD_TYPES": _NOOP_GUARD_TYPES, } classified = frozenset().union(*sets.values()) assert guard_types - classified == set() # "unclassified GuardBuilder guard type(s): add each to exactly one policy set" assert classified - guard_types == set() # "phantom entries: no GuardBuilder method by these names" for (a_name, a), (b_name, b) in itertools.combinations(sets.items(), 2): assert not (a & b) assert _IDENTITY_GUARD_TYPES <= _INVARIANT_DROPPABLE_GUARD_TYPES ``` ```python _is_noop_guard_type("GRAD_MODE") # True _is_noop_guard_type("EMPTY_NN_MODULE_HOOKS_DICT") # True under the default config, False under # torch._dynamo.config.patch(skip_nnmodule_hook_guards=False) ``` Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_guard_policy_classification_is_total python test/dynamo/test_precompile_package.py -k test_noop_guard_type_follows_the_hook_guard_config lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in ca5b700 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197969 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…ered guard code (#197269) (#197970) **Summary.** The invariants report a later commit writes is meant to be committed to a repository and diffed across runs, so anything in a rendered guard that differs run to run has to be scrubbed first. `_normalize` replaces the object address in `___check_obj_id(..., 140311678493200), type=` renderings, the `(id, id)` tuple in `top_saved_tensors_hooks ids == (...)`, the per-process counter Dynamo appends to the builtins dict it installs (`__builtins_dict___6`), and the `_<id>_c<n>` suffix `OutputGraph.install_global_by_id` bakes into an identifier, where neither of the other patterns can see it (transformers' Qwen2 installs three such globals; torch itself is installed under an empty prefix as `_<id>_c<n>`). Those are exactly the three minted families `aot_compile._MINTED_GLOBAL_PREFIXES` names as able to root a serializable guard; `__compiled_fn_*` and `__resume_at_*` are codegen-only `LOAD_GLOBAL` targets and are deliberately not matched, since a pattern for them would have to guess at a shape (`__resume_at_<offset>_<counter>`, `__compiled_fn_<n>_<uuid>`) no guard ever renders. Each pattern is anchored to the call shape that carries the address, because a bare `\b\d{9,}\b` also eats a user constant such as a dict key or slice bound, and two variants guarding different values would then render the same fact and invent an invariant neither holds; for the `install_global_by_id` shape the digit width is that anchor, since the prefix can be empty and `w_1_c2` is a plausible user identifier. `_render_code` applies the normalization to every part of a guard's `code_list`, and `_hash_text` is the 12-hex-digit sha256 prefix the fingerprints that follow use. `test_normalize_scrubs_addresses_and_counters_but_not_user_constants` is a table over both directions: everything run-varying is erased, and nothing meaningful is. ## Before and after ```python from torch._dynamo.precompile_package import _normalize _normalize("___check_obj_id(G['fn'], 140311678493200), type=<class 'function'>") # "___check_obj_id(G['fn'], <id>), type=<class 'function'>" _normalize("G['__builtins_dict___6']['len']") # "G['__builtins_dict___<n>']['len']" _normalize("G['__import_mod_140311678493200_c1']") # "G['__import_mod_<id>_c<n>']" _normalize("G['_140311678493200_c3'] is not None") # "G['_<id>_c<n>'] is not None" _normalize("top_saved_tensors_hooks ids == (139, 140)") # "top_saved_tensors_hooks ids == (<ids>)" _normalize("L['dims'][0] == 140311678493200") # unchanged: a bare number is a user constant, not an address _normalize("L['w_1_c2'] == 3") # unchanged: a short counter-looking identifier is the user's ``` Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_normalize_scrubs_addresses_and_counters_but_not_user_constants lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in 73422e9 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197970 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…e guard report (#197270) (#197971) **Summary.** `_normalize` strips the address an identity guard renders, so the report needs another stable name for the object it guarded, or two variants holding different callables at one source collapse into one fact and are reported as an invariant neither holds. `_object_identity(value)` names a module by `__name__`, and a callable by where it is DEFINED plus a digest of its body: `is @<basename>:<firstlineno>#<fingerprint> <module>.<qualname>`, truncated to 160 characters with the discriminating part FIRST, because a qualname alone can exceed the limit on a transformers lambda nested in a long module path, and a digest appended at the end would be cut off exactly where it is needed. The digest comes from `_code_fingerprint`, a sha256 prefix over `co_code`, `co_names`, `co_varnames`, `co_freevars`, `co_cellvars` and the stable constants, which is what tells apart an `ACT2FN`-style table whose lambdas are all written on one source line and so agree on file AND lineno. `_stable_consts` reduces `co_consts` to what reprs the same in every process, recursing into tuples, frozensets (sorted by repr) and nested code objects instead of dropping them, because two lambdas that differ only in `x * (1, 2)` versus `x * (1, 3)`, or only inside an inner lambda, are genuinely different variants and dropping the container is what let them collide. A const of any other type keeps its SLOT as a type marker for the same reason: `x[..., 0]` and `x[0, ...]` fold to one const tuple at the same index, so dropping the unrecognized `Ellipsis` merged them (Ellipsis and NotImplemented repr by name and are kept by value). Only the code object is named, not the data bound to it, and the docstring says so: two closures from one factory, two functions differing only in `__defaults__`, bound methods of two instances and every `functools.partial` render the same. The digest is stable across processes but not across Python versions, since `co_code` is version-specific bytecode. ## The collision the test pins ```python from torch._dynamo.precompile_package import _code_fingerprint, _object_identity left, right = (lambda x: x * (1, 2)), (lambda x: x * (1, 3)) left.__code__.co_code == right.__code__.co_code # True: only co_consts differ _code_fingerprint(left.__code__) == _code_fingerprint(right.__code__) # False # same for a frozenset constant, a nested code object, and an Ellipsis subscript: (lambda x: x in {1, 2}), (lambda x: x in {1, 3}) (lambda x: (lambda y: y + 1)), (lambda x: (lambda y: y + 2)) (lambda x: x[..., 0]), (lambda x: x[0, ...]) _object_identity(torch.nn.functional) # "is module torch.nn.functional" _object_identity(left) # "is @test_x.py:12#3f9a... __main__.<lambda>" _object_identity(object()) # "is a builtins.object" ``` `test_code_fingerprint_recurses_into_container_and_nested_consts` asserts, for each of the four pairs, that `co_code` agrees and the fingerprints differ, that an unrenderable const keeps its slot, and that the same source compiled twice agrees. `test_code_fingerprint_is_stable_across_processes` checks the digest of a fixed snippet against a fresh interpreter, which is the only thing that holds the "committed and diffed" line. `test_object_identity_puts_the_digest_before_the_truncation_point` pins the module and fallback renderings and that, on a qualname longer than the bound, the site and digest survive the cut. Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_code_fingerprint_recurses_into_container_and_nested_consts python test/dynamo/test_precompile_package.py -k test_code_fingerprint_is_stable_across_processes python test/dynamo/test_precompile_package.py -k test_object_identity_puts_the_digest_before_the_truncation_point lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in e4639d6 as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197971 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
…ization dropped (#197266) (#197972) **Summary.** Serialization drops every identity guard, so precompiling gives up on noticing that a guarded object was rebound; `_is_risky_drop(entry, namespaces)` is the lint that says which of those drops can plausibly change results on a capture-here / serve-there deployment, where the concern is DIVERGENCE: the serving machine runs the same source but a config, flag or environment variable picks a different object. It intersects the binding SITE with who owns the value, because either test alone is wrong: `self.act = getattr(F, cfg.activation)` and `self.act = cfg.act_fn` are the same swappable slot, so calling the first benign because `F.gelu` is torch-owned waves through capture-gelu-serve-silu, while `if flag: import impl_b as impl` then `impl.op` is a read off a module namespace exactly like `F.gelu` but the module is user code an env var chose. Three bindings are waived: a builtin read the ordinary way, an attribute read off a trusted namespace that torch or the stdlib owns or that owns a def of that same name, and a global bound to a def of the same name when torch or the stdlib owns the def or it lives in the file doing the reading; instance attributes, closure cells, aliased imports, cross-module `from x import op`, registry lookups, reads off a config module and an entry whose value could not be read are all risky. The docstring records the KNOWN GAP: every waiver judges the object capture happened to bind, not the statement that bound it, so a name bound conditionally is waived whenever the branch taken at capture is a waived shape, a third party that rebinds `F.gelu` at import is waived, and so is an alias config picks between two torch modules. `dropped_guards` stays the authoritative list; this is a lint over it, not a proof. `test_risky_drop_decision_table` pins every shape found so far on hand-built entries. One shape's source spelling is Dynamo's own: under `nested_graph_breaks=True` a callee's `act = pick()` crosses the break as `L['__nested_frame_values'][0][k]` rather than `L['act']`, and `test_risky_drop_sees_the_slot_behind_a_nested_resume` drives that layout and the flat one through a real compile, so the slot is flagged and the def read inside `pick()` waived either way. The capture-session corpus that drives real compiles through the same predicate belongs to a later stack. ## The decision, in order ```python def _is_risky_drop(entry, namespaces): source, value = entry.orig_guard.originating_source, entry.value if _is_dynamo_synthesized(source): return False # Dynamo's own generated resume functions if source.name in namespaces: return False # the guard IS on a trusted module if _reads_a_builtin(source, value): return False # len, sorted via __builtins_dict__ if not entry.has_value: return True # nothing to judge ownership by if isinstance(source, AttrSource): ns = namespaces.get(source.base.name) if ns is not None: # F.gelu, own_helpers.call ... return not (_is_library_module(ns.__name__) or (_owning_module(value) == ns.__name__ and value.__name__ == source.member)) if isinstance(source, GlobalSource) and getattr(value, "__name__", None) == source.global_name: return not (_is_library_module(_owning_module(value)) # from torch.nn.functional import silu or _defined_where_read(value, source.global_name, entry.orig_guard.user_stack)) # def in this file return True ``` ```python F.gelu(x) # waived: torch owns torch.nn.functional own_helpers.call(x) # waived: own_helpers owns a def named call own_helpers.act(x) # RISKY: act is bound to some other def, i.e. a slot cpkg.op(x) # RISKY: re-exported from cpkg.impl_b, chosen by an import elsewhere self.act(x) # RISKY: an instance attribute is a slot impl.op(x) # import impl_b as impl RISKY: the alias is the slot config.attn_impl(x) # RISKY: a config module is never a trusted namespace ``` Test Plan: ``` python test/dynamo/test_precompile_package.py -k test_risky_drop lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Reverted in e0ba7af as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197972 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Problem. The 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_withinprefix 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_rootsand_torch_roots-- plus_norm/_within, the realpath-normalized prefix test the consumers apply, and_norm_absolute, the gate every root candidate passes through._install_rootsis the load-bearing exclusion:purelibnests insidestdlibin a conda layout and insideplatstdlibin a venv (on a--with-platlibdir=lib64build it isplatlibthat 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, becauserealpathresolves a relative path against the process cwd, and a relative venvhomeorPYTHONHOMEleaves 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_withinare first consulted by_classify_filetwo commits up, and_is_library_module, the ownership verdict the lint applies, arrives three commits up.What the roots look like
_stdlib_rootsThe sources are the directory
os.__file__resolves into, taken only when that path is absolute,sys._stdlib_diron 3.11+, sysconfig'sstdlib/platstdlib, and<base_prefix>\DLLson Windows, where the stdlib's C extensions live besideLibrather than under it --base_prefixand notprefix, since a Windows venv has noDLLsdirectory of its own and readingprefixwould 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.pyis a per-file link into the store, sysconfig andsys._stdlib_diralready 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_filetakes the first stdlib root a path lies under as the outermost._install_rootsThe roots are sysconfig's
purelib/platlibplus whateversite.getsitepackages/getusersitepackagesanswer, minus any directory a stdlib root lies strictly under: on Windowsgetsitepackages()lists the bare prefix, which would otherwise putLibandDLLsinside an install root and classify the whole stdlib as third-party. Thesiteaccessors are reached throughgetattrinside atrythat also covers consuming their answer, because the old-virtualenvsite.pythis 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.
purelibis nested insidestdlibin a conda layout and insideplatstdlibin a venv, and on a--with-platlibdir=lib64build (Fedora, RHEL, openSUSE) it isplatlibthat nests instead, since sysconfig's prefix and venv schemes hard-codelibinpurelibbut interpolateplatlibdirintoplatliband 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_homeis the only one withpurelibatstdlib, and it is reachable only by naming it).test_install_roots_keep_a_directory_that_is_a_stdlib_rootfabricates the shape and pins that asymmetry: restoring the equality clause fails that test and no other._torch_rootsThe roots are the
torchpackage 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 oftorch.__path__, adopted once either spelling is among them; the gate rules out a substitutedsys.modules['torch'], not an entry a third party appended to the real one's__path__, and a relative entry is dropped rather than resolved, sincerealpathwould place it in the process cwd and make the caller's own project read as torch-owned._norm,_norm_absoluteand_within_norm/_withindo 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, theDLLsjoin, bothsiteaccessors and the__path__entries -- passes through_norm_absolute, which keeps only absolute strings, sincerealpathresolves a relative path against the process cwd. That is not hypothetical: a venv whosepyvenv.cfghomeis relative, or a relativePYTHONHOME, leavessys.base_prefix,sys._stdlib_dirand 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-Sskips), and a relativePYTHONUSERBASEleaves 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, whosetorch._Cis an extension module, and a frozen torch has no__file__and returns early;osis the exception that motivates the gate on its side, being frozen since 3.11 with a__file__spelled fromsys._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_withinare first consulted by_classify_filetwo 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 throughos.path.abspath:os.path.join(os.sep, ...)is a bare leading separator, whichntpath.isabsstopped accepting in 3.13, so on a Windows runner_norm_absolutewould 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 runtest/dynamo/, so CI would not have said so).test_roots_locate_the_stdlib_install_and_torch_dirspins the properties of the running interpreter the classifier will depend on: the three tuples are non-empty, the nesting runs one way only (sysconfig'spurelibsurvives 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 nosysconfig/sitelayout produces),os.__file__is under a stdlib root,torch.__file__'s directory is a torch root, and_withintreats/a/bcas 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_underreplays the Windows prefix shape on every platform, since the containment check above can only fail on a Windows runner: withsite.getsitepackagespatched to list the parent of a stdlib root, that directory is not an install root, no stdlib root lies under one, andpurelibstill is. It lists the parent of a root rather thansys.prefixbecause that is a strict ancestor whatever the host's layout is, whilesys.prefixis the host's shape: aconfigure --prefix=/build or a Windows embeddable unpacked at a drive root leaves it at a filesystem root, which this exclusion cannot drop,r + os.sepbeing a doubled separator no root starts with -- harmless in the code, since a root that swallows everything is one_withinmatches nothing against, but an assertion onsys.prefixwould fail there. It replacesgetsitepackages' answer rather than extending it for the reason the code reads it throughgetattrin atry: the old-virtualenvsite.pythis 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 failstest_roots_locate_the_stdlib_install_and_torch_dirswhereverpurelibnests under a stdlib root, which a venv or conda layout does and a Debian or Fedoradist-packagesone does not.test_install_roots_keep_a_directory_that_is_a_stdlib_rootfabricates 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 athird_party.pyin it is within the install roots.test_install_roots_skip_a_site_accessor_that_raisespins thetrywithgetsitepackagesraising, after which sysconfig'spureliband the other accessor's answer are still roots.test_install_roots_take_only_the_strings_a_site_accessor_listspins the consuming side: a non-string entry in a list is dropped rather than handed torealpath, and theNonethatgetusersitepackagesreturns 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_itexercises the trust gate withsys.modules['torch']replaced by a stub: a__path__that does not list thetorchpackage directory this file sits under is ignored and the result is exactly that directory, appending it makes the stub's absolute string entries count (aNoneamong them is dropped rather than handed torealpath, and so are""and a relative entry, whichrealpathwould have placed in the process cwd), a__path__that isNoneis ignored as well, and with no__file__(a frozen torch) the result is empty.test_stdlib_roots_take_the_windows_dlls_dirreplays the win32 branch withsys.platformpatched, since nothing else reaches it off a Windows runner; it primessysconfigbefore patching, because sysconfig's first initialization imports a_sysconfigdata_*_{sys.platform}_*module that does not exist for the patched platform.sys.base_prefixis patched to a fabricated directory in the same block, so the root is pinned tobase_prefixand readingsys.prefixinstead fails the test rather than passing on every interpreter CI runs, where the two coincide.sys.prefixitself is left alone deliberately: sysconfig re-initializes its config vars wheneversys.prefixmoves away from the value it cached (Support tracing through _get_current_dispatch_mode_stack #126789), and that re-init would import the_sysconfigdatamodule 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 patchessysconfig.get_pathsto a venv shape (stdlibat the base prefix,platstdlibthe venv's own lib directory withpurelibnested under it) andsys._stdlib_dirto 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:purelibis under a stdlib root and an install root all the same. Withos.__file__then patched toNone, the shape of a frozen os, andsys.platformpatched offwin32, the result is exactly the three remaining roots in sorted order, which pins the other branch of theos.__file__guard and the ordering_classify_filereads; a relativeos.__file__gives the same three, which pins theisabshalf 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_rootsreads that is not a path, and a Windows runner would add itsDLLsroot to that tuple.test_install_roots_take_purelib_and_platlib_on_a_lib64_build: in that venvpurelibandplatlibcoincide, as they do in every layout whereplatlibdirislib, so this test replays the system-interpreter shape where they do not (stdlibandplatlibunderlib64,purelibunderlib), with every stdlib source (os.__file__,sys._stdlib_dir, sysconfig's two keys) patched onto a made-up prefix andsys.platformpatched offwin32: a Debian or Ubuntu python3.12 has the realos.pyat/usr/lib/python3.12, the parent of a/usr/libpurelib, and a merged-lib host resolves/usr/lib64onto/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 branchtest_stdlib_roots_take_the_windows_dlls_dirpins in the other direction),platlibis under it andpurelibis not, both are install roots, and reading either key alone fails it. The same fixture hassitelist a directory that is a string prefix of the stdlib directory without being its parent (python3besidepython3.12) and pins that the exclusion keeps it:_withinalready pins that/a/bcis outside/a/b, and this is the mirror-image separator in_install_roots.test_norm_resolves_a_symlinked_prefix_into_its_rootbuilds a real symlink in a temporary directory (skipping where symlinks cannot be created) and pins therealpathin_norm: a file reached through a linked directory normalizes to a path under the resolved root, whichabspathwould not give.test_stdlib_roots_follow_a_symlink_farm_into_the_storepins the other shape, a real directory whose entries are links into a per-package store, which is whatpython -m venvmakes of a Nix, Guix or Spack profile: venv records the unresolvedsys._base_executableashome, so the child'sbase_prefix, sysconfig'sstdlibandsys._stdlib_dirall stay on the farm (measured on a venv built over such a farm), whilerealpathof any file in it lands in the store, which none of those sources name; since every consumer normalizes the file it asks about,_stdlib_rootstakes the directoryos.__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 normalizedos.__file__is within them, which fails without the resolved directory.test_torch_roots_follow_a_symlink_farm_into_the_storeis its mirror for_torch_roots: a farmtorchdirectory whose_dynamoandnnsubdirectories 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 normalizednn/functional.pyis within them, which fails when the directory alone is resolved, since then no root names where any torch module resolves and_classify_filewould answer False for all of torch.test_torch_roots_drop_a_link_that_flattens_this_files_depthis the shape that spelling must not follow: the same farm, but this module's link points at a flatpatchdir/precompile_package.pytwo levels below a directory that also holds amy_project/mymod.py; the roots are exactly the farm, and neithermymod.pynor the resolved module itself is within them, where chopping two components off the resolved file unconditionally reports the shared ancestor as a torch root andmymod.pyas torch-owned.test_roots_drop_a_relative_interpreter_pathpins the absolute-only gate on the sources no other test touches: sysconfig's four paths,sys._stdlib_dir,sys.base_prefix(withsys.platformpatched ontowin32so theDLLsjoin runs) and bothsiteaccessors are patched to the relative shapes a relativePYTHONHOMEandPYTHONUSERBASEproduce, and the stdlib roots are then exactly the directory the realos.__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_frompins the zip shape the summary describes: withos.__file__patched to<archive>/os.pyover a real zip, the archive itself, a file, is a stdlib root and aqueue.pybundled beside it is within the stdlib roots, which anisdirgate on that root would silently break.Test Plan:
Authored with an AI assistant.
🤖 Generated with Claude Code
Co-Authored-By: Claude Fable 5.1 [email protected]
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo @azahed98
Differential Revision: D121019756