Skip to content

Skip cudagraphs for kernel-free inductor graphs - #185760

Closed
jansel wants to merge 4 commits into
gh/jansel/1204/basefrom
gh/jansel/1204/head
Closed

jansel wants to merge 4 commits into
gh/jansel/1204/basefrom
gh/jansel/1204/head

Conversation

@jansel

@jansel jansel commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Inductor can lower a CUDA graph that only contains metadata/view work, such as a reshape that remains a view. The non-partition cudagraph path still wrapped that compiled callable, so the first execution attempted to capture a CUDA graph with no kernel launches and emitted the empty CUDA Graph warning.

Fix this by checking the lowered scheduler after codegen and marking cudagraphs disabled when there are no scheduler nodes other than NopKernelSchedulerNode. This uses Inductor's actual lowered work instead of guessing from FX ops, so reshape can still cudagraph when it really lowers to compute, while pure view graphs skip capture cleanly.

I considered suppressing the CUDA warning or deciding from the FX graph, but warning suppression could hide real capture problems and FX-level checks do not know whether reshape becomes a view or a clone. The scheduler check is the narrow point where the kernel/no-kernel distinction is available.

Benchmark Results:

Simulated previous behavior by monkeypatching the new no-kernel check to return True for a CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False. Median first 3 calls: before 0.052442s, after 0.045516s. Median steady 5000 calls: before 0.242688s, after 0.091426s. Before counters: {'cudagraph_recorded_non_static_inputs': 1}; after counters: {'cudagraph_skips': 1}.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_skips_cudagraphs

lintrunner -a

Manual repro: CUDA reshape-only graph emitted 0 empty CUDA Graph warnings and counters {'cudagraph_skips': 1}.

Manual sanity: CUDA x + 1 graph still recorded cudagraphs with counters {'cudagraph_recorded_non_static_inputs': 1}.

Fixes #149653

Generated by my agent

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 31, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (5 Unrelated Failures)

As of commit c041a2c with merge base 757703a (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

BROKEN TRUNK - The following jobs 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.

@jansel

jansel commented May 31, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 31, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 43s —— View job


Code Review: Skip cudagraphs for kernel-free inductor graphs

  • Gather context and read changed files
  • Analyze implementation correctness
  • Check test coverage
  • Post review feedback

Overall: This looks good. The approach is well-motivated — checking at the scheduler level after codegen is the right narrow point where the kernel/no-kernel distinction is known. The implementation is minimal and correctly placed.

Implementation (torch/_inductor/compile_fx.py)

The new _graph_has_kernel_invocations helper at line 762 is clean and correct. any() on an empty graph.scheduler.nodes returns False, so a truly empty graph also skips cudagraphs — which is the desired behavior.

The placement of the new check at line 1752 is correct:

  • It runs after graph.compile_to_module() (line 1615), which calls codegen() → _update_scheduler(), so graph.scheduler.nodes is populated.
  • It runs after check_lowering_disable_cudagraph (line 1739-1750), so it doesn't interfere with that existing path.
  • The guard not V.graph.disable_cudagraphs_reason avoids overwriting an earlier, more specific disable reason.

One minor observation: this check doesn't gate on config.graph_partition unlike the two earlier checks (lines 1683, 1712). That seems intentional and correct — even when graph_partition splits things up, a partition with no kernel work should still skip capture for that partition.

Test (test/inductor/test_cudagraph_trees.py)

The test is well-structured:

  • Uses graph_partition=False to test the non-partition path specifically.
  • Verifies the reshape stays a view (no actual kernel), so no CUDA graph is captured.
  • Asserts no "CUDA Graph is empty" warning, the cudagraph_skips counter is 1, cudagraph_recorded_non_static_inputs is 0, and the manager is None.
  • Uses fullgraph=True to avoid partial compilation ambiguity.

Potential edge cases considered

  1. FusedSchedulerNode: If nodes get fused, do they wrap NopKernelSchedulerNode? Checked — FusedSchedulerNode contains snodes but is itself a BaseSchedulerNode, not a NopKernelSchedulerNode. The fusion logic already excludes nop nodes from fusion with real compute (line 7289), so a graph that is all nop nodes shouldn't produce a fused node containing hidden kernel work.

  2. ExternKernelSchedulerNode: External kernels (e.g., cuBLAS calls) are a separate class that isn't NopKernelSchedulerNode, so they would correctly prevent the skip.

  3. Empty scheduler nodes list: any() returns False → graph reports no kernel invocations → cudagraphs skipped. Correct.

No issues found. LGTM.


@jansel
jansel marked this pull request as ready for review June 2, 2026 06:09
@jansel
jansel requested a review from eellison June 2, 2026 06:09
@jansel jansel added the topic: not user facing topic category label Jun 2, 2026

@eellison eellison left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason this wouldnt' be covered by the min_partition size = 1?

@jansel

jansel commented Jun 4, 2026

Copy link
Copy Markdown
Contributor Author

My agent says the min-partition-size check only runs inside the graph partitioning path (Scheduler.graph_partition). This PR is covering the whole-graph cudagraph path when config.graph_partition=False, where the generated callable can still go through cudagraph_post_compile and capture an empty graph. The added test pins that non-partition path explicitly, so this check is still needed rather than relying on partition min size.

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 5, 2026
Inductor can lower a CUDA graph that only contains metadata/view work, such as a reshape that remains a view. The non-partition cudagraph path still wrapped that compiled callable, so the first execution attempted to capture a CUDA graph with no kernel launches and emitted the empty CUDA Graph warning.

Fix this by checking the lowered scheduler after codegen and marking cudagraphs disabled when there are no scheduler nodes other than NopKernelSchedulerNode. This uses Inductor's actual lowered work instead of guessing from FX ops, so reshape can still cudagraph when it really lowers to compute, while pure view graphs skip capture cleanly.

I considered suppressing the CUDA warning or deciding from the FX graph, but warning suppression could hide real capture problems and FX-level checks do not know whether reshape becomes a view or a clone. The scheduler check is the narrow point where the kernel/no-kernel distinction is available.

Benchmark Results:

Simulated previous behavior by monkeypatching the new no-kernel check to return True for a CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False. Median first 3 calls: before 0.052442s, after 0.045516s. Median steady 5000 calls: before 0.242688s, after 0.091426s. Before counters: {'cudagraph_recorded_non_static_inputs': 1}; after counters: {'cudagraph_skips': 1}.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_skips_cudagraphs

lintrunner -a

Manual repro: CUDA reshape-only graph emitted 0 empty CUDA Graph warnings and counters {'cudagraph_skips': 1}.

Manual sanity: CUDA x + 1 graph still recorded cudagraphs with counters {'cudagraph_recorded_non_static_inputs': 1}.

Fixes #149653

Generated by my agent


ghstack-source-id: fbcb12c
Pull-Request: #185760

@eellison eellison left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, although, can we please unify the num kernel logic ? reuse the existing code ?

@jansel

jansel commented Jun 5, 2026

Copy link
Copy Markdown
Contributor Author

Agent, address that comment above.

[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 7, 2026
Inductor can lower a CUDA graph that only contains metadata/view work, such as a reshape that remains a view. The non-partition cudagraph path still wrapped that compiled callable, so the first execution attempted to capture a CUDA graph with no kernel launches and emitted the empty CUDA Graph warning.

Fix this by checking the lowered scheduler after codegen and marking cudagraphs disabled when the scheduler reports zero kernel nodes. The kernel-node count is shared with the graph-partition min-size logic, so both paths use the same definition of real scheduler kernel work while excluding NopKernelSchedulerNode. This uses Inductor's actual lowered work instead of guessing from FX ops, so reshape can still cudagraph when it really lowers to compute, while pure view graphs skip capture cleanly.

I considered suppressing the CUDA warning or deciding from the FX graph, but warning suppression could hide real capture problems and FX-level checks do not know whether reshape becomes a view or a clone. The scheduler check is the narrow point where the kernel/no-kernel distinction is available.

Benchmark Results:

Simulated previous behavior by monkeypatching the new no-kernel check to return True for a CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False. Median first 3 calls: before 0.052442s, after 0.045516s. Median steady 5000 calls: before 0.242688s, after 0.091426s. Before counters: {'cudagraph_recorded_non_static_inputs': 1}; after counters: {'cudagraph_skips': 1}.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_skips_cudagraphs

python test/inductor/test_cudagraph_trees.py -k test_cudagraph_min_partition_size_skip_small

python test/inductor/test_cudagraph_trees.py -k test_cudagraph_min_partition_size_allow_large

lintrunner -a

Manual repro: CUDA reshape-only graph emitted 0 empty CUDA Graph warnings and counters {'cudagraph_skips': 1}.

Manual sanity: CUDA x + 1 graph still recorded cudagraphs with counters {'cudagraph_recorded_non_static_inputs': 1}.

Fixes #149653

Generated by my agent

ghstack-source-id: b78ffd1
Pull-Request: #185760
@jansel

jansel commented Jun 7, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I addressed the kernel-count unification feedback by moving the NopKernelSchedulerNode-excluding count into Scheduler.count_kernel_nodes and reusing it from both the whole-graph cudagraph skip and the graph-partition min-size check.

@jansel

jansel commented Jun 8, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Jun 8, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m2-15)

Details for Dev Infra team Raised by workflow job

@jansel

jansel commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@claude are those CI failures related to this PR?

@claude

claude Bot commented Jun 9, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 4m 22s —— View job


CI Failure Analysis

No, none of the CI failures are related to this PR.

This PR only touches three files, all in the Inductor cudagraph/scheduler path:

  • test/inductor/test_cudagraph_trees.py
  • torch/_inductor/compile_fx.py
  • torch/_inductor/scheduler.py

The reported failures are in unrelated areas:

Failure Why it's unrelated
NEW: trunk / macos-py3-arm64 / test (mps) — test_group_norm_backward_large_input_float16_trigger_32bit_overflow_True_mps_float16 An MPS (Apple Metal) group_norm backward numerics test. Nothing in this PR touches MPS, group_norm, or the backward path. This is a flaky/known-failing MPS test, not something this Inductor cudagraph change could affect.
BROKEN TRUNK: linux-jammy-aarch64-py3.10 — test_aot_inductor_arrayref.py::...test_quanatized_int8_linear_cpu_with_stack_allocation (x2) Dr. CI marks these as broken trunk — they also fail on the merge base 96a92ea, so they pre-date this PR. AOTI CPU ArrayRef path, unrelated to cudagraphs.
BROKEN TRUNK: torchtitan-test / ...feature_tests Also a broken trunk failure present on the merge base.

The three "broken trunk" failures are explicitly flagged by Dr. CI as failing on the merge base (rebasing onto viable/strict would clear them). The one "new" failure is an MPS test that has no code path in common with this change — it's flaky.

Recommendation: Rebase onto viable/strict to clear the broken-trunk failures, and the MPS failure can be handled with a force-merge (or merge ignoring the unrelated failure) once you confirm it's flaky on HUD.

@jansel

jansel commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchmergebot pytorchmergebot added the ci-no-td Do not run TD on this PR label Jun 11, 2026
@jansel

jansel commented Jun 12, 2026

Copy link
Copy Markdown
Contributor Author

Agent address the following and respond with a confidence level on how safe to reland this is.

--

Revert Analysis: "Skip cudagraphs for kernel-free inductor graphs" (PR #185760 / D108074417)

Summary

PR #185760 was imported as D108074417 and subsequently reverted (commit 82a2694abd) due to a test failure in test_aliasing_static_ref within the cudagraph_trees_expandable_segments test suite.

The Change

The PR added a post-codegen scheduler check in torch/_inductor/compile_fx.py to disable cudagraphs when the lowered scheduler contains only NopKernelSchedulerNode nodes (i.e., the graph has no actual CUDA kernel invocations — only metadata/view operations like reshape or slice).

The intent was to avoid capturing an empty CUDA graph (which triggers a "CUDA Graph is empty" warning) for graphs that only contain view operations.

Key code added (in compile_fx.py, after check_lowering_disable_cudagraph):

if (
    cudagraphs
    and not V.graph.disable_cudagraphs_reason
    and not config.graph_partition
    and not _graph_has_kernel_invocations(graph)
):
    V.graph.disable_cudagraphs_reason = "skipping cudagraphs for kernel-free graph"
    counters["inductor"]["cudagraph_skips"] += 1

Where _graph_has_kernel_invocations returns True only if the scheduler has at least one node that is NOT a NopKernelSchedulerNode.

Failing Test

Test: CudaGraphTreeTests::test_aliasing_static_ref (in test/inductor/test_cudagraph_trees.py)

Error: The test expects both compiled functions to participate in the cudagraph tree, but the kernel-free function is incorrectly excluded, breaking cudagraph tree assertions.

Root Cause

The test does the following:

class Mod(torch.nn.Linear):
    def forward(self, x):
        return self.weight.T @ x, self.weight.T, self.weight[0:4]

m = Mod(10, 10).cuda()

@torch.compile(mode="reduce-overhead")
def foo(mod, x):
    return mod(x)  # has matmul kernel + view ops

@torch.compile(mode="reduce-overhead")
def foo2(x):
    return x[2:]  # ONLY a slice/view operation — NO kernel

for _ in range(3):
    torch.compiler.cudagraph_mark_step_begin()
    out1, alias_1, alias_2 = foo(m, x)
    out2 = foo2(out1)  # <-- this graph is kernel-free
    out2.sum().backward()

# Asserts about cudagraph tree structure:
node = self.curr_node()
first_node = next(node._path_from_root)
self.assertFalse(first_node.unaliased_in_all_paths[0])

What goes wrong:

  1. foo2(x) compiles a graph that does only x[2:] — a pure slice/view with no CUDA kernel.
  2. With the PR, this graph is classified as "kernel-free" → disable_cudagraphs_reason is set.
  3. foo2 is therefore not wrapped in the cudagraph tree — it runs as a plain compiled function.
  4. But foo2 is called in sequence with foo after cudagraph_mark_step_begin(). The cudagraph tree expects both functions to participate so it can properly track:
  • Memory aliasing between out1 and out2 (they share storage since out2 = out1[2:])
  • Output lifetime management across the tree
  • The tree structure assertions (curr_node(), _path_from_root, unaliased_in_all_paths)
  1. Since foo2 doesn't enter the tree, the tree structure is incomplete and the assertions fail.

Key config context: In fbcode, graph_partition defaults to False (unlike OSS where it's True). The PR's check specifically targets not config.graph_partition, so this failure only manifests in the internal CI.

Suggested Fix

The fix should not completely disable cudagraphs for kernel-free graphs. Instead, it should handle the "empty CUDA graph" case within the cudagraph tree mechanism itself. There are several approaches:

Option A: Skip only the CUDA graph recording but still participate in the tree (Recommended)

Instead of setting disable_cudagraphs_reason (which removes the function from the tree entirely), add a flag that tells the cudagraph tree wrapper to skip the cudaStreamBeginCapture/cudaStreamEndCapture step but still track the function as a node in the tree.

# In compile_fx.py, instead of disabling cudagraphs entirely:
if (
    cudagraphs
    and not V.graph.disable_cudagraphs_reason
    and not config.graph_partition
    and not _graph_has_kernel_invocations(graph)
):
    # Mark as kernel-free but DON'T disable cudagraphs tree participation
    V.graph.kernel_free_cudagraph = True
    counters["inductor"]["cudagraph_skips"] += 1

Then in the cudagraph tree's recording logic, check kernel_free_cudagraph and skip the actual CUDA graph capture while still maintaining the tree node for memory/aliasing tracking.

Option B: Only skip for standalone graphs (not in a tree sequence)

Only apply the skip when the function is known to be standalone (no other cudagraph functions before/after it in the same step):

if (
    cudagraphs
    and not V.graph.disable_cudagraphs_reason
    and not config.graph_partition
    and not _graph_has_kernel_invocations(graph)
    # Only skip if this is a standalone graph, not part of a tree sequence
    and not V.graph.has_cudagraph_tree_inputs  # needs new tracking
):
    V.graph.disable_cudagraphs_reason = "skipping cudagraphs for kernel-free graph"

However, this is harder to implement since tree membership isn't known at compile time.

Option C: Suppress the warning instead of disabling cudagraphs

The simplest fix — suppress the "CUDA Graph is empty" warning for intentionally kernel-free graphs rather than disabling cudagraphs entirely:

if (
    cudagraphs
    and not V.graph.disable_cudagraphs_reason
    and not config.graph_partition
    and not _graph_has_kernel_invocations(graph)
):
    # Flag to suppress the empty-graph warning but still use cudagraph tree
    V.graph.suppress_empty_cudagraph_warning = True
    counters["inductor"]["cudagraph_skips"] += 1

This is the least invasive but doesn't save the (minor) overhead of recording an empty graph.

Option D: Move the check to runtime in the cudagraph tree

Check at runtime (during cudagraph tree execution) whether the function is standalone vs. part of a sequence. If standalone and kernel-free, skip recording. If part of a sequence, still participate in the tree.

Additional Context

  • The PR's new test (test_view_only_cuda_graph_skips_cudagraphs) specifically uses @config.patch("graph_partition", False) and tests a standalone view-only function — that case works fine.
  • The bug is specifically about sequenced compiled functions where a kernel-free function follows a kernel-having function within the same cudagraph_mark_step_begin() step.
  • The SRR (Signal Relevance Review) correctly identified this as a real regression: "Good Quality test + low systemic rate + direct topology overlap".

References

jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
Inductor can lower a CUDA graph that only contains metadata/view work, such as a reshape that remains a view. The non-partition cudagraph path still wrapped that compiled callable, so the first execution attempted to capture a CUDA graph with no kernel launches and emitted the empty CUDA Graph warning.

Fix this by checking the lowered scheduler after codegen and marking cudagraphs disabled when there are no scheduler nodes other than NopKernelSchedulerNode. This uses Inductor's actual lowered work instead of guessing from FX ops, so reshape can still cudagraph when it really lowers to compute, while pure view graphs skip capture cleanly.

I considered suppressing the CUDA warning or deciding from the FX graph, but warning suppression could hide real capture problems and FX-level checks do not know whether reshape becomes a view or a clone. The scheduler check is the narrow point where the kernel/no-kernel distinction is available.

Benchmark Results:

Simulated previous behavior by monkeypatching the new no-kernel check to return True for a CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False. Median first 3 calls: before 0.052442s, after 0.045516s. Median steady 5000 calls: before 0.242688s, after 0.091426s. Before counters: {'cudagraph_recorded_non_static_inputs': 1}; after counters: {'cudagraph_skips': 1}.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_skips_cudagraphs

lintrunner -a

Manual repro: CUDA reshape-only graph emitted 0 empty CUDA Graph warnings and counters {'cudagraph_skips': 1}.

Manual sanity: CUDA x + 1 graph still recorded cudagraphs with counters {'cudagraph_recorded_non_static_inputs': 1}.

Fixes pytorch#149653

Generated by my agent

Pull Request resolved: pytorch#185760
Approved by: https://github.com/eellison
jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request Jun 13, 2026
…)"

This reverts commit b1e3edd.

Reverted pytorch#185760 on behalf of https://github.com/wdvr due to reverting due to failing signal on D108074417 - discussed with author ([comment](pytorch#185760 (comment)))
[ghstack-poisoned]
jansel added a commit that referenced this pull request Jun 15, 2026
Inductor can lower a CUDA graph that only contains scheduler nop nodes. A pure view graph such as reshape or slice does not launch CUDA kernels, so recording it as a CUDA graph emits the empty CUDA Graph warning. The original fix disabled cudagraphs for these lowered graphs entirely, but that was too broad for cudagraph trees: a kernel-free compiled function can still create aliases of cudagraph-managed tensors, and removing it from the tree breaks alias/lifetime bookkeeping for later nodes.

Fix this by carrying a kernel_free_cudagraph bit from GraphLowering into cudagraph wrapping. For non-tree cudagraph wrapping, kernel-free callables skip CUDA graph capture and run directly. For cudagraph trees, the callable still becomes a tree node, but CUDAGraphNode does not allocate or replay a torch.cuda.CUDAGraph for it. Instead, the first run executes under the cudagraph memory-pool manager and records output metadata with the existing _add_first_outputs alias/liveness path, so view aliases and allocation-only outputs remain tracked by the tree without entering an empty CUDA graph capture. The flag is also threaded through graph-partition post-compile so zero-kernel partitions use the same path.

The alternatives were either suppressing the warning around empty captures or disabling cudagraph tree participation. Suppression still records an empty CUDA graph and hides real capture issues; disabling tree participation regresses alias tracking. Keeping an explicit kernel-free tree node is the narrow fix because it avoids empty capture while preserving the tree's ownership and lifetime model.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_suppresses_empty_warning

python test/inductor/test_cudagraph_trees.py -k test_kernel_free_allocation_uses_cudagraph_pool

python test/inductor/test_cudagraph_trees.py -k test_aliasing_static_ref

python test/inductor/test_cudagraph_trees.py -k test_cudagraph_min_partition_size_skip_small

python test/inductor/test_cudagraph_trees.py -k test_cudagraph_min_partition_size_allow_large

lintrunner -a

Manual repro: CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False emitted 0 empty CUDA Graph warnings, produced correct output, and kept a cudagraph manager for tree bookkeeping.

Manual regression: allocation-only torch.empty_like graph emitted 0 empty CUDA Graph warnings with graph_partition=False and graph_partition=True while triton.slow_path_cudagraph_asserts=True.

Attempted: python test/test_cuda.py -k test_graph_warn_if_has_zero_nodes. This local environment failed during import before test selection because torchvision was built for CUDA 13.0 while PyTorch was built for CUDA 12.8.

Fixes #149653

Generated by my agent

ghstack-source-id: 201ad90
Pull-Request: #185760
@jansel

jansel commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I addressed the revert by keeping kernel-free compiled functions in cudagraph tree bookkeeping without recording an empty torch.cuda.CUDAGraph. The updated path records output metadata and alias/lifetime state under the cudagraph memory-pool manager, threads the flag through partition wrapping, and adds regressions for the no-partition alias case plus allocation-only kernel-free graphs with slow pool assertions. Confidence to reland: medium-high, because the reverted aliasing case and the fresh-allocation pool case now pass locally; remaining risk is normal CI coverage across internal configurations.

@jansel

jansel commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 6m 34s —— View job


Code Review: reland of "Skip cudagraphs for kernel-free inductor graphs"

  • Read full diff vs base
  • Analyze fix for the revert regression (test_aliasing_static_ref)
  • Check correctness & test coverage
  • Post review + reland confidence

This reland correctly fixes the root cause of the revert, and I'd rate it high confidence to reland.

What changed vs. the reverted version

The original PR set V.graph.disable_cudagraphs_reason for kernel-free graphs, which removed the function from the cudagraph tree entirely. That broke test_aliasing_static_ref (fbcode runs graph_partition=False): when a kernel-free foo2(out1) was sequenced after a kernel-bearing foo(m, x) within one cudagraph_mark_step_begin(), dropping foo2 out of the tree broke cross-node aliasing/lifetime tracking.

This version implements Option A from the revert analysis: it keeps the node in the tree but skips only the CUDA graph capture/replay. A new kernel_free_cudagraph flag threads from compile_fx.py → CompiledFxGraph → cudagraphify → WrappedFunction → CUDAGraphNode. In the node:

  • self.graph is None instead of a fresh CUDAGraph() (cudagraph_trees.py:1088), with register_generator_state and the end-of-__init__ replay() both guarded.
  • run_graph() becomes a no-op (:1357).
  • _record() runs the model eagerly inside _use_cuda_memory_pool_manager (instead of torch.cuda.graph(...) capture), then still calls _add_first_outputs so alias/lifetime tracking is set up identically (:1389-1414).

This is the right call. Because allocations during the eager run still land in self.cuda_graphs_pool, the lifetime/aliasing bookkeeping that the tree relies on is preserved — which is exactly what the failing test needed. The model executes eagerly (no replay needed, correctly guarded), so view-only and allocation-only graphs produce correct outputs.

Correctness review — no blocking issues

  • No double execution: normal path runs the model during capture (no execution) then replay()s; kernel-free path runs eagerly once and skips replay. Both produce real outputs exactly once. ✔
  • Subsequent runs: run() → run_graph() (no-op) → reconstruct_outputs() rebuilds outputs from metadata. For pure views the output aliases input storage; for empty_like it aliases the once-allocated pool storage (uninitialized either way), matching cudagraph semantics. ✔
  • count_kernel_nodes unification (addressing eellison's review): the NopKernelSchedulerNode-excluding count is now a single Scheduler.count_kernel_nodes reused by both the whole-graph check and the partition min_size check (scheduler.py:4139, :9389). ✔
  • graph_partition interaction: the flag is computed once for the whole graph and applied to every partition. If the whole graph is kernel-free, all partitions are too, so it's consistent; otherwise the flag is False. ✔

Test coverage

The exact regression scenario is now pinned: test_aliasing_static_ref is split so the body runs both default and @config.patch("graph_partition", False) (test_aliasing_static_ref_no_graph_partition, :1763) — i.e. the fbcode config that caught the revert. Plus test_view_only_cuda_graph_suppresses_empty_warning asserts the warning is gone and the graph still records (cudagraph_recorded_non_static_inputs == 1, manager not None), and test_kernel_free_allocation_uses_cudagraph_pool covers the allocating-but-kernel-free case across both partition modes. Good, targeted coverage.

Minor / non-blocking observations

  1. Behavior + title drift: the PR no longer "skips cudagraphs" for these graphs — it records them capture-free and they stay in the tree (cudagraph_skips is no longer bumped; cudagraph_recorded_non_static_inputs is). The title/description still describe the old skip-and-cudagraph_skips behavior and quote the old benchmark. Worth a one-line update to the PR body so reviewers/future readers aren't misled.

  2. test_kernel_free_allocation_uses_cudagraph_pool under-tests its name: it only asserts output shape and absence of the empty-graph warning; it doesn't actually verify the allocation landed in the cudagraph pool. Consider asserting pool membership (or the recorded-counter) to match the name, or rename.

  3. Output normalization differs trivially between branches: the kernel-free branch wraps a bare output as a list ([static_outputs], :1407) while the capture branch uses a tuple ((static_outputs,), :1455). Harmless since _add_first_outputs just iterates, but unifying would avoid a future "why are these different" moment. Fix this →

  4. CompiledFxGraph.kernel_free_cudagraph is a non-defaulted bool field (output_code.py:527). It's set in __init__, matching the disabled_cudagraphs_reason pattern, so this is fine — just confirm the FxGraphCache version was bumped if older serialized entries could be loaded (cache key changes usually cover this).

Reland confidence

High. The fix attacks the documented root cause directly (tree participation preserved instead of full disable), and the precise failing configuration (graph_partition=False sequenced aliasing) is now an explicit regression test. The remaining items are documentation/cosmetic, not correctness. Recommend running the full test_cudagraph_trees.py suite (especially the cudagraph_trees_expandable_segments variant that surfaced the original failure) on CI before merge as the final gate.
• branch gh/jansel/1204/head

@jansel jansel added the agentic Created by an AI agent label Jun 15, 2026
malfet pushed a commit that referenced this pull request Jun 15, 2026
#185760)" (#187347)

Revert "Skip cudagraphs for kernel-free inductor graphs (#185760)"

This reverts commit b1e3edd.

Reverted #185760 on behalf of https://github.com/wdvr due to reverting due to failing signal on D108074417 - discussed with author ([comment](#185760 (comment)))

(cherry picked from commit 82a2694)

Co-authored-by: PyTorch MergeBot <[email protected]>
@jansel

jansel commented Jun 17, 2026

Copy link
Copy Markdown
Contributor Author

My agent says I triaged the current Dr. CI failures. TorchBench training failed before Inductor with eager_two_runs_differ, and the MI350 ROCm failures are in Triton autotune/static launcher/opinfo paths unrelated to the kernel-free cudagraph tree changes. I reran the failed trunk, inductor, and torchtitan-test jobs for fresh signal.

@jansel

jansel commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

@claude based on the thread above is this safe to reland? Give a confidence level.

@claude

claude Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 11s —— View job


Reland safety assessment

  • Read current diff vs base
  • Verify the revert root cause is fixed
  • Assess remaining risk
  • Give confidence level

Confidence to reland: High (~85%).

Why the revert is actually fixed

The revert was caused by test_aliasing_static_ref in the graph_partition=False (fbcode default) config: the original PR set disable_cudagraphs_reason, which dropped the kernel-free foo2(out1) out of the cudagraph tree entirely, breaking cross-node alias/lifetime tracking when it was sequenced after a kernel-bearing graph.

This reland switches to Option A from the revert analysis: it no longer disables cudagraphs. Instead it threads a kernel_free_cudagraph flag (graph.py → output_code.py → cudagraphify → WrappedFunction → CUDAGraphNode) and only skips the capture/replay:

  • self.graph = None instead of torch.cuda.CUDAGraph(), with register_generator_state and the __init__ replay() both guarded (cudagraph_trees.py:1088, :1171).
  • run_graph() no-ops (:1357).
  • _record() runs the model eagerly inside _use_cuda_memory_pool_manager then still calls _add_first_outputs (:1389).

This is the correct mechanism: allocations during the eager run land in cuda_graphs_pool, so the alias/lifetime bookkeeping the tree relies on is preserved — exactly what the failing test needed. The node stays in the tree.

The exact failing config is now pinned: test_aliasing_static_ref_no_graph_partition runs the same body under @config.patch("graph_partition", False).

What gives me confidence

  • Root cause is addressed directly (tree participation preserved, not removed).
  • The precise reverting configuration has a dedicated regression test.
  • count_kernel_nodes unification (eellison's review) is clean and reused by both the whole-graph check and the partition min_size check.
  • graph_partition consistency holds: the flag is computed once over graph.scheduler.nodes. If the whole graph has any kernel, flag is False for all partitions, and a kernel-free partition is already handled by the existing min_size skip path — so no empty capture leaks through either way.

Residual risk (the ~15%)

  1. Subsequent-run correctness for view-only graphs with changing inputs is not directly tested. Both new tests reuse the same x across iterations. The model executes eagerly only once during _record; later runs no-op run_graph() and reconstruct_outputs() from metadata. For a pure view this is correct only because input copying into the pool still happens in run() before run_graph(), so the reconstructed view reflects the refreshed pool buffer. This is sound by construction, but a test that varies the input between calls (and asserts numerics) would close the gap and protect against future regressions. Add this →
  2. Internal CI breadth. The original failure only surfaced in fbcode config. The reland was validated locally but, per your last triage note, full internal signal across configs (e.g. cudagraph_trees_expandable_segments) is the real gate and can't be reproduced here.

Recommendation

Reland, but make the final merge gate an explicit full run of test/inductor/test_cudagraph_trees.py — including the cudagraph_trees_expandable_segments variant that surfaced the original failure — rather than -i-ignoring. The fix is correct; the only thing that bit you last time was config coverage, so prove it with the suite that caught it.
• branch gh/jansel/1204/head

@jansel

jansel commented Jun 18, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Inductor can lower a CUDA graph that only contains metadata/view work, such as a reshape that remains a view. The non-partition cudagraph path still wrapped that compiled callable, so the first execution attempted to capture a CUDA graph with no kernel launches and emitted the empty CUDA Graph warning.

Fix this by checking the lowered scheduler after codegen and marking cudagraphs disabled when there are no scheduler nodes other than NopKernelSchedulerNode. This uses Inductor's actual lowered work instead of guessing from FX ops, so reshape can still cudagraph when it really lowers to compute, while pure view graphs skip capture cleanly.

I considered suppressing the CUDA warning or deciding from the FX graph, but warning suppression could hide real capture problems and FX-level checks do not know whether reshape becomes a view or a clone. The scheduler check is the narrow point where the kernel/no-kernel distinction is available.

Benchmark Results:

Simulated previous behavior by monkeypatching the new no-kernel check to return True for a CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False. Median first 3 calls: before 0.052442s, after 0.045516s. Median steady 5000 calls: before 0.242688s, after 0.091426s. Before counters: {'cudagraph_recorded_non_static_inputs': 1}; after counters: {'cudagraph_skips': 1}.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_skips_cudagraphs

lintrunner -a

Manual repro: CUDA reshape-only graph emitted 0 empty CUDA Graph warnings and counters {'cudagraph_skips': 1}.

Manual sanity: CUDA x + 1 graph still recorded cudagraphs with counters {'cudagraph_recorded_non_static_inputs': 1}.

Fixes pytorch#149653

Generated by my agent

Pull Request resolved: pytorch#185760
Approved by: https://github.com/eellison
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…)"

This reverts commit b1e3edd.

Reverted pytorch#185760 on behalf of https://github.com/wdvr due to reverting due to failing signal on D108074417 - discussed with author ([comment](pytorch#185760 (comment)))
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Inductor can lower a CUDA graph that only contains metadata/view work, such as a reshape that remains a view. The non-partition cudagraph path still wrapped that compiled callable, so the first execution attempted to capture a CUDA graph with no kernel launches and emitted the empty CUDA Graph warning.

Fix this by checking the lowered scheduler after codegen and marking cudagraphs disabled when there are no scheduler nodes other than NopKernelSchedulerNode. This uses Inductor's actual lowered work instead of guessing from FX ops, so reshape can still cudagraph when it really lowers to compute, while pure view graphs skip capture cleanly.

I considered suppressing the CUDA warning or deciding from the FX graph, but warning suppression could hide real capture problems and FX-level checks do not know whether reshape becomes a view or a clone. The scheduler check is the narrow point where the kernel/no-kernel distinction is available.

Benchmark Results:

Simulated previous behavior by monkeypatching the new no-kernel check to return True for a CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False. Median first 3 calls: before 0.052442s, after 0.045516s. Median steady 5000 calls: before 0.242688s, after 0.091426s. Before counters: {'cudagraph_recorded_non_static_inputs': 1}; after counters: {'cudagraph_skips': 1}.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_skips_cudagraphs

lintrunner -a

Manual repro: CUDA reshape-only graph emitted 0 empty CUDA Graph warnings and counters {'cudagraph_skips': 1}.

Manual sanity: CUDA x + 1 graph still recorded cudagraphs with counters {'cudagraph_recorded_non_static_inputs': 1}.

Fixes pytorch#149653

Generated by my agent

Pull Request resolved: pytorch#185760
Approved by: https://github.com/eellison
@github-actions
github-actions Bot deleted the gh/jansel/1204/head branch July 19, 2026 02:24
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Inductor can lower a CUDA graph that only contains metadata/view work, such as a reshape that remains a view. The non-partition cudagraph path still wrapped that compiled callable, so the first execution attempted to capture a CUDA graph with no kernel launches and emitted the empty CUDA Graph warning.

Fix this by checking the lowered scheduler after codegen and marking cudagraphs disabled when there are no scheduler nodes other than NopKernelSchedulerNode. This uses Inductor's actual lowered work instead of guessing from FX ops, so reshape can still cudagraph when it really lowers to compute, while pure view graphs skip capture cleanly.

I considered suppressing the CUDA warning or deciding from the FX graph, but warning suppression could hide real capture problems and FX-level checks do not know whether reshape becomes a view or a clone. The scheduler check is the narrow point where the kernel/no-kernel distinction is available.

Benchmark Results:

Simulated previous behavior by monkeypatching the new no-kernel check to return True for a CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False. Median first 3 calls: before 0.052442s, after 0.045516s. Median steady 5000 calls: before 0.242688s, after 0.091426s. Before counters: {'cudagraph_recorded_non_static_inputs': 1}; after counters: {'cudagraph_skips': 1}.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_skips_cudagraphs

lintrunner -a

Manual repro: CUDA reshape-only graph emitted 0 empty CUDA Graph warnings and counters {'cudagraph_skips': 1}.

Manual sanity: CUDA x + 1 graph still recorded cudagraphs with counters {'cudagraph_recorded_non_static_inputs': 1}.

Fixes pytorch#149653

Generated by my agent

Pull Request resolved: pytorch#185760
Approved by: https://github.com/eellison
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…)"

This reverts commit b1e3edd.

Reverted pytorch#185760 on behalf of https://github.com/wdvr due to reverting due to failing signal on D108074417 - discussed with author ([comment](pytorch#185760 (comment)))
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Inductor can lower a CUDA graph that only contains metadata/view work, such as a reshape that remains a view. The non-partition cudagraph path still wrapped that compiled callable, so the first execution attempted to capture a CUDA graph with no kernel launches and emitted the empty CUDA Graph warning.

Fix this by checking the lowered scheduler after codegen and marking cudagraphs disabled when there are no scheduler nodes other than NopKernelSchedulerNode. This uses Inductor's actual lowered work instead of guessing from FX ops, so reshape can still cudagraph when it really lowers to compute, while pure view graphs skip capture cleanly.

I considered suppressing the CUDA warning or deciding from the FX graph, but warning suppression could hide real capture problems and FX-level checks do not know whether reshape becomes a view or a clone. The scheduler check is the narrow point where the kernel/no-kernel distinction is available.

Benchmark Results:

Simulated previous behavior by monkeypatching the new no-kernel check to return True for a CUDA reshape-only graph with triton.cudagraphs=True and graph_partition=False. Median first 3 calls: before 0.052442s, after 0.045516s. Median steady 5000 calls: before 0.242688s, after 0.091426s. Before counters: {'cudagraph_recorded_non_static_inputs': 1}; after counters: {'cudagraph_skips': 1}.

Test Plan:

python test/inductor/test_cudagraph_trees.py -k test_view_only_cuda_graph_skips_cudagraphs

lintrunner -a

Manual repro: CUDA reshape-only graph emitted 0 empty CUDA Graph warnings and counters {'cudagraph_skips': 1}.

Manual sanity: CUDA x + 1 graph still recorded cudagraphs with counters {'cudagraph_recorded_non_static_inputs': 1}.

Fixes pytorch#149653

Generated by my agent

Pull Request resolved: pytorch#185760
Approved by: https://github.com/eellison
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agentic Created by an AI agent ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor Reverted topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants