Skip to content

[inductor] Add scheduler index equivalence for nested reductions - #183432

Closed
eellison wants to merge 5 commits into
gh/eellison/1017/basefrom
gh/eellison/1017/head
Closed

eellison wants to merge 5 commits into
gh/eellison/1017/basefrom
gh/eellison/1017/head

Conversation

@eellison

@eellison eellison commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Nested full-res consumers can see producer outputs through broadcasted or loop-reordered MemoryDep forms. This commit adds an opt-in vertical dependency check for nested candidates and parent-full nested consumers while keeping exact matching as the default path.

One accepted quotient-broadcast shape is a consumer read like MemoryDep('buf', 32*d0 + FloorDiv(d1, 128), (d0, d1), (128, 4096)) matching a producer write like MemoryDep('buf', 32*w0 + w1, (w0, w1), (128, 32)). The helper splits the larger read dimension as w1 * 128 + tail and relies on range simplification to prove the read address reduces to the producer address, while rejecting cases where the tail still affects the address.

The relaxed path still rejects producer-side broadcast or aliasing writes, then proves consumer-side equivalence from the MemoryDep address expression and loop ranges by normalization or conservative broadcast splitting. It also gives these producer-output deps a memory score so fusion choices do not discard them before legality runs.

Authored with Codex.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ You can merge normally! (1 Unrelated Failure)

As of commit 7aea947 with merge base 8e63642 (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.

eellison added 2 commits May 12, 2026 07:19
[ghstack-poisoned]
[ghstack-poisoned]
@PaulZhang12

Copy link
Copy Markdown
Contributor

@claude review this PR and keep in mind potential issues, code quality, and edge cases

1 similar comment
@PaulZhang12

Copy link
Copy Markdown
Contributor

@claude review this PR and keep in mind potential issues, code quality, and edge cases

@claude

claude Bot commented May 12, 2026 •

Copy link
Copy Markdown

Claude finished @PaulZhang12's task in 2m 26s —— View job


PR Review: [inductor] Add scheduler index equivalence for nested reductions

  • Gather context and read changed files
  • Analyze scheduler.py changes
  • Analyze test changes
  • Post review findings

This is a well-structured PR that relaxes the vertical dependency matching for nested reduction fusion paths. The core idea is sound: parent-full consumers can read producer outputs through broadcasted or loop-reordered views, and this commit proves equivalence symbolically rather than requiring exact index matching. Below are my findings.

Overall Assessment

The code is well-organized with clear separation of concerns:

  1. _fusable_read_after_index_equivalence gates on producer-side density/injectivity
  2. _fusable_read_after_broadcast handles the two specific broadcast shapes
  3. Scoring is wired up to prevent the heuristic from discarding valid fusion candidates

The PR is approved by @jansel and the logic appears correct. I have a few observations below.

Observations & Minor Issues

1. Double mutation_renames normalization (harmless but redundant)

can_fuse normalizes index_equivalent_dep_names at line 6933-6936, then score_fusion_memory normalizes it again at line 7626-7630. This is safe since mutation_renames.get(name, name) is idempotent for already-resolved names, but it's unnecessary work on each scoring call. Consider normalizing only at the entry point.

2. _producer_output_names_read_by_consumer called multiple times

In can_fuse, when index_equivalent_dep_names is None and nested_reduction_candidate is True, _producer_output_names_read_by_consumer is called once for scoring (line 7130-7131) and potentially again for vertical legality (line 7195-7196). Since the same (node1, node2) pair is used, the result could be computed once and reused. Not a correctness issue, just a minor efficiency concern since this method iterates all reads/writes.

3. _fusable_read_after_broadcast — write.normalize() called twice in _fusable_read_after_index_equivalence

At scheduler.py:7411-7413:

if not (
    write.normalize().is_contiguous()
    or write.normalize_with_stride_order().is_contiguous()
):

normalize() is potentially called once here, and then again inside deps_match_normalized at line 7417 (which calls dep.normalize() or dep.normalize_with_stride_order() on the write). Depending on whether MemoryDep caches its normalization, this could be re-computed. Low priority since these are small objects.

4. Static symbol names in _fusable_read_after_broadcast

Symbols like _fusable_broadcast_0 are created fresh each call (lines 7460, 7481). This is fine for correctness since they're local to the comparison, but if sympy caches symbols globally, repeated calls will reuse the same Symbol object. This is actually desirable here (no issue), just noting it's intentional.

5. Edge case: empty tail_ranges early-return

At line 7488, if not tail_ranges: return False — this means if all dimensions match exactly between read and write, the method returns False. This is correct because that exact case would have been caught earlier by deps_match_normalized (line 7417). Good defensive design.

6. The "producer alias" test case is important

("producer alias",
 MemoryDep("buf", d0 + d1, (d0, d1), (2, 2)),
 MemoryDep("buf", w0 + w1, (w0, w1), (2, 2)),
 False, False),

This correctly verifies that a non-injective write (where d0+d1 maps multiple input coordinates to the same address) is rejected by the OrderedSet(write.var_names) <= write.index.free_symbols check. Important for soundness.

7. Consider a test for mode_requires_synchronization

The test mocks mode_requires_synchronization to always return False. It would be valuable to add a case where the write has a synchronization mode (e.g., atomic_add) to verify that fusable_read_and_write returns False regardless of allow_index_equivalence=True.

Summary

The implementation is sound. The key safety invariants are:

  • Producer writes must be dense and injective (checked via var_names ⊆ free_symbols and contiguity after normalization)
  • Consumer reads are proven equivalent through range simplification
  • The relaxed path is opt-in, gated by allow_index_equivalence which is only enabled for named producer outputs in the nested reduction path

The test coverage for fusable_read_and_write is good with both positive and negative cases. The integration with the scoring system ensures these deps aren't silently dropped by heuristics.


@claude

claude Bot commented May 12, 2026 •

Copy link
Copy Markdown

Claude finished @PaulZhang12's task in 4m 3s —— View job


PR Review: [inductor] Add scheduler index equivalence for nested reductions

  • Read the changed files and understand the implementation
  • Review torch/_inductor/scheduler.py changes
  • Review test/inductor/test_inductor_scheduler.py changes
  • Identify potential issues, edge cases, and code quality concerns
  • Post final review

Summary

This PR adds relaxed index-equivalence matching for nested reduction fusion. When a consumer reads a producer output through a broadcasted or loop-reordered view (e.g., FloorDiv(d1, 128) quotient indexing), the existing exact-match logic rejects the fusion. This commit introduces an opt-in allow_index_equivalence flag that proves equivalence through normalization or conservative broadcast splitting.

The approach is sound: it keeps exact matching as default, and only relaxes for specifically identified producer-output deps that the nested-reduction path has already domain-classified.


Code Quality

Well-structured layering. The implementation correctly separates concerns:

  1. Domain classification identifies which deps need relaxed matching (FusedNestedReductions.can_fuse_with)
  2. Scoring gives those deps memory weight so fusion heuristics don't discard them early (_score_fusion_memory_by_fusable_read_write)
  3. Vertical legality uses the same relaxed matching for the actual fusion check (can_fuse_vertical)

Good defensive checks in _fusable_read_after_index_equivalence (scheduler.py:7406-7419):

  • Rejects producer-side broadcast (var_names ⊆ free_symbols)
  • Rejects non-injective writes (contiguity after normalization)
  • Falls through to conservative broadcast splitting only after these guards pass

Potential Issues

1. Redundant mutation_renames normalization (minor)

index_equivalent_dep_names gets normalized via mutation_renames.get(name, name) in three places:

  • The caller (FusedNestedReductions.can_fuse_with at line ~2904)
  • can_fuse (line ~6934)
  • score_fusion_memory (line ~7627)

This is safe because mutation_renames is idempotent (targets are never keys), but it's somewhat noisy. Consider documenting the contract (e.g., "names should be passed as canonical; normalization here is defensive") or centralizing it.

2. _fusable_read_after_broadcast symbol collision (theoretical)

At line 7460, fresh symbols _fusable_broadcast_{i} are created. If these names ever collide with actual graph symbols (unlikely given the underscore prefix convention), substitution could produce incorrect results. This is a theoretical concern only — the naming convention makes collision implausible in practice.

3. Edge case: read.size and write.size both symbolic

When both read_size and write_size are symbolic (e.g., s0 and s1), statically_known_equals(Mod(s0, s1), 0) will return False and the quotient path will bail out. The "dynamic dense" test case (line 134-137) handles this via the deps_match_normalized path in _fusable_read_after_index_equivalence, so it's correctly handled — just noting for future reference that the broadcast splitting path is static-only.

4. not tail_ranges early-return (line 7488)

If all dimensions have equal sizes (no quotient needed), tail_ranges is empty and the function returns False. This is intentional — equal-size cases should have matched earlier via deps_match_normalized. But it means a case where read and write have equal sizes but different var names (which somehow failed normalization) would fall through to False here. This seems fine given the earlier normalization checks.


Test Coverage

The test at test_fusable_read_and_write_broadcast_requires_index_equivalence covers the key cases well:

  • Quotient broadcast — core feature path
  • Quotient tail remains — rejects when tail affects address
  • Pure broadcast — broadcast dims absent from index
  • Dynamic dense — symbolic sizes handled through normalization path
  • Exact gapped — non-contiguous but exact-match still works
  • Producer broadcast — correctly rejected (non-injective write)
  • Producer alias — correctly rejected (non-contiguous write)
  • Loop-ordering normalization — existing config-gated path still works with the new flag

Suggestion: Consider adding a test case for:

  • A read with both pure broadcast dims and quotient dims simultaneously (to exercise the read reassignment at line 7445 followed by the quotient path)
  • A case where write.normalize_with_stride_order().is_contiguous() is True but write.normalize().is_contiguous() is False (to exercise the second branch of the guard)

Overall Assessment

This is a well-designed extension that carefully limits its blast radius — the relaxed matching only activates for explicitly identified nested-reduction producer outputs. The injectivity/contiguity guards on the producer write prevent unsound fusions. The scoring integration ensures these deps aren't silently dropped by heuristics before legality checks run.

The PR is already approved by @jansel and the approach looks correct.


[ghstack-poisoned]
@eellison

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

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

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, linux.g5.48xlarge.nvidia.gpu)

Details for Dev Infra team Raised by workflow job

@eellison

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: torchtitan-test / torchtitan-x-pytorch-test / test (torchtitan_models_integration, 1, 1, linux.g5.48xlarge.nvidia.gpu)

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: Command git -C /home/runner/work/pytorch/pytorch cherry-pick -x 5a634eb06ed4d72b8e552f9f5574cf332676bc07 returned non-zero exit code 1

Auto-merging test/inductor/test_inductor_scheduler.py
CONFLICT (content): Merge conflict in test/inductor/test_inductor_scheduler.py
Auto-merging torch/_inductor/scheduler.py
CONFLICT (content): Merge conflict in torch/_inductor/scheduler.py
error: could not apply 5a634eb06ed... [inductor] Add scheduler index equivalence for nested reductions
hint: After resolving the conflicts, mark them with
hint: "git add/rm <pathspec>", then run
hint: "git cherry-pick --continue".
hint: You can instead skip this commit with "git cherry-pick --skip".
hint: To abort and get back to the state before "git cherry-pick",
hint: run "git cherry-pick --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Details for Dev Infra team Raised by workflow job

@eellison

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #183632

jemitche1 pushed a commit to jemitche1/pytorch that referenced this pull request May 14, 2026
…orch#183432)

Nested full-res consumers can see producer outputs through broadcasted or loop-reordered MemoryDep forms. This commit adds an opt-in vertical dependency check for nested candidates and parent-full nested consumers while keeping exact matching as the default path.

One accepted quotient-broadcast shape is a consumer read like `MemoryDep('buf', 32*d0 + FloorDiv(d1, 128), (d0, d1), (128, 4096))` matching a producer write like `MemoryDep('buf', 32*w0 + w1, (w0, w1), (128, 32))`. The helper splits the larger read dimension as w1 * 128 + tail and relies on range simplification to prove the read address reduces to the producer address, while rejecting cases where the tail still affects the address.

The relaxed path still rejects producer-side broadcast or aliasing writes, then proves consumer-side equivalence from the MemoryDep address expression and loop ranges by normalization or conservative broadcast splitting. It also gives these producer-output deps a memory score so fusion choices do not discard them before legality runs.

Authored with Codex.

Pull Request resolved: pytorch#183432
Approved by: https://github.com/jansel, https://github.com/PaulZhang12
pytorchmergebot pushed a commit that referenced this pull request May 14, 2026
The set linter's bracket parser kept f-string state in the same stack as token indices, so nested f-strings could later be interpreted as an index and crash. Track f-string nesting separately and add a regression case.

Authored by Codex.
Pull Request resolved: #183632
Approved by: https://github.com/drisspg, https://github.com/Skylion007
ghstack dependencies: #183432
pytorchmergebot pushed a commit that referenced this pull request May 15, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: #182897
Approved by: https://github.com/jansel
ghstack dependencies: #183432, #183632
pytorchmergebot pushed a commit that referenced this pull request May 20, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: #182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: #183432, #183632
pytorchmergebot pushed a commit to khushi-411/pytorch that referenced this pull request May 20, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: pytorch#183432, pytorch#183632
pytorchmergebot pushed a commit that referenced this pull request May 20, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: #182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: #183432, #183632
pytorchmergebot pushed a commit to weishi-deng/pytorch that referenced this pull request May 21, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: pytorch#183432, pytorch#183632
pytorchmergebot pushed a commit to weishi-deng/pytorch that referenced this pull request May 21, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: pytorch#183432, pytorch#183632
@github-actions
github-actions Bot deleted the gh/eellison/1017/head branch June 14, 2026 02:28
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…orch#183432)

Nested full-res consumers can see producer outputs through broadcasted or loop-reordered MemoryDep forms. This commit adds an opt-in vertical dependency check for nested candidates and parent-full nested consumers while keeping exact matching as the default path.

One accepted quotient-broadcast shape is a consumer read like `MemoryDep('buf', 32*d0 + FloorDiv(d1, 128), (d0, d1), (128, 4096))` matching a producer write like `MemoryDep('buf', 32*w0 + w1, (w0, w1), (128, 32))`. The helper splits the larger read dimension as w1 * 128 + tail and relies on range simplification to prove the read address reduces to the producer address, while rejecting cases where the tail still affects the address.

The relaxed path still rejects producer-side broadcast or aliasing writes, then proves consumer-side equivalence from the MemoryDep address expression and loop ranges by normalization or conservative broadcast splitting. It also gives these producer-output deps a memory score so fusion choices do not discard them before legality runs.

Authored with Codex.

Pull Request resolved: pytorch#183432
Approved by: https://github.com/jansel, https://github.com/PaulZhang12
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
The set linter's bracket parser kept f-string state in the same stack as token indices, so nested f-strings could later be interpreted as an index and crash. Track f-string nesting separately and add a regression case.

Authored by Codex.
Pull Request resolved: pytorch#183632
Approved by: https://github.com/drisspg, https://github.com/Skylion007
ghstack dependencies: pytorch#183432
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/jansel
ghstack dependencies: pytorch#183432, pytorch#183632
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: pytorch#183432, pytorch#183632
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: pytorch#183432, pytorch#183632
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…orch#183432)

Nested full-res consumers can see producer outputs through broadcasted or loop-reordered MemoryDep forms. This commit adds an opt-in vertical dependency check for nested candidates and parent-full nested consumers while keeping exact matching as the default path.

One accepted quotient-broadcast shape is a consumer read like `MemoryDep('buf', 32*d0 + FloorDiv(d1, 128), (d0, d1), (128, 4096))` matching a producer write like `MemoryDep('buf', 32*w0 + w1, (w0, w1), (128, 32))`. The helper splits the larger read dimension as w1 * 128 + tail and relies on range simplification to prove the read address reduces to the producer address, while rejecting cases where the tail still affects the address.

The relaxed path still rejects producer-side broadcast or aliasing writes, then proves consumer-side equivalence from the MemoryDep address expression and loop ranges by normalization or conservative broadcast splitting. It also gives these producer-output deps a memory score so fusion choices do not discard them before legality runs.

Authored with Codex.

Pull Request resolved: pytorch#183432
Approved by: https://github.com/jansel, https://github.com/PaulZhang12
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
The set linter's bracket parser kept f-string state in the same stack as token indices, so nested f-strings could later be interpreted as an index and crash. Track f-string nesting separately and add a regression case.

Authored by Codex.
Pull Request resolved: pytorch#183632
Approved by: https://github.com/drisspg, https://github.com/Skylion007
ghstack dependencies: pytorch#183432
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/jansel
ghstack dependencies: pytorch#183432, pytorch#183632
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: pytorch#183432, pytorch#183632
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
*
[inductor] Lower nested reductions in SIMD codegen

This commit adds the first SIMD/Triton lowering for nested grouped reductions. The target pattern is an outer reduction such as LayerNorm/RMSNorm over `D`, followed by a local grouped reduction over a small block inside that same `D` axis, for example `x_normed.reshape(B, D // G, G).amax(-1)`. Before this commit, the two reductions used different iteration views of the same logical data: the outer stage saw `(B, D)`, while the grouped stage saw `(B, D // G, G)`. That mismatch meant Inductor had to materialize the intermediate and launch a separate grouped-reduction kernel.

The new lowering keeps the outer reduction as the owner of the Triton kernel's grid, tiling, and persistent/looped reduction choice. After the ordinary SIMD outer reduction is emitted, codegen remaps the grouped reduction body into the same parent tile. For this commit's supported case, the local group splits the parent R axis: `[XBLOCK, RBLOCK]` is reshaped to `[XBLOCK, RBLOCK / G, G]`, then Triton reduces axis 2 to produce `[XBLOCK, RBLOCK / G]`. The kernel also forces `min_rblock = G` so the parent tile always contains at least one whole local group.

Most of the implementation is in `torch/_inductor/codegen/simd.py`. `_GroupedReductionLayout` describes the R-axis grouped geometry, derived iteration families switch codegen between parent-full and reduced-output views, and the nested ops handlers remap loads/stores while emitting reshape, reduce, and broadcast operations through new helpers in `torch/_inductor/codegen/triton.py`. Scheduler dispatch is updated so `FusedNestedReductions` routes to `codegen_nested_reduction`, is excluded from combo kernels, and increments `metrics.codegen_nested_reduction`.

The scope is intentionally conservative. This commit enables `triton.nested_reduction` by default, but only supports grouped reductions that split the parent R axis; `GroupedAxis.X` is still rejected here. Group size must be static, power-of-two, and within the existing min-block limits, and nested lowering still excludes higher-rank grouped layouts, multiple grouped reductions, split reductions, cooperative reduction, C++ wrapper support, and tuple/stateful reductions such as argmax or Welford variance.
Authored with Claude.

Pull Request resolved: pytorch#182897
Approved by: https://github.com/mlazos, https://github.com/drisspg
ghstack dependencies: pytorch#183432, pytorch#183632
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants