Skip to content

[aot_autograd] Pin the "example_value" dynamic-shape read against a real Dynamo backend graph - #197988

Closed
bobrenjc93 wants to merge 1 commit into
gh/bobrenjc93/1402/basefrom
gh/bobrenjc93/1402/head
Closed

bobrenjc93 wants to merge 1 commit into
gh/bobrenjc93/1402/basefrom
gh/bobrenjc93/1402/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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]

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (2 Unrelated Failures)

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

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

  • Behavior risk
    • The only non-test hunk rewrites the _graph_has_dynamic_shapes docstring; the body at to_standalone_python.py:844-857 still loops ("val", "example_value") unchanged.
    • No validation, error path, or guard is removed anywhere in the diff.
  • Testing
    • Adds test_dynamo_dynamic_graph_runs_at_multiple_shapes, which lowers a torch.compile(dynamic=True) backend graph via compile_to_python and runs it at sizes 8/16/5, the end-to-end case the existing test_dynamic_shapes_runs_at_multiple_shapes only covered for make_fx.
    • Extends test_graph_has_dynamic_shapes_reads_either_key with the reverse union (symbolic "val" beside static "example_value"), matching the union in the probe loop.
  • Scope
    • Two files only: test/functorch/test_compile_to_python.py and one docstring in torch/_functorch/_aot_autograd/to_standalone_python.py; no public API, workflow, or CI file touched.
    • New flat-input order [n, 4, xi] in the test matches the asserted [SymInt, SymInt, Tensor] example-input signature it lowers.

reason: clean
Reviewed commit: 1829834

Inference job

🐛 Report a wrong verdict

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

This was referenced Sep 21, 2026
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 3 checks: Lint (#197982), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 1, 2, mt-l-x86iamx-8-64, unstable) (#197988), inductor / unit-test / inductor-cpu-test / test (inductor_aoti_fallback, 2, 2, mt-l-x86iamx-8-64, unstable) (#197988)

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

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
@github-actions
github-actions Bot deleted the gh/bobrenjc93/1402/head branch November 27, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants