Repository navigation
[precompile] Decide library ownership by where a module resolves, not by its name - #197264
Closed
bobrenjc93 wants to merge 21 commits into
Closed
bobrenjc93 wants to merge 21 commits into
bobrenjc93 wants to merge 21 commits into
Conversation
[ghstack-poisoned]
This was referenced Sep 16, 2026
Closed
Closed
pytorchgreenlight
Bot
dismissed
their stale review
September 21, 2026 15:12
This pull request was reverted; greenlight's approval no longer applies.
[ghstack-poisoned]
This was referenced Sep 20, 2026
Closed
Closed
Closed
Closed
Closed
Closed
Closed
Closed
bobrenjc93
added a commit
that referenced
this pull request
Sep 21, 2026
) **Summary.** Whatever autocast state the capture ran under is already baked into the artifact -- ATen casts for the eager backend, generated kernels for inductor -- but the artifact still re-dispatches at serve time (the eager graph's ATen calls, and on the inductor path every fallback op, which is emitted at its `.default` overload -- e.g. `aten.addbmm.default`, which AutocastCPU registers), so a serving process with autocast enabled would cast a second time. Both inlined drivers now run the graph under `torch._C._DisableAutocast()`, the `c10::impl::ExcludeDispatchKeyGuard` over `autocast_dispatch_keyset` (`torch/csrc/autograd/init.cpp`) that AOTAutograd already emits into its own generated wrappers as `_DisableAutocast_` when a compile ran under autocast (`torch/_functorch/_aot_autograd/runtime_wrappers.py`). It is one RAII exclusion of the autocast keys for every device: no per-device list, no nesting counter, and no `clear_autocast_cache()` on exit, so it is safe to enter unconditionally on every call and leaves the caller's autocast state exactly as it found it. This pins autocast off for the duration of the call regardless of capture-time or serve-time state, exactly like the eager driver's pre-existing unconditional `no_grad`; the programming-model docstring gets the same sentence in the later commit that rewrites it (E2). AOTAutograd's guard is conditional on the capture having run under autocast; precompile's is unconditional because the leak it closes runs the other way too (a capture made without autocast, served under it), which is the case the test exhibits. An earlier draft of this commit recorded a `GRAPH_DEVICES` metadata field and entered `torch.amp.autocast(dev, enabled=False)` per device; that reimplemented the primitive with a narrower cache-clear hazard (any exit that returns autocast's nesting count to zero wipes the process-wide cast cache), so the field, its emitter and its parser entry are gone and the artifact format is unchanged from the parent. ## Before and after ```python compiled = PrecompiledModule(lambda m, x: m(x), backend="eager") compiled._compile((model, x)) ns = {"__name__": "artifact"} exec(compiled.to_python_code(), ns) with torch.autocast("cpu", dtype=torch.bfloat16): out = ns["forward"](model, x) # parent: the captured graph re-dispatched under autocast and cast its inputs a second time (bf16 out) # now: the driver runs call(...) under torch._C._DisableAutocast() (fp32 out, equal to the # no-autocast call), and the caller's autocast state is as it was afterwards ``` ## The driver change ```python # _eager_forward: with _torch._C._DisableAutocast(), _torch.no_grad(): out = list(call([...])) # _inductor_forward: with _torch._C._DisableAutocast(): out = list(call([...])) ``` `test_artifact_neutralizes_ambient_autocast` (parametrized over both backends, CPU bf16 autocast) captures a `torch.addbmm` model and checks that a call under ambient autocast returns the fp32 result of eager `model(x)` computed outside any autocast, that the ambient region is still live and bf16 after the call, and that autocast is off again after the region. `addbmm` is the op that makes the inductor case load-bearing on CPU: `KERNEL_CPU(addbmm, lower_precision_fp)` registers it for AutocastCPU, `make_fallback(aten.addbmm)` leaves it undecomposed, and `FallbackKernel` keeps builtin aten ops at their functional overload, so the inductor artifact calls `torch.ops.aten.addbmm.default` (the `Linear`/`addmm` graph cannot show this: `extern_kernels.addmm` binds `addmm.out`, which autocast never registers). Deleting either guard fails its case: eager with `bfloat16 != float32`, inductor with `assert_tensor_metadata` raising `expected dtype torch.float32 but got torch.bfloat16`. Test Plan: ``` python test/test_precompile.py -k autocast python test/test_precompile.py lintrunner torch/_precompile.py torch/_precompile_driver.py test/test_precompile.py ``` Authored with an AI assistant. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197279 Approved by: https://github.com/pytorchgreenlight ghstack dependencies: #197277, #197258, #197259, #197356, #197261, #197262, #197263, #197428, #197260, #197264, #197595, #197265, #197267, #197268, #197269, #197270, #197266, #197271, #197272, #197273, #197274, #197275, #197721, #197276, #197278 Re-land of #197279, reverted in 70f4f9b as a dependent of #197262 (whose test the re-land below fixes). ghstack-source-id: bf1865a
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
… 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
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):
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,codeanddistutilsare all stdlib names a third party ships, andimport distutilsin a default setuptools install actually resolves tosite-packages/setuptools/_distutils, selected bySETUPTOOLS_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__) andtorch.ops(aModuleTypesubclass whose__file__is a class attribute the module dict never sees) keep their waiver because their packages are located, while a shadowed submodule (acollections.abcundersite-packages, atorch.foooutside 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) andNoneare all untrusted. The torch arm alone has an escape hatch, and the docstring says so: a frozen torch gives_torch_rootsnothing to anchor to, and then every torch name is waived on its name with no location evidence.Behaviour pinned by the tests
The tests
Two module-level fixtures carry the rows.
_STDLIB_ROOTis sysconfig'sstdlib, 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, whilesite-packages/torchIS one wherever purelib nests under stdlib)._NOT_LIBRARY_MODULESis a table of shadow modules, one row per refused shape, each labelled by the check that refuses it: under an install dir with_install_rootspatched to()(only_INSTALL_DIR_NAMESrefuses it), under a nested install root with nosite-packagescomponent (only the_install_rootsexclusion does), no file and no spec, a relative file (judged with the cwd at_STDLIB_ROOT, where the realgraphlib.pysits, so that without theisabsgate the name would resolve to stdlib and be waived),torchitself andtorch.foooutside 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 shadowedcollections.abc; a__file__with an embedded NUL has no row, because_is_library_modulerefuses it whether_classify_file's NUL gate answers None or_normraises out of_located(the gate is pinned by_classify_file's own tests).test_library_module_requires_the_name_to_resolve_to_the_libraryis parametrized over_NOT_LIBRARY_MODULESso a regression names its row; the rows are built fromtypes.ModuleTypeobjects patched intosys.moduleswith_install_rootspatched 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_rootsis 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: noTruepath is exercised by this commit's test, so on its own it cannot tell the function fromreturn 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:
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