Skip to content

[precompile] Add the multi-graph driver that rebuilds and dispatches captured frames - #197286

Closed
bobrenjc93 wants to merge 52 commits into
gh/bobrenjc93/1242/basefrom
gh/bobrenjc93/1242/head
Closed

bobrenjc93 wants to merge 52 commits into
gh/bobrenjc93/1242/basefrom
gh/bobrenjc93/1242/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary. The previous commit's _build_multigraph_forward 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

# 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, execs 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

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/197286

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

⏳ No Failures, 52 Pending

As of commit ef85cb5 with merge base d78bbf2 (image):
💚 Looks good so far! There are no failures yet. 💚

🟢 GREEN LIGHT - PR approved to be merged without human review:

  • Correctness
    • factory(closure) vs plain dispatch matches install_resume_function_global (torch/_dynamo/output_graph.py:3553) and the factory-call codegen at symbolic_convert.py:3912
    • f_locals is built freevar cells first then bind_locals, the order prepare_f_locals uses at torch/_dynamo/aot_compile.py:730
    • The resume-name pre-pass at torch/_precompile_driver.py:673 and the seeding loop at :692 agree frame by frame, so no name is seeded that was not collision-checked
  • Testing
    • test_multigraph_driver_dispatches_captured_frames asserts each captured call dispatches to its own answer and that rebinding _MULTIGRAPH_SCALE fails the guard rather than serving stale
    • The same test covers the zero-variant, BYPASSED, dead-record and duplicate-resume-name refusals (test/test_precompile.py:857-883)
  • Scope
    • Edits are interior to _build_multigraph_forward; grep finds no caller in torch/, only test/test_precompile.py:795
    • No workflow, CI-gate or policy-doc file is touched, and no public API changes

reason: clean
Reviewed commit: ef85cb5

Inference job

🐛 Report a wrong verdict

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

This was referenced Sep 16, 2026
[ghstack-poisoned]
[ghstack-poisoned]
This was referenced Sep 21, 2026
bobrenjc93 added a commit that referenced this pull request Sep 21, 2026
**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]>

ghstack-source-id: adb0121
Pull-Request: #197743
bobrenjc93 added a commit that referenced this pull request Sep 21, 2026
…graph driver

**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]>

ghstack-source-id: 29c3bfc
Pull-Request: #197286
@bobrenjc93 bobrenjc93 closed this Sep 21, 2026
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
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1242/head branch November 25, 2026 01:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant