Repository navigation
Support non-builtin constexpr objects in user Triton kernels - #189692
AnthonyBarbier wants to merge 17 commits into
Conversation
Fix Inductor codegen for user-defined Triton kernels that pass non-builtin Python objects as `tl.constexpr` values. When such constants are serialized with constructor-style `repr` output, for example `UserDefinedTritonKernelConfig(offset=2)`, generated kernel source and launcher code need the corresponding class in scope. This change imports the constant class into generated kernel source and makes it available in the generated launcher exec scope.
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/189692
Note: Links to docs will display an error until the docs builds have been completed. ✅ You can merge normally! (4 Unrelated Failures)As of commit f942d0c with merge base 1859e8b ( BROKEN TRUNK - The following job failed but were present on the merge base:👉 Rebase onto the `viable/strict` branch to avoid these failures
CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:
This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@claude review these changes |
|
Claude finished @jansel's task in 8m 38s —— View job PR Review: #189692One-sentence summary: The change correctly makes non-builtin Full review detailsSummaryFixes Inductor codegen for user-defined Triton kernels passing non-builtin objects (e.g. a dataclass) as Code Quality
Testing
Correctness / robustness
RecommendationRequest Changes Main blockers: de-duplicate the detection into a shared helper, and handle the non-importable-module / nested-value / nested-class cases (or explicitly document + fail loudly with a clear message). The happy-path test should be expanded to cover at least the |
- Factored the constexpr type detection/import logic into shared get_importable_constexpr_types() in torch/_inductor/utils.py:152. - Updated both wrapper kernel-source imports and launcher-scope imports to use the shared helper. - Added recursive handling for nested containers/dataclasses and nested classes. - Added clear ImportError failures for local / __main__ / conflicting import cases. - Expanded tests with nested constexpr config coverage and local-class failure coverage. - Added importable test config classes in test/inductor/triton_constexpr_configs.py.
|
@jansel any follow up? |
|
@claude review this again, are the prior issues fixed? |
|
I'll analyze this and get back to you. |
|
@claude review this again, are the prior issues fixed? |
|
Claude finished @jansel's task in 19m 18s —— View job Re-review of #189692One-sentence summary: All four structural issues from my previous review are addressed (logic de-duplicated into Full review detailsPrior findings — status
New issues in the shared helper1. Spurious # Both need only `from mod import NS` — this raises today.
Config(a=NS.A(1), b=NS.B(2))
# ImportError: ... conflicting imports for NS: mod.NS.A and mod.NS.BThe genuine conflict is two different roots with the same name, so the check should compare 2. The 3. Traversal over-reports, turning working code into a hard failure. 4. Recursion gaps. Two shapes still slip through:
TestingCoverage is much better — a nested-value unit test, a local-class error test, and an end-to-end compiled-kernel test. Remaining gaps:
Nits
RecommendationRequest changes (minor) — the structural rework is the right shape and the previous blockers are genuinely resolved. Findings 1 and 3 are behavior regressions relative to no-op for valid programs, and finding 2 leaves a common repr shape broken; all three are small, local fixes in |
|
@claude review this again, are the prior issues fixed? |
|
Claude finished @AnthonyBarbier's task in 27m 52s —— View job Re-review of #189692One-sentence summary: All four findings from my last round are fixed and well-tested, but the PR now makes dataclasses a first-class Full review detailsPrior findings — status
I also checked the two things I flagged as structural in round 2 and they hold up: New issue1.
class Mode(IntEnum):
FAST = 1
@dataclasses.dataclass(frozen=True)
class MyConfig:
mode: Mode
The ordering makes this concrete: Fix is to teach 2. Still unaddressed from round 2
Minor
RecommendationRequest changes (minor) — every round-2 finding is genuinely fixed and the test suite now covers each one, so the helper itself is in good shape. Finding 1 is the only blocker: it's a compile-time |
Merge startedYour change will be merged while ignoring the following 1 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, mt-l-x86aavx2-189-704-a10g-8) Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…nt-end, and support stateful incremental capture Restack of #195044 onto main (via viable/strict), self-contained: the old base was a snapshot of a since-abandoned stack, so this commit now FOLDS IN the prerequisite layer that lived there (the compile_to_python extensions in to_standalone_python.py, the backward-retrace machinery in graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and standalone_compile support, and their tests), on top of the two typed-guard commits below it in this stack. Review order: the prerequisite layer first (it is the bulk), then torch/_precompile.py / _precompile_driver.py (the feature), then the trunk reconciliation and fixes below. Two reconciliations with trunk made during the restack: - #189692 (non-builtin constexpr support for user Triton kernels) landed on trunk in parallel and overlapped this stack's constexpr rendering. The merge keeps trunk's get_importable_constexpr_types/get_constexpr_repr_children machinery in _inductor/utils.py and its launcher-side type imports in triton_heuristics.py (all of #189692's unit tests still pass), while this stack's rendering (_constexpr_source/_render_constexpr_mappings, which also emits importable-type references and feeds the autotune-cache matching) takes the wrapper.py kernel-emission sites; trunk's _sanitize_for_repr lost its only caller there and is removed along with its tests. - Two latent bugs in the folded retrace machinery, previously masked by the old base and visible as CI failures (test_pow_backward_dynamic_symint_ exponent, test_gan_repro_trying_to_backward_through_the_graph_a_second_ time): the backward-time retrace re-ran the joint trace WITHOUT the compile-time ambient environment, so factory ops materialized real tensors inside fake tracing ("Please convert all Tensors to FakeTensors"). The retrace now enters the same contexts create_aot_state uses (fake mode from the recorded args, single-threaded autograd, preserved RNG, PhiloxStateTracker, saved-tensor hooks disabled). The folded runtime_wrappers.py was also missing _dealias_marked_returns, which its own folded tests reference; it is included with its call sites. The feature itself is unchanged from #195044 (see that PR for the eleven review rounds): example_inputs= tuples with the positional form kept for compatibility; tracer="dynamo" capturing guarded specializations and recompilations (automatic dynamic across examples, newest-first dispatch at load); training=True with readable Inductor forward/backward source bridged by an emitted autograd.Function; precompile.stateful for crash-safe incremental capture from a caller-owned loop; environment guards dropped by provenance with input guards retained; loud rejections for graph breaks, closures, nn.Module / numpy arguments, overlapping storage, and tensor-reachable globals. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 92 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/functorch/test_aotdispatch.py # 3837 tests; 1 error = pre-existing trunk test needing LAPACK (absent in this local build), 55 expected failures python test/inductor/test_compiled_autograd.py # OK python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK (was failing) python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK (was failing) python test/dynamo/test_guard_serialization.py # 61 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/inductor/test_triton_heuristics.py # OK (5 skipped) python test/dynamo/test_backward_higher_order_ops.py # OK lintrunner <touched files> # ok ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: bec0fe1 Pull-Request: #195288
…nt-end, and support stateful incremental capture Restack of #195044 onto main (via viable/strict), self-contained: the old base was a snapshot of a since-abandoned stack, so this commit now FOLDS IN the prerequisite layer that lived there (the compile_to_python extensions in to_standalone_python.py, the backward-retrace machinery in graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and standalone_compile support, and their tests), on top of the two typed-guard commits below it in this stack. Review order: the prerequisite layer first (it is the bulk), then torch/_precompile.py / _precompile_driver.py (the feature), then the trunk reconciliation and fixes below. Two reconciliations with trunk made during the restack: - #189692 (non-builtin constexpr support for user Triton kernels) landed on trunk in parallel and overlapped this stack's constexpr rendering. The merge keeps trunk's get_importable_constexpr_types/get_constexpr_repr_children machinery in _inductor/utils.py and its launcher-side type imports in triton_heuristics.py (all of #189692's unit tests still pass), while this stack's rendering (_constexpr_source/_render_constexpr_mappings, which also emits importable-type references and feeds the autotune-cache matching) takes the wrapper.py kernel-emission sites; trunk's _sanitize_for_repr lost its only caller there and is removed along with its tests. - Two latent bugs in the folded retrace machinery, previously masked by the old base and visible as CI failures (test_pow_backward_dynamic_symint_ exponent, test_gan_repro_trying_to_backward_through_the_graph_a_second_ time): the backward-time retrace re-ran the joint trace WITHOUT the compile-time ambient environment, so factory ops materialized real tensors inside fake tracing ("Please convert all Tensors to FakeTensors"). The retrace now enters the same contexts create_aot_state uses (fake mode from the recorded args, single-threaded autograd, preserved RNG, PhiloxStateTracker, saved-tensor hooks disabled). The folded runtime_wrappers.py was also missing _dealias_marked_returns, which its own folded tests reference; it is included with its call sites. The feature itself is unchanged from #195044 (see that PR for the eleven review rounds): example_inputs= tuples with the positional form kept for compatibility; tracer="dynamo" capturing guarded specializations and recompilations (automatic dynamic across examples, newest-first dispatch at load); training=True with readable Inductor forward/backward source bridged by an emitted autograd.Function; precompile.stateful for crash-safe incremental capture from a caller-owned loop; environment guards dropped by provenance with input guards retained; loud rejections for graph breaks, closures, nn.Module / numpy arguments, overlapping storage, and tensor-reachable globals. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 92 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/functorch/test_aotdispatch.py # 3837 tests; 1 error = pre-existing trunk test needing LAPACK (absent in this local build), 55 expected failures python test/inductor/test_compiled_autograd.py # OK python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK (was failing) python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK (was failing) python test/dynamo/test_guard_serialization.py # 61 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/inductor/test_triton_heuristics.py # OK (5 skipped) python test/dynamo/test_backward_higher_order_ops.py # OK lintrunner <touched files> # ok ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: bec0fe1 Pull-Request: #195288
…nt-end, and support stateful incremental capture Restack of #195044 onto main (via viable/strict), self-contained: the old base was a snapshot of a since-abandoned stack, so this commit FOLDS IN the prerequisite layer that lived there (the compile_to_python extensions in to_standalone_python.py, the undefined-tangent/backward-retrace machinery in graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and standalone_compile support, and their tests), on top of the two typed-guard commits below it in this stack. Review order: the prerequisite layer first (it is the bulk), then torch/_precompile.py / _precompile_driver.py (the feature), then the reconciliations and hardening below. The folded undefined-tangent machinery is now OPT-IN (torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False): ordinary torch.compile keeps the zero-materialization backward behavior, and precompile enables the flag during training capture. Emitted training artifacts bake the enabled behavior at emission time and never consult ambient config at load. A contract test pins that a default-config partial backward never invokes the machinery and matches eager. A workflow review round (8 finders, 3-lens adversarial verification per finding, all empirically reproduced) hardened the machinery behind the flag: the backward-time retrace now snapshots the compile-time autocast state and falls back to the structural path on mismatch (an AMP forward with a partial backward previously recompiled the backward under the caller's autocast state and crashed or silently changed dtypes); the retrace runs the inductor partitioner inside V.set_fake_mode and is wrapped in a warn-and-fall-back exception guard (dropout graphs previously hard-crashed in replace_random_passes); clearing bw_donated_idxs now also invalidates donation-compiled specialized backwards (a stale donated variant could bypass the retain_graph guard and corrupt gradients); the structural specializer's pruned-zero folds require meta-matching fx.Node survivors (custom backwards like g1+1 previously emitted a Python int gradient); and masking a backward output to None now requires it to be PROVABLY zero (affine custom backwards previously lost nonzero gradients silently) -- provably-safe-but-unprovable cases now materialize zero grads instead of None, and the two subclass fallback tests accept either outcome. Each fix carries a fail-first regression test. Two reconciliations with trunk made during the restack: #189692 (non-builtin constexpr support) is preserved -- constructor-repr rendering for importable dataclass/attrs/pydantic-like constexpr configs now lives as a branch of this stack's _constexpr_source_impl (rendered source is eval-verified to rebuild the exact type before acceptance), while trunk's launcher-side type-import loop is removed (the launcher binds constant objects directly; the loop's validation spuriously rejected class-nested namedtuples and name-shadowing types) and trunk's _sanitize_for_repr (whose only caller was the replaced emission site) is removed with its tests; the previously vacuous e2e test now compiles the kernel via @triton_op with fullgraph=True and asserts the rendered constructor source. Second, two latent retrace bugs previously masked by the old base were fixed (ambient-environment contexts at backward-time retrace; the ported _dealias_marked_returns), and the DTensor sharding-prop cache test isolation fix works around a pre-existing trunk hazard (stale DeviceMesh across pg re-init). The feature itself is unchanged from #195044 (see that PR for its review history): example_inputs= tuples with the positional form kept for compatibility; tracer="dynamo" capturing guarded specializations and recompilations (automatic dynamic across examples, newest-first dispatch at load); training=True with readable Inductor forward/backward source bridged by an emitted autograd.Function; precompile.stateful for crash-safe incremental capture from a caller-owned loop; environment guards dropped by provenance with input guards retained; loud rejections for graph breaks, closures, nn.Module / numpy arguments, overlapping storage, and tensor-reachable globals. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 1f52f73 Pull-Request: #195288
…nt-end, and support stateful incremental capture Restack of #195044 onto main (via viable/strict), self-contained: the old base was a snapshot of a since-abandoned stack, so this commit FOLDS IN the prerequisite layer that lived there (the compile_to_python extensions in to_standalone_python.py, the undefined-tangent/backward-retrace machinery in graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and standalone_compile support, and their tests), on top of the two typed-guard commits below it in this stack. Review order: the prerequisite layer first (it is the bulk), then torch/_precompile.py / _precompile_driver.py (the feature), then the reconciliations and hardening below. The folded undefined-tangent machinery is now OPT-IN (torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False): ordinary torch.compile keeps the zero-materialization backward behavior, and precompile enables the flag during training capture. Emitted training artifacts bake the enabled behavior at emission time and never consult ambient config at load. A contract test pins that a default-config partial backward never invokes the machinery and matches eager. A workflow review round (8 finders, 3-lens adversarial verification per finding, all empirically reproduced) hardened the machinery behind the flag: the backward-time retrace now snapshots the compile-time autocast state and falls back to the structural path on mismatch (an AMP forward with a partial backward previously recompiled the backward under the caller's autocast state and crashed or silently changed dtypes); the retrace runs the inductor partitioner inside V.set_fake_mode and is wrapped in a warn-and-fall-back exception guard (dropout graphs previously hard-crashed in replace_random_passes); clearing bw_donated_idxs now also invalidates donation-compiled specialized backwards (a stale donated variant could bypass the retain_graph guard and corrupt gradients); the structural specializer's pruned-zero folds require meta-matching fx.Node survivors (custom backwards like g1+1 previously emitted a Python int gradient); and masking a backward output to None now requires it to be PROVABLY zero (affine custom backwards previously lost nonzero gradients silently) -- provably-safe-but-unprovable cases now materialize zero grads instead of None, and the two subclass fallback tests accept either outcome. Each fix carries a fail-first regression test. Two reconciliations with trunk made during the restack: #189692 (non-builtin constexpr support) is preserved -- constructor-repr rendering for importable dataclass/attrs/pydantic-like constexpr configs now lives as a branch of this stack's _constexpr_source_impl (rendered source is eval-verified to rebuild the exact type before acceptance), while trunk's launcher-side type-import loop is removed (the launcher binds constant objects directly; the loop's validation spuriously rejected class-nested namedtuples and name-shadowing types) and trunk's _sanitize_for_repr (whose only caller was the replaced emission site) is removed with its tests; the previously vacuous e2e test now compiles the kernel via @triton_op with fullgraph=True and asserts the rendered constructor source. Second, two latent retrace bugs previously masked by the old base were fixed (ambient-environment contexts at backward-time retrace; the ported _dealias_marked_returns), and the DTensor sharding-prop cache test isolation fix works around a pre-existing trunk hazard (stale DeviceMesh across pg re-init). The feature itself is unchanged from #195044 (see that PR for its review history): example_inputs= tuples with the positional form kept for compatibility; tracer="dynamo" capturing guarded specializations and recompilations (automatic dynamic across examples, newest-first dispatch at load); training=True with readable Inductor forward/backward source bridged by an emitted autograd.Function; precompile.stateful for crash-safe incremental capture from a caller-owned loop; environment guards dropped by provenance with input guards retained; loud rejections for graph breaks, closures, nn.Module / numpy arguments, overlapping storage, and tensor-reachable globals. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 1f52f73 Pull-Request: #195288
…nt-end, and support stateful incremental capture Restack of #195044 onto main (via viable/strict), self-contained: the old base was a snapshot of a since-abandoned stack, so this commit FOLDS IN the prerequisite layer that lived there (the compile_to_python extensions in to_standalone_python.py, the undefined-tangent/backward-retrace machinery in graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and standalone_compile support, and their tests), on top of the two typed-guard commits below it in this stack. Review order: the prerequisite layer first (it is the bulk), then torch/_precompile.py / _precompile_driver.py (the feature), then the reconciliations and hardening below. The folded undefined-tangent machinery is now OPT-IN (torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False): ordinary torch.compile keeps the zero-materialization backward behavior, and precompile enables the flag during training capture. Emitted training artifacts bake the enabled behavior at emission time and never consult ambient config at load. A contract test pins that a default-config partial backward never invokes the machinery and matches eager. A workflow review round (8 finders, 3-lens adversarial verification per finding, all empirically reproduced) hardened the machinery behind the flag: the backward-time retrace now snapshots the compile-time autocast state and falls back to the structural path on mismatch (an AMP forward with a partial backward previously recompiled the backward under the caller's autocast state and crashed or silently changed dtypes); the retrace runs the inductor partitioner inside V.set_fake_mode and is wrapped in a warn-and-fall-back exception guard (dropout graphs previously hard-crashed in replace_random_passes); clearing bw_donated_idxs now also invalidates donation-compiled specialized backwards (a stale donated variant could bypass the retain_graph guard and corrupt gradients); the structural specializer's pruned-zero folds require meta-matching fx.Node survivors (custom backwards like g1+1 previously emitted a Python int gradient); and masking a backward output to None now requires it to be PROVABLY zero (affine custom backwards previously lost nonzero gradients silently) -- provably-safe-but-unprovable cases now materialize zero grads instead of None, and the two subclass fallback tests accept either outcome. Each fix carries a fail-first regression test. Two reconciliations with trunk made during the restack: #189692 (non-builtin constexpr support) is preserved -- constructor-repr rendering for importable dataclass/attrs/pydantic-like constexpr configs now lives as a branch of this stack's _constexpr_source_impl (rendered source is eval-verified to rebuild the exact type before acceptance), while trunk's launcher-side type-import loop is removed (the launcher binds constant objects directly; the loop's validation spuriously rejected class-nested namedtuples and name-shadowing types) and trunk's _sanitize_for_repr (whose only caller was the replaced emission site) is removed with its tests; the previously vacuous e2e test now compiles the kernel via @triton_op with fullgraph=True and asserts the rendered constructor source. Second, two latent retrace bugs previously masked by the old base were fixed (ambient-environment contexts at backward-time retrace; the ported _dealias_marked_returns), and the DTensor sharding-prop cache test isolation fix works around a pre-existing trunk hazard (stale DeviceMesh across pg re-init). The feature itself is unchanged from #195044 (see that PR for its review history): example_inputs= tuples with the positional form kept for compatibility; tracer="dynamo" capturing guarded specializations and recompilations (automatic dynamic across examples, newest-first dispatch at load); training=True with readable Inductor forward/backward source bridged by an emitted autograd.Function; precompile.stateful for crash-safe incremental capture from a caller-owned loop; environment guards dropped by provenance with input guards retained; loud rejections for graph breaks, closures, nn.Module / numpy arguments, overlapping storage, and tensor-reachable globals. CI-portability fixes from the first trunk-based CI round: the emitted training artifact's RNG tracker is now written as a constructor call instead of a pickled object (its itertools.count default is unpicklable on Python >= 3.14); the dedup training test is skipped under dynamo-wrapped testing (compiled autograd deliberately rejects the artifact's boxed backward); and the fresh-process artifact test is skipped under crossref (the mode is part of the captured environment, so the plain subprocess correctly fails the environment-invariant contract). The PR carries skip-pr-sanity-checks for the 2000-LOC limit. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 2bf4c63 Pull-Request: #195288
…nt-end, and support stateful incremental capture Restack of #195044 onto main (via viable/strict), self-contained: the old base was a snapshot of a since-abandoned stack, so this commit FOLDS IN the prerequisite layer that lived there (the compile_to_python extensions in to_standalone_python.py, the undefined-tangent/backward-retrace machinery in graph_compile.py / runtime_wrappers.py / schemas.py, compiled_autograd and standalone_compile support, and their tests), on top of the two typed-guard commits below it in this stack. Review order: the prerequisite layer first (it is the bulk), then torch/_precompile.py / _precompile_driver.py (the feature), then the reconciliations and hardening below. The folded undefined-tangent machinery is now OPT-IN (torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False): ordinary torch.compile keeps the zero-materialization backward behavior, and precompile enables the flag during training capture. Emitted training artifacts bake the enabled behavior at emission time and never consult ambient config at load. A contract test pins that a default-config partial backward never invokes the machinery and matches eager. A workflow review round (8 finders, 3-lens adversarial verification per finding, all empirically reproduced) hardened the machinery behind the flag: the backward-time retrace now snapshots the compile-time autocast state and falls back to the structural path on mismatch (an AMP forward with a partial backward previously recompiled the backward under the caller's autocast state and crashed or silently changed dtypes); the retrace runs the inductor partitioner inside V.set_fake_mode and is wrapped in a warn-and-fall-back exception guard (dropout graphs previously hard-crashed in replace_random_passes); clearing bw_donated_idxs now also invalidates donation-compiled specialized backwards (a stale donated variant could bypass the retain_graph guard and corrupt gradients); the structural specializer's pruned-zero folds require meta-matching fx.Node survivors (custom backwards like g1+1 previously emitted a Python int gradient); and masking a backward output to None now requires it to be PROVABLY zero (affine custom backwards previously lost nonzero gradients silently) -- provably-safe-but-unprovable cases now materialize zero grads instead of None, and the two subclass fallback tests accept either outcome. Each fix carries a fail-first regression test. Two reconciliations with trunk made during the restack: #189692 (non-builtin constexpr support) is preserved -- constructor-repr rendering for importable dataclass/attrs/pydantic-like constexpr configs now lives as a branch of this stack's _constexpr_source_impl (rendered source is eval-verified to rebuild the exact type before acceptance), while trunk's launcher-side type-import loop is removed (the launcher binds constant objects directly; the loop's validation spuriously rejected class-nested namedtuples and name-shadowing types) and trunk's _sanitize_for_repr (whose only caller was the replaced emission site) is removed with its tests; the previously vacuous e2e test now compiles the kernel via @triton_op with fullgraph=True and asserts the rendered constructor source. Second, two latent retrace bugs previously masked by the old base were fixed (ambient-environment contexts at backward-time retrace; the ported _dealias_marked_returns), and the DTensor sharding-prop cache test isolation fix works around a pre-existing trunk hazard (stale DeviceMesh across pg re-init). The feature itself is unchanged from #195044 (see that PR for its review history): example_inputs= tuples with the positional form kept for compatibility; tracer="dynamo" capturing guarded specializations and recompilations (automatic dynamic across examples, newest-first dispatch at load); training=True with readable Inductor forward/backward source bridged by an emitted autograd.Function; precompile.stateful for crash-safe incremental capture from a caller-owned loop; environment guards dropped by provenance with input guards retained; loud rejections for graph breaks, closures, nn.Module / numpy arguments, overlapping storage, and tensor-reachable globals. CI-portability fixes from the first trunk-based CI round: the emitted training artifact's RNG tracker is now written as a constructor call instead of a pickled object (its itertools.count default is unpicklable on Python >= 3.14); the dedup training test is skipped under dynamo-wrapped testing (compiled autograd deliberately rejects the artifact's boxed backward); and the fresh-process artifact test is skipped under crossref (the mode is part of the captured environment, so the plain subprocess correctly fails the environment-invariant contract). The PR carries skip-pr-sanity-checks for the 2000-LOC limit. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 2bf4c63 Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - training=True (dynamo + inductor) captures differentiable graphs: each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during training capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 2bf4c63 Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - With the inductor backend, differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is compiled differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly; the eager backend always captures inference). For each differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 99c13fb Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - With the inductor backend, differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is compiled differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly; the eager backend always captures inference). For each differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 99c13fb Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - Differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly). On the inductor backend the backward is precompiled; on the eager backend it is live eager autograd through the emitted ops -- neither captured nor specialized, like torch.compile(backend="eager"). For each inductor differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: af74acd Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - Differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly). On the inductor backend the backward is precompiled; on the eager backend it is live eager autograd through the emitted ops -- neither captured nor specialized, like torch.compile(backend="eager"). For each inductor differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: af74acd Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - Differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly). On the inductor backend the backward is precompiled; on the eager backend it is live eager autograd through the emitted ops -- neither captured nor specialized, like torch.compile(backend="eager"). For each inductor differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 55e2e88 Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - Differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly). On the inductor backend the backward is precompiled; on the eager backend it is live eager autograd through the emitted ops -- neither captured nor specialized, like torch.compile(backend="eager"). For each inductor differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 288 tests, OK python test/inductor/test_codegen_triton.py # 97 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 62 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3855 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 5c7b5c3 Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - Differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly). On the inductor backend the backward is precompiled; on the eager backend it is live eager autograd through the emitted ops -- neither captured nor specialized, like torch.compile(backend="eager"). For each inductor differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. Serving follows the ambient grad mode like eager: under torch.no_grad() freshly created outputs are returned detached (passthrough inputs untouched), and torch.inference_mode() is rejected with a clear error. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 297 tests, OK python test/inductor/test_codegen_triton.py # 102 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 64 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3873 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 64 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: b1ceae8 Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - Differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly). On the inductor backend the backward is precompiled; on the eager backend it is live eager autograd through the emitted ops -- neither captured nor specialized, like torch.compile(backend="eager"). For each inductor differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. Serving follows the ambient grad mode like eager: under torch.no_grad() freshly created outputs are returned detached (passthrough inputs untouched), and torch.inference_mode() is rejected with a clear error. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. - BC note for user-defined Triton kernels (independent of precompile): a plain-Enum constexpr previously reached the generated source value-unwrapped (Mode.A with value 1 was baked as the literal 1); it now bakes the real member, matching direct eager triton launches. A kernel written against the unwrapped behavior (e.g. branching on MODE == 1) sees plain-Enum __eq__ semantics and selects a different branch, and a plain Enum defined in __main__ or a local scope now raises a clear error where value-unwrapping previously compiled. Both are deliberate fidelity fixes, pinned by test_plain_enum_constexpr_in_user_defined_triton_kernel and test_constexpr_source_declines_main_module_enum. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 301 tests, OK python test/inductor/test_codegen_triton.py # 102 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 65 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3873 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 66 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK python test/dynamo/test_pgo.py # 12 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: ae6fc34 Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - Differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly). On the inductor backend the backward is precompiled; on the eager backend it is live eager autograd through the emitted ops -- neither captured nor specialized, like torch.compile(backend="eager"). For each inductor differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. Serving follows the ambient grad mode like eager: under torch.no_grad() freshly created outputs are returned detached (passthrough inputs untouched), and torch.inference_mode() is rejected with a clear error. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. - BC note for user-defined Triton kernels (independent of precompile): a plain-Enum constexpr previously reached the generated source value-unwrapped (Mode.A with value 1 was baked as the literal 1); it now bakes the real member, matching direct eager triton launches. A kernel written against the unwrapped behavior (e.g. branching on MODE == 1) sees plain-Enum __eq__ semantics and selects a different branch, and a plain Enum defined in __main__ or a local scope now raises a clear error where value-unwrapping previously compiled. Both are deliberate fidelity fixes, pinned by test_plain_enum_constexpr_in_user_defined_triton_kernel and test_constexpr_source_declines_main_module_enum. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 301 tests, OK python test/inductor/test_codegen_triton.py # 102 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 65 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3873 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 66 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK python test/dynamo/test_pgo.py # 12 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: b2f1c7a Pull-Request: #195288
…nt-end, and support stateful incremental capture torch.compiler.precompile lowers a whole computation ahead of time to a self-contained, runnable Python source string plus a binary acceleration cache, and reloads it with precompile.load -- no compiler in the serving process, no weights baked into the artifact, and the artifact is auditable text rather than an opaque binary. Until now it captured exactly one execution through make_fx: control flow and shapes were specialized to a single example call. This PR generalizes the API to a SET of observed calls and adds a Dynamo capture front-end: - example_inputs= takes a sequence of positional-argument tuples (the existing positional form keeps working as a single example call; make_fx remains the default tracer and requires exactly one tuple). - tracer="dynamo" executes every example tuple under Dynamo and captures each guarded specialization and recompilation it produces, including the automatically dynamic graphs that appear when a dimension varies across examples (one isolated capture session with a private PGO record, so the result is deterministic regardless of process history). At serve time the artifact dispatches among the captured variants by guard check, newest variant first, and never compiles: a call no variant covers raises. Guards derived from explicit inputs are retained for dispatch, classified by their typed provenance (the commit below in this stack); guards on the Python environment may be dropped, since the environment is a declared caller invariant. Unsupported inputs are rejected loudly at capture: graph breaks, closures, nn.Module / numpy arguments, tensor inputs with overlapping storage, tensor-reachable globals, and global-mutating functions. - Differentiability is inferred per captured graph exactly as torch.compile infers it: capture runs grad-enabled, and a graph whose inputs require grad is differentiable (no-grad inputs stay inference graphs; requires_grad is guarded per input, so a flipped input fails dispatch loudly). On the inductor backend the backward is precompiled; on the eager backend it is live eager autograd through the emitted ops -- neither captured nor specialized, like torch.compile(backend="eager"). For each inductor differentiable graph, each compiled segment carries readable Inductor source for its AOTAutograd forward and backward, bridged by an emitted torch.autograd.Function, so served outputs retain grad_fn and backward() runs the precompiled kernels. Backward variants are specialized to the output-tangent patterns observed during capture (the all-tangents-defined pattern is always covered); an unseen pattern fails instead of compiling at runtime. Serving follows the ambient grad mode like eager: under torch.no_grad() freshly created outputs are returned detached (passthrough inputs untouched), and torch.inference_mode() is rejected with a clear error. - precompile.stateful captures incrementally from a loop the caller owns (e.g. a pipelined train step that precompile cannot drive itself): every call runs its example tuples for real, accumulates newly exercised variants into an opaque resumable state, and atomically rewrites an always-loadable artifact/cache pair on disk, so a job that dies mid-loop keeps a working artifact for the batches it saw. Supporting machinery introduced by this PR, and why it is safe for everyone else: - compile_to_python (to_standalone_python.py) renders AOTAutograd forward/backward pairs as standalone Python source, with values emitted as auditable source expressions rather than pickle blobs (training artifacts bake their behavior at emission time and never consult ambient config at load). - An undefined-tangent backward-specialization layer in AOTAutograd (runtime_wrappers.py / graph_compile.py) lets a partial backward serve a variant specialized to which output tangents are undefined, retracing or structurally pruning the backward per observed pattern. It is OPT-IN: torch._functorch.config.aot_autograd_prune_unused_outputs defaults to False, ordinary torch.compile keeps the existing zero-materialization backward behavior (a contract test pins this), and precompile enables the flag only during dynamo-inductor capture. Behind the flag the layer reconciles autocast state at retrace time, runs the partitioner inside inductor's virtualized context with a fall-back exception guard, invalidates specialized backwards when donation state changes, and only prunes gradients it can prove are zero -- each property carried by a fail-first regression test. - User-defined Triton kernel constexprs render as importable, eval-verified source (enums, containers, torch.Size, and constructor-repr'able dataclass/attrs/pydantic-style configs), with autotune-cache matching that round-trips tuple-valued config kwargs type-faithfully and an async-compile fallback when a worker cannot import a constexpr's module. - BC note for user-defined Triton kernels (independent of precompile): a plain-Enum constexpr previously reached the generated source value-unwrapped (Mode.A with value 1 was baked as the literal 1); it now bakes the real member, matching direct eager triton launches. A kernel written against the unwrapped behavior (e.g. branching on MODE == 1) sees plain-Enum __eq__ semantics and selects a different branch, and a plain Enum defined in __main__ or a local scope now raises a clear error where value-unwrapping previously compiled. Both are deliberate fidelity fixes, pinned by test_plain_enum_constexpr_in_user_defined_triton_kernel and test_constexpr_source_declines_main_module_enum. Suggested review order: to_standalone_python.py and the runtime_wrappers.py / graph_compile.py layer first (the bulk), then torch/_precompile.py and torch/_precompile_driver.py (the API, the capture pipeline, and the emitted serve-time driver), then the inductor constexpr/autotune changes, then tests and docs. Supersedes #195044. Authored with an AI assistant. Test Plan: ``` python test/test_precompile.py # 301 tests, OK python test/inductor/test_codegen_triton.py # 102 tests, OK (2 skipped; includes all #189692 tests) python test/functorch/test_compile_to_python.py # 65 tests, OK python test/inductor/test_compile_to_python.py # 19 tests, OK python test/functorch/test_aotdispatch.py # 3873 tests; sole error is a pre-existing trunk test needing LAPACK (absent in this local build) python test/inductor/test_compiled_autograd.py TestCompiledAutograd # 150 tests, OK (2 expected failures) python test/inductor/test_torchinductor.py CpuTests.test_pow_backward_dynamic_symint_exponent_cpu # OK python test/dynamo/test_repros.py ReproTests.test_gan_repro_trying_to_backward_through_the_graph_a_second_time # OK python test/dynamo/test_guard_serialization.py # 66 tests, OK (1 skipped) python test/dynamo/test_sources.py # 8 tests, OK python test/dynamo/test_backward_higher_order_ops.py # 7 tests, OK python test/dynamo/test_pgo.py # 12 tests, OK lintrunner <all changed files> # ok No lint issues. ``` Co-Authored-By: Claude Fable 5 <[email protected]> ghstack-source-id: 972d7af Pull-Request: #195288
…#189692) Fix Inductor codegen for user-defined Triton kernels that pass non-builtin Python objects as `tl.constexpr` values. When such constants are serialized with constructor-style `repr` output, for example `UserDefinedTritonKernelConfig(offset=2)`, generated kernel source and launcher code need the corresponding class in scope. This change imports the constant class into generated kernel source and makes it available in the generated launcher exec scope. Pull Request resolved: pytorch#189692 Approved by: https://github.com/jansel
Forward fix for D117882973 (#189692), which broke `fbcode//caffe2/test/inductor:codegen_triton` at listing time. That diff added a new helper module `triton_constexpr_configs.py` next to `test_codegen_triton.py` and imported it with two OSS-only fallbacks: ``` try: from triton_constexpr_configs import ... # test/inductor on sys.path except ImportError: from test.inductor.triton_constexpr_configs import ... # pytorch repo root on sys.path ``` The file itself is packaged fine internally -- `:inductor_test_lib` uses `srcs = glob(["*.py"])`, so no BUCK change is needed -- but inside the PAR it resolves under the fbcode base module as `caffe2.test.inductor.triton_constexpr_configs`. Neither branch matches, so both raised `ModuleNotFoundError` and the whole module failed to import, taking down all 22 tests in the suite, not just the new ones: ``` ModuleNotFoundError: No module named 'triton_constexpr_configs' During handling of the above exception, another exception occurred: ModuleNotFoundError: No module named 'test.inductor' ``` Switch to the relative-first pattern already used elsewhere in this directory (`test_codecache.py`, `test_ck_backend.py`). The relative import resolves against whatever package the test module actually lives in, so it covers all three run modes: the fbcode PAR (`caffe2.test.inductor`), OSS pytest from the repo root (`test.inductor`), and `python test/inductor/test_codegen_triton.py` (no package, falls through to the bare import). This also matters beyond the import statement itself. The new `get_importable_constexpr_types` emits `from {type.__module__} import ...` into the generated Triton kernel source, so the helper module has to be reachable under its real package name for `test_user_defined_triton_kernel_non_builtin_constexpr` to compile and run. `xplat/caffe2` is updated to keep it in sync with `fbcode/caffe2`. Differential Revision: [D118378564](https://our.internmc.facebook.com/intern/diff/D118378564/) Pull Request resolved: #195663 Approved by: https://github.com/pytorchgreenlight
…#189692) Fix Inductor codegen for user-defined Triton kernels that pass non-builtin Python objects as `tl.constexpr` values. When such constants are serialized with constructor-style `repr` output, for example `UserDefinedTritonKernelConfig(offset=2)`, generated kernel source and launcher code need the corresponding class in scope. This change imports the constant class into generated kernel source and makes it available in the generated launcher exec scope. Pull Request resolved: pytorch#189692 Approved by: https://github.com/jansel
…ch#195663) Forward fix for D117882973 (pytorch#189692), which broke `fbcode//caffe2/test/inductor:codegen_triton` at listing time. That diff added a new helper module `triton_constexpr_configs.py` next to `test_codegen_triton.py` and imported it with two OSS-only fallbacks: ``` try: from triton_constexpr_configs import ... # test/inductor on sys.path except ImportError: from test.inductor.triton_constexpr_configs import ... # pytorch repo root on sys.path ``` The file itself is packaged fine internally -- `:inductor_test_lib` uses `srcs = glob(["*.py"])`, so no BUCK change is needed -- but inside the PAR it resolves under the fbcode base module as `caffe2.test.inductor.triton_constexpr_configs`. Neither branch matches, so both raised `ModuleNotFoundError` and the whole module failed to import, taking down all 22 tests in the suite, not just the new ones: ``` ModuleNotFoundError: No module named 'triton_constexpr_configs' During handling of the above exception, another exception occurred: ModuleNotFoundError: No module named 'test.inductor' ``` Switch to the relative-first pattern already used elsewhere in this directory (`test_codecache.py`, `test_ck_backend.py`). The relative import resolves against whatever package the test module actually lives in, so it covers all three run modes: the fbcode PAR (`caffe2.test.inductor`), OSS pytest from the repo root (`test.inductor`), and `python test/inductor/test_codegen_triton.py` (no package, falls through to the bare import). This also matters beyond the import statement itself. The new `get_importable_constexpr_types` emits `from {type.__module__} import ...` into the generated Triton kernel source, so the helper module has to be reachable under its real package name for `test_user_defined_triton_kernel_non_builtin_constexpr` to compile and run. `xplat/caffe2` is updated to keep it in sync with `fbcode/caffe2`. Differential Revision: [D118378564](https://our.internmc.facebook.com/intern/diff/D118378564/) Pull Request resolved: pytorch#195663 Approved by: https://github.com/pytorchgreenlight

Fix Inductor codegen for user-defined Triton kernels that pass non-builtin Python objects as
tl.constexprvalues.When such constants are serialized with constructor-style
reproutput, for exampleUserDefinedTritonKernelConfig(offset=2), generated kernel source and launcher code need the corresponding class in scope.This change imports the constant class into generated kernel source and makes it available in the generated launcher exec scope.
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo