Skip to content

[precompile] support torch.compiler.precompile(tracer="dynamo") - #194113

Closed
bobrenjc93 wants to merge 17 commits into
gh/bobrenjc93/997/basefrom
gh/bobrenjc93/997/head
Closed

bobrenjc93 wants to merge 17 commits into
gh/bobrenjc93/997/basefrom
gh/bobrenjc93/997/head

Conversation

@bobrenjc93

@bobrenjc93 bobrenjc93 commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Human note:

This stack distills the subsequent fixes into four reviewable commits. This PR preserves the existing positional call forms while consolidating on example_inputs, and introduces the Dynamo tracer to torch.compiler.precompile.

The precompile contract is:

  1. The environment (globals, context managers, and similar state) is exactly the same at precompile time and runtime.
  2. Only changes to explicit graph inputs may trigger recompilation or guard failure.

The generated artifact never invokes Dynamo or compiles a new variant while serving. Environment changes are outside the contract and may silently miscompute; unsupported or uncovered input changes fail instead of compiling at runtime.

AI-assisted review summary:

Accept multiple observed calls through example_inputs while preserving the existing positional API. Bind each example with inspect.signature.bind, including defaults, *args, and **kwargs, and reject tensor-valued defaults because they would be hidden runtime inputs.

Add the initial tracer="dynamo" capture path. Dynamo runs each example with its normal recompilation and automatic dynamic-shape behavior. The artifact retains readable graph, kernel, and runtime source; serialized guard state and transformed code objects select the first captured variant that matches at runtime.

Isolate capture from unrelated Dynamo and AOTAutograd caches, reject identity relations between explicit inputs and environment objects, and support training artifacts with generated AOTAutograd forward and backward source. Graph breaks and installed-frame serving are layered on by the following commits.

Test Plan:

PRECOMPILE_OVERLAY_ROOT=$PWD TORCH_USE_RTLD_GLOBAL=1 LD_LIBRARY_PATH=/home/bobren/local/e/pytorch-env/lib:/home/bobren/local/e/pytorch-env/lib/python3.10/site-packages/nvidia/cudnn/lib:/usr/local/cuda-12.8/lib64 /home/bobren/local/e/pytorch-env/bin/python /home/bobren/local/e/pytorch/agent_space/run_precompile_root_overlay.py test -k tracer_dynamo -f
PRECOMPILE_OVERLAY_ROOT=$PWD TORCH_USE_RTLD_GLOBAL=1 LD_LIBRARY_PATH=/home/bobren/local/e/pytorch-env/lib:/home/bobren/local/e/pytorch-env/lib/python3.10/site-packages/nvidia/cudnn/lib:/usr/local/cuda-12.8/lib64 /home/bobren/local/e/pytorch-env/bin/python /home/bobren/local/e/pytorch/agent_space/run_precompile_root_overlay.py test_file test/functorch/test_compile_to_python.py
UV_OFFLINE=1 PATH=/home/bobren/.cache/uv/archive-v0/_EbPanZVazvI1jXYMOQC9/bin:/home/bobren/local/e/pytorch-env/bin:/home/bobren/.local/bin:/usr/local/bin:/usr/bin:/bin /home/bobren/.cache/uv/archive-v0/_EbPanZVazvI1jXYMOQC9/bin/lintrunner -a

This change was authored with assistance from an AI coding tool.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 18 New Failures, 1 Unrelated Failure, 1 Unclassified Failure

As of commit de826de with merge base ab5fb26 (image):

NEW FAILURES - The following jobs have 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:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@pytorch-bot

pytorch-bot Bot commented Aug 19, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 19, 2026
Change the experimental precompile API from positional example arguments to a
required keyword-only sequence of positional-argument tuples. This gives future
capture front-ends room to consume multiple example calls while keeping the
current make_fx path explicit: it accepts exactly one tuple because it records a
single execution.

Update the public documentation and all precompile tests to use the new calling
convention. Add coverage for the make_fx tuple-count requirement and for
rejecting positional example_inputs.

Test Plan:

Focused tests were run through a candidate-module harness against a compatible
installed torch because the clean origin/main worktree has no matching compiled
extension:

```
python agent_space/run_candidate_test.py -k make_fx_requires_one_example_input
python agent_space/run_candidate_test.py -k example_inputs_is_keyword_only
python agent_space/run_candidate_test.py -k tracer_default_and_explicit_make_fx
python agent_space/run_candidate_test.py -k tracer_dynamo_not_implemented
```

```
spin lint -- --take RUFF torch/_precompile.py test/test_precompile.py
spin lint -- --take NEWLINE,SPACES docs/source/torch.compiler_api.md docs/source/user_guide/torch_compiler/torch.compiler.md torch/_precompile.py test/test_precompile.py
```

`lintrunner -a` was also run; unavailable cached usort/codespell dependencies and
unrelated full-tree Pyrefly findings prevented a clean full-tree result.

This commit was authored with the assistance of an AI coding agent.

ghstack-source-id: e35b604
Pull-Request: #194113
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [AI-assisted] torch.compiler.precompile: use example_inputs [AI-assisted] torch.compiler.precompile: capture Dynamo recompilations Aug 19, 2026
bobrenjc93 added a commit that referenced this pull request Aug 19, 2026
Change the experimental precompile API from positional example arguments to a
required keyword-only sequence of positional-argument tuples. The make_fx path
continues to accept exactly one tuple, while the sequence gives capture front-ends
room to observe several calls.

Use that interface to add the initial tracer="dynamo" path. Dynamo executes every
example tuple with its normal automatic dynamic-shape policy and records each
guarded recompilation. The generated artifact keeps compiled graphs, kernels, and
runtime glue as Python source; only Dynamo's guard state and transformed code
objects are stored as opaque inline data. Loading rebuilds the guard managers and
dispatches to the first matching captured variant, raising on a miss instead of
compiling at runtime.

This first implementation requires a full graph and a module-level Python function
with tensor/scalar arguments. Graph breaks, closure cells, nn.Module arguments, and
custom decompositions are rejected explicitly. The standalone Python lowering now
reuses Dynamo's active fake mode so static and automatically dynamic recompilations
can both pass through AOTAutograd and Inductor without mixing fake modes.

Review the example_inputs signature and make_fx call-site migration first, followed
by the Dynamo capture/source emitter and the emitted runtime dispatcher. The tests
then demonstrate the intended recompilation behavior: sizes 2, 3, and 5 produce a
static variant plus an automatically dynamic variant, an unseen size 7 is served by
the dynamic graph, and a size outside the captured guards is rejected.

Test Plan:

Focused tests loaded the changed Python modules against a compatible installed
torch because this clean worktree has no matching compiled extension:

```bash
/home/bobren/local/b/pytorch-env/bin/python /home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/run_dynamo_candidate_tests.py
```

This ran:

```text
test_tracer_default_and_explicit_make_fx
test_cache_envelope_is_weights_only_safe
test_tracer_dynamo_recompiles_to_dynamic_graph
test_tracer_dynamo_rejects_graph_break
```

```bash
PATH=/home/bobren/.conda/envs/xlformers_finetune_conda-newest/bin:$PATH TMPDIR=/home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/lintrunner_tmp UV_OFFLINE=1 lintrunner -a
```

This commit was authored with the assistance of an AI coding agent.

ghstack-source-id: 27d103a
Pull-Request: #194113
bobrenjc93 added a commit that referenced this pull request Aug 20, 2026
Change the experimental precompile API from positional example arguments to a
required keyword-only sequence of positional-argument tuples. The make_fx path
continues to accept exactly one tuple, while the sequence gives capture front-ends
room to observe several calls.

Use that interface to add the initial tracer="dynamo" path. Dynamo executes every
example tuple with its normal automatic dynamic-shape policy and records each
guarded recompilation. The generated artifact keeps compiled graphs, kernels, and
runtime glue as Python source; only Dynamo's guard state and transformed code
objects are stored as opaque inline data. Loading rebuilds the guard managers and
dispatches to the first matching captured variant, raising on a miss instead of
compiling at runtime.

This first implementation requires a full graph and a module-level Python function
with tensor/scalar arguments. Graph breaks, closure cells, nn.Module arguments, and
custom decompositions are rejected explicitly. The standalone Python lowering now
reuses Dynamo's active fake mode so static and automatically dynamic recompilations
can both pass through AOTAutograd and Inductor without mixing fake modes.

Review the example_inputs signature and make_fx call-site migration first, followed
by the Dynamo capture/source emitter and the emitted runtime dispatcher. The tests
then demonstrate the intended recompilation behavior: sizes 2, 3, and 5 produce a
static variant plus an automatically dynamic variant, an unseen size 7 is served by
the dynamic graph, and a size outside the captured guards is rejected.

Test Plan:

Focused tests loaded the changed Python modules against a compatible installed
torch because this clean worktree has no matching compiled extension:

```bash
/home/bobren/local/b/pytorch-env/bin/python /home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/run_dynamo_candidate_tests.py
```

This ran:

```text
test_tracer_default_and_explicit_make_fx
test_cache_envelope_is_weights_only_safe
test_tracer_dynamo_recompiles_to_dynamic_graph
test_tracer_dynamo_rejects_graph_break
```

```bash
PATH=/home/bobren/.conda/envs/xlformers_finetune_conda-newest/bin:$PATH TMPDIR=/home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/lintrunner_tmp UV_OFFLINE=1 lintrunner -a
```

This commit was authored with the assistance of an AI coding agent.

ghstack-source-id: 27d103a
Pull-Request: #194113
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 20, 2026
Change the experimental precompile API from positional example arguments to a
required keyword-only sequence of positional-argument tuples. The make_fx path
continues to accept exactly one tuple, while the sequence gives capture front-ends
room to observe several calls.

Use that interface to add the initial tracer="dynamo" path. Dynamo executes every
example tuple with its normal automatic dynamic-shape policy and records each
guarded recompilation. The generated artifact keeps compiled graphs, kernels, and
runtime glue as Python source; only Dynamo's guard state and transformed code
objects are stored as opaque inline data. Loading rebuilds the guard managers and
dispatches to the first matching captured variant, raising on a miss instead of
compiling at runtime.

This first implementation requires a full graph and a module-level Python function
with tensor/scalar arguments. Graph breaks, closure cells, nn.Module arguments, and
custom decompositions are rejected explicitly. The standalone Python lowering now
reuses Dynamo's active fake mode so static and automatically dynamic recompilations
can both pass through AOTAutograd and Inductor without mixing fake modes.

Review the example_inputs signature and make_fx call-site migration first, followed
by the Dynamo capture/source emitter and the emitted runtime dispatcher. The tests
then demonstrate the intended recompilation behavior: sizes 2, 3, and 5 produce a
static variant plus an automatically dynamic variant, an unseen size 7 is served by
the dynamic graph, and a size outside the captured guards is rejected.

Test Plan:

Focused tests loaded the changed Python modules against a compatible installed
torch because this clean worktree has no matching compiled extension:

```bash
/home/bobren/local/b/pytorch-env/bin/python /home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/run_dynamo_candidate_tests.py
```

This ran:

```text
test_tracer_default_and_explicit_make_fx
test_cache_envelope_is_weights_only_safe
test_tracer_dynamo_recompiles_to_dynamic_graph
test_tracer_dynamo_rejects_graph_break
```

```bash
PATH=/home/bobren/.conda/envs/xlformers_finetune_conda-newest/bin:$PATH TMPDIR=/home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/lintrunner_tmp UV_OFFLINE=1 lintrunner -a
```

This commit was authored with the assistance of an AI coding agent.

ghstack-source-id: 6f1fb0f
Pull-Request: #194113
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 20, 2026
Change the experimental precompile API from positional example arguments to a
required keyword-only sequence of positional-argument tuples. The make_fx path
continues to accept exactly one tuple, while the sequence gives capture front-ends
room to observe several calls.

Use that interface to add the initial tracer="dynamo" path. Dynamo executes every
example tuple with its normal automatic dynamic-shape policy and records each
guarded recompilation. The generated artifact keeps compiled graphs, kernels, and
runtime glue as Python source; only Dynamo's guard state and transformed code
objects are stored as opaque inline data. Loading rebuilds the guard managers and
dispatches to the first matching captured variant, raising on a miss instead of
compiling at runtime.

This first implementation requires a full graph and a module-level Python function
with tensor/scalar arguments. Graph breaks, closure cells, nn.Module arguments, and
custom decompositions are rejected explicitly. The standalone Python lowering now
reuses Dynamo's active fake mode so static and automatically dynamic recompilations
can both pass through AOTAutograd and Inductor without mixing fake modes.

Review the example_inputs signature and make_fx call-site migration first, followed
by the Dynamo capture/source emitter and the emitted runtime dispatcher. The tests
then demonstrate the intended recompilation behavior: sizes 2, 3, and 5 produce a
static variant plus an automatically dynamic variant, an unseen size 7 is served by
the dynamic graph, and a size outside the captured guards is rejected.

Test Plan:

Focused tests loaded the changed Python modules against a compatible installed
torch because this clean worktree has no matching compiled extension:

```bash
/home/bobren/local/b/pytorch-env/bin/python /home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/run_dynamo_candidate_tests.py
```

This ran:

```text
test_tracer_default_and_explicit_make_fx
test_cache_envelope_is_weights_only_safe
test_tracer_dynamo_recompiles_to_dynamic_graph
test_tracer_dynamo_rejects_graph_break
```

```bash
PATH=/home/bobren/.conda/envs/xlformers_finetune_conda-newest/bin:$PATH TMPDIR=/home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/lintrunner_tmp UV_OFFLINE=1 lintrunner -a
```

This commit was authored with the assistance of an AI coding agent.

ghstack-source-id: a91d780
Pull-Request: #194113
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 20, 2026
Change the experimental precompile API from positional example arguments to a
required keyword-only sequence of positional-argument tuples. The make_fx path
continues to accept exactly one tuple, while the sequence gives capture front-ends
room to observe several calls.

Use that interface to add the initial tracer="dynamo" path. Dynamo executes every
example tuple with its normal automatic dynamic-shape policy and records each
guarded recompilation. The generated artifact keeps compiled graphs, kernels, and
runtime glue as Python source; only Dynamo's guard state and transformed code
objects are stored as opaque inline data. Loading rebuilds the guard managers and
dispatches to the first matching captured variant, raising on a miss instead of
compiling at runtime.

This first implementation requires a full graph and a module-level Python function
with tensor/scalar arguments. Graph breaks, closure cells, nn.Module arguments, and
custom decompositions are rejected explicitly. The standalone Python lowering now
reuses Dynamo's active fake mode so static and automatically dynamic recompilations
can both pass through AOTAutograd and Inductor without mixing fake modes.

Review the example_inputs signature and make_fx call-site migration first, followed
by the Dynamo capture/source emitter and the emitted runtime dispatcher. The tests
then demonstrate the intended recompilation behavior: sizes 2, 3, and 5 produce a
static variant plus an automatically dynamic variant, an unseen size 7 is served by
the dynamic graph, and a size outside the captured guards is rejected.

Test Plan:

Focused tests loaded the changed Python modules against a compatible installed
torch because this clean worktree has no matching compiled extension:

```bash
/home/bobren/local/b/pytorch-env/bin/python /home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/run_dynamo_candidate_tests.py
```

This ran:

```text
test_tracer_default_and_explicit_make_fx
test_cache_envelope_is_weights_only_safe
test_tracer_dynamo_recompiles_to_dynamic_graph
test_tracer_dynamo_rejects_graph_break
```

```bash
PATH=/home/bobren/.conda/envs/xlformers_finetune_conda-newest/bin:$PATH TMPDIR=/home/bobren/local/e/pytorch/agent_space/precompile-example-inputs/agent_space/lintrunner_tmp UV_OFFLINE=1 lintrunner -a
```

This commit was authored with the assistance of an AI coding agent.

ghstack-source-id: 35effc0
Pull-Request: #194113
[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added ciflow/torchtitan Run TorchTitan integration tests module: inductor labels Aug 24, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [precompile] capture Dynamo recompilations [precompile] Support tracer="dynamo" in torch.compiler.precompile Aug 25, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
bobrenjc93 added a commit that referenced this pull request Aug 27, 2026
…ests

Alternative to the top commit of #194113 (same ghstack base, same feature
set) that applies the fixes and coverage from its code review. Review the
diff against #194113's head in this order: the guard-minimization loop in
_filter_dynamo_guards, then the error-surface changes (driver arity errors,
defaults picklability, AssertionError translation), then the test additions.

Root causes fixed:

- _filter_dynamo_guards iterated three guard-record lists but its try_drop
  refused two of them unconditionally, leaving unreachable trial-list
  branches; minimization now explicitly walks only kept_guards.
- The identity-guard AssertionError translation string-matched a message
  that only exists as "check_fn.guards_state must not be None" in
  torch/_dynamo/convert_frame.py; the two sides now share the
  GUARDS_STATE_NONE_MESSAGE constant defined in convert_frame.py.
- An unpicklable function default (e.g. a lambda) failed inside the
  artifact-state pickle and was misreported as a guards/bytecode
  serialization failure; defaults are now probed up front with an accurate
  message.
- Wrong-arity calls on a loaded dynamo artifact leaked a raw TypeError from
  signature.bind while make_fx artifacts raise PrecompileError; the dynamo
  dispatcher now matches the make_fx error surface (keyword calls stay
  TypeError on both tracers, documented).
- _CompileToPythonState's docstring claimed finalize removes the live
  compiler hook; the caller does that cleanup, and the docstring now states
  the actual read/finalize/cleanup contract.
- _SourceLiteral gained __eq__/__hash__ so cached rendered constexpr configs
  compare by source instead of identity; the driver's hand-rolled closure
  cell builder became types.CellType.

A second review round (of this PR's own diff) fixed:

- The tensor-default check only walked containers, unlike its sibling
  input-alias walk, so a picklable object default holding a tensor slipped
  past both the tensor check and the pickle probe and embedded real tensor
  bytes inside _DYNAMO_STATE, violating the no-tensor-data contract. Both
  traversals are now one predicate-driven `reaches` walk that also descends
  object __dict__.
- The nn.Module rejection only checked top-level example arguments; a module
  nested in a container was silently accepted into an unvalidated capture
  path. The check now uses the same `reaches` walk.
- A non-interchangeable Enum in an autotune triton.Config reaches the
  runtime as a real Enum member (the constexpr rendering rewrite made that
  path work at all), but AutotuneCache.save JSON-encodes config kwargs and
  raised TypeError whenever there was more than one config and the
  (default-on) local autotune cache. Save and the cached-config match now
  normalize Enum members to their underlying values (_json_config_value).
- _constexpr_source_impl matched OrderedSet but not builtin set (OrderedSet
  is not a set subclass), leaving builtin sets to render via repr in
  nondeterministic hash order; both now render sorted and deterministic.
- Hardening: _parse_artifact_metadata requires the dynamo driver globals so
  a truncated dynamo artifact fails load with a clean PrecompileError
  instead of a NameError from exec; _convert_constant falls back to binding
  the object on any literal_eval exception (repr of an unhashable-key dict
  raises TypeError, not just SyntaxError/ValueError); _passthrough_source
  renders nonfinite floats as float('inf')/float('nan') instead of invalid
  bare inf/nan; the THREADING docstring states that capture-time global
  config patches are visible to concurrent torch.compile calls on other
  threads.

New coverage: every dynamo-tracer rejection path (non-function fn, closure
cells, nn.Module example args -- top-level and nested in a container,
decompositions, eager get_attr, unpicklable defaults, tensors hidden inside
object defaults, unserializable identity guards), dynamo cache robustness
(corrupt bundle degrades to JIT with correct numerics, weights_only
envelope, code/cache mismatch, truncated artifact), fresh-process runs of
the inference artifact, a _load_dynamo_state AST accessor replacing the
test helper's brittle line-prefix parse of _DYNAMO_STATE plus direct unit
tests for it and for _filter_dynamo_guards' unmatched-variant invariant,
the dynamo numeric tests moved into the device-generic
TestPrecompileNumerics, plain-Enum autotune configs end to end (codegen +
autotune-cache save) plus a unit test of the cached-config Enum match, set
and empty-set constexpr rendering, and nonfinite-float passthrough
rendering.

This PR was authored by an AI assistant (Claude Code) at the stack owner's
direction, from the plan derived from the review of #194113; every change
was verified on a from-source build.

Test Plan:

On a from-source editable build of this branch (H100, triton 3.7, py3.12):

```
.venv/bin/python test/test_precompile.py
# Ran 216 tests ... OK

.venv/bin/python test/inductor/test_codegen_triton.py
# Ran 53 tests ... OK (skipped=2)

.venv/bin/python test/functorch/test_compile_to_python.py
# Ran 62 tests ... OK

lintrunner torch/_precompile.py torch/_dynamo/convert_frame.py \
  torch/_inductor/codegen/wrapper.py \
  torch/_inductor/runtime/triton_heuristics.py \
  torch/_inductor/runtime/autotune_cache.py \
  torch/_inductor/standalone_compile.py \
  test/test_precompile.py test/inductor/test_codegen_triton.py \
  test/functorch/test_compile_to_python.py
# ok No lint issues.
```

The new autotune-cache test was verified load-bearing: with the
autotune_cache.py fix stashed, test_plain_enum_constexpr_in_autotune_config
fails with "TypeError: Object of type TrainingState is not JSON
serializable". The embedded-tensor and nested-module repros were likewise
confirmed to fail before the fixes and raise typed errors after.

Plus a 17-check behavioral harness (rejection paths, artifact hygiene
including a no-tensor-bytes-in-artifact scan, environment-drift semantics,
CPU/CUDA training numerics, guard-minimization timing): 17/17 pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
bobrenjc93 added a commit that referenced this pull request Aug 27, 2026
…ests

Alternative to the top commit of #194113 (same ghstack base, same feature
set) that applies the fixes and coverage from its code review. Review the
diff against #194113's head in this order: the guard-minimization loop in
_filter_dynamo_guards, then the error-surface changes (driver arity errors,
defaults picklability, AssertionError translation), then the test additions.

Root causes fixed:

- _filter_dynamo_guards iterated three guard-record lists but its try_drop
  refused two of them unconditionally, leaving unreachable trial-list
  branches; minimization now explicitly walks only kept_guards.
- The identity-guard AssertionError translation string-matched a message
  that only exists as "check_fn.guards_state must not be None" in
  torch/_dynamo/convert_frame.py; the two sides now share the
  GUARDS_STATE_NONE_MESSAGE constant defined in convert_frame.py.
- An unpicklable function default (e.g. a lambda) failed inside the
  artifact-state pickle and was misreported as a guards/bytecode
  serialization failure; defaults are now probed up front with an accurate
  message.
- Wrong-arity calls on a loaded dynamo artifact leaked a raw TypeError from
  signature.bind while make_fx artifacts raise PrecompileError; the dynamo
  dispatcher now matches the make_fx error surface (keyword calls stay
  TypeError on both tracers, documented).
- _CompileToPythonState's docstring claimed finalize removes the live
  compiler hook; the caller does that cleanup, and the docstring now states
  the actual read/finalize/cleanup contract.
- _SourceLiteral gained __eq__/__hash__ so cached rendered constexpr configs
  compare by source instead of identity; the driver's hand-rolled closure
  cell builder became types.CellType.

A second review round (of this PR's own diff) fixed:

- The tensor-default check only walked containers, unlike its sibling
  input-alias walk, so a picklable object default holding a tensor slipped
  past both the tensor check and the pickle probe and embedded real tensor
  bytes inside _DYNAMO_STATE, violating the no-tensor-data contract. Both
  traversals are now one predicate-driven `reaches` walk that also descends
  object __dict__.
- The nn.Module rejection only checked top-level example arguments; a module
  nested in a container was silently accepted into an unvalidated capture
  path. The check now uses the same `reaches` walk.
- A non-interchangeable Enum in an autotune triton.Config reaches the
  runtime as a real Enum member (the constexpr rendering rewrite made that
  path work at all), but AutotuneCache.save JSON-encodes config kwargs and
  raised TypeError whenever there was more than one config and the
  (default-on) local autotune cache. Save and the cached-config match now
  normalize Enum members to their underlying values (_json_config_value).
- _constexpr_source_impl matched OrderedSet but not builtin set (OrderedSet
  is not a set subclass), leaving builtin sets to render via repr in
  nondeterministic hash order; both now render sorted and deterministic.
- Hardening: _parse_artifact_metadata requires the dynamo driver globals so
  a truncated dynamo artifact fails load with a clean PrecompileError
  instead of a NameError from exec; _convert_constant falls back to binding
  the object on any literal_eval exception (repr of an unhashable-key dict
  raises TypeError, not just SyntaxError/ValueError); _passthrough_source
  renders nonfinite floats as float('inf')/float('nan') instead of invalid
  bare inf/nan; the THREADING docstring states that capture-time global
  config patches are visible to concurrent torch.compile calls on other
  threads.

A third review round (of the updated head) fixed:

- autotune_to_one_config stamped found_by_coordesc from the global
  coordinate_descent_tuning flag with no eligibility gate, while coordesc
  itself never runs for USER_AUTOTUNE/TEMPLATE/FIXED kernels
  (_should_coordesc_tune). A warm cache load seeing that flag skips
  candidate matching and reconstructs the Config from the JSON payload,
  which hands a user kernel raw values where it expects Enum constexprs.
  The stamp is now gated on _should_coordesc_tune; coordesc's own save
  path (which runs after coordesc actually refines a config) still stamps
  True.
- The three tests importing torch.distributed.fsdp TrainingState now skip
  when distributed is unavailable: on USE_DISTRIBUTED=0 builds the import
  chain fails at torch._C._distributed_c10d
  (fsdp/_common_utils -> _flat_param -> testing fake_pg).

New coverage: every dynamo-tracer rejection path (non-function fn, closure
cells, nn.Module example args -- top-level and nested in a container,
decompositions, eager get_attr, unpicklable defaults, tensors hidden inside
object defaults, unserializable identity guards), dynamo cache robustness
(corrupt bundle degrades to JIT with correct numerics, weights_only
envelope, code/cache mismatch, truncated artifact), fresh-process runs of
the inference artifact, a _load_dynamo_state AST accessor replacing the
test helper's brittle line-prefix parse of _DYNAMO_STATE plus direct unit
tests for it and for _filter_dynamo_guards' unmatched-variant invariant,
the dynamo numeric tests moved into the device-generic
TestPrecompileNumerics, plain-Enum autotune configs end to end (codegen +
autotune-cache save) plus a unit test of the cached-config Enum match, set
and empty-set constexpr rendering, and nonfinite-float passthrough
rendering.

This PR was authored by an AI assistant (Claude Code) at the stack owner's
direction, from the plan derived from the review of #194113; every change
was verified on a from-source build.

Test Plan:

On a from-source editable build of this branch (H100, triton 3.7, py3.12):

```
.venv/bin/python test/test_precompile.py
# Ran 216 tests ... OK

.venv/bin/python test/inductor/test_codegen_triton.py
# Ran 54 tests ... OK (skipped=2)

.venv/bin/python test/functorch/test_compile_to_python.py
# Ran 62 tests ... OK

lintrunner torch/_precompile.py torch/_dynamo/convert_frame.py \
  torch/_inductor/codegen/wrapper.py \
  torch/_inductor/runtime/triton_heuristics.py \
  torch/_inductor/runtime/autotune_cache.py \
  torch/_inductor/standalone_compile.py \
  test/test_precompile.py test/inductor/test_codegen_triton.py \
  test/functorch/test_compile_to_python.py
# ok No lint issues.
```

The new autotune-cache test was verified load-bearing: with the
autotune_cache.py fix stashed, test_plain_enum_constexpr_in_autotune_config
fails with "TypeError: Object of type TrainingState is not JSON
serializable". The embedded-tensor and nested-module repros were likewise
confirmed to fail before the fixes and raise typed errors after, and
test_user_autotune_cache_not_stamped_coordesc fails without the
found_by_coordesc gate and passes with it.
test/inductor/test_coordinate_descent_tuner.py stays OK, pinning that
coordesc-eligible kernels are unaffected by the gate.

Plus a 17-check behavioral harness (rejection paths, artifact hygiene
including a no-tensor-bytes-in-artifact scan, environment-drift semantics,
CPU/CUDA training numerics, guard-minimization timing): 17/17 pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93 bobrenjc93 changed the title [precompile] Support tracer="dynamo" in torch.compiler.precompile [precompile] support torch.compiler.precompile(tracer="dynamo") Aug 28, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@bobrenjc93

Copy link
Copy Markdown
Contributor Author

Superseded by the canonical precompile stack #195353-#195362: the dynamo tracer was re-implemented in #195360 (the guard-drop policy replaces the bytecode environment-contract analyzer) and the install machinery in #195355. Closing to consolidate review there.

@bobrenjc93 bobrenjc93 closed this Sep 3, 2026
@github-actions
github-actions Bot deleted the gh/bobrenjc93/997/head branch November 10, 2026 01:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant