Repository navigation
[precompile] Recognise the trusted module namespaces an attribute guard hangs off - #197265
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:07
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
…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
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. Dynamo guards every module it walks through, so the path down to
F.geluis 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 aGlobalSourceand returns the TRUSTED ones, mapped from source name to module._source_root(source), a one-line walk downChainedSource.baseto the root, is added here as the helper that finds thatGlobalSource. 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_xalias 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 plainimport own_subinside the parent) or the parent's name plus the attribute (from . import sub, andimport mypkg.layers, which Dynamo guards asG['mypkg'].layers). An ALIASED user module is none of those:if flag: import impl_b as implpicks whatimpl.opresolves to per machine, and so doesfrom . import impl_b as implin 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 Fincluded; the price, taken deliberately because flaggingFwould 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_torchalias, only the attributes read off it, so aliases with no module-valued entry are recovered from their name rather than treatingtorch.Tensoras 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 insideis_trusted, not a filter on what is collected, so a config module recovered from an__import_xalias (from torch._dynamo.config import verbosein an inlined function) is refused the same way as one bound under a plain name.Which namespaces are trusted
The result feeds
_is_risky_drop(next commit): a dropped guard whose source is in the returned dict, or whosesource.base.nameis 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_repointbuilds each shape above from hand-madeGuardFilterEntryvalues and asserts the exact trusted set.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