Skip to content

[inductor][NVGEMM] Generalize block-scaled GEMM epilogues - #194792

Closed
mlazos wants to merge 5 commits into
gh/mlazos/312/basefrom
gh/mlazos/312/head
Closed

mlazos wants to merge 5 commits into
gh/mlazos/312/basefrom
gh/mlazos/312/head

Conversation

@mlazos

@mlazos mlazos commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Replace the block-scaled kernel's string-selected reduction implementation
with a generated CuTeDSL callback contract. The wrapper materializes the
associative operation, identity, source transform, finalizer, and optional
consumer while the vendored kernel retains only fragment traversal,
synchronization, cross-warp combination, and output storage.

Generalize epilogue input and output transport using packed arguments so the
provider is not limited to a fixed number of captured tensors or auxiliary
outputs.

Test Plan:

python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_capabilities.py torch/_inductor/kernel/gemm_epilogue.py torch/_inductor/kernel/gemm_epilogue_codegen.py torch/_inductor/kernel/vendored_templates/cutedsl/dense_blockscaled_gemm_persistent.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py
lintrunner -a

Authored with an AI assistant.

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 25, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

As of commit c3737ab with merge base 96043a9 (image):

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

@mlazos

mlazos commented Aug 26, 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

  • [medium] Full-axis reductions are incorrectly squeezed — Location: nv_universal_gemm_kernel.py:1450-1452. Trigger: axis-1 reduction with M=128, N=32, group=32, or axis-0 with M=group=16. Failure sequence: the rank-2 output is squeezed to rank 1, then the block-scaled provider rejects it because _supports requires (M, N/group) or (M/group, N). Impact: valid fused reductions fail compilation. Reviewers: Codex Bug Review.

  • [medium] Unsupported reduction groups are committed to fusion — Location: nv_universal_gemm_scheduling.py:245-269,495-497; epilogue_capabilities.py:49-53. Trigger: a block-scaled GEMM with a non-power-of-two group, such as an axis-0 sum with group 3. Failure sequence: scheduling accepts the reduction and removes the unfused path, but the provider later rejects the contract’s non-power-of-two group. Impact: torch.compile fails instead of declining fusion. Reviewers: Claude Design Review, Codex Design Review.

  • [medium] Feed-main fusion is accepted before verifying consumer lowerability — Location: nv_universal_gemm_scheduling.py:605-634,783-789; loop_ir_cutedsl_codegen.py:60-63. Trigger: a feed-main expression whose primary term includes a dtype bitcast, such as result.view(torch.int16).float() - grouped_mean. Failure sequence: the matcher strips the bitcast and accepts fusion; preflight skips consumer lowering; actual codegen rejects to_dtype_bitcast and re-raises NotImplementedError. Impact: graph compilation aborts. Reviewers: Codex Design Review.

  • [low] Source-fusion test asserts the removed argument spelling — Location: test_nv_universal_gemm.py:1540. Trigger: run test_scaled_mm_grouped_reduce_source_fusion. Failure sequence: generated code contains source_type='square', but the test searches for 'local_reduce_source': 'square'. Impact: deterministic test failure after successful compilation. Reviewers: Codex Bug Review.

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

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #195231

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

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #194873

1 similar comment
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #194873

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

> Give the dense EFC kernel the same callback-based reduction interface as the
> block-scaled kernel. The wrapper materializes source, combine, finalize, and
> consumer functions, while the vendored kernel owns fragment traversal,
> synchronization, cross-thread combination, and output storage.
>
> The generated epilogue owns pointwise and fragment-local reduction semantics.
> Physical reduction geometry uses generated combine and finalize callbacks;
> the reduction primitive identifies the operation and does not select a
> runtime algorithm.
>
> Remove the dense reduction descriptor parser and hardcoded affine and boolean
> consumer arithmetic so both vendored kernels use the same callback contract.
>
> ## Test Plan
>
> ```bash
> python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_capabilities.py torch/_inductor/kernel/gemm_epilogue.py torch/_inductor/kernel/gemm_epilogue_analysis.py torch/_inductor/kernel/gemm_epilogue_codegen.py torch/_inductor/kernel/loop_ir_epilogue_lowering.py torch/_inductor/kernel/vendored_templates/cutedsl/dense_gemm_efc.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_gemm_efc_kernel.py
> PYTORCH_WORKTREE=$PWD env -u PYTHONPATH python agent_space/run_worktree_python.py test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmHeuristics.test_dense_reduction_uses_generated_callback_contract TestNVUniversalGemm.test_scaled_gemm_grouped_n_reduce_provider -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: #194793
Approved by: https://github.com/eellison
ghstack dependencies: #194792
pytorchmergebot pushed a commit that referenced this pull request Sep 1, 2026
> This connects PyTorch Inductor to the vendored dense and block-scaled matrix
> multiplication kernels that can perform extra work before storing their
> outputs. It gives both kernels one shared description of grouped reductions,
> validates whether a requested group size and direction are supported, builds
> the kernel arguments and output buffers, and includes those choices in the
> compilation cache key.
>
> Unsupported shapes or operations are rejected before launch so Inductor can
> use another implementation. Keeping this contract shared prevents the dense
> and block-scaled paths from interpreting the same post-processing differently.
>
> ## Architecture
>
> This commit introduces the common boundary between Inductor and the vendored
> kernels. Inductor describes the post-matrix-multiply work as one
> `GemmEpiloguePlan`; provider capability objects decide whether the dense or
> block-scaled kernel can implement it. The selected wrapper converts the plan
> into compile-time callbacks, runtime tensor arguments, output buffers, and
> cache specialization data. Each backend therefore receives the same validated
> contract instead of reconstructing the operation independently.
>
> ## Example
>
> For `result = a @ b`, a caller can group every 16 columns, compute a sum for
> each group, and return both `result` and the compact tensor of sums. This
> commit carries the group size, column direction, sum operation, and two output
> buffers from Inductor into either supported vendored kernel.
>
>
> ```python
> def fn(a, b):
>     result = a @ b
>     grouped = result.float().view(m, n // 16, 16)
>     group_sums = grouped.sum(dim=-1)
>     return result, group_sums
> ```
>
> ## Test Plan
>
> ```bash
> python -m py_compile torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_gemm_efc_kernel.py
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: #190821
Approved by: https://github.com/drisspg
ghstack dependencies: #194792, #194793
pytorchmergebot pushed a commit that referenced this pull request Sep 1, 2026
<human note needed>

> Define a shared representation for grouped GEMM reductions and use it as the
> boundary between epilogue analysis and backend-specific code generation.
>
> ## Shared reduction representation
>
> `GemmReductionGeometry` describes which logical GEMM output axis is reduced
> and how many adjacent elements belong to each group. It also determines
> whether the reduction fits inside one TensorSSA fragment or requires physical
> cross-thread combination.
>
> `GemmReductionPlan` carries the complete semantic contract:
>
> - the grouped reduction geometry;
> - the associative primitive, such as sum, product, minimum, or maximum;
> - generated source, combine, finalize, and consumer callbacks;
> - the primary and auxiliary output buffers;
> - whether the reduction feeds the primary GEMM output; and
> - whether the generated tensor epilogue returns a fragment-local reduction.
>
> This separates the mathematical operation from the physical reduction
> mechanism. Backends implement fragment traversal, synchronization, and
> storage, while generated callbacks describe the computation applied at each
> stage.
>
> ## Loop IR analysis
>
> Extend the Loop IR analysis to recognize both explicit reduction nodes and
> reductions expressed as unrolled pointwise operations. For an unrolled
> reduction, the analysis:
>
> 1. Finds the repeated loads from the GEMM output.
> 2. Uses their index ranges and strides to infer the group size and M/N axis.
> 3. Verifies that every lane applies the same pointwise source expression.
> 4. Identifies the associative primitive.
> 5. Preserves the source expression for later CuTeDSL callback generation.
>
> For example, an expression equivalent to:
>
> ```python
> grouped = output.float().view(m, n // 4, 4)
> reduced = torch.exp(grouped).sum(dim=-1)
> ```
>
> is represented as an N-axis group-of-four sum whose source expression is
> `exp(value)`.
>
> ## FlexGEMM integration
>
> Replace FlexGEMM's parallel template-time reduction description with a wrapper
> around `GemmReductionPlan`. The FlexGEMM wrapper retains only provider-specific
> information: the auxiliary-output index, output layout, and operand-swap
> state.
>
> FlexGEMM lowering now passes `epilogue_analysis.reduction_plan` directly into
> that wrapper. The shared geometry also owns the fragment-width and
> physical-callback decision previously implemented by a FlexGEMM-specific
> helper.
>
> This gives FlexGEMM and NVGEMM the same semantic reduction plan while allowing
> each provider to retain its own runtime ABI and code-generation machinery.
>
> ## Relationship between FlexGEMM and NVGEMM
>
> Both backends use the same semantic reduction plan, while retaining their
> existing analysis and runtime interfaces:
>
> ```mermaid
> flowchart LR
>     FX["FlexGEMM FX epilogue"] --> FXA["GemmLocalReduceAnalysis"]
>     LOOP["NVGEMM scheduler Loop IR"] --> LIA["GemmEpilogueIRAnalysis"]
>
>     FXA --> PLAN["GemmReductionPlan<br/>geometry, primitive, callbacks, outputs"]
>     LIA --> CFG["GemmReductionConfig"]
>     CFG --> PLAN
>
>     PLAN --> FLEXCFG["FlexGemmEpilogueLocalReduceConfig<br/>plan + output index + layout + swap_ab"]
>     FLEXCFG --> FLEXRT["FlexGemmRuntimeLocalReducePlan"]
>     FLEXRT --> QUACK["FlexGEMM / QuACK"]
>
>     PLAN --> NVCAP["NVGEMM capability validation"]
>     NVCAP --> NVARGS["GemmReductionArguments"]
>     NVARGS --> NVKERNEL["Vendored NVGEMM kernel"]
> ```
>
> `GemmReductionPlan` is the shared semantic boundary. FlexGEMM adds only the
> output placement and layout information needed by its template, while NVGEMM
> binds the plan to runtime tensors and cache-specialization fields.
>
> ## Testing
>
> Unit coverage for the shared reduction plan and FlexGEMM adapter is included
> in this PR.
>
> End-to-end dense and block-scaled generated-epilogue coverage is provided by
> [#190825](#190825).
>
> ```bash
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: #195231
Approved by: https://github.com/drisspg
ghstack dependencies: #194792, #194793, #190821
pytorchmergebot pushed a commit that referenced this pull request Sep 1, 2026
<human note needed>

> Introduce the semantic lowering and CuTeDSL emission layer for scheduler-owned
> GEMM epilogues. A candidate sequence of scheduler nodes is captured as Loop IR,
> classified from iteration ranges and access strides, and represented as one
> `NVGemmEpilogueProgram` containing pointwise work, grouped reduction regions,
> output ownership, and any callbacks required by the kernel.
>
> ## Architecture
>
> `NVGemmEpilogueCapture` interprets the candidate nodes without selecting a
> named reduction algorithm. `reduction_type` identifies only the associative
> primitive; the captured expressions define source transforms, finalizers,
> consumers, and compositions of multiple reductions with pointwise operations.
>
> `LoopIRCuteDSLCodegen` replays those expressions through the shared CuTeDSL
> operation overrides. Fragment-local reductions remain in the generated tensor
> epilogue. When a reduction crosses fragments or threads, the generated plan
> supplies combine and finalize callbacks while the vendored kernel owns
> traversal, synchronization, and storage.
>
> `NVGemmEpilogueProgram` is the validation boundary used by scheduling. It
> records which nodes belong to reduction regions, which outputs remain visible,
> whether a reduction feeds the main GEMM output, and whether every reduction in
> the candidate prefix has a supported lowering.
>
> ## Examples
>
> A pointwise epilogue becomes one generated callback:
>
> ```python
> result = a @ b
> return torch.relu(result.float() + bias)
> ```
>
> Multiple reductions and pointwise consumers remain one semantic program:
>
> ```python
> result = a @ b
> grouped = result.float().view(m, n // 4, 4)
> scale = grouped.sum(-1) + grouped.amax(-1)
> return (grouped / scale.unsqueeze(-1)).reshape(m, n), scale
> ```
>
> The second example is represented as an N-axis reduction with group size four.
> The generated epilogue computes both primitive reductions and the division; a
> larger or cross-thread geometry additionally receives generated physical
> reduction callbacks.
>
> ## Test Plan
>
> ```bash
> spin lint torch/_inductor/codegen/nv_universal_gemm/epilogue_lowering.py torch/_inductor/kernel/loop_ir_cutedsl_codegen.py
> lintrunner -a
> python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_lowering.py torch/_inductor/kernel/loop_ir_cutedsl_codegen.py
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: #194873
Approved by: https://github.com/drisspg
ghstack dependencies: #194792, #194793, #190821, #195231
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…4792)

<human note needed>

> Replace the block-scaled kernel's string-selected reduction implementation
> with a generated CuTeDSL callback contract. The wrapper materializes the
> associative operation, identity, source transform, finalizer, and optional
> consumer while the vendored kernel retains only fragment traversal,
> synchronization, cross-warp combination, and output storage.
>
> Generalize epilogue input and output transport using packed arguments so the
> provider is not limited to a fixed number of captured tensors or auxiliary
> outputs.
>
> Test Plan:
>
> ```bash
> python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_capabilities.py torch/_inductor/kernel/gemm_epilogue.py torch/_inductor/kernel/gemm_epilogue_codegen.py torch/_inductor/kernel/vendored_templates/cutedsl/dense_blockscaled_gemm_persistent.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py
> lintrunner -a
> ```
>
> Authored with an AI assistant.

Pull Request resolved: pytorch#194792
Approved by: https://github.com/eellison
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
<human note needed>

> Give the dense EFC kernel the same callback-based reduction interface as the
> block-scaled kernel. The wrapper materializes source, combine, finalize, and
> consumer functions, while the vendored kernel owns fragment traversal,
> synchronization, cross-thread combination, and output storage.
>
> The generated epilogue owns pointwise and fragment-local reduction semantics.
> Physical reduction geometry uses generated combine and finalize callbacks;
> the reduction primitive identifies the operation and does not select a
> runtime algorithm.
>
> Remove the dense reduction descriptor parser and hardcoded affine and boolean
> consumer arithmetic so both vendored kernels use the same callback contract.
>
> ## Test Plan
>
> ```bash
> python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_capabilities.py torch/_inductor/kernel/gemm_epilogue.py torch/_inductor/kernel/gemm_epilogue_analysis.py torch/_inductor/kernel/gemm_epilogue_codegen.py torch/_inductor/kernel/loop_ir_epilogue_lowering.py torch/_inductor/kernel/vendored_templates/cutedsl/dense_gemm_efc.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_gemm_efc_kernel.py
> PYTORCH_WORKTREE=$PWD env -u PYTHONPATH python agent_space/run_worktree_python.py test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmHeuristics.test_dense_reduction_uses_generated_callback_contract TestNVUniversalGemm.test_scaled_gemm_grouped_n_reduce_provider -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#194793
Approved by: https://github.com/eellison
ghstack dependencies: pytorch#194792
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
> This connects PyTorch Inductor to the vendored dense and block-scaled matrix
> multiplication kernels that can perform extra work before storing their
> outputs. It gives both kernels one shared description of grouped reductions,
> validates whether a requested group size and direction are supported, builds
> the kernel arguments and output buffers, and includes those choices in the
> compilation cache key.
>
> Unsupported shapes or operations are rejected before launch so Inductor can
> use another implementation. Keeping this contract shared prevents the dense
> and block-scaled paths from interpreting the same post-processing differently.
>
> ## Architecture
>
> This commit introduces the common boundary between Inductor and the vendored
> kernels. Inductor describes the post-matrix-multiply work as one
> `GemmEpiloguePlan`; provider capability objects decide whether the dense or
> block-scaled kernel can implement it. The selected wrapper converts the plan
> into compile-time callbacks, runtime tensor arguments, output buffers, and
> cache specialization data. Each backend therefore receives the same validated
> contract instead of reconstructing the operation independently.
>
> ## Example
>
> For `result = a @ b`, a caller can group every 16 columns, compute a sum for
> each group, and return both `result` and the compact tensor of sums. This
> commit carries the group size, column direction, sum operation, and two output
> buffers from Inductor into either supported vendored kernel.
>
>
> ```python
> def fn(a, b):
>     result = a @ b
>     grouped = result.float().view(m, n // 16, 16)
>     group_sums = grouped.sum(dim=-1)
>     return result, group_sums
> ```
>
> ## Test Plan
>
> ```bash
> python -m py_compile torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_gemm_efc_kernel.py
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#190821
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#194792, pytorch#194793
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…h#195231)

<human note needed>

> Define a shared representation for grouped GEMM reductions and use it as the
> boundary between epilogue analysis and backend-specific code generation.
>
> ## Shared reduction representation
>
> `GemmReductionGeometry` describes which logical GEMM output axis is reduced
> and how many adjacent elements belong to each group. It also determines
> whether the reduction fits inside one TensorSSA fragment or requires physical
> cross-thread combination.
>
> `GemmReductionPlan` carries the complete semantic contract:
>
> - the grouped reduction geometry;
> - the associative primitive, such as sum, product, minimum, or maximum;
> - generated source, combine, finalize, and consumer callbacks;
> - the primary and auxiliary output buffers;
> - whether the reduction feeds the primary GEMM output; and
> - whether the generated tensor epilogue returns a fragment-local reduction.
>
> This separates the mathematical operation from the physical reduction
> mechanism. Backends implement fragment traversal, synchronization, and
> storage, while generated callbacks describe the computation applied at each
> stage.
>
> ## Loop IR analysis
>
> Extend the Loop IR analysis to recognize both explicit reduction nodes and
> reductions expressed as unrolled pointwise operations. For an unrolled
> reduction, the analysis:
>
> 1. Finds the repeated loads from the GEMM output.
> 2. Uses their index ranges and strides to infer the group size and M/N axis.
> 3. Verifies that every lane applies the same pointwise source expression.
> 4. Identifies the associative primitive.
> 5. Preserves the source expression for later CuTeDSL callback generation.
>
> For example, an expression equivalent to:
>
> ```python
> grouped = output.float().view(m, n // 4, 4)
> reduced = torch.exp(grouped).sum(dim=-1)
> ```
>
> is represented as an N-axis group-of-four sum whose source expression is
> `exp(value)`.
>
> ## FlexGEMM integration
>
> Replace FlexGEMM's parallel template-time reduction description with a wrapper
> around `GemmReductionPlan`. The FlexGEMM wrapper retains only provider-specific
> information: the auxiliary-output index, output layout, and operand-swap
> state.
>
> FlexGEMM lowering now passes `epilogue_analysis.reduction_plan` directly into
> that wrapper. The shared geometry also owns the fragment-width and
> physical-callback decision previously implemented by a FlexGEMM-specific
> helper.
>
> This gives FlexGEMM and NVGEMM the same semantic reduction plan while allowing
> each provider to retain its own runtime ABI and code-generation machinery.
>
> ## Relationship between FlexGEMM and NVGEMM
>
> Both backends use the same semantic reduction plan, while retaining their
> existing analysis and runtime interfaces:
>
> ```mermaid
> flowchart LR
>     FX["FlexGEMM FX epilogue"] --> FXA["GemmLocalReduceAnalysis"]
>     LOOP["NVGEMM scheduler Loop IR"] --> LIA["GemmEpilogueIRAnalysis"]
>
>     FXA --> PLAN["GemmReductionPlan<br/>geometry, primitive, callbacks, outputs"]
>     LIA --> CFG["GemmReductionConfig"]
>     CFG --> PLAN
>
>     PLAN --> FLEXCFG["FlexGemmEpilogueLocalReduceConfig<br/>plan + output index + layout + swap_ab"]
>     FLEXCFG --> FLEXRT["FlexGemmRuntimeLocalReducePlan"]
>     FLEXRT --> QUACK["FlexGEMM / QuACK"]
>
>     PLAN --> NVCAP["NVGEMM capability validation"]
>     NVCAP --> NVARGS["GemmReductionArguments"]
>     NVARGS --> NVKERNEL["Vendored NVGEMM kernel"]
> ```
>
> `GemmReductionPlan` is the shared semantic boundary. FlexGEMM adds only the
> output placement and layout information needed by its template, while NVGEMM
> binds the plan to runtime tensors and cache-specialization fields.
>
> ## Testing
>
> Unit coverage for the shared reduction plan and FlexGEMM adapter is included
> in this PR.
>
> End-to-end dense and block-scaled generated-epilogue coverage is provided by
> [pytorch#190825](pytorch#190825).
>
> ```bash
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#195231
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#194792, pytorch#194793, pytorch#190821
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
…h#194873)

<human note needed>

> Introduce the semantic lowering and CuTeDSL emission layer for scheduler-owned
> GEMM epilogues. A candidate sequence of scheduler nodes is captured as Loop IR,
> classified from iteration ranges and access strides, and represented as one
> `NVGemmEpilogueProgram` containing pointwise work, grouped reduction regions,
> output ownership, and any callbacks required by the kernel.
>
> ## Architecture
>
> `NVGemmEpilogueCapture` interprets the candidate nodes without selecting a
> named reduction algorithm. `reduction_type` identifies only the associative
> primitive; the captured expressions define source transforms, finalizers,
> consumers, and compositions of multiple reductions with pointwise operations.
>
> `LoopIRCuteDSLCodegen` replays those expressions through the shared CuTeDSL
> operation overrides. Fragment-local reductions remain in the generated tensor
> epilogue. When a reduction crosses fragments or threads, the generated plan
> supplies combine and finalize callbacks while the vendored kernel owns
> traversal, synchronization, and storage.
>
> `NVGemmEpilogueProgram` is the validation boundary used by scheduling. It
> records which nodes belong to reduction regions, which outputs remain visible,
> whether a reduction feeds the main GEMM output, and whether every reduction in
> the candidate prefix has a supported lowering.
>
> ## Examples
>
> A pointwise epilogue becomes one generated callback:
>
> ```python
> result = a @ b
> return torch.relu(result.float() + bias)
> ```
>
> Multiple reductions and pointwise consumers remain one semantic program:
>
> ```python
> result = a @ b
> grouped = result.float().view(m, n // 4, 4)
> scale = grouped.sum(-1) + grouped.amax(-1)
> return (grouped / scale.unsqueeze(-1)).reshape(m, n), scale
> ```
>
> The second example is represented as an N-axis reduction with group size four.
> The generated epilogue computes both primitive reductions and the division; a
> larger or cross-thread geometry additionally receives generated physical
> reduction callbacks.
>
> ## Test Plan
>
> ```bash
> spin lint torch/_inductor/codegen/nv_universal_gemm/epilogue_lowering.py torch/_inductor/kernel/loop_ir_cutedsl_codegen.py
> lintrunner -a
> python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_lowering.py torch/_inductor/kernel/loop_ir_cutedsl_codegen.py
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#194873
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#194792, pytorch#194793, pytorch#190821, pytorch#195231
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…4792)

<human note needed>

> Replace the block-scaled kernel's string-selected reduction implementation
> with a generated CuTeDSL callback contract. The wrapper materializes the
> associative operation, identity, source transform, finalizer, and optional
> consumer while the vendored kernel retains only fragment traversal,
> synchronization, cross-warp combination, and output storage.
>
> Generalize epilogue input and output transport using packed arguments so the
> provider is not limited to a fixed number of captured tensors or auxiliary
> outputs.
>
> Test Plan:
>
> ```bash
> python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_capabilities.py torch/_inductor/kernel/gemm_epilogue.py torch/_inductor/kernel/gemm_epilogue_codegen.py torch/_inductor/kernel/vendored_templates/cutedsl/dense_blockscaled_gemm_persistent.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py
> lintrunner -a
> ```
>
> Authored with an AI assistant.

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

> Give the dense EFC kernel the same callback-based reduction interface as the
> block-scaled kernel. The wrapper materializes source, combine, finalize, and
> consumer functions, while the vendored kernel owns fragment traversal,
> synchronization, cross-thread combination, and output storage.
>
> The generated epilogue owns pointwise and fragment-local reduction semantics.
> Physical reduction geometry uses generated combine and finalize callbacks;
> the reduction primitive identifies the operation and does not select a
> runtime algorithm.
>
> Remove the dense reduction descriptor parser and hardcoded affine and boolean
> consumer arithmetic so both vendored kernels use the same callback contract.
>
> ## Test Plan
>
> ```bash
> python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_capabilities.py torch/_inductor/kernel/gemm_epilogue.py torch/_inductor/kernel/gemm_epilogue_analysis.py torch/_inductor/kernel/gemm_epilogue_codegen.py torch/_inductor/kernel/loop_ir_epilogue_lowering.py torch/_inductor/kernel/vendored_templates/cutedsl/dense_gemm_efc.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_gemm_efc_kernel.py
> PYTORCH_WORKTREE=$PWD env -u PYTHONPATH python agent_space/run_worktree_python.py test/inductor/test_nv_universal_gemm.py TestNVUniversalGemmHeuristics.test_dense_reduction_uses_generated_callback_contract TestNVUniversalGemm.test_scaled_gemm_grouped_n_reduce_provider -v
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#194793
Approved by: https://github.com/eellison
ghstack dependencies: pytorch#194792
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
> This connects PyTorch Inductor to the vendored dense and block-scaled matrix
> multiplication kernels that can perform extra work before storing their
> outputs. It gives both kernels one shared description of grouped reductions,
> validates whether a requested group size and direction are supported, builds
> the kernel arguments and output buffers, and includes those choices in the
> compilation cache key.
>
> Unsupported shapes or operations are rejected before launch so Inductor can
> use another implementation. Keeping this contract shared prevents the dense
> and block-scaled paths from interpreting the same post-processing differently.
>
> ## Architecture
>
> This commit introduces the common boundary between Inductor and the vendored
> kernels. Inductor describes the post-matrix-multiply work as one
> `GemmEpiloguePlan`; provider capability objects decide whether the dense or
> block-scaled kernel can implement it. The selected wrapper converts the plan
> into compile-time callbacks, runtime tensor arguments, output buffers, and
> cache specialization data. Each backend therefore receives the same validated
> contract instead of reconstructing the operation independently.
>
> ## Example
>
> For `result = a @ b`, a caller can group every 16 columns, compute a sum for
> each group, and return both `result` and the compact tensor of sums. This
> commit carries the group size, column direction, sum operation, and two output
> buffers from Inductor into either supported vendored kernel.
>
>
> ```python
> def fn(a, b):
>     result = a @ b
>     grouped = result.float().view(m, n // 16, 16)
>     group_sums = grouped.sum(dim=-1)
>     return result, group_sums
> ```
>
> ## Test Plan
>
> ```bash
> python -m py_compile torch/_inductor/codegen/cutedsl/cutedsl_op_overrides.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_blockscaled_gemm_kernel.py torch/_inductor/kernel/vendored_templates/cutedsl/wrappers/dense_gemm_efc_kernel.py
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#190821
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#194792, pytorch#194793
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…h#195231)

<human note needed>

> Define a shared representation for grouped GEMM reductions and use it as the
> boundary between epilogue analysis and backend-specific code generation.
>
> ## Shared reduction representation
>
> `GemmReductionGeometry` describes which logical GEMM output axis is reduced
> and how many adjacent elements belong to each group. It also determines
> whether the reduction fits inside one TensorSSA fragment or requires physical
> cross-thread combination.
>
> `GemmReductionPlan` carries the complete semantic contract:
>
> - the grouped reduction geometry;
> - the associative primitive, such as sum, product, minimum, or maximum;
> - generated source, combine, finalize, and consumer callbacks;
> - the primary and auxiliary output buffers;
> - whether the reduction feeds the primary GEMM output; and
> - whether the generated tensor epilogue returns a fragment-local reduction.
>
> This separates the mathematical operation from the physical reduction
> mechanism. Backends implement fragment traversal, synchronization, and
> storage, while generated callbacks describe the computation applied at each
> stage.
>
> ## Loop IR analysis
>
> Extend the Loop IR analysis to recognize both explicit reduction nodes and
> reductions expressed as unrolled pointwise operations. For an unrolled
> reduction, the analysis:
>
> 1. Finds the repeated loads from the GEMM output.
> 2. Uses their index ranges and strides to infer the group size and M/N axis.
> 3. Verifies that every lane applies the same pointwise source expression.
> 4. Identifies the associative primitive.
> 5. Preserves the source expression for later CuTeDSL callback generation.
>
> For example, an expression equivalent to:
>
> ```python
> grouped = output.float().view(m, n // 4, 4)
> reduced = torch.exp(grouped).sum(dim=-1)
> ```
>
> is represented as an N-axis group-of-four sum whose source expression is
> `exp(value)`.
>
> ## FlexGEMM integration
>
> Replace FlexGEMM's parallel template-time reduction description with a wrapper
> around `GemmReductionPlan`. The FlexGEMM wrapper retains only provider-specific
> information: the auxiliary-output index, output layout, and operand-swap
> state.
>
> FlexGEMM lowering now passes `epilogue_analysis.reduction_plan` directly into
> that wrapper. The shared geometry also owns the fragment-width and
> physical-callback decision previously implemented by a FlexGEMM-specific
> helper.
>
> This gives FlexGEMM and NVGEMM the same semantic reduction plan while allowing
> each provider to retain its own runtime ABI and code-generation machinery.
>
> ## Relationship between FlexGEMM and NVGEMM
>
> Both backends use the same semantic reduction plan, while retaining their
> existing analysis and runtime interfaces:
>
> ```mermaid
> flowchart LR
>     FX["FlexGEMM FX epilogue"] --> FXA["GemmLocalReduceAnalysis"]
>     LOOP["NVGEMM scheduler Loop IR"] --> LIA["GemmEpilogueIRAnalysis"]
>
>     FXA --> PLAN["GemmReductionPlan<br/>geometry, primitive, callbacks, outputs"]
>     LIA --> CFG["GemmReductionConfig"]
>     CFG --> PLAN
>
>     PLAN --> FLEXCFG["FlexGemmEpilogueLocalReduceConfig<br/>plan + output index + layout + swap_ab"]
>     FLEXCFG --> FLEXRT["FlexGemmRuntimeLocalReducePlan"]
>     FLEXRT --> QUACK["FlexGEMM / QuACK"]
>
>     PLAN --> NVCAP["NVGEMM capability validation"]
>     NVCAP --> NVARGS["GemmReductionArguments"]
>     NVARGS --> NVKERNEL["Vendored NVGEMM kernel"]
> ```
>
> `GemmReductionPlan` is the shared semantic boundary. FlexGEMM adds only the
> output placement and layout information needed by its template, while NVGEMM
> binds the plan to runtime tensors and cache-specialization fields.
>
> ## Testing
>
> Unit coverage for the shared reduction plan and FlexGEMM adapter is included
> in this PR.
>
> End-to-end dense and block-scaled generated-epilogue coverage is provided by
> [pytorch#190825](pytorch#190825).
>
> ```bash
> lintrunner -a
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#195231
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#194792, pytorch#194793, pytorch#190821
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…h#194873)

<human note needed>

> Introduce the semantic lowering and CuTeDSL emission layer for scheduler-owned
> GEMM epilogues. A candidate sequence of scheduler nodes is captured as Loop IR,
> classified from iteration ranges and access strides, and represented as one
> `NVGemmEpilogueProgram` containing pointwise work, grouped reduction regions,
> output ownership, and any callbacks required by the kernel.
>
> ## Architecture
>
> `NVGemmEpilogueCapture` interprets the candidate nodes without selecting a
> named reduction algorithm. `reduction_type` identifies only the associative
> primitive; the captured expressions define source transforms, finalizers,
> consumers, and compositions of multiple reductions with pointwise operations.
>
> `LoopIRCuteDSLCodegen` replays those expressions through the shared CuTeDSL
> operation overrides. Fragment-local reductions remain in the generated tensor
> epilogue. When a reduction crosses fragments or threads, the generated plan
> supplies combine and finalize callbacks while the vendored kernel owns
> traversal, synchronization, and storage.
>
> `NVGemmEpilogueProgram` is the validation boundary used by scheduling. It
> records which nodes belong to reduction regions, which outputs remain visible,
> whether a reduction feeds the main GEMM output, and whether every reduction in
> the candidate prefix has a supported lowering.
>
> ## Examples
>
> A pointwise epilogue becomes one generated callback:
>
> ```python
> result = a @ b
> return torch.relu(result.float() + bias)
> ```
>
> Multiple reductions and pointwise consumers remain one semantic program:
>
> ```python
> result = a @ b
> grouped = result.float().view(m, n // 4, 4)
> scale = grouped.sum(-1) + grouped.amax(-1)
> return (grouped / scale.unsqueeze(-1)).reshape(m, n), scale
> ```
>
> The second example is represented as an N-axis reduction with group size four.
> The generated epilogue computes both primitive reductions and the division; a
> larger or cross-thread geometry additionally receives generated physical
> reduction callbacks.
>
> ## Test Plan
>
> ```bash
> spin lint torch/_inductor/codegen/nv_universal_gemm/epilogue_lowering.py torch/_inductor/kernel/loop_ir_cutedsl_codegen.py
> lintrunner -a
> python -m py_compile torch/_inductor/codegen/nv_universal_gemm/epilogue_lowering.py torch/_inductor/kernel/loop_ir_cutedsl_codegen.py
> ```
>
> Description drafted with an AI assistant.

Pull Request resolved: pytorch#194873
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#194792, pytorch#194793, pytorch#190821, pytorch#195231
@github-actions
github-actions Bot deleted the gh/mlazos/312/head branch November 13, 2026 01:44
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.

3 participants