Skip to content

Support tracing through _get_current_dispatch_mode_stack - #126789

Closed
seanxwzhang wants to merge 1 commit into
pytorch:mainfrom
seanxwzhang:sz/fix_get_mode_stack_during_compilation
Closed

seanxwzhang wants to merge 1 commit into
pytorch:mainfrom
seanxwzhang:sz/fix_get_mode_stack_during_compilation

Conversation

@seanxwzhang

@seanxwzhang seanxwzhang commented May 21, 2024 •

Copy link
Copy Markdown

Summary

Fixes #125694

This PR allow dynamo tracing through _get_current_dispatch_mode_stack but only returns a [] as per @ezyang's comment

Test Plan

Added tests for this, locally passing. CI should help too.

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

@pytorch-bot

pytorch-bot Bot commented May 21, 2024 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 49 New Failures

As of commit 4c0e2a1 with merge base 2f53747 (image):

NEW FAILURES - The following jobs have failed:

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

@janeyx99
janeyx99 requested a review from anijain2305 May 21, 2024 17:39
@janeyx99 janeyx99 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 21, 2024
@ezyang

ezyang commented May 21, 2024

Copy link
Copy Markdown
Contributor

I don't support this particular implementation, because there's a hidden invariant here that's not obvious from the implementation. _get_current_dispatch_mode_stack doesn't necessarily return an empty list at compile time, it just happens that it will be empty because we don't support it in Dynamo. So it's much more logical for this logic to live in Dynamo, for the _C binding, because the knowledge of if you should do this or not is an internal decision to Dynamo. And someday, if we do support dispatch mode stack dynamo tracing, we'd be obligated to return the real stack in that case.

@ezyang

ezyang commented May 21, 2024

Copy link
Copy Markdown
Contributor

Also, it's important to fix #115653 first, because without that, we aren't actually checking the dispatch stack is empty

@seanxwzhang

Copy link
Copy Markdown
Author

Thanks for the comments, I'll adjust accordingly.

@seanxwzhang

Copy link
Copy Markdown
Author

I don't support this particular implementation, because there's a hidden invariant here that's not obvious from the implementation. _get_current_dispatch_mode_stack doesn't necessarily return an empty list at compile time, it just happens that it will be empty because we don't support it in Dynamo. So it's much more logical for this logic to live in Dynamo, for the _C binding, because the knowledge of if you should do this or not is an internal decision to Dynamo. And someday, if we do support dispatch mode stack dynamo tracing, we'd be obligated to return the real stack in that case.

On a closer look, it seems to me that _get_current_dispatch_mode_stack does not happen to return an an empty list at compile time in the current implementation, but rather it will always return [<torch._subclasses.fake_tensor.FakeTensorMode>] because

  1. When compiling, all user modes are disabled , and a fake tensor mode is added to facilitate tracing.
  2. As a result, when _get_current_dispatch_mode_stack gets traced, it will always return a list with the fake mode, from the C binding side.

To make sure it returns [], I think distinguishing the fake tensor mode "injected" by dynamo is necessary, and doing it from python side is arguably cleaner than doing it from C binding (which requires at least a variable to keep track of whether we are compiling)?

(I've tested above)

@ezyang please let me know if I'm missing something here

@ezyang

ezyang commented May 28, 2024

Copy link
Copy Markdown
Contributor

Ah yes, you don't want to actually return the real dispatch mode stack in the implementation, because of the aforementioned fake tensor mode. (Except if you're doing torch.export within an outer fake tensor mode, in which case that mode had better show up on the list!)

@github-actions

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been updated in a while so we're going to go ahead and mark this as Stale.
Feel free to remove the Stale label if you feel this was a mistake.
If you are unable to remove the Stale label please contact a maintainer in order to do so.
If you want the bot to never mark this PR stale again, add the no-stale label.
Stale pull requests will automatically be closed after 30 days of inactivity.

@github-actions github-actions Bot added the Stale label Jul 27, 2024
@github-actions github-actions Bot closed this Aug 26, 2024
pytorchmergebot pushed a commit that referenced this pull request Sep 19, 2026
…e-ownership lint (#197262)

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

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

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

## What the roots look like

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

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

## `_stdlib_roots`

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

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

## `_install_roots`

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

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

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

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

## `_torch_roots`

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

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

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

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

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

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

## What calls these

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

## Tests

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

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

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_roots_locate_the_stdlib_install_and_torch_dirs -k test_norm_resolves_a_symlinked_prefix_into_its_root -k test_stdlib_roots_follow_a_symlink_farm_into_the_store -k test_torch_roots_follow_a_symlink_farm_into_the_store -k test_torch_roots_drop_a_link_that_flattens_this_files_depth -k test_roots_drop_a_relative_interpreter_path -k test_stdlib_roots_take_the_archive_a_zipped_os_comes_from -k test_stdlib_roots_take_the_windows_dlls_dir -k test_stdlib_roots_take_each_source_in_a_venv_layout -k test_install_roots_take_purelib_and_platlib_on_a_lib64_build -k test_install_roots_drop_a_directory_the_stdlib_sits_under -k test_install_roots_keep_a_directory_that_is_a_stdlib_root -k test_install_roots_skip_a_site_accessor_that_raises -k test_install_roots_take_only_the_strings_a_site_accessor_lists -k test_torch_roots_trust_torch_path_only_when_this_file_is_in_it
lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py
```

Authored with an AI assistant.

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

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

Pull Request resolved: #197262
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197277, #197258, #197259, #197356, #197261
pytorchmergebot pushed a commit that referenced this pull request Sep 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor module: dynamo open source Stale triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Dynamo] Support tracing through _get_current_dispatch_mode_stack

4 participants