Repository navigation
[precompile] Make _parse_artifact_metadata tracer-aware (#197278) - #197980
Closed
bobrenjc93 wants to merge 1 commit into
Closed
bobrenjc93 wants to merge 1 commit into
bobrenjc93 wants to merge 1 commit into
Conversation
[ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/197980
Note: Links to docs will display an error until the docs builds have been completed. ❌ 1 New Failure, 1 Unclassified FailureAs of commit 8863e93 with merge base d78bbf2 ( 🟢 GREEN LIGHT - PR approved to be merged without human review:
reason: NEW FAILURE - The following job has failed:
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:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
This was referenced Sep 21, 2026
Closed
Closed
Closed
Closed
Closed
This was referenced Sep 21, 2026
Closed
Closed
Closed
Collaborator
|
Starting merge as part of PR stack under #197981 |
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 21, 2026
) (#197981) **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]> Reverted in 70f4f9b as a dependent of #197262 and back in the stack unchanged. Pull Request resolved: #197981 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, #197980
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…pes (#197982) **Summary.** These are the three public-facing types of the caller-driven precompile API that later commits build on, added here as plain classes in `torch/_precompile.py` with no public export yet. `MakeFxTracer` is a frozen dataclass holding the one make_fx-specific knob, `decompositions`, and is what a caller will pass as `tracer=` to select the single-trace front-end. `PrecompiledRunnable` is the base type `load` will return: a callable with the captured `fn`'s calling convention that can also be entered as a context manager and unloaded, with `installed = False` and no-op `__enter__`/`__exit__`/`unload` for a standalone artifact. `Capture` is the base type the capture entry point will return, whose three methods all raise `NotImplementedError` until a concrete capture fills them in. `PrecompiledModule`, the existing make_fx runnable, now subclasses `PrecompiledRunnable` and forwards keyword arguments from `__call__` to the loaded forward; the make_fx drivers take positional arguments only, so a keyword argument fails there with the usual `TypeError` at the call, and the multi-graph driver will bind them. The three types keep their truthful `__module__` (`torch._precompile`) here: nothing exports them yet, and the commit that makes `torch.compiler.precompile` a module re-homes `MakeFxTracer` and `Capture` under it together with the other re-exports. `MakeFxTracer` has no consumer yet either: the callable API's string `tracer=` and its separate `decompositions=` parameter are retired together with that API later in this stack, where `tracer=MakeFxTracer(...)` takes over. The new `Self` annotation import lives in the `TYPE_CHECKING` block, next to the `Callable`/`Mapping` one the module already had. ```python @dataclasses.dataclass(frozen=True) class MakeFxTracer: decompositions: dict | None = None # forwarded to make_fx as decomposition_table class PrecompiledRunnable: installed: bool = False # True for the installing shape, added later def __call__(self, *args, **kwargs): raise NotImplementedError def __enter__(self): return self def __exit__(self, *exc): self.unload() def unload(self) -> None: ... # no-op: a standalone artifact installed nothing class Capture: def __enter__(self): raise NotImplementedError def __exit__(self, *exc): raise NotImplementedError def __call__(self, *args, **kwargs): raise NotImplementedError class PrecompiledModule(PrecompiledRunnable): # was: class PrecompiledModule: def __call__(self, *args, **kwargs): ... return self._loaded_forward(*args, **kwargs) # was: (*args) ``` ```python f = PrecompiledModule._from_loaded(forward, backend="eager") # what load() builds isinstance(f, PrecompiledRunnable) # True now with f: # enters and exits as a no-op f(model, x) ``` `test_precompiled_module_is_a_standalone_runnable` pins the reparenting: `isinstance`, `installed == False`, the no-op `with`/`unload`, keyword forwarding, and the not-runnable refusal of a bare `PrecompiledModule`. Test Plan: ``` python test/test_precompile.py -k test_precompiled_module_is_a_standalone_runnable 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]> Pull Request resolved: #197982 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, #197980, #197981
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
… optional (#197983) **Summary.** `_make_inlined_forward(python_code)` is the no-cache path of `load`: it `exec`s the self-contained artifact and hands back its `forward`, logging a warning first because `python_code` is untrusted executable input. It gains a keyword-only `warn=True`. Every `load` keeps warning exactly as before; the one caller that will pass `warn=False` is the capture itself, which in the caller-driven design renders the artifact in-process and immediately self-loads it to run the caller's call -- that source was just produced by this process, is not untrusted input, and warning on every capture would drown the real warning. The comment above the warning says the same: a load is never silent, only the capture-time self-load passes `warn=False`. The `options` dict handed to `compile_to_python` is annotated `dict[str, object]` instead of `dict[str, Any]`; no runtime change. The existing export/reload tests in `test/test_precompile.py` cover the warning path, which is unchanged for them, and `test_inlined_forward_warns_unless_told_not_to` pins both settings directly: one warning per `_make_inlined_forward(code)` and none for `warn=False`. ## Before and after ```python _make_inlined_forward(python_code) # parent and now: warns # WARNING torch.compiler.precompile.load is about to EXEC python_code, which is untrusted # executable input (it runs inlined kernels / graph code). Only exec python_code you produced # or otherwise trust (Note [precompile programming model], invariant 7). _make_inlined_forward(python_code, warn=False) # new: silent, for the capture-time self-load only ``` Test Plan: ``` python test/test_precompile.py -k test_inlined_forward_warns_unless_told_not_to 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]> Pull Request resolved: #197983 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, #197980, #197981, #197982
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…frame (#197984) **Summary.** A capture with graph breaks or several guarded variants is not one graph, so its artifact cannot inline a single `call`; it has to carry every frame Dynamo compiled and dispatch among them. `_multigraph_frames(entry)` turns a `_DynamoCacheEntry` into the list of plain dicts the driver rebuilds from, one per code: `is_entry` for `codes[0]`, which is where `CompilePackage` records the captured callable and reads it back from (`main, *codes`), so no name heuristic is involved and neither a bypassed entry nor a same-named submodule frame can move it; `bypassed`, the code's flag; the serialized `code`; its `python_module`; the `import_sources` aliases its bytecode reads; the `resume_names` a continuation is bound under; and one `variants` record per guarded code holding `guards_state` and `dynamo_code`. A bypassed code keeps its record, flagged and without variants, the way `install()` keeps its global binding but none of its guarded codes: the frame ahead of a bypassed continuation still does `LOAD_GLOBAL` on its resume name, so dropping the record would leave a dangling global, and a bypassed code's guarded codes are dead (they name a backend that was missing at save time). `_MULTIGRAPH_GENERATED_HEADER` is the banner of that artifact and `_SERVING_NOTES` the two paragraphs, keyed by serving mode, that say what loading the artifact does to the process (a standalone artifact mutates nothing and refuses uncovered calls; an installed one mutates code objects and compiles fresh on a miss). `_b64` is the base64-of-pickle encoding the opaque sections use. Nothing renders these yet; the source builder that does is part of the capture session. `test_multigraph_frames_record_every_dynamo_frame` in `test/test_precompile.py` builds a real `_DynamoCacheEntry` (bypassed entry, same-named helper, healthy and bypassed continuations) and checks the records. ```python _multigraph_frames(entry) ``` Test Plan: ``` python test/test_precompile.py -k test_multigraph_frames_record_every_dynamo_frame 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]> Pull Request resolved: #197984 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, #197980, #197981, #197982, #197983
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…dispatch (#197985) **Summary.** A standalone multi-graph artifact dispatches explicitly: the caller invokes the entry frame, and a continuation is reached only because the frame ahead of it does `LOAD_GLOBAL` on the resume name capture minted. A frame Dynamo compiled that is entered by an ordinary Python call -- an inner `nn.Module.__call__` wrapper, an un-inlinable helper -- is reachable only through the frame evaluator, which a source artifact does not use, so it would run eager when served. `_reachable_frames(frames)` computes the set that IS reachable as a worklist fixpoint: start from the entry, and each time a frame becomes reachable add the `co_names` of its variant bytecode (recursing into nested code constants) to the names seen, then admit every frame one of whose `resume_names` is among them. Each frame's bytecode is walked once. Asking merely whether a frame carries a resume name is not the same question, because a continuation whose parent is itself unreachable is just as dead, and counting it as covered under-reports how much of the artifact will run eager. `_serving_mode(frames)` reduces that to the artifact's mode: `"standalone"` when the reachable frames are exactly the frames with variants, `"installed"` otherwise. Either mismatch defeats a source artifact: an unreachable frame with variants would silently give up its compiled variant and run eager, and a reachable frame WITHOUT variants -- a bypassed continuation -- would raise on the very path capture exercised, since a standalone artifact has no compiler behind it. Installing has one, so such captures are served that way. `test_reachable_frames_follow_resume_names` in `test/test_precompile.py` covers the multi-hop chain (one hop through a nested code object), the unreachable helper, a continuation named only by that helper, an unreferenced resume name, and the bypassed-continuation case. ```python frames = [entry, cont_a, cont_b, helper] _reachable_frames(frames) # {0, 1, 2} _serving_mode(frames) # "installed": helper has variants but is unreachable _serving_mode(frames[:3]) # "standalone" _serving_mode([entry, bypassed_cont_a, cont_b]) # "installed": reachable, but nothing to serve ``` Test Plan: ``` python test/test_precompile.py -k test_reachable_frames_follow_resume_names 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]> Pull Request resolved: #197985 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, #197980, #197981, #197982, #197983, #197984
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
… and name the cause (#197986) **Summary.** The multi-graph driver rebuilds the entry function from its code object, and a code object carries no closure: a closure entry cannot be built at all. That is a capture-time fact, so `_reject_uninstallable_entry(frames, entry)` refuses it at capture rather than at load on the serving machine. (Defaults, which a code object does not carry either, are recorded into the artifact by a later commit rather than refused.) It also handles the entry with no dispatchable graph, which has two very different causes that call for different advice. If Dynamo BYPASSED the entry frame -- its guards could not be serialized, or a backend artifact was missing when the package was saved -- the frame record carries the `bypassed` flag `_multigraph_frames` copied from the code, and the error says so and points at where Dynamo logged the reason (the package-bypass warning; the `precompile_cache_bypass` / `dynamo_cache_bypass` artifacts under tlparse), because the thin-wrapper advice would then send the caller restructuring code that was never the problem. If the entry compiled but produced no guarded code, the caller handed precompile a thin wrapper -- an `nn.Module`, or a forward that immediately delegates -- so Dynamo compiled the wrapper's inner frame instead, and the error says to capture the function that calls the model. Only the ENTRY record is consulted, so a bypassed helper or continuation beside a healthy entry refuses nothing, and a capture with no frames at all says nothing rather than guess. `test_no_dispatchable_graph_names_the_cause` in `test/test_precompile.py` builds real `_DynamoCacheEntry` / `_DynamoCodeCacheEntry` values and feeds them through `_multigraph_frames`, so it exercises the records the function actually receives; it walks the bypassed entry, the thin wrapper beside a bypassed helper, the healthy entry beside a bypassed continuation, the empty capture and the closure entry. ## The diagnostics ```python _reject_uninstallable_entry(_multigraph_frames(entry_whose_codes0_is_bypassed), entry) # PrecompileError: precompile captured no dispatchable graph for 'fwd_loss_bwd': the entry # frame was BYPASSED during capture (its guards could not be serialized, or a backend # artifact was missing when the package was saved), so no variant of it can be served. # Dynamo logged the reason: look for the package-bypass warning, or the # precompile_cache_bypass / dynamo_cache_bypass artifacts under tlparse. Fix that rather # than restructuring the captured callable. _reject_uninstallable_entry([{"is_entry": True, "bypassed": False, "variants": [], ...}], entry) # PrecompileError: ... The entry frame produced no guarded code, so the artifact would serve # nothing. This happens when the captured callable is a thin wrapper ... Capture the function # that CALLS the model, e.g. precompile.capture(lambda m, x: m(x), ...) and calling cap(model, x). _reject_uninstallable_entry([healthy_entry, bypassed_continuation], entry) # returns _reject_uninstallable_entry([], entry) # returns _reject_uninstallable_entry([{"is_entry": True, "variants": [v], "code": code_with_freevars, ...}], entry) # PrecompileError: precompile cannot build a self-contained artifact for 'step': it closes over # ['scale'], and this capture has to rebuild the entry from its code object ... ``` Test Plan: ``` python test/test_precompile.py -k test_no_dispatchable_graph_names_the_cause 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]> Pull Request resolved: #197986 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, #197980, #197981, #197982, #197983, #197984, #197985
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…7987) **Summary.** `_build_multigraph_forward` is the driver a multi-graph artifact inlines: where the single-graph drivers call one `call`, this one rebuilds the captured ENTRY frame from its `_FRAMES` record and returns a `forward` that DISPATCHES among that frame's variants at call time. It is deliberately standalone -- nothing is installed onto the running program's code objects and no frame evaluator is involved -- so an artifact serves exactly what it captured and writes nothing into the captured module but names Dynamo minted while tracing; a call no variant's guards accept RAISES a `PrecompileError` rather than compiling, because there is no compiler behind a source artifact. That error names both ways a call can miss -- a guard on the arguments or on a module global the graph baked in no longer holds (restore the environment), or a call shape capture never exercised (add an example and recapture) -- since only the second is a coverage gap that recapturing fixes. It rebuilds one `GuardManager` per variant through `load_guards_state`/`load_guard_manager`, re-minting the `__builtins_dict___N` key Dynamo guards builtins through (the tracing process had it in its globals; a loading process never traced, and `CompilePackage.install` re-mints it the same way), wraps each variant's transformed bytecode in a `types.FunctionType` over the live globals of the module the frame was compiled in, and dispatches by rebuilding the frame's `f_locals` from the call: the arguments bound with `inspect.Signature` through `torch._dynamo.aot_compile.bind_locals`, so keyword-only parameters, `*args`, `**kwargs` and the entry's recorded defaults land under their names exactly as Python binds them. The first variant whose `manager.check(f_locals)` passes runs; the managers are checked in two passes, as `AOTCompiledModel.__call__` does, because a tag-safe root's no-tensor-aliasing fast path (`GuardManager::check_nopybind`) can refuse without running its tree and disarms itself, so only a second `check` evaluates the tree it skipped. An entry with free variables is refused (capture already refuses one, so its arrival is a malformed artifact, not something to rebuild over empty cells); that refusal and the recorded defaults are gated on the record's `is_entry` flag, so neither reaches a continuation once one is built. Those globals are the LIVE module dict, as `CompilePackage.install` has it, for the rebuilt bytecode and the guards alike: a module-level global the graph baked in as a constant is guarded by EQUALS_MATCH, which the default filter keeps, and only a live dict lets a rebinding after load fail that guard instead of passing against a stale copy, and lets a global the frame writes (side-effect replay emits `STORE_GLOBAL` into the transformed bytecode) land where the module reads it. The driver binds none of its own names there -- not the metadata constants, not `forward` -- only names Dynamo minted while tracing: that module's import aliases, re-imported; its builtins dict key; and the artifact's compiled subgraphs under their backend ids behind `torch._dynamo.disable` (every backend id is seeded into each module the driver opens, where `install` binds a code entry's own ids only; the ids are uuid-suffixed dunders, so no user name is shadowed). The standalone note in `_SERVING_NOTES` is narrowed to match: nothing is installed onto code objects and no frame evaluator is involved, and the only global state loading touches is the captured module, where those minted names are re-seeded and stay. Each is bound the way `install` binds it, `CleanupHook.disown` first so a pre-reset compile's hook cannot delete the binding once its code object is collected, and the builtins key is refused if it is already bound to anything but the module's builtins dict, as `install` refuses it. A module that does not import here -- the defining module or an alias alike -- surfaces as the documented torch-build lock `PrecompileError`, and a frame captured from a script's `__main__` is refused outright, because `importlib.import_module("__main__")` succeeds in every process and would hand the serving script's globals to the guards silently. An entry with no variant -- BYPASSED at capture, or trivial and run eager by Dynamo -- is diagnosed by cause at build rather than as a coverage gap at the call. Before any of that, `_DYNAMO_PYTHON_VERSION` is checked against the running interpreter, because `SerializedCode.to_code_object` feeds the recorded `co_*` fields to `types.CodeType` in the running interpreter's `get_code_keys()` order, so a foreign artifact either raises a bare `TypeError` on a changed field set or builds a code object whose bytecode is foreign and crashes when a variant runs, and `TORCH_VERSION` against `torch.__version__`, because `_FRAMES` carries pickled Dynamo guard state that no other build promises to unpickle and the import check cannot see a build whose modules all still import. Both names, like `_FRAMES`, `_BACKENDS` and `_ENTRY_BINDING`, are read bare: `_parse_artifact_metadata` already refuses a dynamo artifact that lacks them. Only the entry frame is rebuilt here. A graph-break continuation is reached by `LOAD_GLOBAL` on the resume name Dynamo minted, so serving one means binding its dispatcher in the module under that name, with the closure factory a continuation that closes over locals is emitted as, and a zero-variant continuation's refusal deferred to the call that reaches it; that is #197286. Nothing emits this driver into an artifact yet, so no artifact with a graph break exists in between. The function is a single `def` with nested helpers, with its `TYPE_CHECKING` placeholders; keeping it one unit is what lets the source builder emit it with one `inspect.getsource`. ## Dispatch ```python # emitted into the artifact after the metadata and the subgraph sources forward = _build_multigraph_forward() forward(model, x) # f_locals = {"model": model, "x": x, "rest": (), "scale": 2.0} # (Signature.bind + the recorded defaults); the first # variant whose guard manager accepts them runs forward(model, x, scale=3.0) # no variant matches: # PrecompileError: precompile: no captured variant of 'step' matches this call (2 captured). # Either a guard on the call's arguments or on a module global the graph baked in no longer # holds (restore that environment), or this call shape was never captured: the artifact serves # only what capture exercised, so add an example covering it and recapture. ``` ```python # on a different Python # PrecompileError: precompile: this artifact was produced on Python 3.12 and cannot load on 3.13: # it inlines serialized code objects whose bytecode and field layout are Python-version-locked. # Regenerate the artifact under the serving Python. ``` Nothing emits this driver into an artifact yet; the source builder that does is part of the capture session. The test builds the records the driver reads from a real `CompilePackage` capture of a function with no graph break (two calls, the second passing a `*args` tensor: `len(rest)` is a constant in the graph, so the entry recompiles and carries two variants whose outputs differ by one, and dispatch has to pick rather than just run; a keyword-only default the call omits; a module global the entry reads), asserts `_serving_mode` calls it standalone with one frame of two variants, `exec`s the driver's source into a bare namespace with the Dynamo-minted globals scrubbed from the test module, and checks that each captured call dispatches to the variant that produced its answer, that rebinding the module global the entry reads fails its guard and refuses rather than serving the stale graph (and serves again once restored), that an uncovered call refuses, that the builtins key is minted into the captured module and a foreign binding of it is refused, and that every build-time refusal is diagnosed by its own cause: both version locks, a `__main__` frame, an unimportable module, a BYPASSED and a trivial entry, a closure entry, and a record set with no entry. Test Plan: ``` python test/test_precompile.py -k test_multigraph_driver_dispatches_entry_frame python test/test_precompile.py lintrunner --take RUFF,PYFMT,FLAKE8,CODESPELL,PYREFLY 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: #197987 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, #197980, #197981, #197982, #197983, #197984, #197985, #197986
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…eal Dynamo backend graph (#197988) **Summary.** This is a follow-up to the `_graph_has_dynamic_shapes` fix that made the probe read `"example_value"` as well as `"val"`: it adds the end-to-end regression test that fix was missing and tightens the surrounding prose. `test_dynamo_dynamic_graph_runs_at_multiple_shapes` compiles a module with `torch.compile(dynamic=True)` through a recording backend, lowers the captured graph with `compile_to_python`, and runs the artifact at three batch sizes; on the parent of the original fix the artifact specialized to the example size and failed `assert_size_stride` at every other size. The helper's docstring and the two unit tests now say precisely which graphs carry which key: make_fx writes only `"val"`, the graph Dynamo hands a torch.compile backend carries only `"example_value"`, and Dynamo's export paths stamp `"val"` as well, so `"val"` alone does not identify a make_fx graph. The unit test also covers the union in the other direction (a symbolic `"val"` beside a static `"example_value"`). The code change is prose only; the behaviour under test is the `_graph_has_dynamic_shapes` change in #197258 (the second commit of this stack), which is kept byte-identical because it is already approved. ## Test Plan ``` python test/functorch/test_compile_to_python.py -k dynamic_graph_runs_at_multiple_shapes python test/functorch/test_compile_to_python.py -k graph_has_dynamic_shapes python test/functorch/test_compile_to_python.py ``` Authored with an AI assistant (Claude Code). Co-Authored-By: Claude Fable 5.1 <[email protected]> Pull Request resolved: #197988 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, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…iver (#197989) **Summary.** The entry-only `_build_multigraph_forward` from #197743 rebuilds and dispatches the entry frame only; this one makes it rebuild every captured frame from the `_FRAMES` records, so a capture with graph breaks serves standalone. A continuation is reached the way Dynamo emits it -- the frame ahead of it does `LOAD_GLOBAL` on the resume name Dynamo minted in the module both were compiled in (a continuation is recorded under its parent's module; under `config.nested_graph_breaks`, default False, an inlined frame's continuation is recorded under the inlined function's module while the root frame's bytecode does the `LOAD_GLOBAL`) -- so the driver now builds a dispatcher per frame and binds each continuation's dispatcher in that module under its resume names, `CleanupHook.disown` first like the other minted names. A continuation that closes over locals is bound as a FACTORY taking the closure tuple, the way Dynamo emits it and the frame ahead of it calls it, and its `f_locals` are rebuilt the way `AOTCompiledFunction.prepare_f_locals` does: the closure cells' contents first (a cell unbound at the graph break is absent, as it is from a real frame's `f_locals`), then the arguments bound through `bind_locals`, with a comprehension iterator argument that Dynamo spells `.N` in the resume code's `co_varnames` renamed back from the `implicitN` that `inspect.signature` gives it, since the guards are rooted at the bytecode name; the `inspect.Signature` is taken over a throwaway function with empty cells since a code object with free variables cannot be wrapped without them. A module is opened only for a frame with variants: a zero-variant record is dead, never imports its module, and binds its refusal only into a module a live frame already opened (an unopened module means no frame is left to name it), so a dead record naming a module the serving process cannot import neither refuses the load nor binds anything. Resume names are minted by a per-process counter (`unique_id_unbound_in`; backend ids carry a uuid4 and cannot collide), so two standalone artifacts of the same module captured in different processes can mint the same resume name and, loaded into one process, would silently overwrite each other's continuations (the entry bytecode's `LOAD_GLOBAL` cannot be renamed at load); every continuation dispatcher the driver binds under a resume name therefore carries its artifact's tag (the first 16 hex digits of the sha256 of `_FRAMES` and `_BACKENDS` together, so two artifacts emitted from one capture with different backends get different tags) in `__precompile_artifact__` -- the entry dispatcher handed back as `forward` carries nothing -- and, before anything is seeded, a pre-pass over the frames checks every resume name a frame would bind (in a module some frame with variants opens; the check imports the module and seeds nothing): the name must be unbound or hold this artifact's own dispatcher (rebuilding rebinds), otherwise the load is refused with a `PrecompileError` naming the module and the resume name and, for a holder carrying another artifact's tag, both tags and "only one standalone artifact per captured module can serve continuations in a process", or, for an untagged holder, "this process already holds it (a live compile of the same function, or a user binding); load the artifact in a fresh process". There is deliberately no same-continuation permit: a live compile of the same function holds its resume name for entry bytecode Dynamo already emitted, and rebinding it would point that `LOAD_GLOBAL` at a dispatcher that cannot recompile, so the capturing process itself is refused when it loads the artifact it just emitted, and a fresh process serves it. Because the check precedes the dispatcher loop, a refused load mutates nothing in the module; in particular a second artifact of one capture (the same backend ids, other `_BACKENDS`) cannot rebind the live artifact's subgraphs before it is refused. `_seed` itself stays the plain disown-and-overwrite of the previous commit, so the untagged values (import aliases, the builtins dict, the compiled subgraphs) overwrite as before. An artifact with no entry frame is now refused before any module is opened. A load the driver refuses for another reason partway through (a later frame's unimportable alias, a foreign builtins key) leaves the names it had already seeded in the captured module; there is no unwind, and the docstring says so. A frame with no variant -- BYPASSED at capture, or trivial and run eager by Dynamo -- is still diagnosed by cause rather than as a coverage gap, but where the entry raises at build, a continuation's refusal is deferred to the call that reaches it, since by `_serving_mode`'s contract a standalone artifact's zero-variant continuation is unreachable yet must still bind its resume names. Everything else -- the version locks, the `__main__` and import refusals, the live module dict, the builtins key re-mint, the coverage-gap `PrecompileError` -- is unchanged from the previous commit. The edits are interior to the one function, which stays a single `def` with nested helpers so the source builder can still emit it with one `inspect.getsource`. ## Dispatch ```python # emitted into the artifact after the metadata and the subgraph sources forward = _build_multigraph_forward() forward(model, x) # entry f_locals = {"model": model, "x": x, "rest": (), "scale": 2.0}; # the entry's bytecode reaches the continuation by LOAD_GLOBAL on # __resume_at_N, bound in the captured module by this driver forward(model, x, torch.ones(1), torch.ones(1)) # entry matches, no continuation variant does: # PrecompileError: precompile: no captured variant of 'torch_dynamo_resume_in_step_at_N' matches # this call (2 captured). Either a guard on the call's arguments or on a module global the graph # baked in no longer holds (restore that environment), or this call shape was never captured: the # artifact serves only what capture exercised, so add an example covering it and recapture. ``` Nothing emits this driver into an artifact yet; the source builder that does is part of the capture session. The test builds the records the driver reads from a real `CompilePackage` capture (two calls, so the continuation carries two variants whose outputs differ; a keyword-only default the call omits, `*args`, and a continuation closing over a cell of the entry frame), asserts `_serving_mode` calls it standalone and the continuation carries more than one variant, `exec`s the driver's source into a bare namespace that also binds `torch` to `None` (the collision the captured module's binding has to win), builds once in the capturing process before the Dynamo-minted globals are scrubbed from the test module (the live compile still holds the continuation's resume name, so the load is refused with the fresh-process message), then with those globals scrubbed checks that every captured call dispatches to the variant that produced its answer, that rebinding a module global the entry reads fails its guard and refuses rather than serving the stale graph (and serves again once restored), that an uncovered call refuses at the entry and at the continuation, that rebuilding the same artifact succeeds, that a foreign function bound under one of its resume names refuses the build, as does an artifact with the same `_FRAMES` and backend ids but other `_BACKENDS` (a second artifact of one capture, its subgraphs rotated across the ids), after which the live artifact still serves its own answer -- the refusal preceded any rebinding of the shared backend ids -- and one with other `_FRAMES` and renamed backend ids (another process's capture), each refused on the resume name it shares with the live one (the later rows scrub the live artifact first), that a zero-variant continuation, trivial or BYPASSED, is diagnosed by cause at the call that reaches it (the BYPASSED build succeeds), and that a dead record naming an unimportable module neither refuses the load nor binds anything. The build-time refusals (the version locks, `__main__`, the builtins key, a zero-variant or closure entry, no entry) stay covered by the previous commit's entry-only test, which keeps passing unchanged. Test Plan: ``` python test/test_precompile.py -k test_multigraph_driver_dispatches_captured_frames python test/test_precompile.py -k multigraph python test/test_precompile.py lintrunner --take RUFF,PYFMT,FLAKE8,CODESPELL,PYREFLY 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: #197989 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, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987, #197988
pytorchmergebot
pushed a commit
that referenced
this pull request
Sep 22, 2026
…197990) **Summary.** Two small pieces complete the multi-graph artifact plumbing in `torch/_precompile.py`. `_entry_binding(fn)` records the entry's `__defaults__` and `__kwdefaults__`, which a code object does not carry; without them a defaulted parameter is absent from the served call's `f_locals` and every guard misses. Closure cells are deliberately not recorded: a closure entry is refused earlier (a rebuilt cell would be a new object Dynamo's identity guard misses anyway), and the driver refuses one that arrives regardless rather than rebuilding it over empty cells. `_emit_multigraph_driver_source()` renders `_build_multigraph_forward` into the artifact with `inspect.getsource`, the same path the other drivers use, followed by `forward = _build_multigraph_forward()` and the same `if __name__ == "__main__"` hint block the single-graph artifacts end in. `import inspect` moves to module scope, replacing the function-local import `_emit_driver_source` had. Because that section ends in a top-level assignment, `_parse_artifact_metadata` no longer describes one as hypothetical and skips `forward` without the "unrecognized assignment" debug line, which stays a signal for a malformed artifact. ## Examples ```python def step(model, x, scale=2.0, *, mode="sum"): ... _entry_binding(step) # {"defaults": (2.0,), "kwdefaults": {"mode": "sum"}} _emit_multigraph_driver_source() # "\ndef _build_multigraph_forward():\n ...\n\n\nforward = _build_multigraph_forward()\n\n\nif __name__ == \"__main__\":\n ..." ``` Test Plan: ``` python test/test_precompile.py -k test_entry_binding_records_defaults -k test_emit_multigraph_driver_source_is_a_complete_section 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]> Pull Request resolved: #197990 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, #197980, #197981, #197982, #197983, #197984, #197985, #197986, #197987, #197988, #197989
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.
loadrecovers the calling convention of an artifact by parsingpython_codewithastand reading the top-levelNAME = <literal>assignments, and until now it required one fixed set of names: the make_fx driver'sPARAM_NAMES,OUT_SPEC,USER_INPUT_SHAPESand 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 theTRACERliteral: absent (every artifact written before this) or anything but"dynamo"keeps the make_fx set unchanged, while"dynamo"requiresBACKEND,FN_NAME,FRAMES,DROPPED_GUARDS,RISKY_DROPPED_GUARDS,WONT_GENERALIZE,_FRAMES,_BACKENDS,_ENTRY_BINDINGand the two versions that lock the blobs to the build that wrote them,_DYNAMO_PYTHON_VERSIONfor the marshalled bytecode andTORCH_VERSIONfor 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 aSERVING_MODE == "installed"artifact swaps_FRAMES/_BACKENDSfor_PACKAGEandUNREACHABLE_WITHOUT_INSTALL. The parser collects the top-level assignments in one pass, last assignment winning as it would underexec, 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,TRACERandSERVING_MODEincluded, raisesPrecompileErrornaming the constant instead of a rawValueError(or, for a set or dict literal with an unhashable member,TypeError) out ofast.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:TRACERandSERVING_MODE, which select the required set and so would check nothing as members of it (SERVING_MODEdefaults to"standalone"in the result), and the guard-audit sectionsPOLICY_DROPPED_GUARDSandDROPPED_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
test_parse_artifact_metadata_required_set_follows_tracerpins the three required sets from hand-written sources (make_fx both withTRACERabsent and withTRACER = 'other'), andtest_parse_artifact_metadata_literalsparses a complete standalone and a complete installed dynamo source and covers the optional sections, theSERVING_MODEdefault, 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:
Authored with an AI assistant.
🤖 Generated with 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.