Skip to content

[precompile] Make _parse_artifact_metadata tracer-aware - #197278

Closed
bobrenjc93 wants to merge 35 commits into
gh/bobrenjc93/1234/basefrom
gh/bobrenjc93/1234/head
Closed

bobrenjc93 wants to merge 35 commits into
gh/bobrenjc93/1234/basefrom
gh/bobrenjc93/1234/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary. load recovers the calling convention of an artifact by parsing python_code with ast and reading the top-level NAME = <literal> assignments, and until now it required one fixed set of names: the make_fx driver's PARAM_NAMES, OUT_SPEC, USER_INPUT_SHAPES and so on. A dynamo-tracer artifact carries a different set, because its multi-graph driver rehydrates frames from opaque blobs rather than reading a parameter list, so the required set is now chosen by the TRACER literal: absent (every artifact written before this) or anything but "dynamo" keeps the make_fx set unchanged, while "dynamo" requires BACKEND, FN_NAME, FRAMES, DROPPED_GUARDS, RISKY_DROPPED_GUARDS, WONT_GENERALIZE, _FRAMES, _BACKENDS, _ENTRY_BINDING and the two versions that lock the blobs to the build that wrote them, _DYNAMO_PYTHON_VERSION for the marshalled bytecode and TORCH_VERSION for the pickled guard state (the multi-graph driver refuses to unpickle it under another torch build; a make_fx artifact inlines neither, so it needs no such lock), and a SERVING_MODE == "installed" artifact swaps _FRAMES/_BACKENDS for _PACKAGE and UNREACHABLE_WITHOUT_INSTALL. The parser collects the top-level assignments in one pass, last assignment winning as it would under exec, so the literal that selects the required set and the value reported for it are the same assignment. A consumed name whose value is not a Python literal, TRACER and SERVING_MODE included, raises PrecompileError naming the constant instead of a raw ValueError (or, for a set or dict literal with an unhashable member, TypeError) out of ast.literal_eval; an unconsumed top-level assignment is still skipped with a debug log. Four names are parsed when present but never required, so an auditor gets them back as data and older artifacts load unchanged: TRACER and SERVING_MODE, which select the required set and so would check nothing as members of it (SERVING_MODE defaults to "standalone" in the result), and the guard-audit sections POLICY_DROPPED_GUARDS and DROPPED_GUARD_CODE. The emitter of the dynamo set lives further up the stack; this commit lands the reader first so those artifacts load the moment they are produced.

Before and after

from torch._precompile import _parse_artifact_metadata

_parse_artifact_metadata('TRACER = "dynamo"\nBACKEND = "eager"\n')
# parent: PrecompileError: python_code is missing calling-convention metadata ['BUFFER_NAMES', ...]
#         (the make_fx names were always required)
# now:    PrecompileError: python_code is missing calling-convention metadata
#         ['DROPPED_GUARDS', 'FN_NAME', 'FRAMES', 'RISKY_DROPPED_GUARDS', ...]  -- the dynamo set

_parse_artifact_metadata("BACKEND = object()\n...")
# parent: ValueError: malformed node or string ...   (out of ast.literal_eval)
# now:    PrecompileError: python_code 'BACKEND' calling-convention metadata is malformed; it must be a Python literal.

meta = _parse_artifact_metadata(make_fx_python_code)
meta["SERVING_MODE"]     # "standalone": filled in for artifacts that predate the field

test_parse_artifact_metadata_required_set_follows_tracer pins the three required sets from hand-written sources (make_fx both with TRACER absent and with TRACER = 'other'), and test_parse_artifact_metadata_literals parses a complete standalone and a complete installed dynamo source and covers the optional sections, the SERVING_MODE default, last-assignment-wins and the malformed-literal error on both a call and an unhashable set member. The existing load tests (test_load_invalid_python_code_rejected, test_missing_calling_convention_metadata_rejected, the export/reload round trips) keep passing.

Test Plan:

python test/test_precompile.py -k parse_artifact_metadata
python test/test_precompile.py
lintrunner torch/_precompile.py test/test_precompile.py

Authored with an AI assistant.

🤖 Generated with Claude Code

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

[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/197278

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

⏳ 52 Pending, 25 Unrelated Failures

As of commit e1d88f9 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.

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.

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 13:12

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
…97980)

**Summary.** `load` recovers the calling convention of an artifact by parsing `python_code` with `ast` and reading the top-level `NAME = <literal>` assignments, and until now it required one fixed set of names: the make_fx driver's `PARAM_NAMES`, `OUT_SPEC`, `USER_INPUT_SHAPES` and so on. A dynamo-tracer artifact carries a different set, because its multi-graph driver rehydrates frames from opaque blobs rather than reading a parameter list, so the required set is now chosen by the `TRACER` literal: absent (every artifact written before this) or anything but `"dynamo"` keeps the make_fx set unchanged, while `"dynamo"` requires `BACKEND`, `FN_NAME`, `FRAMES`, `DROPPED_GUARDS`, `RISKY_DROPPED_GUARDS`, `WONT_GENERALIZE`, `_FRAMES`, `_BACKENDS`, `_ENTRY_BINDING` and the two versions that lock the blobs to the build that wrote them, `_DYNAMO_PYTHON_VERSION` for the marshalled bytecode and `TORCH_VERSION` for the pickled guard state (the multi-graph driver refuses to unpickle it under another torch build; a make_fx artifact inlines neither, so it needs no such lock), and a `SERVING_MODE == "installed"` artifact swaps `_FRAMES`/`_BACKENDS` for `_PACKAGE` and `UNREACHABLE_WITHOUT_INSTALL`. The parser collects the top-level assignments in one pass, last assignment winning as it would under `exec`, so the literal that selects the required set and the value reported for it are the same assignment. A consumed name whose value is not a Python literal, `TRACER` and `SERVING_MODE` included, raises `PrecompileError` naming the constant instead of a raw `ValueError` (or, for a set or dict literal with an unhashable member, `TypeError`) out of `ast.literal_eval`; an unconsumed top-level assignment is still skipped with a debug log. Four names are parsed when present but never required, so an auditor gets them back as data and older artifacts load unchanged: `TRACER` and `SERVING_MODE`, which select the required set and so would check nothing as members of it (`SERVING_MODE` defaults to `"standalone"` in the result), and the guard-audit sections `POLICY_DROPPED_GUARDS` and `DROPPED_GUARD_CODE`. The emitter of the dynamo set lives further up the stack; this commit lands the reader first so those artifacts load the moment they are produced.

## Before and after

```python
from torch._precompile import _parse_artifact_metadata

_parse_artifact_metadata('TRACER = "dynamo"\nBACKEND = "eager"\n')
# parent: PrecompileError: python_code is missing calling-convention metadata ['BUFFER_NAMES', ...]
#         (the make_fx names were always required)
# now:    PrecompileError: python_code is missing calling-convention metadata
#         ['DROPPED_GUARDS', 'FN_NAME', 'FRAMES', 'RISKY_DROPPED_GUARDS', ...]  -- the dynamo set

_parse_artifact_metadata("BACKEND = object()\n...")
# parent: ValueError: malformed node or string ...   (out of ast.literal_eval)
# now:    PrecompileError: python_code 'BACKEND' calling-convention metadata is malformed; it must be a Python literal.

meta = _parse_artifact_metadata(make_fx_python_code)
meta["SERVING_MODE"]     # "standalone": filled in for artifacts that predate the field
```

`test_parse_artifact_metadata_required_set_follows_tracer` pins the three required sets from hand-written sources (make_fx both with `TRACER` absent and with `TRACER = 'other'`), and `test_parse_artifact_metadata_literals` parses a complete standalone and a complete installed dynamo source and covers the optional sections, the `SERVING_MODE` default, last-assignment-wins and the malformed-literal error on both a call and an unhashable set member. The existing load tests (`test_load_invalid_python_code_rejected`, `test_missing_calling_convention_metadata_rejected`, the export/reload round trips) keep passing.

Test Plan:

```
python test/test_precompile.py -k parse_artifact_metadata
python test/test_precompile.py
lintrunner torch/_precompile.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]>

Reverted in bc6503f as a dependent of #197262 and back in the stack unchanged.
Pull Request resolved: #197980
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #197961, #197962, #197963, #197964, #197965, #197966, #197967, #197968, #197969, #197970, #197971, #197972, #197973, #197974, #197975, #197976, #197977, #197978, #197979
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1234/head branch November 25, 2026 01:48
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/trunk Trigger trunk jobs on your pull request Merged Reverted topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants