Skip to content

[precompile] Complete the guard-type classification and pin it with a totality test - #197268

Closed
bobrenjc93 wants to merge 28 commits into
gh/bobrenjc93/1224/basefrom
gh/bobrenjc93/1224/head
Closed

bobrenjc93 wants to merge 28 commits into
gh/bobrenjc93/1224/basefrom
gh/bobrenjc93/1224/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary. With the shape-bearing and unmodelled sets in place, this commit adds the other two and the test that makes the classification enforceable. _IDENTITY_GUARD_TYPES freezes CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES, both for the fingerprinting code that follows and as the base of _INVARIANT_DROPPABLE_GUARD_TYPES, the ONLY guard types an invariance policy may drop, and only when proven invariant across every captured variant: the identity guards the default filter drops anyway as unserializable, derived from that same set so the two cannot disagree, plus BUILTIN_MATCH, an identity match the default filter keeps; the ambient-state guards (DEFAULT_DEVICE, FUNCTORCH_STACK_MATCH, DUAL_LEVEL, AUTOGRAD_SAVED_TENSORS_HOOKS) are unmodelled per the previous commit, so nothing outside identity is droppable. _NOOP_GUARD_TYPES (DETERMINISTIC_ALGORITHMS, GRAD_MODE) are markers whose GuardBuilder method is pass and whose check is made by GLOBAL_STATE's leaf, so nothing about them is ever serialized or dropped, and _is_noop_guard_type adds EMPTY_NN_MODULE_HOOKS_DICT under the default skip_nnmodule_hook_guards, where the builder emits nothing for it; with the skip off it emits a real SEQUENCE_LENGTH, which is why the previous commit classified it shape-bearing rather than droppable. test_guard_policy_classification_is_total enumerates every uppercase callable on GuardBuilder (through dir, so a method added on GuardBuilderBase or a mixin counts) and asserts the four sets cover all of them, contain nothing else, are pairwise disjoint, and that the identity set is inside the droppable one, so a guard type added to Dynamo fails this test until someone triages it and is KEPT unconditionally until then. Guards installed outside GuardBuilder -- the root manager's DuplicateInputs and StorageOverlap exprs and the dimension-marking lambda -- never reach the guard filter and are outside the policy as well. test_noop_guard_type_follows_the_hook_guard_config pins the config-dependent answer.

The test

guard_types = {name for name in dir(GuardBuilder) if name.isupper() and callable(getattr(GuardBuilder, name))}
sets = {
    "_SHAPE_BEARING_GUARD_TYPES": _SHAPE_BEARING_GUARD_TYPES,
    "_UNMODELLED_GUARD_TYPES": _UNMODELLED_GUARD_TYPES,
    "_INVARIANT_DROPPABLE_GUARD_TYPES": _INVARIANT_DROPPABLE_GUARD_TYPES,
    "_NOOP_GUARD_TYPES": _NOOP_GUARD_TYPES,
}
classified = frozenset().union(*sets.values())
assert guard_types - classified == set()   # "unclassified GuardBuilder guard type(s): add each to exactly one policy set"
assert classified - guard_types == set()   # "phantom entries: no GuardBuilder method by these names"
for (a_name, a), (b_name, b) in itertools.combinations(sets.items(), 2):
    assert not (a & b)
assert _IDENTITY_GUARD_TYPES <= _INVARIANT_DROPPABLE_GUARD_TYPES
_is_noop_guard_type("GRAD_MODE")                     # True
_is_noop_guard_type("EMPTY_NN_MODULE_HOOKS_DICT")    # True under the default config, False under
                                                     # torch._dynamo.config.patch(skip_nnmodule_hook_guards=False)

Test Plan:

python test/dynamo/test_precompile_package.py -k test_guard_policy_classification_is_total
python test/dynamo/test_precompile_package.py -k test_noop_guard_type_follows_the_hook_guard_config
lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py

Authored with an AI assistant.

🤖 Generated with Claude Code

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 Sep 16, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 36 Pending, 25 Unrelated Failures, 1 Unclassified Failure

As of commit b2adb22 with merge base d78bbf2 (image):

🟡 GREEN LIGHT - PR was reverted - re-landing requires human review:

Green Light will not review this PR again, on this or any later commit; re-landing it needs a human approval.

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

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

@pytorch-bot pytorch-bot Bot added ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests module: dynamo labels Sep 16, 2026
This was referenced Sep 16, 2026
@pytorchmergebot pytorchmergebot added Reverted ci-no-td Do not run TD on this PR labels Sep 21, 2026
@pytorchgreenlight
pytorchgreenlight Bot dismissed their stale review September 21, 2026 14:57

This pull request was reverted; greenlight's approval no longer applies.

[ghstack-poisoned]
This was referenced Sep 21, 2026
@bobrenjc93 bobrenjc93 closed this Sep 21, 2026
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
… totality test (#197268) (#197969)

**Summary.** With the shape-bearing and unmodelled sets in place, this commit adds the other two and the test that makes the classification enforceable. `_IDENTITY_GUARD_TYPES` freezes `CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES`, both for the fingerprinting code that follows and as the base of `_INVARIANT_DROPPABLE_GUARD_TYPES`, the ONLY guard types an invariance policy may drop, and only when proven invariant across every captured variant: the identity guards the default filter drops anyway as unserializable, derived from that same set so the two cannot disagree, plus `BUILTIN_MATCH`, an identity match the default filter keeps; the ambient-state guards (`DEFAULT_DEVICE`, `FUNCTORCH_STACK_MATCH`, `DUAL_LEVEL`, `AUTOGRAD_SAVED_TENSORS_HOOKS`) are unmodelled per the previous commit, so nothing outside identity is droppable. `_NOOP_GUARD_TYPES` (`DETERMINISTIC_ALGORITHMS`, `GRAD_MODE`) are markers whose `GuardBuilder` method is `pass` and whose check is made by `GLOBAL_STATE`'s leaf, so nothing about them is ever serialized or dropped, and `_is_noop_guard_type` adds `EMPTY_NN_MODULE_HOOKS_DICT` under the default `skip_nnmodule_hook_guards`, where the builder emits nothing for it; with the skip off it emits a real `SEQUENCE_LENGTH`, which is why the previous commit classified it shape-bearing rather than droppable. `test_guard_policy_classification_is_total` enumerates every uppercase callable on `GuardBuilder` (through `dir`, so a method added on `GuardBuilderBase` or a mixin counts) and asserts the four sets cover all of them, contain nothing else, are pairwise disjoint, and that the identity set is inside the droppable one, so a guard type added to Dynamo fails this test until someone triages it and is KEPT unconditionally until then. Guards installed outside `GuardBuilder` -- the root manager's `DuplicateInputs` and `StorageOverlap` exprs and the dimension-marking lambda -- never reach the guard filter and are outside the policy as well. `test_noop_guard_type_follows_the_hook_guard_config` pins the config-dependent answer.

## The test

```python
guard_types = {name for name in dir(GuardBuilder) if name.isupper() and callable(getattr(GuardBuilder, name))}
sets = {
    "_SHAPE_BEARING_GUARD_TYPES": _SHAPE_BEARING_GUARD_TYPES,
    "_UNMODELLED_GUARD_TYPES": _UNMODELLED_GUARD_TYPES,
    "_INVARIANT_DROPPABLE_GUARD_TYPES": _INVARIANT_DROPPABLE_GUARD_TYPES,
    "_NOOP_GUARD_TYPES": _NOOP_GUARD_TYPES,
}
classified = frozenset().union(*sets.values())
assert guard_types - classified == set()   # "unclassified GuardBuilder guard type(s): add each to exactly one policy set"
assert classified - guard_types == set()   # "phantom entries: no GuardBuilder method by these names"
for (a_name, a), (b_name, b) in itertools.combinations(sets.items(), 2):
    assert not (a & b)
assert _IDENTITY_GUARD_TYPES <= _INVARIANT_DROPPABLE_GUARD_TYPES
```

```python
_is_noop_guard_type("GRAD_MODE")                     # True
_is_noop_guard_type("EMPTY_NN_MODULE_HOOKS_DICT")    # True under the default config, False under
                                                     # torch._dynamo.config.patch(skip_nnmodule_hook_guards=False)
```

Test Plan:

```
python test/dynamo/test_precompile_package.py -k test_guard_policy_classification_is_total
python test/dynamo/test_precompile_package.py -k test_noop_guard_type_follows_the_hook_guard_config
lintrunner torch/_dynamo/precompile_package.py test/dynamo/test_precompile_package.py
```

Authored with an AI assistant.

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

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

Reverted in ca5b700 as a dependent of #197262 and back in the stack unchanged.

Pull Request resolved: #197969
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1224/head branch November 25, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo Reverted topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants