Skip to content

[inductor][NVGEMM] Cover epilogue providers and share reduction metadata - #192298

Closed
mlazos wants to merge 22 commits into
gh/mlazos/297/basefrom
gh/mlazos/297/head
Closed

mlazos wants to merge 22 commits into
gh/mlazos/297/basefrom
gh/mlazos/297/head

Conversation

@mlazos

@mlazos mlazos commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Wire scheduler Loop IR epilogue plans into NVGEMM fusion and CuTeDSL code
generation. When the scheduler considers another node, NVGEMM reinterprets
the complete candidate prefix, validates that every reduction is claimed, and
accepts the node only when the resulting program has a supported lowering.

LoopIRCuteDSLCodegen replays the captured expressions through CuTeDSL
operation overrides to generate the tensor epilogue and any source, combine,
finalize, or consumer callbacks. Dense and block-scaled providers consume the
same generated contract.

Reduction selection is based on captured IR and geometry, not an algorithm
name. The reduction kind identifies only the associative primitive. A
fragment-local composition can contain multiple reductions and pointwise
operations and returns its local result from the generated epilogue. Geometry
that requires cross-thread work receives generated combine and finalize
callbacks; the kernel supplies only the physical reduction mechanism.

Centralize reduction geometry and capability checks so NVGEMM and FlexGEMM
share the same primitive reduction contract, cache specialization, and safe
fallback behavior. Add focused coverage for callback generation, provider
support, cache keys, and unsupported patterns.

Reduction representation

flowchart TD
    NODES["Candidate scheduler nodes"] --> CAPTURE["NVGemmEpilogueCapture"]
    CAPTURE --> PROGRAM["NVGemmEpilogueProgram<br/>captured expressions + reduction regions"]
    PROGRAM --> PLAN["GemmReductionPlan"]

    PLAN --> MODE{"Reduction representation"}
    MODE -->|"Kernel reduction"| PHYSICAL["reduction_type + source_fn<br/>optional finalizer and consumers"]
    MODE -->|"Generated tensor reduction"| GENERATED["tensor epilogue computes the local result<br/>optional combine/finalize callbacks"]

    PHYSICAL --> NVARGS["GemmReductionArguments<br/>runtime tensors + specialization fields"]
    GENERATED --> NVARGS
    NVARGS --> NVKERNEL["Dense or block-scaled NVGEMM kernel"]

    FX["FlexGEMM FX body"] --> FXANALYSIS["GemmLocalReduceAnalysis"]
    FXANALYSIS --> PLAN
    PLAN --> FLEXCFG["FlexGemmEpilogueLocalReduceConfig"]
    FLEXCFG --> FLEXRT["FlexGemmRuntimeLocalReducePlan"]
    FLEXRT --> FLEXKERNEL["FlexGEMM / QuACK"]
Loading

The shared GemmReductionPlan records:

  • group and axis: the logical reduction geometry;
  • reduction_type: only the associative primitive (sum, mean, prod,
    max, or min);
  • source_fn: the generated transformation applied before a physical
    reduction;
  • combine_fn and finalizer_fn: generated callbacks needed when partial
    results cross fragments or threads;
  • consumer_fn and secondary_consumer_fn: generated operations that consume
    the reduced value;
  • reduction_output, feed_output, and secondary_feed_output: output
    ownership; and
  • tensor_epilogue_returns_local_reduce: whether the generated tensor
    epilogue computes the fragment-local reduction itself.

There are two valid forms:

Form Representation
Kernel-driven reduction source_fn computes each value and reduction_type specifies how the kernel combines those values. The kernel handles traversal and synchronization.
Generated tensor reduction reduction_type and source_fn are None; the generated tensor epilogue computes the local reduction and returns it. A generated combine_fn is supplied only when the geometry requires cross-fragment combination.

NVGEMM converts the shared plan to GemmReductionArguments, replacing buffer
names with runtime tensors and including the semantic fields in cache
specialization. FlexGEMM wraps the same plan with its output index, output
layout, and operand-swap state, then renders its existing runtime reduction
plan and callbacks.

Multiple compatible fragment-local reductions and their pointwise consumers
remain encoded in the generated epilogue expression. There is no string or
enum selecting a composite algorithm; reduction_type identifies only the
associative primitive.

Test Plan

PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmHeuristics -v
PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_flex_gemm.py TestFlexGemmRuntimeHelpers -v
lintrunner -a

Description drafted with an AI assistant.

cc @albanD @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 6, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 1 Unrelated Failure

As of commit 3665326 with merge base 3ee461f (image):

NEW FAILURE - The following job has failed:

  • Lint / pr-sanity-checks (gh)
    LOC which is more than the 2000 maximum

    AI verdict: AI verdict: related

    The pr-sanity-checks job fails because the PR is 2459 LOC, exceeding the 2000 LOC maximum. This is directly caused by the size of the code changes in this commit.

    Full reasoning on HUD →

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

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

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

@pytorch-bot

pytorch-bot Bot commented Aug 6, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@mlazos

mlazos commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor Author

AI-Review

Automated multi-agent review (2 Claude + 2 Codex + GPT-5.6 verification). This is AI-generated — please verify findings manually.


Verified Issues

  • [high] Dense EFC reduction ABI is misaligned — Location: gemm_epilogue_codegen.py:GemmReductionCompileConfig.constexprs and vendored_templates/cutedsl/dense_gemm_efc.py:PersistentDenseGemmEFCKernel.__call__. Trigger: any dense NVGEMM epilogue-fusion kernel. Failure sequence: the serializer emits 11 fields in the new order, while the kernel still expects the old 12-field ABI; every field after axis shifts and the first epilogue parameter is consumed as a reduction callback. Impact: dense EFC kernels fail compilation or execute invalid reduction paths. Reviewers: Codex Bug Review.

  • [high] Generated TensorSSA reductions are not emitted into the epilogue result — Location: epilogue_lowering.py:_generated_epilogue_reduction_plan, nv_universal_gemm_scheduling.py:codegen_template, and dense_blockscaled_gemm_persistent.py:1773. Trigger: a scaled GEMM followed by a compressed manually unrolled reduction such as summing four grouped elements. Failure sequence: lowering creates a tensor-return reduction plan and removes the reduction node from pointwise_nodes, but codegen neither passes generated_reduction_geometries nor suppresses/emits the hidden reduction output. The kernel then interprets an ordinary accumulator result as that hidden output. Impact: the requested reduction is not computed, producing invalid generated code or incorrect output. Reviewers: Codex Bug Review.

  • [high] Remapped reduction-consumer loads silently use the wrong element — Location: epilogue_lowering.py:_feed_main_config/_feed_plan and loop_ir_cutedsl_codegen.py:consumer_from_buffer. Trigger: a feed-main consumer reads a same-shaped reduction through a transpose or other index remapping. Failure sequence: matching compares only buffer names and shapes; consumer_from_buffer replaces every load of the reduction buffer with the current group’s scalar and discards its load index. Impact: the fused kernel silently computes with r[i,j] instead of the requested remapped value such as r[j,i]. Reviewers: Codex Bug Review.

  • [medium] Reduction groups unsupported by available block-scaled kernels pass fusion checks — Location: epilogue_capabilities.py:NVGemmReductionCapabilities.supports_contract, nv_universal_gemm_scheduling.py:_can_fuse_epilogue_impl/get_nv_gemm_buffer_from_node, and dense_blockscaled_gemm_kernel.py:_supports. Trigger: for example, an M-axis block-scaled reduction with group 128, or an N-axis group larger than every available tile. Failure sequence: the shared capability check accepts any power-of-two group, fusion succeeds, and rejection occurs only during kernel selection/provider validation. Impact: compilation fails instead of declining fusion; pinned undersized choices may also be replaced and benchmarked under the wrong choice identity. Reviewers: Claude Bug Review and Codex Bug Review.

[ghstack-poisoned]
@mlazos
mlazos requested a review from drisspg August 7, 2026 07:10
mlazos added a commit that referenced this pull request Aug 7, 2026
Add focused coverage for the vendored NVGEMM epilogue providers. This commit
also establishes the backend-neutral grouped-reduction metadata used by the
following scheduler-lowering change, keeping that PR below the repository size
limit without weakening its contracts.

Test Plan:

```text
python test/inductor/test_nv_universal_gemm.py -v
python test/inductor/test_flex_gemm.py -v
lintrunner -a
```

Authored with an AI assistant.

ghstack-source-id: 8408045
Pull-Request: #192298
mlazos added a commit that referenced this pull request Aug 11, 2026
Add focused coverage for the vendored NVGEMM epilogue providers. This commit
also establishes the backend-neutral grouped-reduction metadata used by the
following scheduler-lowering change, keeping that PR below the repository size
limit without weakening its contracts.

Test Plan:

```text
python test/inductor/test_nv_universal_gemm.py -v
python test/inductor/test_flex_gemm.py -v
lintrunner -a
```

Authored with an AI assistant.

ghstack-source-id: 8408045
Pull-Request: #192298
[ghstack-poisoned]
mlazos added 6 commits August 11, 2026 02:31
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
mlazos added a commit that referenced this pull request Aug 12, 2026
Add focused coverage for the vendored NVGEMM epilogue providers. This commit
also establishes the backend-neutral grouped-reduction metadata used by the
following scheduler-lowering change, keeping that PR below the repository size
limit without weakening its contracts.

Test Plan:

```text
python test/inductor/test_nv_universal_gemm.py -v
python test/inductor/test_flex_gemm.py -v
lintrunner -a
```

Authored with an AI assistant.

ghstack-source-id: c3f392d
Pull-Request: #192298
[ghstack-poisoned]
mlazos added a commit that referenced this pull request Aug 18, 2026
Add focused coverage for the vendored NVGEMM epilogue providers. This commit
also establishes the backend-neutral grouped-reduction metadata used by the
following scheduler-lowering change, keeping that PR below the repository size
limit without weakening its contracts.

Test Plan:

```text
python test/inductor/test_nv_universal_gemm.py -v
python test/inductor/test_flex_gemm.py -v
lintrunner -a
```

Authored with an AI assistant.

ghstack-source-id: f0bed0d
Pull-Request: #192298
[ghstack-poisoned]
mlazos added 2 commits August 31, 2026 21:56
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #192928

1 similar comment
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #192928

pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
<human note needed>

> Add scheduler hooks that let a CUDA template backend keep a validated
> reduction region together during fusion. Reduction-pair compatibility and
> reduction-epilogue decisions are delegated to the backend before generic
> fusion can consume only part of the region.
>
> NVGEMM uses these hooks to prioritize supported reduction chains, reject
> conflicting partial fusions, and keep NVGEMM boolean outputs out of unrelated
> horizontal fusion. The Loop IR capture and validation logic lives in the
> preceding commits; this commit only adds the scheduler coordination needed to
> treat its result atomically.
>
> ## Test Plan
>
> ```bash
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.
Pull Request resolved: #190822
Approved by: https://github.com/drisspg
ghstack dependencies: #192298
pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
prepares dense kernel for direct cutedsl codegen (instead of EVT)

> This updates the vendored dense matrix-multiply kernel so it can run the
> post-processing function generated directly by Inductor. It maps captured
> tensors such as biases into the layout expected by the kernel, exposes the
> operations used by the generated function, and stores each requested output.
>
> The older metadata format remains supported in this commit so the kernel
> change can land separately from the scheduler change that starts using the
> direct path.
>
> ## Example
>
> The direct epilogue represents a computation such as:
>
> ```python
> def fn(a, b, bias):
>     return torch.relu((a @ b) + bias)
> ```
>
> Given generated source for this epilogue, the adapter maps the bias into the
> dense kernel's broadcast layout, evaluates the addition and ReLU, and stores
> the result. This commit teaches the provider to accept that direct function;
> the following commit switches scheduler selection from the older CUTLASS
> expression-graph representation to this path.
>
> ## Test Plan
>
> ```bash
> CUDA_VISIBLE_DEVICES=0 TORCHINDUCTOR_COMPILE_THREADS=1 python test/inductor/test_nv_universal_gemm.py -k matmul_pointwise_epilogue_fusion -v
> CUDA_VISIBLE_DEVICES=0 TORCHINDUCTOR_COMPILE_THREADS=1 python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmEpilogueFusion.test_matmul_multi_store_epilogue_fusion -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.
Pull Request resolved: #191514
Approved by: https://github.com/drisspg
ghstack dependencies: #192298, #190822
pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
…191515)

> Enable shared Loop IR to CuTeDSL lowering for dense NVGEMM epilogues. The
> scheduler selects generated CuTeDSL source when the complete captured
> expression is supported and retains CUTLASS EVT lowering as the fallback.
>
> Preserve captured input dtypes and broadcast layouts, compose bias through
> the same epilogue plan, reuse common subexpressions, and reject unsupported
> operand swaps or reduction layouts before selecting the direct path.
>
> ## Example
>
> ```python
> result = (a @ b).float()
> return torch.relu(result), result + bias
> ```
>
> Both stores are generated from one captured Loop IR program. Expressions that
> cannot be represented by the direct path continue through EVT.
>
> ## Test Plan
>
> ```bash
> PYTORCH_WORKTREE=$PWD env -u PYTHONPATH python agent_space/run_worktree_python.py test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmEpilogueFusion.test_matmul_multi_store_epilogue_fusion -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: #191515
Approved by: https://github.com/drisspg
ghstack dependencies: #192298, #190822, #191514
pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
> Add focused parity coverage for generated CuTeDSL callbacks across dense and
> block-scaled grouped reductions. The tests cover both reduction axes,
> primitive and pointwise-transformed sources, multiple reductions in one
> epilogue, reduction consumers, and finalization after cross-warp combination.
>
> Keep the transposed output layout explicit when NVGEMM swaps the GEMM operands.
> Let FlexGEMM request the broader tuned NVGEMM configuration while rejecting
> unsupported NVGEMM options.
>
> ## Test Plan
>
> ```bash
> PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmHeuristics -v
> PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmEpilogueFusion.test_bf16_grouped_m_reduce_finalizes_after_cross_warp_combine TestNVUniversalGemmEpilogueFusion.test_bf16_grouped_n_composite_reduction_fusion TestNVUniversalGemmEpilogueFusion.test_scaled_mm_grouped_n_composite_reduction_fusion TestNVUniversalGemmEpilogueFusion.test_scaled_mm_grouped_m_reduce_finalizes_after_cross_warp_combine -v
> PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmEpilogueFusion.test_bf16_grouped_reduce_epilogue_fusion_axis_1_group_4_sum TestNVUniversalGemmEpilogueFusion.test_bf16_grouped_reduce_epilogue_fusion_axis_0_group_64_abs_amax TestNVUniversalGemmEpilogueFusion.test_flex_gemm_grouped_n_reduce_epilogue_fusion_feeds_main_True -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: #190825
Approved by: https://github.com/karthickai
ghstack dependencies: #192298, #190822, #191514, #191515
pytorchmergebot pushed a commit that referenced this pull request Sep 2, 2026
doesn't run hese tests in fbcode until we add operator API internally

> This skips two low-level tests only in fbcode because fbcode does not include
> the optional CUTLASS package those tests use to construct and run kernel
> objects directly. The tests fail while importing or creating the operator,
> before they exercise the NVGEMM behavior they are intended to check.
>
> The tests still run in the open-source build, and the higher-level
> `torch.compile` tests remain enabled in fbcode.
>
> ## Architecture
>
> This is a test-only environment boundary. The two tests that directly import
> the optional CUTLASS Operator API are skipped individually when `IS_FBCODE` is
> true. No production lowering, provider registration, or generated-kernel
> behavior changes. The tests continue running in open source, while fbcode
> retains the higher-level compiler coverage.
>
> ## Example
>
> The affected tests directly compile a grouped-reduction provider and a
> unit-dimension epilogue on a non-current CUDA stream. In fbcode, the required
> operator-construction API is absent, so skipping those two tests avoids
> reporting an environment limitation as an NVGEMM correctness failure.
>
>
> ```python
> @unittest.skipIf(
>     IS_FBCODE,
>     "CUTLASS Operator API is not available in fbcode",
> )
> def test_scaled_gemm_grouped_n_reduce_provider(self):
>     ...
> ```
>
> ## Test Plan
>
> ```bash
> PYTORCH_TEST_FBCODE=1 python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemm.test_scaled_gemm_grouped_n_reduce_provider TestNVUniversalGemm.test_scaled_gemm_unit_dim_epilogue_non_current_stream -v
> python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemm.test_scaled_gemm_grouped_n_reduce_provider TestNVUniversalGemm.test_scaled_gemm_unit_dim_epilogue_non_current_stream -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: #192928
Approved by: https://github.com/karthickai
ghstack dependencies: #192298, #190822, #191514, #191515, #190825
bobrenjc93 added a commit to bobrenjc93/pytorch that referenced this pull request Sep 3, 2026
Use object instead of Any for the expression-tree walker inputs in
loop_ir_epilogue_lowering.py. These helpers walk a tree whose leaves are
genuinely heterogeneous (nested GemmEpilogueIRExpression nodes, sympy
indices, dtypes, ints, floats), which is precisely why the parameter
cannot just be the IR type. Every helper already isinstance-narrows
before touching expression members, so object captures the accepted
boundary while removing the unchecked attribute access Any permits.

This is a rebase onto current main. The file was largely rewritten
upstream by the NVGEMM epilogue work (pytorch#194793, pytorch#195231, pytorch#192298), which
deleted ten of the seventeen helpers this change originally touched --
the affine/softmax/variance matchers, including _source_transform. Seven
of the original sites survive; the same treatment is applied to the
three walkers that rewrite introduced (_expression_pattern,
_synthetic_reduction_element_ir, _synthetic_reductions_ir) so the module
is consistent rather than half converted.

Return types are deliberately left as Any. These walkers hand back raw
tree leaves, so narrowing the returns is a separate and much larger
change to every caller.

Test Plan:

```
lintrunner --take PYFMT,RUFF,CODESPELL,FLAKE8 \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

Pyrefly 0.58.0 reports 0 errors on the file both before and after, so
there are no net-new type errors:

```
uvx [email protected] check \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

The module's tests pass locally on an H100 (21 passed, 168 skipped; the
skips are the Blackwell-gated end-to-end cases, and the tests that do
run cover the walkers directly -- grouped reduction pattern matching,
region construction and the reduction finalizer):

```
python -m pytest test/inductor/test_nv_universal_gemm.py -q
```

Authored with assistance from an AI coding assistant.
pytorchmergebot pushed a commit to bobrenjc93/pytorch that referenced this pull request Sep 3, 2026
Use object instead of Any for the expression-tree walker inputs in
loop_ir_epilogue_lowering.py. These helpers walk a tree whose leaves are
genuinely heterogeneous (nested GemmEpilogueIRExpression nodes, sympy
indices, dtypes, ints, floats), which is precisely why the parameter
cannot just be the IR type. Every helper already isinstance-narrows
before touching expression members, so object captures the accepted
boundary while removing the unchecked attribute access Any permits.

This is a rebase onto current main. The file was largely rewritten
upstream by the NVGEMM epilogue work (pytorch#194793, pytorch#195231, pytorch#192298), which
deleted ten of the seventeen helpers this change originally touched --
the affine/softmax/variance matchers, including _source_transform. Seven
of the original sites survive; the same treatment is applied to the
three walkers that rewrite introduced (_expression_pattern,
_synthetic_reduction_element_ir, _synthetic_reductions_ir) so the module
is consistent rather than half converted.

Return types are deliberately left as Any. These walkers hand back raw
tree leaves, so narrowing the returns is a separate and much larger
change to every caller.

Test Plan:

```
lintrunner --take PYFMT,RUFF,CODESPELL,FLAKE8 \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

Pyrefly 0.58.0 reports 0 errors on the file both before and after, so
there are no net-new type errors:

```
uvx [email protected] check \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

The module's tests pass locally on an H100 (21 passed, 168 skipped; the
skips are the Blackwell-gated end-to-end cases, and the tests that do
run cover the walkers directly -- grouped reduction pattern matching,
region construction and the reduction finalizer):

```
python -m pytest test/inductor/test_nv_universal_gemm.py -q
```

Authored with assistance from an AI coding assistant.
pytorchmergebot pushed a commit to bobrenjc93/pytorch that referenced this pull request Sep 4, 2026
Use object instead of Any for the expression-tree walker inputs in
loop_ir_epilogue_lowering.py. These helpers walk a tree whose leaves are
genuinely heterogeneous (nested GemmEpilogueIRExpression nodes, sympy
indices, dtypes, ints, floats), which is precisely why the parameter
cannot just be the IR type. Every helper already isinstance-narrows
before touching expression members, so object captures the accepted
boundary while removing the unchecked attribute access Any permits.

This is a rebase onto current main. The file was largely rewritten
upstream by the NVGEMM epilogue work (pytorch#194793, pytorch#195231, pytorch#192298), which
deleted ten of the seventeen helpers this change originally touched --
the affine/softmax/variance matchers, including _source_transform. Seven
of the original sites survive; the same treatment is applied to the
three walkers that rewrite introduced (_expression_pattern,
_synthetic_reduction_element_ir, _synthetic_reductions_ir) so the module
is consistent rather than half converted.

Return types are deliberately left as Any. These walkers hand back raw
tree leaves, so narrowing the returns is a separate and much larger
change to every caller.

Test Plan:

```
lintrunner --take PYFMT,RUFF,CODESPELL,FLAKE8 \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

Pyrefly 0.58.0 reports 0 errors on the file both before and after, so
there are no net-new type errors:

```
uvx [email protected] check \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

The module's tests pass locally on an H100 (21 passed, 168 skipped; the
skips are the Blackwell-gated end-to-end cases, and the tests that do
run cover the walkers directly -- grouped reduction pattern matching,
region construction and the reduction finalizer):

```
python -m pytest test/inductor/test_nv_universal_gemm.py -q
```

Authored with assistance from an AI coding assistant.
pytorchmergebot pushed a commit that referenced this pull request Sep 4, 2026
…194825)

The tree's leaves are genuinely heterogeneous (nested `GemmEpilogueIRExpression` nodes, sympy indices, dtypes, ints, floats), which is precisely why the parameter cannot just be the IR type. Every walker already `isinstance`-narrows before touching expression members, so `object` captures the accepted boundary while removing the unchecked attribute access `Any` permits.

**Rebased onto current main.** The file was largely rewritten upstream by the NVGEMM epilogue work (#194793, #195231, #192298), which deleted ten of the seventeen helpers this PR originally touched -- the affine/softmax/variance matchers, including `_source_transform`. Seven of the original sites survive, and the same treatment is applied to the three walkers that rewrite introduced (`_expression_pattern`, `_synthetic_reduction_element_ir`, `_synthetic_reductions_ir`) so the module is consistent rather than half converted.

Return types are deliberately left as `Any`: these walkers hand back raw tree leaves, so narrowing the returns is a separate and much larger change to every caller.

### Test plan

```
lintrunner --take PYFMT,RUFF,CODESPELL,FLAKE8 \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

Pyrefly 0.58.0 reports 0 errors on the file both before and after, so there are no net-new type errors:

```
uvx [email protected] check \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

The module's tests pass locally on an H100 (21 passed, 168 skipped; the skips are the Blackwell-gated end-to-end cases, and the tests that do run cover the walkers directly -- grouped reduction pattern matching, region construction and the reduction finalizer):

```
python -m pytest test/inductor/test_nv_universal_gemm.py -q
```

Authored with assistance from an AI coding assistant.

Pull Request resolved: #194825
Approved by: https://github.com/pytorchgreenlight
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ata (pytorch#192298)

<human note needed>

> Wire scheduler Loop IR epilogue plans into NVGEMM fusion and CuTeDSL code
> generation. When the scheduler considers another node, NVGEMM reinterprets
> the complete candidate prefix, validates that every reduction is claimed, and
> accepts the node only when the resulting program has a supported lowering.
>
> `LoopIRCuteDSLCodegen` replays the captured expressions through CuTeDSL
> operation overrides to generate the tensor epilogue and any source, combine,
> finalize, or consumer callbacks. Dense and block-scaled providers consume the
> same generated contract.
>
> Reduction selection is based on captured IR and geometry, not an algorithm
> name. The reduction kind identifies only the associative primitive. A
> fragment-local composition can contain multiple reductions and pointwise
> operations and returns its local result from the generated epilogue. Geometry
> that requires cross-thread work receives generated combine and finalize
> callbacks; the kernel supplies only the physical reduction mechanism.
>
> Centralize reduction geometry and capability checks so NVGEMM and FlexGEMM
> share the same primitive reduction contract, cache specialization, and safe
> fallback behavior. Add focused coverage for callback generation, provider
> support, cache keys, and unsupported patterns.
>
> ## Reduction representation
>
> ```mermaid
> flowchart TD
>     NODES["Candidate scheduler nodes"] --> CAPTURE["NVGemmEpilogueCapture"]
>     CAPTURE --> PROGRAM["NVGemmEpilogueProgram<br/>captured expressions + reduction regions"]
>     PROGRAM --> PLAN["GemmReductionPlan"]
>
>     PLAN --> MODE{"Reduction representation"}
>     MODE -->|"Kernel reduction"| PHYSICAL["reduction_type + source_fn<br/>optional finalizer and consumers"]
>     MODE -->|"Generated tensor reduction"| GENERATED["tensor epilogue computes the local result<br/>optional combine/finalize callbacks"]
>
>     PHYSICAL --> NVARGS["GemmReductionArguments<br/>runtime tensors + specialization fields"]
>     GENERATED --> NVARGS
>     NVARGS --> NVKERNEL["Dense or block-scaled NVGEMM kernel"]
>
>     FX["FlexGEMM FX body"] --> FXANALYSIS["GemmLocalReduceAnalysis"]
>     FXANALYSIS --> PLAN
>     PLAN --> FLEXCFG["FlexGemmEpilogueLocalReduceConfig"]
>     FLEXCFG --> FLEXRT["FlexGemmRuntimeLocalReducePlan"]
>     FLEXRT --> FLEXKERNEL["FlexGEMM / QuACK"]
> ```
>
> The shared `GemmReductionPlan` records:
>
> - `group` and `axis`: the logical reduction geometry;
> - `reduction_type`: only the associative primitive (`sum`, `mean`, `prod`,
>   `max`, or `min`);
> - `source_fn`: the generated transformation applied before a physical
>   reduction;
> - `combine_fn` and `finalizer_fn`: generated callbacks needed when partial
>   results cross fragments or threads;
> - `consumer_fn` and `secondary_consumer_fn`: generated operations that consume
>   the reduced value;
> - `reduction_output`, `feed_output`, and `secondary_feed_output`: output
>   ownership; and
> - `tensor_epilogue_returns_local_reduce`: whether the generated tensor
>   epilogue computes the fragment-local reduction itself.
>
> There are two valid forms:
>
> | Form | Representation |
> | --- | --- |
> | Kernel-driven reduction | `source_fn` computes each value and `reduction_type` specifies how the kernel combines those values. The kernel handles traversal and synchronization. |
> | Generated tensor reduction | `reduction_type` and `source_fn` are `None`; the generated tensor epilogue computes the local reduction and returns it. A generated `combine_fn` is supplied only when the geometry requires cross-fragment combination. |
>
> NVGEMM converts the shared plan to `GemmReductionArguments`, replacing buffer
> names with runtime tensors and including the semantic fields in cache
> specialization. FlexGEMM wraps the same plan with its output index, output
> layout, and operand-swap state, then renders its existing runtime reduction
> plan and callbacks.
>
> Multiple compatible fragment-local reductions and their pointwise consumers
> remain encoded in the generated epilogue expression. There is no string or
> enum selecting a composite algorithm; `reduction_type` identifies only the
> associative primitive.
>
> ## Test Plan
>
> ```bash
> PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmHeuristics -v
> PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_flex_gemm.py TestFlexGemmRuntimeHelpers -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#192298
Approved by: https://github.com/drisspg
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
<human note needed>

> Add scheduler hooks that let a CUDA template backend keep a validated
> reduction region together during fusion. Reduction-pair compatibility and
> reduction-epilogue decisions are delegated to the backend before generic
> fusion can consume only part of the region.
>
> NVGEMM uses these hooks to prioritize supported reduction chains, reject
> conflicting partial fusions, and keep NVGEMM boolean outputs out of unrelated
> horizontal fusion. The Loop IR capture and validation logic lives in the
> preceding commits; this commit only adds the scheduler coordination needed to
> treat its result atomically.
>
> ## Test Plan
>
> ```bash
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.
Pull Request resolved: pytorch#190822
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#192298
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ch#191514)

prepares dense kernel for direct cutedsl codegen (instead of EVT)

> This updates the vendored dense matrix-multiply kernel so it can run the
> post-processing function generated directly by Inductor. It maps captured
> tensors such as biases into the layout expected by the kernel, exposes the
> operations used by the generated function, and stores each requested output.
>
> The older metadata format remains supported in this commit so the kernel
> change can land separately from the scheduler change that starts using the
> direct path.
>
> ## Example
>
> The direct epilogue represents a computation such as:
>
> ```python
> def fn(a, b, bias):
>     return torch.relu((a @ b) + bias)
> ```
>
> Given generated source for this epilogue, the adapter maps the bias into the
> dense kernel's broadcast layout, evaluates the addition and ReLU, and stores
> the result. This commit teaches the provider to accept that direct function;
> the following commit switches scheduler selection from the older CUTLASS
> expression-graph representation to this path.
>
> ## Test Plan
>
> ```bash
> CUDA_VISIBLE_DEVICES=0 TORCHINDUCTOR_COMPILE_THREADS=1 python test/inductor/test_nv_universal_gemm.py -k matmul_pointwise_epilogue_fusion -v
> CUDA_VISIBLE_DEVICES=0 TORCHINDUCTOR_COMPILE_THREADS=1 python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmEpilogueFusion.test_matmul_multi_store_epilogue_fusion -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.
Pull Request resolved: pytorch#191514
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#192298, pytorch#190822
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ytorch#191515)

> Enable shared Loop IR to CuTeDSL lowering for dense NVGEMM epilogues. The
> scheduler selects generated CuTeDSL source when the complete captured
> expression is supported and retains CUTLASS EVT lowering as the fallback.
>
> Preserve captured input dtypes and broadcast layouts, compose bias through
> the same epilogue plan, reuse common subexpressions, and reject unsupported
> operand swaps or reduction layouts before selecting the direct path.
>
> ## Example
>
> ```python
> result = (a @ b).float()
> return torch.relu(result), result + bias
> ```
>
> Both stores are generated from one captured Loop IR program. Expressions that
> cannot be represented by the direct path continue through EVT.
>
> ## Test Plan
>
> ```bash
> PYTORCH_WORKTREE=$PWD env -u PYTHONPATH python agent_space/run_worktree_python.py test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmEpilogueFusion.test_matmul_multi_store_epilogue_fusion -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#191515
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#192298, pytorch#190822, pytorch#191514
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
> Add focused parity coverage for generated CuTeDSL callbacks across dense and
> block-scaled grouped reductions. The tests cover both reduction axes,
> primitive and pointwise-transformed sources, multiple reductions in one
> epilogue, reduction consumers, and finalization after cross-warp combination.
>
> Keep the transposed output layout explicit when NVGEMM swaps the GEMM operands.
> Let FlexGEMM request the broader tuned NVGEMM configuration while rejecting
> unsupported NVGEMM options.
>
> ## Test Plan
>
> ```bash
> PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmHeuristics -v
> PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmEpilogueFusion.test_bf16_grouped_m_reduce_finalizes_after_cross_warp_combine TestNVUniversalGemmEpilogueFusion.test_bf16_grouped_n_composite_reduction_fusion TestNVUniversalGemmEpilogueFusion.test_scaled_mm_grouped_n_composite_reduction_fusion TestNVUniversalGemmEpilogueFusion.test_scaled_mm_grouped_m_reduce_finalizes_after_cross_warp_combine -v
> PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmEpilogueFusion.test_bf16_grouped_reduce_epilogue_fusion_axis_1_group_4_sum TestNVUniversalGemmEpilogueFusion.test_bf16_grouped_reduce_epilogue_fusion_axis_0_group_64_abs_amax TestNVUniversalGemmEpilogueFusion.test_flex_gemm_grouped_n_reduce_epilogue_fusion_feeds_main_True -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#190825
Approved by: https://github.com/karthickai
ghstack dependencies: pytorch#192298, pytorch#190822, pytorch#191514, pytorch#191515
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
doesn't run hese tests in fbcode until we add operator API internally

> This skips two low-level tests only in fbcode because fbcode does not include
> the optional CUTLASS package those tests use to construct and run kernel
> objects directly. The tests fail while importing or creating the operator,
> before they exercise the NVGEMM behavior they are intended to check.
>
> The tests still run in the open-source build, and the higher-level
> `torch.compile` tests remain enabled in fbcode.
>
> ## Architecture
>
> This is a test-only environment boundary. The two tests that directly import
> the optional CUTLASS Operator API are skipped individually when `IS_FBCODE` is
> true. No production lowering, provider registration, or generated-kernel
> behavior changes. The tests continue running in open source, while fbcode
> retains the higher-level compiler coverage.
>
> ## Example
>
> The affected tests directly compile a grouped-reduction provider and a
> unit-dimension epilogue on a non-current CUDA stream. In fbcode, the required
> operator-construction API is absent, so skipping those two tests avoids
> reporting an environment limitation as an NVGEMM correctness failure.
>
>
> ```python
> @unittest.skipIf(
>     IS_FBCODE,
>     "CUTLASS Operator API is not available in fbcode",
> )
> def test_scaled_gemm_grouped_n_reduce_provider(self):
>     ...
> ```
>
> ## Test Plan
>
> ```bash
> PYTORCH_TEST_FBCODE=1 python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemm.test_scaled_gemm_grouped_n_reduce_provider TestNVUniversalGemm.test_scaled_gemm_unit_dim_epilogue_non_current_stream -v
> python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemm.test_scaled_gemm_grouped_n_reduce_provider TestNVUniversalGemm.test_scaled_gemm_unit_dim_epilogue_non_current_stream -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#192928
Approved by: https://github.com/karthickai
ghstack dependencies: pytorch#192298, pytorch#190822, pytorch#191514, pytorch#191515, pytorch#190825
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…ytorch#194825)

The tree's leaves are genuinely heterogeneous (nested `GemmEpilogueIRExpression` nodes, sympy indices, dtypes, ints, floats), which is precisely why the parameter cannot just be the IR type. Every walker already `isinstance`-narrows before touching expression members, so `object` captures the accepted boundary while removing the unchecked attribute access `Any` permits.

**Rebased onto current main.** The file was largely rewritten upstream by the NVGEMM epilogue work (pytorch#194793, pytorch#195231, pytorch#192298), which deleted ten of the seventeen helpers this PR originally touched -- the affine/softmax/variance matchers, including `_source_transform`. Seven of the original sites survive, and the same treatment is applied to the three walkers that rewrite introduced (`_expression_pattern`, `_synthetic_reduction_element_ir`, `_synthetic_reductions_ir`) so the module is consistent rather than half converted.

Return types are deliberately left as `Any`: these walkers hand back raw tree leaves, so narrowing the returns is a separate and much larger change to every caller.

### Test plan

```
lintrunner --take PYFMT,RUFF,CODESPELL,FLAKE8 \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

Pyrefly 0.58.0 reports 0 errors on the file both before and after, so there are no net-new type errors:

```
uvx [email protected] check \
  torch/_inductor/kernel/loop_ir_epilogue_lowering.py
```

The module's tests pass locally on an H100 (21 passed, 168 skipped; the skips are the Blackwell-gated end-to-end cases, and the tests that do run cover the walkers directly -- grouped reduction pattern matching, region construction and the reduction finalizer):

```
python -m pytest test/inductor/test_nv_universal_gemm.py -q
```

Authored with assistance from an AI coding assistant.

Pull Request resolved: pytorch#194825
Approved by: https://github.com/pytorchgreenlight
pytorchmergebot pushed a commit that referenced this pull request Sep 10, 2026
Orient generated reduction geometry, output layouts, and runtime tensors when NVGEMM swaps GEMM operands. Dense and block-scaled epilogues continue to use the shared generated source, combine, and finalizer callbacks.

Keep the kernel reduction mechanism unchanged. Candidate validation filters physical tile layouts that cross CTA or warp ownership, leaving valid configurations in the normal autotuning set and falling back safely when a layout cannot implement the reduction.

## Test Plan

```bash
PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py -k swap_ab
PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py -k grouped_reduce
spin quicklint
lintrunner -a
```

Authored with an AI assistant.

Pull Request resolved: #195538
Approved by: https://github.com/karthickai
ghstack dependencies: #192298, #190822, #191514, #191515, #190825, #192928
pytorchmergebot pushed a commit that referenced this pull request Sep 10, 2026
Generate vendored dense EFC variants for the validated SM100 N-tile widths through 256, including 160, 192, and 224. This makes the configurations available to nvMatmulHeuristics without retaining them unconditionally.

Keep the existing supplemented benchmark space unchanged. Wider candidates enter autotuning only when nvMatmulHeuristics selects them, avoiding additional profiling by default.

## Test Plan

```bash
PYTHONPATH=/data/users/mlazos/pytorch/agent_space/runtime_overlay PYTORCH_BOUNDARY_ROOT=$PWD python test/inductor/test_nv_universal_gemm.py TestNVUniversalGemm.test_vendored_dense_efc_exposes_wide_n_tiles -v
lintrunner -a
```

Authored with an AI assistant.

Pull Request resolved: #195539
Approved by: https://github.com/karthickai
ghstack dependencies: #192298, #190822, #191514, #191515, #190825, #192928, #195538
@github-actions
github-actions Bot deleted the gh/mlazos/297/head branch November 14, 2026 01:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants