Skip to content

[inductor] Enable per-region cudagraphs for invoke_subgraph via auto graph partition - #190091

Closed
desertfire wants to merge 10 commits into
gh/desertfire/748/basefrom
gh/desertfire/748/head
Closed

desertfire wants to merge 10 commits into
gh/desertfire/748/basefrom
gh/desertfire/748/head

Conversation

@desertfire

@desertfire desertfire commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Nested compile-region CUDA Graph options were visible while compiling an
InvokeSubgraph body but did not control how the enclosing Inductor graph was
partitioned or wrapped. A region therefore could not opt into capture when the
top level was disabled, opt out when it was enabled, or select a different
forward and backward policy.

Derive the top-level and regional decisions before AOT dispatch. When a region
differs and graph partitioning is disabled, temporarily enable a region-only
mode that keeps enclosing work inline and isolates only explicitly enabled
regions. Preserve the decision through freezing, re-derive it from the backward
graph, and retain regional safety and minimum-size checks from the partitioner.
Configured regions remain separate runtime units.

Use a graph-local cudagraphs_post_compile_override for serialized FX graph state
because regional forward and backward graphs may each force capture on or off.
Keep the existing cudagraphs_bwd_override for the pre-AOT backward annotation.
Add optional override and region-only fields to cache inputs only when active so
ordinary cache keys remain stable.

Reject conflicting nested-region settings and combinations with
torch._dynamo.override_cudagraphs. For partial forward capture, conservatively
treat saved inline activations as dynamic backward inputs. Resolve the CUDA
Graph manager lazily so backward-only capture, runtime capture-size filtering,
and AOTAutograd cache hits work even when the forward created no manager.

Test Plan:

python test/dynamo/test_aot_autograd_cache.py -k optional_cudagraph_kwargs_omitted_when_unset -v
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "invoke_subgraph", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "region_backward", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
lintrunner -a

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

Differential Revision: D112182755

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 22 New Failures, 1 Unrelated Failure

As of commit b8e2e85 with merge base 5a7eae4 (image):

NEW FAILURES - The following jobs have failed:

BROKEN TRUNK - The following job failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

@desertfire

Copy link
Copy Markdown
Contributor Author

@desertfire has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jul 15, 2026
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Jul 16, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 10m 7s —— View job


PR Review: #190091

One-sentence summary: The mechanism is well-designed and correct for the tested paths, but the region-body cudagraph-safety check drops two safety checks that the main should_partition path applies, and one of them (unsafe unbacked symints) is a real capture-correctness gap that is currently untested.

Full review

Summary

Enables per-region cudagraphs for invoke_subgraph regions: a region can opt into or out of triton.cudagraphs independently of the enclosing graph, and should_partition isolates the region into (or out of) its own cudagraph partition. I verified the core isolation mechanism holds together — the MultiOutput→InvokeSubgraph isinstance check is correct (MultiOutput.inputs[0] is the InvokeSubgraph IR node directly, not a wrapping buffer), and the opt-in/opt-out partition semantics work because should_partition returning None keeps a node cudagraphable while a non-None reason isolates it. The findings below are about the body-level safety check and a couple of subtle couplings.

Testing

  • Unsafe unbacked symint use in a region body is untested and uncaptured (correctness gap). _invoke_subgraph_body_cudagraph_skip_reason (scheduler.py:8935-8965) deliberately omits _uses_cudagraph_unsafe_unbacked_symint, and the docstring notes it "is not replicated." But _get_cudagraph_unsafe_unbacked_symints (scheduler.py:9048) only scans the top-level self.nodes, so ops inside a region body that are listed in config.cudagraph_unsafe_unbacked_ops are invisible to both the body check and the top-level check. An opted-in region whose body contains such an op followed by a consumer would be captured into a cudagraph despite being unsafe. It is gated behind the non-default config.cudagraph_unsafe_unbacked_ops, so severity is limited, but there is no test asserting this is skipped. Either handle it in the body check or add a test documenting it as an explicit known limitation. Fix this →

  • Dynamic-shape detection in the body check is narrower than the main path. The body loop uses op.get_free_symbol_uses() (scheduler.py:8961) to apply cudagraph_skip_dynamic_graphs, but the main path uses get_scheduler_node_symbol_uses(node) (scheduler.py:9042), which additionally unions get_layout_symints(...) over outputs (scheduler.py:3931-3934). A region body whose only dynamic-ness lives in an output layout (dynamic size/stride/offset) rather than in an op's free symbols would evade the skip and be captured. The test_invoke_subgraph_region_cudagraph_dynamic_body_skips test only covers the get_free_symbol_uses case (cos/sin over a dynamic dim). Consider aligning the body check with get_scheduler_node_symbol_uses, or add a comment explaining why layout symints cannot appear on region-body ops.

Code Quality

  • Load-bearing coupling to config.triton.cudagraphs is undocumented at the point it matters. The opt-in-with-top-level-off path intentionally sets the cudagraphs BoxedBool to True while leaving config.triton.cudagraphs unpatched (patch_config_for_cudagraphs=False, compile_fx.py:2634-2648). The isolation of the enclosing graph's nodes then depends on should_partition's not torch._inductor.config.triton.cudagraphs → "partition includes all ops when cudagraphs is disabled" check (scheduler.py:9015) still reading False. That is the actual mechanism that keeps everything except the region out of the cudagraph, but neither cudagraph_annotation_context's new patch_config param nor scheduler.py:9015 notes this dependency. A one-line comment at the scheduler check (or in CompilerConfigExtra.patch_config_for_cudagraphs) explaining that region isolation relies on this staying unpatched would prevent a future refactor from silently breaking opt-in.

Performance / Behavior

  • cudagraph_min_partition_size can silently defeat an explicit opt-in. An opted-in region that ends up with fewer kernels than triton.cudagraph_min_partition_size is marked non-cudagraphable at scheduler.py:9564-9576, with a log that does not tie the decision back to the region. Since the region opt-in is explicit user intent, this silent override is surprising. Consider whether an explicit region opt-in should bypass the threshold, or at least emit a region-specific log. Needs discussion.

Backward path

  • graph_compile.py:1255-1258 stamping nested_region_config onto new_bw_node.meta["custom"] (in addition to the subgraph module meta) is correct and necessary — _iter_subgraph_cudagraph_patches in compile_fx.py reads the config off the HOP node's meta["custom"], and the backward re-derives the partition decision in compile_fx_backward from gm. No issue; noting it because it is the linchpin that makes the backward _any_subgraph_* calls see the region config.

Recommendation

Needs Discussion — no blocking bug in the tested paths, but the unsafe-unbacked-symint gap is a genuine (if niche) capture-correctness hole with no test, and the min_partition_size interaction warrants an explicit decision. Addressing the two testing items would move this to Approve.

[ghstack-poisoned]
desertfire added a commit that referenced this pull request Jul 16, 2026
…graph partition

Building on nested Inductor configs, a region can set triton.cudagraphs to opt
into or out of cudagraphs independently of the enclosing graph. When a region's
preference differs from the enclosing graph and graph partition is globally off,
compile_fx enables graph partition just for that compile and should_partition
isolates the region: an opted-in region becomes its own cudagraph partition
(captured even when the enclosing graph has cudagraphs off), while an opted-out
region stays inlined (excluded from the enclosing cudagraph). The region body is
codegened without inner partitioning, so it is captured or skipped as a unit; a
region whose body has a non-cudagraphable op falls back to running uncaptured.

Forward and backward are controlled separately: bw_inductor_config_patches (from
the fw/bw config split below) sets triton.cudagraphs for the backward, and
compile_fx_backward re-derives the region-partition decision from the backward
graph since the forward-derived config cannot see the backward regions. The partition detection reads the backward HOP node's config on
node.meta["custom"], which the fw/bw config change below stamps in
run_joint_graph_passes_on_hops.

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

ghstack-source-id: 08a0f2c
Pull-Request: #190091
@desertfire

Copy link
Copy Markdown
Contributor Author

@desertfire has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

[ghstack-poisoned]
desertfire added a commit that referenced this pull request Jul 16, 2026
…graph partition

Building on nested Inductor configs, a region can set triton.cudagraphs to opt
into or out of cudagraphs independently of the enclosing graph. When a region's
preference differs from the enclosing graph and graph partition is globally off,
compile_fx enables graph partition just for that compile and should_partition
isolates the region: an opted-in region becomes its own cudagraph partition
(captured even when the enclosing graph has cudagraphs off), while an opted-out
region stays inlined (excluded from the enclosing cudagraph). The region body is
codegened without inner partitioning, so it is captured or skipped as a unit; a
region whose body has a non-cudagraphable op falls back to running uncaptured.

Forward and backward are controlled separately: bw_inductor_config_patches (from
the fw/bw config split below) sets triton.cudagraphs for the backward, and
compile_fx_backward re-derives the region-partition decision from the backward
graph since the forward-derived config cannot see the backward regions. The partition detection reads the backward HOP node's config on
node.meta["custom"], which the fw/bw config change below stamps in
run_joint_graph_passes_on_hops.

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

ghstack-source-id: e95de42
Pull-Request: #190091
@desertfire

Copy link
Copy Markdown
Contributor Author

@desertfire has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

desertfire added a commit that referenced this pull request Jul 16, 2026
…graph partition

Building on nested Inductor configs, a region can set triton.cudagraphs to opt
into or out of cudagraphs independently of the enclosing graph. When a region's
preference differs from the enclosing graph and graph partition is globally off,
compile_fx enables graph partition just for that compile and should_partition
isolates the region: an opted-in region becomes its own cudagraph partition
(captured even when the enclosing graph has cudagraphs off), while an opted-out
region stays inlined (excluded from the enclosing cudagraph). The region body is
codegened without inner partitioning, so it is captured or skipped as a unit; a
region whose body has a non-cudagraphable op falls back to running uncaptured.

Forward and backward are controlled separately: bw_inductor_config_patches (from
the fw/bw config split below) sets triton.cudagraphs for the backward, and
compile_fx_backward re-derives the region-partition decision from the backward
graph since the forward-derived config cannot see the backward regions. The partition detection reads the backward HOP node's config on
node.meta["custom"], which the fw/bw config change below stamps in
run_joint_graph_passes_on_hops.

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

ghstack-source-id: e95de42
Pull-Request: #190091
@aorenste
aorenste removed their request for review July 30, 2026 23:28
@desertfire

Copy link
Copy Markdown
Contributor Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Rebase failed due to Command git -C /home/runner/work/pytorch/pytorch rebase refs/remotes/origin/viable/strict gh/desertfire/748/orig returned non-zero exit code 1

warning: skipped previously applied commit 8d7b4ed187c
warning: skipped previously applied commit 05558efdf43
hint: use --reapply-cherry-picks to include skipped commits
hint: Disable this message with "git config set advice.skippedCherryPicks false"
Rebasing (1/1)
Auto-merging test/inductor/test_cudagraph_trees.py
CONFLICT (content): Merge conflict in test/inductor/test_cudagraph_trees.py
Auto-merging torch/_inductor/compile_fx.py
Auto-merging torch/_inductor/scheduler.py
CONFLICT (content): Merge conflict in torch/_inductor/scheduler.py
error: could not apply 17b8f4d3ad8... [inductor] Enable per-region cudagraphs for invoke_subgraph via auto graph partition
hint: Resolve all conflicts manually, mark them as resolved with
hint: "git add/rm <conflicted_files>", then run "git rebase --continue".
hint: You can instead skip this commit: run "git rebase --skip".
hint: To abort and get back to the state before "git rebase", run "git rebase --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Could not apply 17b8f4d3ad8... # [inductor] Enable per-region cudagraphs for invoke_subgraph via auto graph partition

Raised by https://github.com/pytorch/pytorch/actions/runs/31534542220

[ghstack-poisoned]
desertfire added a commit that referenced this pull request Aug 13, 2026
…graph partition

Building on nested Inductor configs, a region can set triton.cudagraphs to opt
into or out of cudagraphs independently of the enclosing graph. When a region's
preference differs from the enclosing graph and graph partition is globally off,
compile_fx enables graph partition just for that compile and should_partition
isolates the region: an opted-in region becomes its own cudagraph partition
(captured even when the enclosing graph has cudagraphs off), while an opted-out
region stays inlined (excluded from the enclosing cudagraph). The region body is
codegened without inner partitioning, so it is captured or skipped as a unit; a
region whose body has a non-cudagraphable op falls back to running uncaptured.

Forward and backward are controlled separately: bw_inductor_config_patches (from
the fw/bw config split below) sets triton.cudagraphs for the backward, and
compile_fx_backward re-derives the region-partition decision from the backward
graph since the forward-derived config cannot see the backward regions. The partition detection reads the backward HOP node's config on
node.meta["custom"], which the fw/bw config change below stamps in
run_joint_graph_passes_on_hops.

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

ghstack-source-id: 4c9fa38
Pull-Request: #190091
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review this pr

@claude

claude Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 24m 25s —— View job


PR Review: #190091

One-sentence summary: The isolation mechanism is sound on the cold-compile path the tests exercise, but it makes config.graph_partition transiently true for a single compile — and the AOTAutogradCache warm-start path never re-applies that patch, so a cache hit takes the whole-graph cudagraph path on a partitioned graph; separately, the opt-in early return None in should_partition drops three safety checks the node used to go through.

Full review

Summary

Lets an invoke_subgraph region opt into/out of triton.cudagraphs independently of the enclosing graph, by turning on config.graph_partition for just that compile and having should_partition isolate the region. Verified working on the cold-compile paths the new tests cover. Three problems below: one warm-start correctness hazard, one dropped-safety-check regression, and one overloaded field.

Correctness

1. Warm start (AOTAutogradCache hit) diverges from cold compile — config.graph_partition is not re-patched. compile_fx.py:2978-2982 and 3066-3071 patch graph_partition=True only around inner_compile. On an AOTAutogradCache hit, compile_fx_forward / compile_fx_backward are never called: AOTAutogradCache.try_load builds fx_config (autograd_cache.py:1093) and goes straight to CompiledFxGraph.post_compile. There, output_code.py:922 reads the global config.graph_partition:

if config.graph_partition and policy is None:
    cudagraph_partition_post_compile(...)   # per-partition cudagraphify
else:
    cudagraph_post_compile(...)             # whole-graph cudagraphify

Because this PR is the first thing to compile a partitioned graph while the global flag stays False, a cache hit loads a graph with non-empty partition_maps and cudagraphifies current_callable — the entire call fn — instead of each partition. For an opt-out region that is a correctness bug: the region was excluded precisely because it isn't capture-safe (.cpu() round-trip, cudagraph_unsafe custom op), and on a warm run it gets captured anyway. The cache key does not distinguish the two runs (the key is computed before the patch is applied, from the same forward-derived compiler_config_extra), so the entry is reused. The new tests all run under fresh_cache() (torch/_inductor/test_case.py:46), so this path is entirely untested. Either persist the region-partition decision onto CompiledFxGraph and re-patch during post_compile, or gate on compiled_graph.partition_maps instead of the global config at output_code.py:922. Fix this →

2. Backward-only region opt-in is silently lost on a cache hit. Same root cause, second symptom. With only bw_inductor_config_patches={"triton.cudagraphs": True} (the test_invoke_subgraph_region_cudagraph_backward_optin config), create_compiler_config_extra runs on the dynamo graph, which carries only the forward patches, so compiler_config_extra.cudagraphs stays BoxedBool(False). Cold path: compile_fx.py:3064 bumps it to True from the backward graph. Warm path: bw_fx_config["cudagraphs"] is that same BoxedBool(False) (aot_autograd_result.py:484-487), so output_code.py:894's if cudagraphs: is falsy and the backward is never captured. The backward re-derivation at compile_fx.py:3056-3071 has no cache-hit equivalent. Worth at least a test that runs the backward-optin case twice across a torch._dynamo.reset() with the cache warm, asserting the manager is still non-None.

3. The opt-in return None bypasses three checks the node previously went through. The new region block sits at scheduler.py:9436-9453, above the general per-node checks. When the body is safe it does return None (:9446), skipping:

  • node.is_gpu() (:9474)
  • _uses_cudagraph_unsafe_unbacked_symint(node) (:9480)
  • the dynamic-shape check via get_scheduler_node_symbol_uses(node) (:9485), which unions get_layout_symints over outputs (:4031-4034) — the body check only inspects op.get_free_symbol_uses() per body op (:9399), so dynamic-ness living solely in the region's output layout (size/stride/offset) evades it.

This is a behavior change even when the region agrees with the enclosing graph: with config.graph_partition=True and config.triton.cudagraphs=True, a region that sets triton.cudagraphs: True is not isolated (_any_subgraph_cudagraph_pref_differs is False) yet still hits the new block and returns early, losing checks it passed through before this PR. Consider running the body check and then falling through to the general checks rather than returning, or explicitly document why each skipped check cannot fire on an InvokeSubgraph node.

Code Quality

4. patch_config_for_cudagraphs is overloaded and its name no longer matches its use. Declared as "whether cudagraph_annotation_context should patch config.triton.cudagraphs" (compile_fx.py:2743-2745), but compile_fx.py:3048 uses it as "was the top-level cudagraph decision on?" to pick the backward baseline. Two distinct meanings behind one boolean, in the one place where getting it wrong silently drops cudagraphs for the backward. Split it, or rename to something like top_level_cudagraphs and derive the patch flag from it at the call site.

5. The region-isolation mechanism's dependence on config.triton.cudagraphs staying unpatched is undocumented where it matters. The opt-in-with-top-level-off path deliberately leaves config.triton.cudagraphs alone so that scheduler.py:9458-9462 ("partition includes all ops when cudagraphs is disabled") still fires and inlines everything except the region. That is the actual mechanism achieving isolation, but neither cudagraph_annotation_context's new patch_config param nor scheduler.py:9458 mentions it. One line at the scheduler check would stop a future refactor from silently breaking opt-in.

6. The forward decision is computed from a different graph than it is applied to. enable_region_graph_partition is derived in create_compiler_config_extra from model_ (the pre-AOT dynamo graph, compile_fx.py:3431) but applied around the compile of the post-AOT gm. If AOT inlines the region away (the tests defend against this with inline_single_use_invoke_subgraph=False), graph_partition is enabled for a graph with no region to isolate. Harmless but wasteful; the backward already re-derives from its own gm — worth a comment noting the forward intentionally does not.

Testing

7. Body scan does not recurse into ir.WhileLoop. _invoke_subgraph_body_cudagraph_skip_reason recurses only into nested ir.InvokeSubgraph (scheduler.py:9391). ir.Switch (torch.cond) is handled conservatively — _ir_node_cudagraph_skip_reason returns "Switch ops" for it (:9364) — but ir.WhileLoop (ir.py:11345) holds cond_subgraph/body_subgraph as separate GraphLowerings whose ops never appear in the parent's operations list, and it is in neither check. A torch.while_loop inside an opted-in region whose body has a .cpu() or a cudagraph_unsafe op would be captured. The main should_partition path has the same blind spot on the base branch, so this is not newly introduced, but the body check is a new place where it now matters. Either add ir.WhileLoop to _ir_node_cudagraph_skip_reason or recurse via op.get_subgraphs().

8. Unsafe unbacked symints in a region body remain undetected and untested. Repeating from my earlier pass since it is unaddressed: _get_cudagraph_unsafe_unbacked_symints (scheduler.py:9491) scans only top-level self.nodes, and the body check deliberately omits _uses_cudagraph_unsafe_unbacked_symint (docstring at :9379-9380). An op in config.cudagraph_unsafe_unbacked_ops inside a region body is invisible to both. Gated behind a non-default config, so low severity, but it deserves either handling or a test that pins it as a known limitation.

Recommendation

Request Changes — finding 1 is a warm-start capture-correctness hazard on an untested path, and finding 3 is a silent loss of existing safety checks. Findings 2, 4, 7, 8 should be resolved or explicitly deferred with a comment.

| Branch: `gh/desertfire/748/head`

@desertfire

Copy link
Copy Markdown
Contributor Author

@desertfire has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator.

[ghstack-poisoned]
desertfire added a commit that referenced this pull request Aug 19, 2026
…graph partition

Building on nested Inductor configs, a region can set triton.cudagraphs to opt
into or out of cudagraphs independently of the enclosing graph. When a region's
preference differs from the enclosing graph and graph partition is globally off,
compile_fx enables graph partition just for that compile and should_partition
isolates the region: an opted-in region becomes its own cudagraph partition
(captured even when the enclosing graph has cudagraphs off), while an opted-out
region stays inlined (excluded from the enclosing cudagraph). The region body is
codegened without inner partitioning, so it is captured or skipped as a unit; a
region whose body has a non-cudagraphable op falls back to running uncaptured.

Forward and backward are controlled separately: bw_inductor_config_patches (from
the fw/bw config split below) sets triton.cudagraphs for the backward, and
compile_fx_backward re-derives the region-partition decision from the backward
graph since the forward-derived config cannot see the backward regions. The partition detection reads the backward HOP node's config on
node.meta["custom"], which the fw/bw config change below stamps in
run_joint_graph_passes_on_hops.

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

ghstack-source-id: e85e7ab
Pull-Request: #190091
@desertfire
desertfire removed the request for review from bdhirsh August 19, 2026 18:10
[ghstack-poisoned]
desertfire added a commit that referenced this pull request Aug 19, 2026
…graph partition

Allow an invoke_subgraph region to opt into or out of cudagraph capture
independently of its enclosing graph, with separate forward and backward
configuration. When a region differs from the top-level decision and graph
partitioning is globally disabled, temporarily enable partitioning and isolate
that region as the unit that is captured or skipped.

Cold compilation previously depended on transient global config patches and on
re-deriving backward state from the backward graph. AOTAutograd cache hits bypass
both paths, which could capture an unsafe opt-out region or lose a backward-only
opt-in. Persist each graph's post-compile cudagraph override in CompiledFxGraph,
include the backward annotation decision in the cache configuration, and select
partition post-processing from the serialized partition maps. Persisting the
decision with the compiled artifact avoids reconstructing cold-path global state
during cache loading.

An explicit region opt-in also bypassed general scheduler-node safety checks, and
the region-body scan did not cover nested control-flow subgraphs or unsafe
unbacked SymInts. Apply the scheduler checks to the complete region family,
recurse through IR subgraphs such as WhileLoop, include output-layout symbols,
and share unsafe-unbacked-SymInt analysis between scheduled nodes and region IR.
Compiler state names now distinguish forward-derived, backward-local, top-level,
and graph-local post-compile decisions.

Test Plan:

```bash
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv=["test_cudagraph_trees.py", "-v", "-k", "aot_cache"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv=["test_cudagraph_trees.py", "-v", "-k", "invoke_subgraph"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv=["test_cudagraph_trees.py", "-v", "CudaGraphTreeTests.test_graph_partition_saved_activation_not_static", "CudaGraphTreeTests.test_graph_partition_no_partition_keeps_static"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
spin quicklint
lintrunner -a
```

The nine cache and scheduler regression instances failed on the original pre-fix
commit. The WhileLoop and unsafe-unbacked-SymInt tests also failed before their
corresponding fixes.

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

ghstack-source-id: 4f12977
Pull-Request: #190091
desertfire added a commit that referenced this pull request Aug 19, 2026
…graph partition

Allow an invoke_subgraph region to opt into or out of cudagraph capture
independently of its enclosing graph, with separate forward and backward
configuration. When a region differs from the top-level decision and graph
partitioning is globally disabled, temporarily enable partitioning and isolate
that region as the unit that is captured or skipped.

Cold compilation previously depended on transient global config patches and on
re-deriving backward state from the backward graph. AOTAutograd cache hits bypass
both paths, which could capture an unsafe opt-out region or lose a backward-only
opt-in. Persist each graph's post-compile cudagraph override in CompiledFxGraph,
include the backward annotation decision in the cache configuration, and select
partition post-processing from the serialized partition maps. Persisting the
decision with the compiled artifact avoids reconstructing cold-path global state
during cache loading.

An explicit region opt-in also bypassed general scheduler-node safety checks, and
the region-body scan did not cover nested control-flow subgraphs or unsafe
unbacked SymInts. Apply the scheduler checks to the complete region family,
recurse through IR subgraphs such as WhileLoop, include output-layout symbols,
and share unsafe-unbacked-SymInt analysis between scheduled nodes and region IR.
Compiler state names now distinguish forward-derived, backward-local, top-level,
and graph-local post-compile decisions.

Test Plan:

```bash
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv=["test_cudagraph_trees.py", "-v", "-k", "aot_cache"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv=["test_cudagraph_trees.py", "-v", "-k", "invoke_subgraph"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv=["test_cudagraph_trees.py", "-v", "CudaGraphTreeTests.test_graph_partition_saved_activation_not_static", "CudaGraphTreeTests.test_graph_partition_no_partition_keeps_static"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
spin quicklint
lintrunner -a
```

The nine cache and scheduler regression instances failed on the original pre-fix
commit. The WhileLoop and unsafe-unbacked-SymInt tests also failed before their
corresponding fixes.

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

ghstack-source-id: 4f12977
Pull-Request: #190091
@desertfire

Copy link
Copy Markdown
Contributor Author

@claude review this pr again

@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Claude finished @desertfire's task in 36m 34s —— View job


PR Review: #190091 (re-review)

One-sentence summary: The cache-persistence rework correctly closes the warm-start hole from my last pass and the dropped-safety-check regression is fixed, but the opt-in mode's deliberate choice to leave global config.triton.cudagraphs off means two other code paths still read that global and silently defeat the opt-in — most seriously, a single CPU op anywhere in the enclosing graph disables cudagraphs for the whole graph, including the region that asked for them.

Full review

Status of prior findings

Verified fixed: (1) warm-start config.graph_partition divergence — output_code.py:857 and :935 now gate on self.partition_maps is not None, which is serialized with CompiledFxGraph, and cudagraphs_post_compile_override persists the graph-local decision through fx_kwargs; (2) backward-only opt-in lost on cache hit — same mechanism plus backward_cudagraphs_annotation_override in create_fx_config; (3) dropped safety checks — _invoke_subgraph_family_cudagraph_skip_reason now runs the full scheduler-node checks over the region and its MultiOutputs, and _subgraph_cudagraph_skip_reason unions get_layout_symints; (4) patch_config_for_cudagraphs split into top_level_cudagraphs + forward_cudagraphs_post_compile_override; (5)/(6) comments added at scheduler.py:9534-9537 and compile_fx.py:3479-3482; (7) ir.WhileLoop covered via op.get_subgraphs() recursion; (8) unbacked symints handled by _get_cudagraph_unsafe_unbacked_symints_from_ir_nodes. New findings below.

Correctness

1. A CPU op in the enclosing graph silently disables the opted-in region's cudagraph. The opt-in mode deliberately leaves global config.triton.cudagraphs == False (_cudagraph_config_patch_context, compile_fx.py:2728-2742) while patching graph_partition=True and passing a cudagraphs BoxedBool of True. But is_using_cudagraph_partition() (utils.py:4268-4272) reads the global, so it returns False in exactly this mode:

return (torch._inductor.config.triton.cudagraphs
        or _unstable_customized_partition_wrapper.wrapper is not None
       ) and torch._inductor.config.graph_partition

Meanwhile the guard at compile_fx.py:2061 (if cudagraphs and not V.graph.disable_cudagraphs_reason) reads the BoxedBool, which is True — so check_lowering_disable_cudagraph does run, and check_multiple_devices_or_any_cpu_nodes (cudagraph_utils.py:343-359) skips its device_node_mapping.pop(torch.device("cpu")) line because is_using_cudagraph_partition() is False. Any CPU node in the enclosing graph therefore sets V.graph.disable_cudagraphs_reason, and post_compile (output_code.py:911-918) then calls BoxedBool.disable(graph_cudagraphs) for the whole graph. The user asked for the region to be captured; partitioning was already enabled and could have isolated the CPU op; and nothing is captured. This is the whole point of the feature failing on an ordinary graph shape, and there is no test with a CPU op outside the region. Either make is_using_cudagraph_partition() consult the runtime decision, or pass the effective decision through to check_lowering_disable_cudagraph. Fix this →

2. bw_inductor_config_patches is absent from the cache key, and this PR makes that load-bearing. _collect_nested_region_inductor_config_patches (codecache.py:1308-1329) reads only inductor_config_patches; it never reads bw_inductor_config_patches, which remains a separate field on NestedCompileRegionOptions (invoke_subgraph.py:89) until get_backward_nested_region_config (:114-133) materializes it onto a replaced copy — after the AOTAutograd key is computed from the pre-AOT graph (autograd_cache.py:947-959). So two compiles differing only in bw_inductor_config_patches={"triton.cudagraphs": True} vs False share a key and serve each other's artifacts. Before this PR that field could not change cudagraph capture, so the omission was benign; test_invoke_subgraph_region_cudagraph_backward_optin is precisely the case that now depends on it. The new test_cudagraph_backward_override_affects_aot_cache_key covers the override_cudagraphs(bwd=...) annotation path only, not this one. Fix this →

Testing

3. The unsafe-body hole remains open for regions that do not set the flag. The new body scan is gated on "triton.cudagraphs" in patches (scheduler.py:9514). A plain @torch.compiler.nested_compile_region with no options has inductor_config_patches is None, so under the already-supported graph_partition=True, triton.cudagraphs=True combination its body is still never scanned: the parent's self.nodes holds only the InvokeSubgraph/MultiOutput nodes; add_device_info (graph.py:1047-1052) writes to self.device_node_mapping, and the body is lowered under V.set_graph_handler(subgraph.graph) (ir.py:11023-11024), so body devices never reach the parent's mapping; and get_first_incompatible_cudagraph_node is skipped by not config.graph_partition (compile_fx.py:2028-2035) — and does not recurse into subgraphs anyway. A .cpu() round-trip or a cudagraph_unsafe-tagged op inside an unannotated region is captured. That predates this PR, but the PR builds exactly the machinery to detect it and then declines to apply it in the default case. Running the body scan for every InvokeSubgraph regardless of patches would close it; at minimum add a test pinning the current behavior as a known limitation.

4. The new scheduler unit tests bypass IR constructors, so they cannot catch real breakage. test_invoke_subgraph_region_cudagraph_optin_runs_scheduler_checks, test_invoke_subgraph_nested_dynamic_output_layout_skips, test_invoke_subgraph_while_loop_unsafe_body_skips, and test_invoke_subgraph_unsafe_unbacked_symint_body_skips all build IR via object.__new__(ir.InvokeSubgraph) / object.__new__(ir.WhileLoop) plus hand-set attributes and mock.Mock(operations=..., device_types=...) graphs, and three of them mock out _ir_node_cudagraph_skip_reason — the very function under test in the WhileLoop case. They assert that the recursion visits mocks, not that a real torch.while_loop or a real dynamic output layout is excluded. The while_loop and dynamic-output-layout cases in particular should be reachable end-to-end (compile a region containing torch.while_loop with an unsafe body and assert no partition_0 is emitted, in the style of the neighbouring test_invoke_subgraph_region_cudagraph_nested_unsafe_body_skips). Keep the structural tests if you like, but they should not be the only coverage for these paths.

5. _subgraph_cudagraph_skip_reason's non-GPU check is near-tautological. At scheduler.py:9407-9409 it iterates the subgraph's graph.device_types. SubgraphLowering starts with its own empty set (graph.py:465) which its own run() populates (:1048), and codegen_subgraph later rebinds it to the parent's set (:3027) — so at should_partition time it holds only devices the body itself touched. That is the right set, but note it makes the check redundant with the ir.DeviceCopy check for the common .cpu() case, and it will not fire for a body op that is CPU-only without a device copy in the body. Worth a comment stating which set is being read and when, since the :3027 rebind makes this easy to misread.

Performance

6. Partition reordering is silently disabled in the new opt-in mode. scheduler.py:4481-4490 gates maybe_reorder_for_minimizing_partition / reorder_for_partition_with_simple_dependency on config.graph_partition and config.triton.cudagraphs. In opt-in mode the first is patched True but the second is deliberately left False, so a graph that is being partitioned never gets the reordering pass that exists to reduce partition count. Not a correctness issue, but it means the opt-in path takes a systematically worse partition layout than the equivalent graph_partition=True compile. Same root cause as finding 1: the global is used as a proxy for "are we partitioning for cudagraphs".

7. Third lookup in _invoke_subgraph_family_cudagraph_skip_reason looks unreachable. scheduler.py:9464-9472 linearly scans self.name_to_node.values() for candidate.node is ir_node. Both InvokeSubgraph (ir.py:10938) and MultiOutput are registered buffers and operations, so name_to_buf[ir_node.get_name()] → name_to_node[buffer.defining_op_name()] should always resolve. should_partition is called once per node in each of four passes (:9546, :9935, :10037, :10059), so if the fallback is reachable it is an O(n) scan inside an O(n) loop. Either drop it or replace it with an assertion that the first two lookups succeeded.

Code Quality

8. getattr(region.subgraph, "inductor_config_patches", None) at scheduler.py:9513 — ir.Subgraph declares this as a dataclass field with a None default (ir.py:10906), so the getattr default is dead defensiveness. Use region.subgraph.inductor_config_patches.

9. cudagraph_min_partition_size can still silently override an explicit opt-in (scheduler.py:10074-10086), with a log that does not mention the region. Default is 0 so it is off unless configured, and I raised this last time without resolution — worth a one-line decision either way, since an explicit region opt-in is stronger user intent than a global heuristic threshold.

Recommendation

Request Changes — finding 1 defeats the feature on any enclosing graph containing a CPU op and is untested; finding 2 is a cache-collision that this PR newly makes load-bearing. Findings 3 and 4 are testing gaps worth closing before landing; 5-9 can be addressed or explicitly deferred with a comment.

| Branch: `gh/desertfire/748/head`

[ghstack-poisoned]
desertfire added a commit that referenced this pull request Aug 24, 2026
…graph partition

Allow invoke_subgraph regions to opt into or out of CUDA Graph capture
independently of their enclosing graph, including separate forward and backward
configuration. When a region differs from the top-level decision and graph
partitioning is disabled, temporarily enable a region-only partitioning mode.
Only explicitly opted-in regions become capture partitions; the enclosing graph
and opted-out regions remain inline.

Derive the regional decision before AOT dispatch, preserve it through freezing,
and re-derive backward settings from the backward graph. Region identity keeps
adjacent eligible regions as separate runtime units, while regional capture
continues to respect global profitability settings unless the region overrides
them locally.

Nested regions cannot currently be partitioned independently from their
enclosing region, so reject conflicting nested CUDA Graph settings, including
regions reached through other higher-order-op subgraphs. Also reject combining
regional CUDA Graph settings with torch._dynamo.override_cudagraphs instead of
silently applying two competing override mechanisms.

Record partial forward capture and conservatively treat saved activations from
inline work as dynamic backward inputs. Resolve the CUDA Graph manager lazily at
backward execution so backward-only capture, runtime capture-size filtering, and
AOTAutograd cache hits do not require a manager that the forward has not created.

Test Plan:

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "invoke_subgraph", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "region_backward_saved_activation_is_dynamic", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
lintrunner -a
```

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

ghstack-source-id: dc8ad4d
Pull-Request: #190091
[ghstack-poisoned]
desertfire added a commit that referenced this pull request Aug 25, 2026
…graph partition

Allow invoke_subgraph regions to opt into or out of CUDA Graph capture
independently of their enclosing graph, including separate forward and backward
configuration. When a region differs from the top-level decision and graph
partitioning is disabled, temporarily enable a region-only partitioning mode.
Only explicitly opted-in regions become capture partitions; the enclosing graph
and opted-out regions remain inline.

Derive the regional decision before AOT dispatch, preserve it through freezing,
and re-derive backward settings from the backward graph. Region identity keeps
adjacent eligible regions as separate runtime units, while regional capture
continues to respect global profitability settings unless the region overrides
them locally.

Nested regions cannot currently be partitioned independently from their
enclosing region, so reject conflicting nested CUDA Graph settings, including
regions reached through other higher-order-op subgraphs. Also reject combining
regional CUDA Graph settings with torch._dynamo.override_cudagraphs instead of
silently applying two competing override mechanisms.

Record partial forward capture and conservatively treat saved activations from
inline work as dynamic backward inputs. Resolve the CUDA Graph manager lazily at
backward execution so backward-only capture, runtime capture-size filtering, and
AOTAutograd cache hits do not require a manager that the forward has not created.

Test Plan:

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "invoke_subgraph", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "region_backward_saved_activation_is_dynamic", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
lintrunner -a
```

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

ghstack-source-id: 6298238
Pull-Request: #190091
desertfire added a commit that referenced this pull request Aug 25, 2026
…graph partition

Allow invoke_subgraph regions to opt into or out of CUDA Graph capture
independently of their enclosing graph, including separate forward and backward
configuration. When a region differs from the top-level decision and graph
partitioning is disabled, temporarily enable a region-only partitioning mode.
Only explicitly opted-in regions become capture partitions; the enclosing graph
and opted-out regions remain inline.

Derive the regional decision before AOT dispatch, preserve it through freezing,
and re-derive backward settings from the backward graph. Region identity keeps
adjacent eligible regions as separate runtime units, while regional capture
continues to respect global profitability settings unless the region overrides
them locally.

Nested regions cannot currently be partitioned independently from their
enclosing region, so reject conflicting nested CUDA Graph settings, including
regions reached through other higher-order-op subgraphs. Also reject combining
regional CUDA Graph settings with torch._dynamo.override_cudagraphs instead of
silently applying two competing override mechanisms.

Record partial forward capture and conservatively treat saved activations from
inline work as dynamic backward inputs. Resolve the CUDA Graph manager lazily at
backward execution so backward-only capture, runtime capture-size filtering, and
AOTAutograd cache hits do not require a manager that the forward has not created.

Test Plan:

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "invoke_subgraph", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "region_backward_saved_activation_is_dynamic", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
lintrunner -a
```

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

ghstack-source-id: 6298238
Pull-Request: #190091
[ghstack-poisoned]
desertfire added a commit that referenced this pull request Aug 26, 2026
…graph partition

Nested compile-region CUDA Graph options were visible while compiling an
InvokeSubgraph body but did not control how the enclosing Inductor graph was
partitioned or wrapped. A region therefore could not opt into capture when the
top level was disabled, opt out when it was enabled, or select a different
forward and backward policy.

Derive the top-level and regional decisions before AOT dispatch. When a region
differs and graph partitioning is disabled, temporarily enable a region-only
mode that keeps enclosing work inline and isolates only explicitly enabled
regions. Preserve the decision through freezing, re-derive it from the backward
graph, and retain regional safety and minimum-size checks from the partitioner.
Configured regions remain separate runtime units.

Generalize the backward-only disable flag to a graph-local
cudagraphs_post_compile_override because regional forward and backward graphs
may each force capture on or off. Serialize the effective value with each FX
graph, while adding optional override and region-only fields to cache inputs only
when active so ordinary cache keys remain stable.

Reject conflicting nested-region settings and combinations with
`torch._dynamo.override_cudagraphs`. For partial forward capture, conservatively
treat saved inline activations as dynamic backward inputs. Resolve the CUDA
Graph manager lazily so backward-only capture, runtime capture-size filtering,
and AOTAutograd cache hits work even when the forward created no manager.

Test Plan:

```
python test/dynamo/test_aot_autograd_cache.py -k optional_cudagraph_kwargs_omitted_when_unset -v
```

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "invoke_subgraph", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "region_backward", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
lintrunner -a
```

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

ghstack-source-id: 6a95c10
Pull-Request: #190091
[ghstack-poisoned]
desertfire added a commit that referenced this pull request Aug 27, 2026
…graph partition

Nested compile-region CUDA Graph options were visible while compiling an
InvokeSubgraph body but did not control how the enclosing Inductor graph was
partitioned or wrapped. A region therefore could not opt into capture when the
top level was disabled, opt out when it was enabled, or select a different
forward and backward policy.

Derive the top-level and regional decisions before AOT dispatch. When a region
differs and graph partitioning is disabled, temporarily enable a region-only
mode that keeps enclosing work inline and isolates only explicitly enabled
regions. Preserve the decision through freezing, re-derive it from the backward
graph, and retain regional safety and minimum-size checks from the partitioner.
Configured regions remain separate runtime units.

Use a graph-local cudagraphs_post_compile_override for serialized FX graph state
because regional forward and backward graphs may each force capture on or off.
Keep the existing cudagraphs_bwd_override for the pre-AOT backward annotation.
Add optional override and region-only fields to cache inputs only when active so
ordinary cache keys remain stable.

Reject conflicting nested-region settings and combinations with
`torch._dynamo.override_cudagraphs`. For partial forward capture, conservatively
treat saved inline activations as dynamic backward inputs. Resolve the CUDA
Graph manager lazily so backward-only capture, runtime capture-size filtering,
and AOTAutograd cache hits work even when the forward created no manager.

Test Plan:

```
python test/dynamo/test_aot_autograd_cache.py -k optional_cudagraph_kwargs_omitted_when_unset -v
```

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "invoke_subgraph", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
python -c 'import runpy, sys, torch; torch.backends.cudnn.enabled = False; sys.argv = ["test/inductor/test_cudagraph_trees.py", "-k", "region_backward", "-v"]; runpy.run_path("test/inductor/test_cudagraph_trees.py", run_name="__main__")'
```

```
lintrunner -a
```

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

ghstack-source-id: 08d2b05
Pull-Request: #190091
@desertfire
desertfire marked this pull request as draft August 27, 2026 00:24
@desertfire desertfire closed this Aug 27, 2026
@github-actions
github-actions Bot deleted the gh/desertfire/748/head branch November 10, 2026 01:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants