Skip to content

[inductor] Make CUDA graph autotuning measurements consistent - #194649

Closed
mlazos wants to merge 20 commits into
gh/mlazos/308/basefrom
gh/mlazos/308/head
Closed

mlazos wants to merge 20 commits into
gh/mlazos/308/basefrom
gh/mlazos/308/head

Conversation

@mlazos

@mlazos mlazos commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Human commentary: I want every candidate in an autotune decision measured under the same launch policy so the selected kernel reflects production execution.

AI-assisted content:

Problem

Fixes #198171

Autotune requests can be created under one Inductor configuration and executed later in another process. Without carrying the effective CUDA-graph policy on the request, candidates from the same decision can be timed under different launch conditions. CUTLASS closures also used to capture a stream too early, before CUDA graph capture selected its stream.

Summary

Make CUDA-graph autotuning policy request-scoped and consistent across current-process, subprocess, extern, Triton, and CUTLASS benchmark paths.

Architecture

BenchmarkRequest snapshots the effective max-autotune and automatic CUDA-graph settings when the compiler creates it. Those values are serialized with the request, applied while a worker runs it, and included in the timing-cache namespace together with the effective eager/automatic/required graph mode and replay count.

The shared GPU benchmark path owns device selection, CUDA-graph replay unrolling, and optional rotation of cold inputs and outputs. It finds the GPU from all input and output metadata, captures the requested number of launches, rotates independent buffers when requested, and reports normalized per-launch time. Extern and generated-kernel callers use this path so candidates in one decision are comparable.

CUTLASS benchmark closures resolve the raw CUDA stream at invocation time. During graph capture the launch therefore uses the active capture stream, rather than a stream saved when the closure was constructed. A capture failure remains an ordinary failed candidate; this change does not add an eager-retry or CUDA-worker-recovery protocol.

Examples

  • A request created with automatic CUDA-graph benchmarking enabled retains that policy after serialization into an autotune worker whose process defaults differ.
  • A replay count of 16 captures 16 kernel invocations and normalizes the replay duration per invocation. CUTLASS obtains the stream immediately before each launch.

Test Plan

python test/inductor/test_select_algorithm.py -k test_automatic_cudagraph_policy_takes_precedence_over_profiler
python test/inductor/test_benchmarking.py -k cudagraph
lintrunner -a
git diff --check

Tests also cover serialized policy, cache identity, GPU discovery from input/output metadata, replay normalization, gradients, thread-local recursion protection, rotating buffers, extern/template routing, and late CUTLASS stream lookup.

Checklist

  • Passes lint
  • Added or updated tests
  • Updated documentation where applicable
  • Performance claims are limited to measurement correctness

BC-breaking?

No.

PR prepared with assistance from an AI tool.

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 Aug 24, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (2 Unrelated Failures)

As of commit 70fa224 with merge base ee0d01e (image):

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

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

@mlazos

mlazos commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor Author

AI-Review

Automated multi-agent review (architecture, correctness, simplification, generalization, and GPT-5.6 final approval). This is AI-generated — please verify findings manually.


Verified Issues

  • [medium] Automatic CUDA-graph capture no longer falls back to eager timing — Location: torch/_inductor/autotune_process.py:700-706. Trigger: an otherwise valid candidate raises RuntimeError during graph capture with automatic CUDA-graph benchmarking enabled. Failure sequence: benchmark_run_fn calls do_bench_with_cudagraphs directly, bypassing the eager fallback in runtime/benchmarking.py:711-733; autotuning converts the exception to inf. Impact: viable candidates are discarded, producing a slower selection or NoValidChoicesError. Reviewers: final review only.

  • [medium] NVGEMM bypasses the serialized automatic policy — Location: torch/_inductor/codegen/nv_universal_gemm/nv_universal_gemm.py:120-150. Trigger: a request created with automatic CUDA-graph benchmarking enabled executes in a long-lived worker whose global setting is disabled. Failure sequence: the override checks only benchmark_with_cudagraphs and calls eager do_bench, while competing requests restore and use the serialized graph policy. Impact: incomparable timings can select the wrong kernel. Reviewers: correctness and generalization.

  • [medium] ROCm benchmark closures launch on the pre-capture stream — Location: torch/_inductor/codegen/rocm/rocm_benchmark_request.py:73-92; reached through autotune_process.py:889-950. Trigger: CK/CKTILE benchmarking uses CUDA/HIP graph timing after the closure was created on the default stream. Failure sequence: capture uses a new side stream, but the closure launches on the stored default-stream pointer, invalidating capture and causing the candidate to be recorded as failed. Impact: valid ROCm candidates are excluded from selection. Reviewers: generalization.

  • [medium] ROCm profiling still overrides the request’s graph policy — Location: torch/_inductor/codegen/rocm/rocm_kernel.py:256-262. Trigger: automatic or required graph benchmarking and profile_bandwidth_with_do_bench_using_profiling=True are both enabled. Failure sequence: ROCmTemplateCaller unconditionally chooses profiling, while Triton, CUTLASS, extern, and subgraph candidates use graph replay. Impact: inconsistent timings can select the wrong kernel. Reviewers: final review only.

  • [low] CUDA-specific policy tests fail on XPU — Location: test/inductor/test_select_algorithm.py:188-205 and :238-260. Trigger: run the suite on a sufficiently large XPU, where GPU_TYPE == "xpu". Failure sequence: production correctly enables automatic graph policy only for device type "cuda", but both tests expect it enabled for GPU_TYPE. Impact: two deterministic XPU test failures. Reviewers: final review only.

[ghstack-poisoned]
[ghstack-poisoned]
mlazos added 2 commits August 28, 2026 14:08
[ghstack-poisoned]
[ghstack-poisoned]
mlazos added 2 commits August 28, 2026 19:08
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@mlazos mlazos added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 25, 2026
[ghstack-poisoned]

@karthickai karthickai left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM overall. An agent flagged the issue below, and it looks legitimate. Please address it before landing.

NVGEMM’s benchmark override skips the saved CUDA graph settings, so autotuning in a separate process can time Triton with CUDA graphs and NVGEMM without them. Can we use benchmark_run_fn() in the NVGEMM override before landing?

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #197485

pytorchmergebot pushed a commit that referenced this pull request Oct 3, 2026
Human commentary: Short NVFP4 inference GEMMs need a small automatic candidate set and measurements that reflect transformer decode execution.

AI-assisted content:

> ## Problem
>
> Fixes #198172
>
> `nvMatmulHeuristics` does not cover several Blackwell NVFP4 decode winners, while an unrestricted supplemental pool adds substantial compile and profiling cost. The related shape rules were also split between code generation and candidate filtering, which made the policy difficult to audit.
>
> ## Summary
>
> Add a bounded, shape-aware NVFP4 candidate policy for Blackwell decode workloads and centralize every NVFP4 shape decision in the NVGEMM heuristics module.
>
> ## Architecture
>
> `torch/_inductor/heuristics/template/nv_universal_gemm.py` is the single policy boundary. It identifies the NVFP4 1x16 recipe, decides when to expose swap-AB, chooses the CUDA-graph replay count and cold-weight scope, applies the profiling cap, and returns the shape-scoped primary and prefetch candidate keys. The codegen integration passes problem metadata to these helpers but contains no independent shape cutoffs.
>
> The ranked `nvMatmulHeuristics` result remains the primary pool. Successful heuristic ranking is capped at three candidates in each ordinary and epilogue-fusion-capable (EFC) pool by default; fallback, supplemental, and wide-tile paths may add more. Within measured shape ranges, the centralized policy adds missing narrow-N decode tactics, medium-M native and swapped tactics, selected prefetch variants, and a large-M 256x192 tile with a 2x2 cluster. Candidate keys are deduplicated, unranked fallback paths retain primary non-prefetch variants, and dynamic-N problems exclude tactics that require a known narrow N. Explicit controls can still request fewer candidates or the broader fixed supplemental table.
>
> NVGEMM-only decode requests use 16 CUDA-graph replays and rotate weight, scale, and output buffers to avoid permanently L2-hot selection. Mixed-backend decisions in this PR retain the shared global policy; the next PR uses the opt-in hook added here to apply one override to every choice. Runtime EFC lookup also retains the GEMM's pre-fusion output dtype, avoiding reconstruction of the full operator manifest for output-cast fusions.
>
> ## Examples
>
> - Logical `M=32, N=4096` NVFP4 projections add the measured transposed 32/64-wide tactics that `nvMatmulHeuristics` misses.
> - Logical `M=128, N <= 16384` native projections admit the measured 128x64 and 128x128 prefetch variants. FP8, MXFP4, and BF16 keep their ordinary policy; dynamic-N NVFP4 excludes narrow-N tactics and uses only candidates valid without a concrete N.
>
> ## Performance
>
> On the later complete stack with the final selective-PDL policy, changing only the ranked-family cap from five to three preserved or improved selected-kernel latency for all 15 shapes. It reduced aggregate candidate time from 189.03 s to 164.93 s (12.75%). A Qwen3-14B batch-32 run reduced NVGEMM tuning from 49.684 s to 40.738 s (18.0%); its 0.10% end-to-end change was below unlocked-clock run spread.
>
> ## Test Plan
>
> ```bash
> python test/inductor/test_nv_universal_gemm.py -k TestNVUniversalGemmHeuristics
> lintrunner -a
> git diff --check
> ```
>
> Focused policy validation covers recipe detection, swap-AB, replay/cold-cache boundaries, profiling caps, supplemental and prefetch candidate tables, fallback ordering, dynamic N, MXFP4 exclusion, and PDL-independent integration behavior.
>
> ## Checklist
>
> - [x] Passes lint
> - [x] Added or updated tests
> - [x] Updated documentation where applicable
> - [x] Included benchmark results
>
> ## BC-breaking?
>
> No user-facing BC. The ranked-family cap applies recipe-wide to NVFP4 1x16; swap-AB, replay, cold-cache rotation, and automatic supplemental tactics remain shape-scoped. The explicit full-supplement override remains recipe-wide.
>
> PR prepared with assistance from an AI tool.

Pull Request resolved: #194652
Approved by: https://github.com/karthickai
ghstack dependencies: #194649
pytorchmergebot pushed a commit that referenced this pull request Oct 3, 2026
Human commentary: ModelOpt NVFP4 linear layers multiply `_scaled_mm` output by a scalar dequantization factor. Folding that factor before QKV fan-out removes one standalone scale launch per layer and lets autotuning consider the GEMM implementation that applies it directly.

AI-assisted content:

> ## Problem
>
> Fixes #198173
>
> ModelOpt NVFP4 linears materialize a separate pointwise multiply after `_scaled_mm`. That launch is especially visible during decode. Waiting until scheduler fusion is too late for two reasons: GEMM candidates have already been constructed, so native NVGEMM output scaling cannot participate in autotuning; and a QKV split/view fan-out no longer looks like one simple pointwise suffix that the scheduler can attach to a single producer.
>
> ## Summary
>
> Fold eligible NVFP4 output scaling into the selected scaled-matmul implementation while preserving semantically equivalent ATen fallback choices and tensor-parallel transformations.
>
> ## Architecture
>
> Two post-grad graph patterns recognize `aten._scaled_mm(...) * output_scale` in either multiply order. A variadic `_scaled_mm` subpattern and schema normalization handle omitted or explicitly supplied default arguments without duplicating registrations. Post-grad is the earliest existing boundary that has the required graph structure while still preceding lowering, candidate construction, and scheduling. Rewriting there exposes native-alpha NVGEMM candidates to the autotuner instead of trying to modify the already-selected kernel later.
>
> The QKV case is the main fan-out rationale. The original graph contains one multiply before `chunk`/split/view consumers. Folding it into the GEMM produces the already-scaled buffer consumed by every branch and removes that one standalone launch per layer. If the multiply survives until scheduling, moving it through the multi-consumer fan-out would require a separate cross-consumer transformation; ordinary single-consumer epilogue fusion cannot recover the same result. Conversely, a complete pointwise suffix with no such boundary remains untouched so the scheduler can use its existing epilogue fusion.
>
> Schema-normalized validation accepts packed FP4 inputs with E4M3 1x16 block scales and a zero-dimensional CUDA FP32 multiplier. Pattern structure excludes existing bias and public `scale_result`; the predicate rejects fast accumulation, shared GEMM output, incompatible scale recipes, pipelined autotuning, and tensor-parallel structures that the micro-pipeline pass can consume.
>
> The rewritten node carries the scale tensor through IR, candidate construction, subprocess precompile metadata, cache specialization, swap-AB, and runtime pointer refresh. The vendored block-scaled NVGEMM provider advertises native output-scale support explicitly. For mixed `ATEN,NVGEMM` tuning, an ATen extern candidate performs `_scaled_mm` followed by multiply under the same replay and cold-buffer policy. If every native folded choice fails, lowering restores the ordinary scaled matmul and multiply.
>
> ## Examples
>
> ```python
> out = torch._scaled_mm(
>     a, b, scale_a=sa, scale_b=sb, out_dtype=torch.bfloat16
> )
> q, k, v = (out * output_scale).chunk(3, dim=-1)
> ```
>
> When an NVGEMM choice wins, the scale becomes that provider's alpha before the split/view fan-out. A direct all-gather form eligible for micro-pipeline tensor parallelism is left unchanged; unsupported or reshaped collective forms may use the fold.
>
> ## Performance
>
> On GB200 with Llama-3.1-8B NVFP4 at batch 64, the fold removes 32 launches per decode step and reduces the captured graph from 481 to 449 nodes. The later complete stack measured representative graph spans of 2.175--2.180 ms versus 2.232--2.237 ms before the fold; those span numbers also include later PDL overlap and are not isolated attribution to this PR. Candidate selection remains the larger source of the complete-stack speedup; this PR removes the residual per-layer scale launch and makes the native scaled candidate selectable.
>
> ## Test Plan
>
> ```bash
> python test/inductor/test_nv_universal_gemm.py -k output_scale
> python test/distributed/tensor/parallel/test_micro_pipeline_tp.py -k test_scaled_mm_output_scale_preserves_all_gather_fusion
> lintrunner -a
> git diff --check
> ```
>
> Focused validation on GB200 passed 18 output-scale cases and 3 tensor-parallel preservation cases after test consolidation. Coverage includes both multiply orders, QKV split/view fan-out, pointwise-versus-nonpointwise consumer boundaries, fast-accum rejection, public `scale_result`, MXFP4 exclusion, shared outputs, native-choice fallback, the generated runtime path, worker-precompile serialization, and tensor-parallel preservation.
>
> ## Checklist
>
> - [x] Passes lint
> - [x] Added or updated tests
> - [x] Updated documentation where applicable
> - [x] Included benchmark results
>
> ## BC-breaking?
>
> No. Ineligible patterns continue through ordinary lowering.
>
> PR prepared with assistance from an AI tool.

Pull Request resolved: #194651
Approved by: https://github.com/karthickai
ghstack dependencies: #194649, #194652
pytorchmergebot pushed a commit that referenced this pull request Oct 3, 2026
…rs (#197485)

Human commentary: Adds provider-side PDL for NVGEMM.

AI-assisted content:

> ## Problem
>
> Fixes #198174
> Fixes #198175
>
> NVGEMM kernels could not participate in CUDA programmatic dependent launch (PDL), so direct Triton consumers waited for ordinary kernel completion instead of overlapping their launch setup with the producer tail.
>
> ## Summary
>
> Add selective PDL for measured NVFP4 decode shapes and connect eligible NVGEMM providers to direct same-stream Triton consumers.
>
> ## Architecture
>
> The NVGEMM heuristics module owns the complete shape policy. In `"auto"` mode it generates PDL-capable operators only for NVFP4 1x16 problems with `0 < M <= 256` and logical `N` and `K` in `[1024, 65536]`, excluding the measured regression band `32 < M <= 64` and `2048 < min(N, K) < 4096`. `"0"` disables PDL, while `"1"` forces it for experiments. The policy receives packed FP4 K from `MMKernelInputs` and performs the packed-to-logical conversion internally.
>
> The selected policy is represented in operator metadata and included in generated-precompile, runtime, and persistent-artifact cache identities. Original logical M is also part of specialization when swap-AB changes the physical orientation.
>
> Inside the CuTeDSL provider, an NVGEMM kernel that depends on an earlier launch calls `cute.arch.griddepcontrol_wait()` before consuming dependency-produced inputs. The producer calls `cute.arch.griddepcontrol_launch_dependents()` after issuing its output stores, allowing the dependent grid to begin launch setup while those stores drain. A direct Triton consumer launches with `launch_pdl` and calls `tl.extra.cuda.gdc_wait()` before reading the producer output, preserving completion and visibility. For measured small-K decode shapes, descriptor and layout setup is moved before the wait so independent prologue work overlaps; other shapes retain the conservative early wait.
>
> Scheduler code generation tracks the previous concrete scheduler node independently per device and stream. A Triton launch opts into PDL only when the immediately preceding same-stream node resolves to a selected PDL-capable NVGEMM and the consumer has a true read-after-write dependency on its output. Composite launches, multi-kernel wrappers, workspaces, unsupported reductions, cross-stream consumers, and unrelated nodes retain ordinary launch behavior.
>
> ## Examples
>
> - An eligible NVFP4 decode projection followed directly on the same stream by a Triton cast or add launches the consumer with `launch_pdl` and waits through `gdc_wait`.
> - A consumer on another stream behind an event, or one separated by an unrelated same-stream kernel, uses ordinary stream/event ordering and receives no PDL launch attribute.
>
> ## Performance
>
> Standard `vllm bench latency` runs on GB200 used 32 input tokens, 128 output tokens, 10 warmups, 30 samples, `-O2`, static compilation/CUDA graphs, dummy weights, and tuned FlashInfer 0.6.18.post1 as control. Only vLLM's per-quant `nvfp4_w4a4` linear backend changed; unrelated linears, attention, and sampling remained matched.
>
> These are cumulative complete-stack results, not isolated attribution to this PR:
>
> - Llama-3.1-8B NVFP4: Torch/NVGEMM was 7.81%, 7.42%, 8.29%, and 7.83% faster than tuned FlashInfer at batches 8, 32, 64, and 128.
> - Qwen3-14B NVFP4: Torch/NVGEMM was 5.15%, 5.67%, 7.87%, and 5.23% faster at batches 8, 32, 64, and 128.
> - Nemotron-Nano-9B-v2 NVFP4 revalidation: Torch/NVGEMM was 4.83% faster at batch 32 (5.59% in the adjacent warmed pair), 6.29% faster at batch 64, and within 0.16% at batch 128, which is treated as parity.
> - A Llama batch-64 PDL ablation improved the midpoint of two PDL medians by 7.27% over the intervening no-PDL run. Forced PDL improved four isolated Nemotron decode GEMMs by 11.1%--13.2%; automatic policy excludes the nearby end-to-end regression band.
>
> ## Test Plan
>
> ```bash
> python test/inductor/test_nv_universal_gemm.py -k pdl
> lintrunner -a
> git diff --check
> ```
>
> A focused PDL-chain run passed 11 cases, and the broader heuristic/PDL-metadata run collected 95 cases: 94 passed and 1 skipped. Tests cover policy boundaries, PDL candidate preference and fallback, provider wait/release placement, logical-shape cache specialization, pointer refresh, direct same-stream dependencies, cross-stream event ordering, reductions, deferred copies, composite launches, multi-kernel wrappers, and workspaces.
>
> ## Checklist
>
> - [x] Passes lint
> - [x] Added or updated tests
> - [x] Updated documentation where applicable
> - [x] Included benchmark results
>
> ## BC-breaking?
>
> No. Automatic PDL is shape-scoped; `TORCHINDUCTOR_NVGEMM_PDL=0` and `=1` remain explicit overrides.
>
> PR prepared with assistance from an AI tool.

Pull Request resolved: #197485
Approved by: https://github.com/karthickai
ghstack dependencies: #194649, #194652, #194651
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…h#194649)

Human commentary: I want every candidate in an autotune decision measured under the same launch policy so the selected kernel reflects production execution.

AI-assisted content:

> ## Problem
>
> Fixes pytorch#198171
>
> Autotune requests can be created under one Inductor configuration and executed later in another process. Without carrying the effective CUDA-graph policy on the request, candidates from the same decision can be timed under different launch conditions. CUTLASS closures also used to capture a stream too early, before CUDA graph capture selected its stream.
>
> ## Summary
>
> Make CUDA-graph autotuning policy request-scoped and consistent across current-process, subprocess, extern, Triton, and CUTLASS benchmark paths.
>
> ## Architecture
>
> `BenchmarkRequest` snapshots the effective max-autotune and automatic CUDA-graph settings when the compiler creates it. Those values are serialized with the request, applied while a worker runs it, and included in the timing-cache namespace together with the effective eager/automatic/required graph mode and replay count.
>
> The shared GPU benchmark path owns device selection, CUDA-graph replay unrolling, and optional rotation of cold inputs and outputs. It finds the GPU from all input and output metadata, captures the requested number of launches, rotates independent buffers when requested, and reports normalized per-launch time. Extern and generated-kernel callers use this path so candidates in one decision are comparable.
>
> CUTLASS benchmark closures resolve the raw CUDA stream at invocation time. During graph capture the launch therefore uses the active capture stream, rather than a stream saved when the closure was constructed. A capture failure remains an ordinary failed candidate; this change does not add an eager-retry or CUDA-worker-recovery protocol.
>
> ## Examples
>
> - A request created with automatic CUDA-graph benchmarking enabled retains that policy after serialization into an autotune worker whose process defaults differ.
> - A replay count of 16 captures 16 kernel invocations and normalizes the replay duration per invocation. CUTLASS obtains the stream immediately before each launch.
>
> ## Test Plan
>
> ```bash
> python test/inductor/test_select_algorithm.py -k test_automatic_cudagraph_policy_takes_precedence_over_profiler
> python test/inductor/test_benchmarking.py -k cudagraph
> lintrunner -a
> git diff --check
> ```
>
> Tests also cover serialized policy, cache identity, GPU discovery from input/output metadata, replay normalization, gradients, thread-local recursion protection, rotating buffers, extern/template routing, and late CUTLASS stream lookup.
>
> ## Checklist
>
> - [x] Passes lint
> - [x] Added or updated tests
> - [x] Updated documentation where applicable
> - [x] Performance claims are limited to measurement correctness
>
> ## BC-breaking?
>
> No.
>
> PR prepared with assistance from an AI tool.
Pull Request resolved: pytorch#194649
Approved by: https://github.com/karthickai
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
Human commentary: Short NVFP4 inference GEMMs need a small automatic candidate set and measurements that reflect transformer decode execution.

AI-assisted content:

> ## Problem
>
> Fixes pytorch#198172
>
> `nvMatmulHeuristics` does not cover several Blackwell NVFP4 decode winners, while an unrestricted supplemental pool adds substantial compile and profiling cost. The related shape rules were also split between code generation and candidate filtering, which made the policy difficult to audit.
>
> ## Summary
>
> Add a bounded, shape-aware NVFP4 candidate policy for Blackwell decode workloads and centralize every NVFP4 shape decision in the NVGEMM heuristics module.
>
> ## Architecture
>
> `torch/_inductor/heuristics/template/nv_universal_gemm.py` is the single policy boundary. It identifies the NVFP4 1x16 recipe, decides when to expose swap-AB, chooses the CUDA-graph replay count and cold-weight scope, applies the profiling cap, and returns the shape-scoped primary and prefetch candidate keys. The codegen integration passes problem metadata to these helpers but contains no independent shape cutoffs.
>
> The ranked `nvMatmulHeuristics` result remains the primary pool. Successful heuristic ranking is capped at three candidates in each ordinary and epilogue-fusion-capable (EFC) pool by default; fallback, supplemental, and wide-tile paths may add more. Within measured shape ranges, the centralized policy adds missing narrow-N decode tactics, medium-M native and swapped tactics, selected prefetch variants, and a large-M 256x192 tile with a 2x2 cluster. Candidate keys are deduplicated, unranked fallback paths retain primary non-prefetch variants, and dynamic-N problems exclude tactics that require a known narrow N. Explicit controls can still request fewer candidates or the broader fixed supplemental table.
>
> NVGEMM-only decode requests use 16 CUDA-graph replays and rotate weight, scale, and output buffers to avoid permanently L2-hot selection. Mixed-backend decisions in this PR retain the shared global policy; the next PR uses the opt-in hook added here to apply one override to every choice. Runtime EFC lookup also retains the GEMM's pre-fusion output dtype, avoiding reconstruction of the full operator manifest for output-cast fusions.
>
> ## Examples
>
> - Logical `M=32, N=4096` NVFP4 projections add the measured transposed 32/64-wide tactics that `nvMatmulHeuristics` misses.
> - Logical `M=128, N <= 16384` native projections admit the measured 128x64 and 128x128 prefetch variants. FP8, MXFP4, and BF16 keep their ordinary policy; dynamic-N NVFP4 excludes narrow-N tactics and uses only candidates valid without a concrete N.
>
> ## Performance
>
> On the later complete stack with the final selective-PDL policy, changing only the ranked-family cap from five to three preserved or improved selected-kernel latency for all 15 shapes. It reduced aggregate candidate time from 189.03 s to 164.93 s (12.75%). A Qwen3-14B batch-32 run reduced NVGEMM tuning from 49.684 s to 40.738 s (18.0%); its 0.10% end-to-end change was below unlocked-clock run spread.
>
> ## Test Plan
>
> ```bash
> python test/inductor/test_nv_universal_gemm.py -k TestNVUniversalGemmHeuristics
> lintrunner -a
> git diff --check
> ```
>
> Focused policy validation covers recipe detection, swap-AB, replay/cold-cache boundaries, profiling caps, supplemental and prefetch candidate tables, fallback ordering, dynamic N, MXFP4 exclusion, and PDL-independent integration behavior.
>
> ## Checklist
>
> - [x] Passes lint
> - [x] Added or updated tests
> - [x] Updated documentation where applicable
> - [x] Included benchmark results
>
> ## BC-breaking?
>
> No user-facing BC. The ranked-family cap applies recipe-wide to NVFP4 1x16; swap-AB, replay, cold-cache rotation, and automatic supplemental tactics remain shape-scoped. The explicit full-supplement override remains recipe-wide.
>
> PR prepared with assistance from an AI tool.

Pull Request resolved: pytorch#194652
Approved by: https://github.com/karthickai
ghstack dependencies: pytorch#194649
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
Human commentary: ModelOpt NVFP4 linear layers multiply `_scaled_mm` output by a scalar dequantization factor. Folding that factor before QKV fan-out removes one standalone scale launch per layer and lets autotuning consider the GEMM implementation that applies it directly.

AI-assisted content:

> ## Problem
>
> Fixes pytorch#198173
>
> ModelOpt NVFP4 linears materialize a separate pointwise multiply after `_scaled_mm`. That launch is especially visible during decode. Waiting until scheduler fusion is too late for two reasons: GEMM candidates have already been constructed, so native NVGEMM output scaling cannot participate in autotuning; and a QKV split/view fan-out no longer looks like one simple pointwise suffix that the scheduler can attach to a single producer.
>
> ## Summary
>
> Fold eligible NVFP4 output scaling into the selected scaled-matmul implementation while preserving semantically equivalent ATen fallback choices and tensor-parallel transformations.
>
> ## Architecture
>
> Two post-grad graph patterns recognize `aten._scaled_mm(...) * output_scale` in either multiply order. A variadic `_scaled_mm` subpattern and schema normalization handle omitted or explicitly supplied default arguments without duplicating registrations. Post-grad is the earliest existing boundary that has the required graph structure while still preceding lowering, candidate construction, and scheduling. Rewriting there exposes native-alpha NVGEMM candidates to the autotuner instead of trying to modify the already-selected kernel later.
>
> The QKV case is the main fan-out rationale. The original graph contains one multiply before `chunk`/split/view consumers. Folding it into the GEMM produces the already-scaled buffer consumed by every branch and removes that one standalone launch per layer. If the multiply survives until scheduling, moving it through the multi-consumer fan-out would require a separate cross-consumer transformation; ordinary single-consumer epilogue fusion cannot recover the same result. Conversely, a complete pointwise suffix with no such boundary remains untouched so the scheduler can use its existing epilogue fusion.
>
> Schema-normalized validation accepts packed FP4 inputs with E4M3 1x16 block scales and a zero-dimensional CUDA FP32 multiplier. Pattern structure excludes existing bias and public `scale_result`; the predicate rejects fast accumulation, shared GEMM output, incompatible scale recipes, pipelined autotuning, and tensor-parallel structures that the micro-pipeline pass can consume.
>
> The rewritten node carries the scale tensor through IR, candidate construction, subprocess precompile metadata, cache specialization, swap-AB, and runtime pointer refresh. The vendored block-scaled NVGEMM provider advertises native output-scale support explicitly. For mixed `ATEN,NVGEMM` tuning, an ATen extern candidate performs `_scaled_mm` followed by multiply under the same replay and cold-buffer policy. If every native folded choice fails, lowering restores the ordinary scaled matmul and multiply.
>
> ## Examples
>
> ```python
> out = torch._scaled_mm(
>     a, b, scale_a=sa, scale_b=sb, out_dtype=torch.bfloat16
> )
> q, k, v = (out * output_scale).chunk(3, dim=-1)
> ```
>
> When an NVGEMM choice wins, the scale becomes that provider's alpha before the split/view fan-out. A direct all-gather form eligible for micro-pipeline tensor parallelism is left unchanged; unsupported or reshaped collective forms may use the fold.
>
> ## Performance
>
> On GB200 with Llama-3.1-8B NVFP4 at batch 64, the fold removes 32 launches per decode step and reduces the captured graph from 481 to 449 nodes. The later complete stack measured representative graph spans of 2.175--2.180 ms versus 2.232--2.237 ms before the fold; those span numbers also include later PDL overlap and are not isolated attribution to this PR. Candidate selection remains the larger source of the complete-stack speedup; this PR removes the residual per-layer scale launch and makes the native scaled candidate selectable.
>
> ## Test Plan
>
> ```bash
> python test/inductor/test_nv_universal_gemm.py -k output_scale
> python test/distributed/tensor/parallel/test_micro_pipeline_tp.py -k test_scaled_mm_output_scale_preserves_all_gather_fusion
> lintrunner -a
> git diff --check
> ```
>
> Focused validation on GB200 passed 18 output-scale cases and 3 tensor-parallel preservation cases after test consolidation. Coverage includes both multiply orders, QKV split/view fan-out, pointwise-versus-nonpointwise consumer boundaries, fast-accum rejection, public `scale_result`, MXFP4 exclusion, shared outputs, native-choice fallback, the generated runtime path, worker-precompile serialization, and tensor-parallel preservation.
>
> ## Checklist
>
> - [x] Passes lint
> - [x] Added or updated tests
> - [x] Updated documentation where applicable
> - [x] Included benchmark results
>
> ## BC-breaking?
>
> No. Ineligible patterns continue through ordinary lowering.
>
> PR prepared with assistance from an AI tool.

Pull Request resolved: pytorch#194651
Approved by: https://github.com/karthickai
ghstack dependencies: pytorch#194649, pytorch#194652
cyyever pushed a commit to BakeLab/pytorch that referenced this pull request Oct 11, 2026
…rs (pytorch#197485)

Human commentary: Adds provider-side PDL for NVGEMM.

AI-assisted content:

> ## Problem
>
> Fixes pytorch#198174
> Fixes pytorch#198175
>
> NVGEMM kernels could not participate in CUDA programmatic dependent launch (PDL), so direct Triton consumers waited for ordinary kernel completion instead of overlapping their launch setup with the producer tail.
>
> ## Summary
>
> Add selective PDL for measured NVFP4 decode shapes and connect eligible NVGEMM providers to direct same-stream Triton consumers.
>
> ## Architecture
>
> The NVGEMM heuristics module owns the complete shape policy. In `"auto"` mode it generates PDL-capable operators only for NVFP4 1x16 problems with `0 < M <= 256` and logical `N` and `K` in `[1024, 65536]`, excluding the measured regression band `32 < M <= 64` and `2048 < min(N, K) < 4096`. `"0"` disables PDL, while `"1"` forces it for experiments. The policy receives packed FP4 K from `MMKernelInputs` and performs the packed-to-logical conversion internally.
>
> The selected policy is represented in operator metadata and included in generated-precompile, runtime, and persistent-artifact cache identities. Original logical M is also part of specialization when swap-AB changes the physical orientation.
>
> Inside the CuTeDSL provider, an NVGEMM kernel that depends on an earlier launch calls `cute.arch.griddepcontrol_wait()` before consuming dependency-produced inputs. The producer calls `cute.arch.griddepcontrol_launch_dependents()` after issuing its output stores, allowing the dependent grid to begin launch setup while those stores drain. A direct Triton consumer launches with `launch_pdl` and calls `tl.extra.cuda.gdc_wait()` before reading the producer output, preserving completion and visibility. For measured small-K decode shapes, descriptor and layout setup is moved before the wait so independent prologue work overlaps; other shapes retain the conservative early wait.
>
> Scheduler code generation tracks the previous concrete scheduler node independently per device and stream. A Triton launch opts into PDL only when the immediately preceding same-stream node resolves to a selected PDL-capable NVGEMM and the consumer has a true read-after-write dependency on its output. Composite launches, multi-kernel wrappers, workspaces, unsupported reductions, cross-stream consumers, and unrelated nodes retain ordinary launch behavior.
>
> ## Examples
>
> - An eligible NVFP4 decode projection followed directly on the same stream by a Triton cast or add launches the consumer with `launch_pdl` and waits through `gdc_wait`.
> - A consumer on another stream behind an event, or one separated by an unrelated same-stream kernel, uses ordinary stream/event ordering and receives no PDL launch attribute.
>
> ## Performance
>
> Standard `vllm bench latency` runs on GB200 used 32 input tokens, 128 output tokens, 10 warmups, 30 samples, `-O2`, static compilation/CUDA graphs, dummy weights, and tuned FlashInfer 0.6.18.post1 as control. Only vLLM's per-quant `nvfp4_w4a4` linear backend changed; unrelated linears, attention, and sampling remained matched.
>
> These are cumulative complete-stack results, not isolated attribution to this PR:
>
> - Llama-3.1-8B NVFP4: Torch/NVGEMM was 7.81%, 7.42%, 8.29%, and 7.83% faster than tuned FlashInfer at batches 8, 32, 64, and 128.
> - Qwen3-14B NVFP4: Torch/NVGEMM was 5.15%, 5.67%, 7.87%, and 5.23% faster at batches 8, 32, 64, and 128.
> - Nemotron-Nano-9B-v2 NVFP4 revalidation: Torch/NVGEMM was 4.83% faster at batch 32 (5.59% in the adjacent warmed pair), 6.29% faster at batch 64, and within 0.16% at batch 128, which is treated as parity.
> - A Llama batch-64 PDL ablation improved the midpoint of two PDL medians by 7.27% over the intervening no-PDL run. Forced PDL improved four isolated Nemotron decode GEMMs by 11.1%--13.2%; automatic policy excludes the nearby end-to-end regression band.
>
> ## Test Plan
>
> ```bash
> python test/inductor/test_nv_universal_gemm.py -k pdl
> lintrunner -a
> git diff --check
> ```
>
> A focused PDL-chain run passed 11 cases, and the broader heuristic/PDL-metadata run collected 95 cases: 94 passed and 1 skipped. Tests cover policy boundaries, PDL candidate preference and fallback, provider wait/release placement, logical-shape cache specialization, pointer refresh, direct same-stream dependencies, cross-stream event ordering, reductions, deferred copies, composite launches, multi-kernel wrappers, and workspaces.
>
> ## Checklist
>
> - [x] Passes lint
> - [x] Added or updated tests
> - [x] Updated documentation where applicable
> - [x] Included benchmark results
>
> ## BC-breaking?
>
> No. Automatic PDL is shape-scoped; `TORCHINDUCTOR_NVGEMM_PDL=0` and `=1` remain explicit overrides.
>
> PR prepared with assistance from an AI tool.

Pull Request resolved: pytorch#197485
Approved by: https://github.com/karthickai
ghstack dependencies: pytorch#194649, pytorch#194652, pytorch#194651
pytorchmergebot pushed a commit that referenced this pull request Oct 14, 2026
…ed test (#200861)

`test_max_autotune_cutlass_backend_sparse_semi_structured_mm` fails with a
`KeyError` on its inputs key because it reads the autotune local cache with a
key the cache no longer writes. #194649 made `PersistentCache` store timings
under `create_benchmark_cache_key(inputs_key, ...)`, which appends the
benchmark policy (`:benchmark_policy=eager` by default), but this lookup
still uses the bare inputs key. The test now builds the key with the same
helper, inside the `config.patch` block because the policy depends on
`max_autotune`.

This is the only test that reads `LocalCache` directly. OSS CI did not catch
it for the same reason it missed #199248: the test is gated to sm_8x exactly,
and no OSS job runs `test_cutlass_backend.py` on that hardware. It fails in
fbcode, where the file runs on A100.

Test Plan:
On an A100 (sm_80), with CUDA 13.0 `nvcc` on PATH:

```
python test/inductor/test_cutlass_backend.py -k test_max_autotune_cutlass_backend_sparse_semi_structured_mm
```

Fails with `KeyError: "[('cuda', 'torch.float16', 32, 32, 32, 1, 0), ...]"`
before this change and passes after, including with an empty
`TORCHINDUCTOR_CACHE_DIR`.

This PR was authored with the assistance of an AI coding assistant (Claude).

Pull Request resolved: #200861
Approved by: https://github.com/pytorchgreenlight
pytorchmergebot pushed a commit that referenced this pull request Nov 2, 2026
…UDA graphs (#200460)

Author's note: With CUDA-graph autotune benchmarking, multi-kernel candidates launched on the wrong stream and nested lazy-autotune benchmarks were timed eagerly, so the wrong candidate could win. Each fix has a test that fails without it, and both match how `CachingAutotuner.bench` already handles the stream.

The description below was drafted with an AI assistant (Claude):

> With `max_autotune` and `autotune_cudagraph_benchmarking`, two bugs make
> candidates that launch through multi-kernel, or that autotune on their first
> launch, escape graph timing: they are timed eagerly with launch overhead, or
> not at all. Either way the wrong candidate can win.
>
> 1. `MultiKernelCall.benchmark_sub_kernels` forwards the `stream` kwarg it was
>    called with to every candidate launch. The benchmarker captures the callable
>    on a side stream, so the launch escapes the capture: the graph is empty and
>    the candidate times as nearly free, or the capture errors and falls back to
>    eager timing. The stream is now resolved at call time, as
>    `CachingAutotuner.bench` already does (#179246). Outside of capture the
>    current stream is the one that was passed in, so eager benchmarking is
>    unchanged.
>
> 2. `InductorBenchmarker.benchmark_gpu` times GPU callables through
>    `benchmark_gpu_with_cuda_graph`: warmup, capture, then
>    `self.benchmark_gpu(cuda_graph.replay)`. `_in_cudagraph_benchmark` (a
>    thread-local depth since #194649) exists so that last call times the replay
>    directly instead of capturing it again, but the `InductorBenchmarker`
>    override raised it for the whole method, warmup included. A callable that autotunes on its first launch benchmarks other
>    callables during that warmup, and those nested benchmarks saw the flag and
>    were timed eagerly. Two callers hit this:
>    `MultiKernelCall.benchmark_sub_kernels`, which times `CachingAutotuner.run`
>    on sub-kernels that have not picked a config yet, and
>    `SubgraphChoiceCaller.benchmark`, which times a compiled module whose
>    kernels autotune on first call and calls `benchmark_gpu_with_cuda_graph`
>    directly. The thread-local depth now moves to the base `Benchmarker`, and
>    `benchmark_gpu_with_cuda_graph` raises it only around the replay timing;
>    the `InductorBenchmarker` override is dropped.
>
>    An alternative is running the callable once before entering the graph path,
>    so lazy autotuning finishes first. That adds a launch to every graph-mode
>    benchmark and misses the direct `benchmark_gpu_with_cuda_graph` caller.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_benchmarking.py test/inductor/test_multi_kernel.py test/inductor/test_static_triton_launcher.py test/inductor/test_custom_op_autotune.py
> ```
> `test_benchmark_sub_kernels_captures_on_current_stream` captures a candidate in
> a real CUDA graph and checks that replay runs it; it fails without fix 1.
> `test_benchmark_gpu_with_cuda_graph_nested_benchmark_uses_graph` fails when the
> flag covers the whole method (the nested benchmark is timed eagerly). On
> MI300X, compiling a softmax with `triton.multi_kernel=1`, the 10 sub-kernel
> config benchmarks run eagerly before this change and through graph capture
> after it.
>
> This change was prepared with an AI assistant.

Pull Request resolved: #200460
Approved by: https://github.com/drisspg
ghstack dependencies: #200459
pytorchmergebot pushed a commit that referenced this pull request Nov 3, 2026
…UDA graphs (#200460)

Author's note: With CUDA-graph autotune benchmarking, multi-kernel candidates launched on the wrong stream and nested lazy-autotune benchmarks were timed eagerly, so the wrong candidate could win. Each fix has a test that fails without it, and both match how `CachingAutotuner.bench` already handles the stream.

The description below was drafted with an AI assistant (Claude):

> With `max_autotune` and `autotune_cudagraph_benchmarking`, two bugs make
> candidates that launch through multi-kernel, or that autotune on their first
> launch, escape graph timing: they are timed eagerly with launch overhead, or
> not at all. Either way the wrong candidate can win.
>
> 1. `MultiKernelCall.benchmark_sub_kernels` forwards the `stream` kwarg it was
>    called with to every candidate launch. The benchmarker captures the callable
>    on a side stream, so the launch escapes the capture: the graph is empty and
>    the candidate times as nearly free, or the capture errors and falls back to
>    eager timing. The stream is now resolved at call time, as
>    `CachingAutotuner.bench` already does (#179246). Outside of capture the
>    current stream is the one that was passed in, so eager benchmarking is
>    unchanged.
>
> 2. `InductorBenchmarker.benchmark_gpu` times GPU callables through
>    `benchmark_gpu_with_cuda_graph`: warmup, capture, then
>    `self.benchmark_gpu(cuda_graph.replay)`. `_in_cudagraph_benchmark` (a
>    thread-local depth since #194649) exists so that last call times the replay
>    directly instead of capturing it again, but the `InductorBenchmarker`
>    override raised it for the whole method, warmup included. A callable that autotunes on its first launch benchmarks other
>    callables during that warmup, and those nested benchmarks saw the flag and
>    were timed eagerly. Two callers hit this:
>    `MultiKernelCall.benchmark_sub_kernels`, which times `CachingAutotuner.run`
>    on sub-kernels that have not picked a config yet, and
>    `SubgraphChoiceCaller.benchmark`, which times a compiled module whose
>    kernels autotune on first call and calls `benchmark_gpu_with_cuda_graph`
>    directly. The thread-local depth now moves to the base `Benchmarker`, and
>    `benchmark_gpu_with_cuda_graph` raises it only around the replay timing;
>    the `InductorBenchmarker` override is dropped.
>
>    An alternative is running the callable once before entering the graph path,
>    so lazy autotuning finishes first. That adds a launch to every graph-mode
>    benchmark and misses the direct `benchmark_gpu_with_cuda_graph` caller.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_benchmarking.py test/inductor/test_multi_kernel.py test/inductor/test_static_triton_launcher.py test/inductor/test_custom_op_autotune.py
> ```
> `test_benchmark_sub_kernels_captures_on_current_stream` captures a candidate in
> a real CUDA graph and checks that replay runs it; it fails without fix 1.
> `test_benchmark_gpu_with_cuda_graph_nested_benchmark_uses_graph` fails when the
> flag covers the whole method (the nested benchmark is timed eagerly). On
> MI300X, compiling a softmax with `triton.multi_kernel=1`, the 10 sub-kernel
> config benchmarks run eagerly before this change and through graph capture
> after it.
>
> This change was prepared with an AI assistant.

Pull Request resolved: #200460
Approved by: https://github.com/drisspg
ghstack dependencies: #200459
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…UDA graphs (pytorch#200460)

Author's note: With CUDA-graph autotune benchmarking, multi-kernel candidates launched on the wrong stream and nested lazy-autotune benchmarks were timed eagerly, so the wrong candidate could win. Each fix has a test that fails without it, and both match how `CachingAutotuner.bench` already handles the stream.

The description below was drafted with an AI assistant (Claude):

> With `max_autotune` and `autotune_cudagraph_benchmarking`, two bugs make
> candidates that launch through multi-kernel, or that autotune on their first
> launch, escape graph timing: they are timed eagerly with launch overhead, or
> not at all. Either way the wrong candidate can win.
>
> 1. `MultiKernelCall.benchmark_sub_kernels` forwards the `stream` kwarg it was
>    called with to every candidate launch. The benchmarker captures the callable
>    on a side stream, so the launch escapes the capture: the graph is empty and
>    the candidate times as nearly free, or the capture errors and falls back to
>    eager timing. The stream is now resolved at call time, as
>    `CachingAutotuner.bench` already does (pytorch#179246). Outside of capture the
>    current stream is the one that was passed in, so eager benchmarking is
>    unchanged.
>
> 2. `InductorBenchmarker.benchmark_gpu` times GPU callables through
>    `benchmark_gpu_with_cuda_graph`: warmup, capture, then
>    `self.benchmark_gpu(cuda_graph.replay)`. `_in_cudagraph_benchmark` (a
>    thread-local depth since pytorch#194649) exists so that last call times the replay
>    directly instead of capturing it again, but the `InductorBenchmarker`
>    override raised it for the whole method, warmup included. A callable that autotunes on its first launch benchmarks other
>    callables during that warmup, and those nested benchmarks saw the flag and
>    were timed eagerly. Two callers hit this:
>    `MultiKernelCall.benchmark_sub_kernels`, which times `CachingAutotuner.run`
>    on sub-kernels that have not picked a config yet, and
>    `SubgraphChoiceCaller.benchmark`, which times a compiled module whose
>    kernels autotune on first call and calls `benchmark_gpu_with_cuda_graph`
>    directly. The thread-local depth now moves to the base `Benchmarker`, and
>    `benchmark_gpu_with_cuda_graph` raises it only around the replay timing;
>    the `InductorBenchmarker` override is dropped.
>
>    An alternative is running the callable once before entering the graph path,
>    so lazy autotuning finishes first. That adds a launch to every graph-mode
>    benchmark and misses the direct `benchmark_gpu_with_cuda_graph` caller.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_benchmarking.py test/inductor/test_multi_kernel.py test/inductor/test_static_triton_launcher.py test/inductor/test_custom_op_autotune.py
> ```
> `test_benchmark_sub_kernels_captures_on_current_stream` captures a candidate in
> a real CUDA graph and checks that replay runs it; it fails without fix 1.
> `test_benchmark_gpu_with_cuda_graph_nested_benchmark_uses_graph` fails when the
> flag covers the whole method (the nested benchmark is timed eagerly). On
> MI300X, compiling a softmax with `triton.multi_kernel=1`, the 10 sub-kernel
> config benchmarks run eagerly before this change and through graph capture
> after it.
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200460
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…UDA graphs (pytorch#200460)

Author's note: With CUDA-graph autotune benchmarking, multi-kernel candidates launched on the wrong stream and nested lazy-autotune benchmarks were timed eagerly, so the wrong candidate could win. Each fix has a test that fails without it, and both match how `CachingAutotuner.bench` already handles the stream.

The description below was drafted with an AI assistant (Claude):

> With `max_autotune` and `autotune_cudagraph_benchmarking`, two bugs make
> candidates that launch through multi-kernel, or that autotune on their first
> launch, escape graph timing: they are timed eagerly with launch overhead, or
> not at all. Either way the wrong candidate can win.
>
> 1. `MultiKernelCall.benchmark_sub_kernels` forwards the `stream` kwarg it was
>    called with to every candidate launch. The benchmarker captures the callable
>    on a side stream, so the launch escapes the capture: the graph is empty and
>    the candidate times as nearly free, or the capture errors and falls back to
>    eager timing. The stream is now resolved at call time, as
>    `CachingAutotuner.bench` already does (pytorch#179246). Outside of capture the
>    current stream is the one that was passed in, so eager benchmarking is
>    unchanged.
>
> 2. `InductorBenchmarker.benchmark_gpu` times GPU callables through
>    `benchmark_gpu_with_cuda_graph`: warmup, capture, then
>    `self.benchmark_gpu(cuda_graph.replay)`. `_in_cudagraph_benchmark` (a
>    thread-local depth since pytorch#194649) exists so that last call times the replay
>    directly instead of capturing it again, but the `InductorBenchmarker`
>    override raised it for the whole method, warmup included. A callable that autotunes on its first launch benchmarks other
>    callables during that warmup, and those nested benchmarks saw the flag and
>    were timed eagerly. Two callers hit this:
>    `MultiKernelCall.benchmark_sub_kernels`, which times `CachingAutotuner.run`
>    on sub-kernels that have not picked a config yet, and
>    `SubgraphChoiceCaller.benchmark`, which times a compiled module whose
>    kernels autotune on first call and calls `benchmark_gpu_with_cuda_graph`
>    directly. The thread-local depth now moves to the base `Benchmarker`, and
>    `benchmark_gpu_with_cuda_graph` raises it only around the replay timing;
>    the `InductorBenchmarker` override is dropped.
>
>    An alternative is running the callable once before entering the graph path,
>    so lazy autotuning finishes first. That adds a launch to every graph-mode
>    benchmark and misses the direct `benchmark_gpu_with_cuda_graph` caller.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_benchmarking.py test/inductor/test_multi_kernel.py test/inductor/test_static_triton_launcher.py test/inductor/test_custom_op_autotune.py
> ```
> `test_benchmark_sub_kernels_captures_on_current_stream` captures a candidate in
> a real CUDA graph and checks that replay runs it; it fails without fix 1.
> `test_benchmark_gpu_with_cuda_graph_nested_benchmark_uses_graph` fails when the
> flag covers the whole method (the nested benchmark is timed eagerly). On
> MI300X, compiling a softmax with `triton.multi_kernel=1`, the 10 sub-kernel
> config benchmarks run eagerly before this change and through graph capture
> after it.
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200460
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…UDA graphs (pytorch#200460)

Author's note: With CUDA-graph autotune benchmarking, multi-kernel candidates launched on the wrong stream and nested lazy-autotune benchmarks were timed eagerly, so the wrong candidate could win. Each fix has a test that fails without it, and both match how `CachingAutotuner.bench` already handles the stream.

The description below was drafted with an AI assistant (Claude):

> With `max_autotune` and `autotune_cudagraph_benchmarking`, two bugs make
> candidates that launch through multi-kernel, or that autotune on their first
> launch, escape graph timing: they are timed eagerly with launch overhead, or
> not at all. Either way the wrong candidate can win.
>
> 1. `MultiKernelCall.benchmark_sub_kernels` forwards the `stream` kwarg it was
>    called with to every candidate launch. The benchmarker captures the callable
>    on a side stream, so the launch escapes the capture: the graph is empty and
>    the candidate times as nearly free, or the capture errors and falls back to
>    eager timing. The stream is now resolved at call time, as
>    `CachingAutotuner.bench` already does (pytorch#179246). Outside of capture the
>    current stream is the one that was passed in, so eager benchmarking is
>    unchanged.
>
> 2. `InductorBenchmarker.benchmark_gpu` times GPU callables through
>    `benchmark_gpu_with_cuda_graph`: warmup, capture, then
>    `self.benchmark_gpu(cuda_graph.replay)`. `_in_cudagraph_benchmark` (a
>    thread-local depth since pytorch#194649) exists so that last call times the replay
>    directly instead of capturing it again, but the `InductorBenchmarker`
>    override raised it for the whole method, warmup included. A callable that autotunes on its first launch benchmarks other
>    callables during that warmup, and those nested benchmarks saw the flag and
>    were timed eagerly. Two callers hit this:
>    `MultiKernelCall.benchmark_sub_kernels`, which times `CachingAutotuner.run`
>    on sub-kernels that have not picked a config yet, and
>    `SubgraphChoiceCaller.benchmark`, which times a compiled module whose
>    kernels autotune on first call and calls `benchmark_gpu_with_cuda_graph`
>    directly. The thread-local depth now moves to the base `Benchmarker`, and
>    `benchmark_gpu_with_cuda_graph` raises it only around the replay timing;
>    the `InductorBenchmarker` override is dropped.
>
>    An alternative is running the callable once before entering the graph path,
>    so lazy autotuning finishes first. That adds a launch to every graph-mode
>    benchmark and misses the direct `benchmark_gpu_with_cuda_graph` caller.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_benchmarking.py test/inductor/test_multi_kernel.py test/inductor/test_static_triton_launcher.py test/inductor/test_custom_op_autotune.py
> ```
> `test_benchmark_sub_kernels_captures_on_current_stream` captures a candidate in
> a real CUDA graph and checks that replay runs it; it fails without fix 1.
> `test_benchmark_gpu_with_cuda_graph_nested_benchmark_uses_graph` fails when the
> flag covers the whole method (the nested benchmark is timed eagerly). On
> MI300X, compiling a softmax with `triton.multi_kernel=1`, the 10 sub-kernel
> config benchmarks run eagerly before this change and through graph capture
> after it.
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200460
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…UDA graphs (pytorch#200460)

Author's note: With CUDA-graph autotune benchmarking, multi-kernel candidates launched on the wrong stream and nested lazy-autotune benchmarks were timed eagerly, so the wrong candidate could win. Each fix has a test that fails without it, and both match how `CachingAutotuner.bench` already handles the stream.

The description below was drafted with an AI assistant (Claude):

> With `max_autotune` and `autotune_cudagraph_benchmarking`, two bugs make
> candidates that launch through multi-kernel, or that autotune on their first
> launch, escape graph timing: they are timed eagerly with launch overhead, or
> not at all. Either way the wrong candidate can win.
>
> 1. `MultiKernelCall.benchmark_sub_kernels` forwards the `stream` kwarg it was
>    called with to every candidate launch. The benchmarker captures the callable
>    on a side stream, so the launch escapes the capture: the graph is empty and
>    the candidate times as nearly free, or the capture errors and falls back to
>    eager timing. The stream is now resolved at call time, as
>    `CachingAutotuner.bench` already does (pytorch#179246). Outside of capture the
>    current stream is the one that was passed in, so eager benchmarking is
>    unchanged.
>
> 2. `InductorBenchmarker.benchmark_gpu` times GPU callables through
>    `benchmark_gpu_with_cuda_graph`: warmup, capture, then
>    `self.benchmark_gpu(cuda_graph.replay)`. `_in_cudagraph_benchmark` (a
>    thread-local depth since pytorch#194649) exists so that last call times the replay
>    directly instead of capturing it again, but the `InductorBenchmarker`
>    override raised it for the whole method, warmup included. A callable that autotunes on its first launch benchmarks other
>    callables during that warmup, and those nested benchmarks saw the flag and
>    were timed eagerly. Two callers hit this:
>    `MultiKernelCall.benchmark_sub_kernels`, which times `CachingAutotuner.run`
>    on sub-kernels that have not picked a config yet, and
>    `SubgraphChoiceCaller.benchmark`, which times a compiled module whose
>    kernels autotune on first call and calls `benchmark_gpu_with_cuda_graph`
>    directly. The thread-local depth now moves to the base `Benchmarker`, and
>    `benchmark_gpu_with_cuda_graph` raises it only around the replay timing;
>    the `InductorBenchmarker` override is dropped.
>
>    An alternative is running the callable once before entering the graph path,
>    so lazy autotuning finishes first. That adds a launch to every graph-mode
>    benchmark and misses the direct `benchmark_gpu_with_cuda_graph` caller.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_benchmarking.py test/inductor/test_multi_kernel.py test/inductor/test_static_triton_launcher.py test/inductor/test_custom_op_autotune.py
> ```
> `test_benchmark_sub_kernels_captures_on_current_stream` captures a candidate in
> a real CUDA graph and checks that replay runs it; it fails without fix 1.
> `test_benchmark_gpu_with_cuda_graph_nested_benchmark_uses_graph` fails when the
> flag covers the whole method (the nested benchmark is timed eagerly). On
> MI300X, compiling a softmax with `triton.multi_kernel=1`, the 10 sub-kernel
> config benchmarks run eagerly before this change and through graph capture
> after it.
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200460
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459
@github-actions
github-actions Bot deleted the gh/mlazos/308/head branch December 3, 2026 02:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor release notes: inductor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants