Skip to content

[dynamo] Add typed guard provenance: a closed, total classification of where guards are rooted - #195286

Closed
bobrenjc93 wants to merge 15 commits into
gh/bobrenjc93/1083/basefrom
gh/bobrenjc93/1083/head
Closed

bobrenjc93 wants to merge 15 commits into
gh/bobrenjc93/1083/basefrom
gh/bobrenjc93/1083/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Guard-serialization consumers (torch._dynamo.package, torch._dynamo.aot_compile,
torch.compiler.precompile) all need the same classification: is a guard derived
from the traced frame's inputs (dispatch-relevant, must keep), or from the
surrounding Python environment (an environment-invariant contract may drop it)?
Today that question is answered ad hoc -- aot_compile keys off is_global, which
is true only for a chain rooted at exactly a GlobalSource and so misses imported
modules (ImportSource) and says nothing about interpreter/process-wide state. This
commit is additive infrastructure: it introduces a typed provenance so the
consumers added later in this stack classify guards structurally rather than
reinventing it.

Provenance is computed once from the typed Source chain, never by parsing the
rendered guard name. That choice is deliberate: rendered names embed input roots
inside call expressions (___tuple_iterator_getitem(L['it'], 0),
___from_numpy(L['x']), type(L['x']), list(dict.keys(L['d']))[0], ...), so a
name-prefix test would misfile those input guards as droppable environment
guards, and a dropped input guard serves a stale specialization with no error.

The classification is a closed GuardProvenance enum (INPUT, GLOBAL, AMBIENT,
SYNTHETIC), declared by every ROOT Source class and delegated through
ChainedSource, exposed as Guard.provenance and on GuardFilterEntry so
guard_filter_fn policies can key off it; GuardProvenance is re-exported from
torch.compiler for that purpose. It is fail-closed in both directions: an
unclassified root raises at classification time instead of defaulting, and a
totality test walks every Source subclass so a new source cannot land
unclassified. GLOBAL covers both module globals and imports (the latter is what
is_global misses); AMBIENT names interpreter/process-wide state (grad mode,
torch-function stack, streams), which is_global simply does not classify;
is_global keeps its existing narrow meaning for backward compatibility.

Three classification decisions worth calling out:

  • GlobalWeakRefSource is INPUT, not GLOBAL: dynamo-installed weakref proxies
    (G['_optimizer...']) stand in for the identity/liveness of traced runtime
    objects, so their WEAKREF_ALIVE guards are dispatch-relevant even though the
    lookup goes through globals (an end-to-end test pins this on a compiled
    optimizer step).
  • ShapeEnvSource is INPUT despite its synthetic root: the singleton SHAPE_ENV
    guard rooted there encodes the symbolic-shape constraints derived from the
    inputs, so a drop policy must never treat it as environment.
  • BackwardStateSource is SYNTHETIC, and ConstantSource is SYNTHETIC on the guard
    axis only (it cannot be guarded on); the latter's reconstruction bytecode
    still loads a dynamo-installed global, which the Note spells out so non-guard
    consumers do not over-infer.

Review order: the Note [Guard provenance] and enum in torch/_guards.py, the
Source/ChainedSource/Guard plumbing there, then the per-root declarations in
torch/_dynamo/source.py, the GuardFilterEntry field, and the tests.

Authored with an AI assistant.

Test Plan:

python test/dynamo/test_sources.py                 # 9 tests, OK (6 new)
python test/dynamo/test_guard_serialization.py     # 60 tests, OK (2 skipped)
lintrunner <touched files>                         # ok

Compatibility notes. GuardFilterEntry (a private dataclass in
torch._dynamo.types, handed to guard_filter_fn callbacks) gains a required
trailing provenance field: readers are unaffected, but out-of-tree code that
constructs entries itself must now pass it. Source.provenance fails closed
(NotImplementedError) for a root Source that does not declare _provenance; it
is evaluated whenever a guard filter is active and unconditionally when guards
are serialized for a package, so an out-of-tree root Source must declare its
provenance before it can be used with caching_precompile or guard_filter_fn.
Both are deliberate: a default would let a new root silently classify as
droppable.

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

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 11 Cancelled Jobs, 11 Pending

As of commit 3469f2c with merge base 3d3d3f4 (image):

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 30, 2026
…f where guards are rooted

Guard-serialization consumers (torch._dynamo.package, aot_compile,
torch.compiler.precompile) all need to answer the same question: is a guard
derived from the traced frame's inputs (dispatch-relevant, must keep) or from
the surrounding Python environment (an environment-invariant contract may
drop it)? Each consumer answers it today by re-deriving provenance from the
guard -- aot_compile keys off is_global, precompile originally parsed the
rendered guard name. Rendered names embed input roots inside call
expressions (___tuple_iterator_getitem(L['it'], 0), ___from_numpy(L['x']),
type(L['x'])), so string classification silently misfiles input guards as
droppable environment guards, and a dropped input guard serves a stale
specialization with no error.

This change makes provenance a first-class, typed property computed
structurally from the Source chain: a closed GuardProvenance enum (INPUT,
GLOBAL, AMBIENT, SYNTHETIC), declared by every ROOT Source class and
delegated through ChainedSource, exposed as Guard.provenance and on
GuardFilterEntry so guard_filter_fn policies can key off it. It is
deliberately fail-closed in both directions: an unclassified root raises at
classification time instead of defaulting, and a totality test walks every
Source subclass so a new source cannot land unclassified. AMBIENT separates
interpreter/process-wide state (grad mode, shape env, torch-function stack,
streams, backward state) from module globals, a distinction is_global
conflates; is_global keeps its existing narrow meaning for backward
compatibility.

Two classification decisions worth calling out. GlobalWeakRefSource is
INPUT, not GLOBAL: dynamo-installed weakref proxies (G['__optimizer_...'])
stand in for the identity/liveness of traced runtime objects -- their
WEAKREF_ALIVE guards distinguish e.g. optimizer instances, so an
environment-drop policy must never see them as droppable (an end-to-end test
pins this on a compiled optimizer step). ConstantSource is SYNTHETIC on the
guard axis only (it cannot be guarded on); its reconstruction bytecode still
loads a dynamo-installed global, which the Note spells out so non-guard
consumers do not over-infer.

Review order: the Note [Guard provenance] and enum in torch/_guards.py, the
Source/ChainedSource/Guard plumbing there, then the per-root declarations in
torch/_dynamo/source.py, the GuardFilterEntry field, and the tests.

Authored with an AI assistant.

Test Plan:

```
python test/dynamo/test_sources.py                 # 8 tests, OK (5 new)
python test/dynamo/test_guard_serialization.py     # 60 tests, OK (1 skipped)
python test/dynamo/test_guard_manager.py           # OK
python test/dynamo/test_aot_compile.py             # 42 tests, OK
lintrunner <touched files>                         # ok
```

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

ghstack-source-id: 1b353b6
Pull-Request: #195286
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@claude

@claude

claude Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Reviewing this PR

  • Gather context (diff, PR body, repo guidelines)
  • Deep review: Source hierarchy totality, fail-closed behavior, consumers
  • Fact-check findings
  • Post review

View job run

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "release notes: dynamo"

@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Closing in favor of the canonical stack #195353-#195362 (now also #195911-#195929). Note for future readers: this change has no counterpart there yet; the code remains in this PR's history if it is wanted later.

@bobrenjc93 bobrenjc93 closed this Sep 3, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1083/head branch November 14, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant