Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/194651
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 9bd0fff with merge base ee0d01e ( 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. |
This was referenced Aug 24, 2026
Contributor
Author
AI-Review
Verified Issues
|
This was referenced Aug 25, 2026
mlazos
added a commit
that referenced
this pull request
Sep 22, 2026
Human commentary: ModelOpt NVFP4 linear layers multiply `_scaled_mm` output by a scalar dequantization factor, and that multiply can be represented directly by the selected GEMM implementation. AI-assisted content: > ## Issue > > Fixes #198173 > > ## Summary > > A scalar tensor multiply immediately after `aten._scaled_mm` is emitted as a > separate operation, including before QKV-style split/view fan-out. Folding only > the NVGEMM choice would either discard configured alternatives or compare > candidates with different semantics and timing policies. > > ## Architecture > > Recognize an eligible zero-dimensional CUDA FP32 tensor multiply, rewrite it > into a synthesized `_scaled_mm(..., scale_result=...)` node, and mark that node > as compiler-created. Carry the scale tensor through IR, > candidate construction, subprocess precompile, cache specialization, swapped > operands, and runtime pointer refresh. NVGEMM providers advertise native ABI > support explicitly. > > For mixed `ATEN,NVGEMM` tuning, add an equivalent ATen extern choice that > performs `_scaled_mm` and the multiply as one candidate and receives the same > request-level replay/cold-cache policy. If the folded choices fail, return to > ordinary lowering. Other configured GEMM backends are never silently removed. > > The fold is restricted to the NVFP4 1x16 recipe and preserves public > `scale_result`, bias, shared-output, scalar, rounding, and overflow semantics. > Tensor-parallel handling uses the real structural all-gather/reduce-scatter > eligibility checks instead of disabling the fold whenever TP is enabled. > > ## 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) > ``` > > The output scale is carried into the selected implementation before the views > are formed. With `ATEN,NVGEMM`, both candidates implement the same result. > > ## Performance and test plan > > Measurements below used a GB200 and vLLM > `5302d1fe40e6969b854e0ab288d34825653767c6` with Llama-3.1-8B NVFP4 at > batch 64, 32 input tokens, 128 output tokens, static compilation/CUDA graphs, > and unlocked GPU clocks. Graph spans and node counts came from the same > steady-state captured decode graph. > > On Llama-3.1-8B batch 64, the fold removed 32 separate output-scale launches > per decode step: the CUDA graph fell from 481 to 449 nodes. Representative > steady graph spans improved from 2.232--2.237 ms to 2.175--2.180 ms. This is > the direct mechanism measurement; model-level numbers also include later > autotuning and PDL commits. > > - Coverage includes split/view fan-out, swapped operands, CUDA-graph pointer > refresh, generated and worker precompile metadata, shared outputs, literal > and non-scalar rejection, public `scale_result`, fallback, and mixed backends. > - TP tests cover eligible all-gather preservation and unmatched or unsupported > collective cases. > - `python test/inductor/test_compile_worker.py TestSubprocessEnv -v` > - `python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemm -v` > - `python test/distributed/tensor/parallel/test_micro_pipeline_tp.py -v` > - `git diff --check origin/main...HEAD` > - `spin fixlint` > - `spin quicklint` > > ## Checklist > > - [ ] Passes lint (`spin fixlint` child linter is clean; local wrapper error) > - [x] Added/updated tests > - [x] Updated documentation (if applicable) > - [x] Included benchmark results (for PRs impacting perf) > > ## BC-breaking? > > No. > > PR prepared with assistance from an AI tool. ghstack-source-id: 26d30df Pull-Request: #194651
mlazos
added a commit
that referenced
this pull request
Sep 22, 2026
Human commentary: ModelOpt NVFP4 linear layers multiply `_scaled_mm` output by a scalar dequantization factor, and that multiply can be represented directly by the selected GEMM implementation. AI-assisted content: > ## Issue > > Fixes #198173 > > ## Summary > > A scalar tensor multiply immediately after `aten._scaled_mm` is emitted as a > separate operation, including before QKV-style split/view fan-out. Folding only > the NVGEMM choice would either discard configured alternatives or compare > candidates with different semantics and timing policies. > > ## Architecture > > Recognize an eligible zero-dimensional CUDA FP32 tensor multiply, rewrite it > into a synthesized `_scaled_mm(..., scale_result=...)` node, and mark that node > as compiler-created. Carry the scale tensor through IR, > candidate construction, subprocess precompile, cache specialization, swapped > operands, and runtime pointer refresh. NVGEMM providers advertise native ABI > support explicitly. > > For mixed `ATEN,NVGEMM` tuning, add an equivalent ATen extern choice that > performs `_scaled_mm` and the multiply as one candidate and receives the same > request-level replay/cold-cache policy. If the folded choices fail, return to > ordinary lowering. Other configured GEMM backends are never silently removed. > > The fold is restricted to the NVFP4 1x16 recipe and preserves public > `scale_result`, bias, shared-output, scalar, rounding, and overflow semantics. > Tensor-parallel handling uses the real structural all-gather/reduce-scatter > eligibility checks instead of disabling the fold whenever TP is enabled. > > ## 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) > ``` > > The output scale is carried into the selected implementation before the views > are formed. With `ATEN,NVGEMM`, both candidates implement the same result. > > ## Performance and test plan > > Measurements below used a GB200 and vLLM > `5302d1fe40e6969b854e0ab288d34825653767c6` with Llama-3.1-8B NVFP4 at > batch 64, 32 input tokens, 128 output tokens, static compilation/CUDA graphs, > and unlocked GPU clocks. Graph spans and node counts came from the same > steady-state captured decode graph. > > On Llama-3.1-8B batch 64, the fold removed 32 separate output-scale launches > per decode step: the CUDA graph fell from 481 to 449 nodes. Representative > steady graph spans improved from 2.232--2.237 ms to 2.175--2.180 ms. This is > the direct mechanism measurement; model-level numbers also include later > autotuning and PDL commits. > > - Coverage includes split/view fan-out, swapped operands, CUDA-graph pointer > refresh, generated and worker precompile metadata, shared outputs, literal > and non-scalar rejection, public `scale_result`, fallback, and mixed backends. > - TP tests cover eligible all-gather preservation and unmatched or unsupported > collective cases. > - `python test/inductor/test_compile_worker.py TestSubprocessEnv -v` > - `python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemm -v` > - `python test/distributed/tensor/parallel/test_micro_pipeline_tp.py -v` > - `git diff --check origin/main...HEAD` > - `spin fixlint` > - `spin quicklint` > > ## Checklist > > - [ ] Passes lint (`spin fixlint` child linter is clean; local wrapper error) > - [x] Added/updated tests > - [x] Updated documentation (if applicable) > - [x] Included benchmark results (for PRs impacting perf) > > ## BC-breaking? > > No. > > PR prepared with assistance from an AI tool. ghstack-source-id: 26d30df Pull-Request: #194651
karthickai
approved these changes
Oct 1, 2026
Collaborator
|
Starting merge as part of PR stack under #197485 |
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
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stack from ghstack (oldest at bottom):
Human commentary: ModelOpt NVFP4 linear layers multiply
_scaled_mmoutput 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:
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo