Skip to content

Reindex pointwise iteration loops to enable fusion with reductions - #176927

Closed
eellison wants to merge 8 commits into
gh/eellison/963/basefrom
gh/eellison/963/head
Closed

eellison wants to merge 8 commits into
gh/eellison/963/basefrom
gh/eellison/963/head

Conversation

@eellison

@eellison eellison commented Mar 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

When a pointwise and reduction operate on the same data but with
different iteration spaces (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Motivation is to fuse qknorm.

Authored with Claude.

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

When a pointwise and reduction operate on the same data but with
different loop decompositions (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Authored with Claude.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Mar 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 8f82588 with merge base 58e3fb0 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot

pytorch-bot Bot commented Mar 9, 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.

sandy-gags pushed a commit to sandy-gags/pytorch that referenced this pull request Mar 12, 2026
When a pointwise and reduction operate on the same data but with
different loop decompositions (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Authored with Claude.

ghstack-source-id: 22a7ca9
Pull Request resolved: pytorch/pytorch#176927
@pytorch-bot pytorch-bot Bot added the ciflow/torchtitan Run TorchTitan integration tests label Apr 1, 2026
…ductions"

When a pointwise and reduction operate on the same data but with
different loop decompositions (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Authored with Claude.

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

[ghstack-poisoned]
@eellison
eellison requested a review from shunting314 April 2, 2026 15:37
…ductions"


When a pointwise and reduction operate on the same data but with
different iteration spaces (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Authored with Claude.

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

[ghstack-poisoned]
@eellison
eellison requested a review from PaulZhang12 April 3, 2026 18:24
Comment thread torch/_inductor/scheduler.py Resolved
@PaulZhang12

Copy link
Copy Markdown
Contributor

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

@PaulZhang12 PaulZhang12 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Generally LGTM, do we want a dashboard run if we turn this on by default?

@claude

claude Bot commented Apr 3, 2026 •

Copy link
Copy Markdown

Claude finished @PaulZhang12's task in 16m 7s —— View job


PR Review: Reindex pointwise iteration loops to enable fusion with reductions

  • Read changed files and understand the implementation
  • Analyze edge cases and potential issues
  • Post review feedback

Summary

This PR adds a loop reindexing pass that re-expresses a pointwise node's iteration variables (via FloorDiv/ModularIndexing of a flat index) to match a reduction's loop factorization. This enables fusion when a reshape changes the iteration space (e.g., [M, N] → [M*num_heads, head_dim]). The implementation handles both single SchedulerNode and FusedSchedulerNode cases.

The approach is sound and well-motivated. Below are the issues and edge cases I identified, ranging from a real correctness concern to minor suggestions.


Issue 1: Irreversible mutation before fusion is confirmed (the big one)

scheduler.py:5697-5702

The TODO comment on line 5697 correctly identifies the core problem: _try_reindex_pointwise_for_reduction mutates nodes in place before can_fuse has finished its checks. Specifically, after shared_data_after_reordering_loop returns, there are still multiple rejection points in can_fuse:

  1. V.choices.can_fuse(...) at line 6116
  2. can_fuse_vertical(...) / can_fuse_horizontal(...) at lines 6121-6129

If any of these checks reject the fusion, the pointwise node (and its sub-nodes if a FusedSchedulerNode) is left permanently reindexed. This corrupted state then affects all subsequent scheduling decisions for that node.

This is not unique to this PR — the existing reorder_loops_by_dep_pair and shared_data_after_inverting_indexing have the same problem. However, reindexing is a more drastic transformation than reordering (it changes the number and meaning of iteration dimensions, not just their order), so the consequences of an unrolled mutation may be worse.

Recommended mitigation: Consider snapshotting _body, _sizes, group, and read_writes before mutation and restoring them if fusion ultimately fails. Alternatively, validate that can_fuse_vertical/can_fuse_horizontal will succeed before committing the reindexing. This could be a follow-up.


Issue 2: reindex_iter_loops doesn't assert the numel invariant

loop_body.py:291-341

The caller (_try_reindex_pointwise_for_reduction) validates that the pointwise node's total iter numel equals the reduction's numel * rnumel, but reindex_iter_loops itself doesn't assert this invariant. If the method is ever called from another site without this pre-check, silent data corruption could result (the ModularIndexing expressions would be mathematically wrong).

Adding a defensive assert would be inexpensive:

assert sympy_product(old_iter_sizes) == sympy_product(new_iter_sizes)

This is a sympy symbolic equality check and might be tricky to get right for symbolic shapes, but for static shapes it would catch misuse.


Issue 3: Config default is enabled ("1") everywhere

config.py:842-844

loop_reindexing_after_fusion defaults to "1" unconditionally. In contrast, loop_ordering_after_fusion defaults to "0" in fbcode. Given @PaulZhang12's comment about potential default perf impact, consider:

  • Matching the fbcode-off pattern of loop_ordering_after_fusion
  • Or at minimum, running a dashboard benchmark before landing with default-on

Issue 4: score_fusion_memory fallback path after reindexing

scheduler.py:5575-5579

After successful reindexing, if _try_reorder_loops_for_candidates still returns -1 (no candidates with matching normalized stride order), the code falls through to:

return typing.cast(int, self.score_fusion_memory(node1, node2))

This means even if loop reordering can't find matching candidates, the function returns a non-negative score (potentially 0), which can_fuse at line 6087 will treat as a successful reordering (new_shared_data_score >= 0). This could result in:

  • Reindexing the pointwise node
  • Returning a low score (e.g., 0)
  • Which then may fail the score_fusion_memory_threshold check, making the reindexing pointless

Returning score_fusion_memory as a fallback is reasonable if the reindexing alone is sufficient for fusion (the deps now match without needing loop reordering). But it would be clearer to document why this fallback is valid — after reindexing, the deps should naturally align, so score_fusion_memory should return a meaningful positive score. If it returns 0, the reindexing was ineffective and we've mutated the node for nothing.


Issue 5: No test for failed-reindexing recovery

The tests cover the happy path (fusion succeeds after reindexing), but there are no tests for:

  • Cases where is_compatible returns False and reindexing is correctly skipped
  • Cases where numel doesn't match (e.g., pointwise with different total numel than the reduction)
  • The mutation-then-rejection scenario described in Issue 1

Adding a test where reindexing is attempted but fusion is rejected downstream would help catch regressions if the rollback mechanism is added later.


Issue 6: Symbolic shape handling

scheduler.py:5683-5689

The statically_known_equals check will return False for dynamic/symbolic shapes that aren't provably equal at compile time, causing the optimization to be silently skipped. This is the safe behavior, but it means the optimization won't fire for models with dynamic batch dimensions even when the shapes are actually compatible at runtime. This is fine for now but worth noting in the context of future dynamic shape work.


Minor observations

  • loop_body.py:312: The new_body closure captures new_iter_sizes from the enclosing scope. Since new_iter_sizes is a Sequence, if a caller passes a mutable list and modifies it later, the closure would see the mutated value. This is unlikely in practice but tuple(new_iter_sizes) would be safer.

  • test_loop_ordering.py:486: torch._dynamo.reset() is called at the end of test_reshape_reindexing_fused_pointwise but not test_reshape_reindexing_for_reduction. Is the reset intentional for only the fused case?


Overall assessment

The core idea is well-implemented and addresses a real fusion gap for RMS norm patterns. The main concern is the pre-existing architectural issue of mutating-before-confirming-fusion, which this PR inherits and should address (even if just with the existing TODO). The config default and lack of negative test cases are the most actionable items before landing.

@eellison

eellison commented Apr 3, 2026

Copy link
Copy Markdown
Contributor Author

I will do a perf run. ive seen a couple patterns where this allows fusions already. but i agree it would be nice to be more certain that when we reindex, we will fuse.

@shunting314 shunting314 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

How does it work with an non-contiguous input for the pointwise nodes? It may not be a valid setup since the view op on the non-contiguous input may fail in some cases

@shunting314

Copy link
Copy Markdown
Contributor

An interesting alternative is: instead of reindexing, we can try to merge/flatten loops of the pointwise node

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
…ductions"


When a pointwise and reduction operate on the same data but with
different iteration spaces (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Motivation is to fuse qknorm.

Authored with Claude.

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

[ghstack-poisoned]
@eellison

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

…ductions"


When a pointwise and reduction operate on the same data but with
different iteration spaces (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Motivation is to fuse qknorm.

Authored with Claude.

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

[ghstack-poisoned]
@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 pushed a commit that referenced this pull request Apr 15, 2026
…79090)

_try_reorder_loops_for_candidates picks the largest common buffer to guide loop reordering. When a shared read (e.g., an input to both kernels) is larger than a write→read dep, it gets picked. Instead, we should prioritize based on the dependencies that are blocking fusion.

This pr prioritizes those dependencies, and detects when loop re-ordering will not be able to successfully fix a failed fusion. In this case we do not reorder the node’s loops. Loop ordering after fusion was interfering with loop reindexing. Potential other approaches would be either saving a pre-modified node prior to loop reordering, or, finding a way to reverse the transformation.

This fixes an fp8 grouped quantization fusion where reshape changes the iteration domain (e.g., [8, 7168] vs [448, 128]). The reduction and pointwise share the input tensor (large, normalizes to match) but the reduction output (small, different factorization) blocks can_fuse_vertical.

Authored with Claude.

Pull Request resolved: #179090
Approved by: https://github.com/shunting314
ghstack dependencies: #176927
pytorchmergebot pushed a commit that referenced this pull request Apr 15, 2026
Pointwise cat evaluates every input's computation for each output element (masked), so fusing reductions in is normally wasteful. When cat inputs just recombine a reduction's output (e.g. qknorm → RoPE → cat), no computation is duplicated — exclude that specific reduction from the guard so pointwise cat can enable fusion.

Authored with Claude.

Pull Request resolved: #179091
Approved by: https://github.com/PaulZhang12
ghstack dependencies: #176927, #179090
@github-actions
github-actions Bot deleted the gh/eellison/963/head branch May 16, 2026 02:27
pytorchmergebot pushed a commit that referenced this pull request May 22, 2026
…uction-broadcast fusion (#183521)

Edited by claude.

## Motivation

While profiling Llama4-Maverick-17B-128E with TorchAO MXFP8 quantization, every RMSNorm + block-wise MXFP8 quant layer produces **3 kernels instead of 2**. The root cause is a `FloorDiv` index mismatch in vertical fusion: the block-amax reduction writes `buf[256*p0 + p1]` (`p1 ∈ [0, 256)`) but the fp8-quantize pointwise reads `buf[256*p0 + (p1 // 32)]` (`p1 ∈ [0, 8192)`). `fusable_read_and_write` in `can_fuse_vertical` rejects this with `"memory deps did not match"`.

The existing `_try_reindex_pointwise_for_reduction` (from #176927) can resolve this mismatch by rewriting the pointwise's iteration domain to match the reduction's. However, it currently only runs inside `shared_data_after_reordering_loop` (the scoring/loop-ordering path) — by then, `can_fuse_vertical` has already rejected the pair.

This affects any block-wise quantization pattern (MXFP8, MXFP4, etc.) where a per-block scale is broadcast back to element granularity via `unsqueeze`.

Fixes #183542

## Solution

In `can_fuse` (the top-level fusion entry point), when vertical fusion fails, attempt `_try_reindex_pointwise_for_reduction` as a fallback before giving up. If reindexing succeeds, retry the full `can_fuse_vertical` chain:

```python
if node1.get_operation_names() & node2.ancestors:
    # Try vertical fusion normally first
    if (
        self.can_fuse_vertical(node1, node2)
        and V.choices.can_fuse_vertical(...)
        and self.get_backend(device).can_fuse_vertical(...)
    ):
        return True

    # Vertical fusion failed — try reindexing pointwise to match
    # reduction's iteration domain (e.g. FloorDiv broadcast)
    if (
        config.loop_reindexing_after_fusion
        and self._try_reindex_pointwise_for_reduction(node1, node2)
    ):
        return (
            self.can_fuse_vertical(node1, node2)
            and V.choices.can_fuse_vertical(...)
            and self.get_backend(device).can_fuse_vertical(...)
        )

    return False
```

`_try_reindex_pointwise_for_reduction` has a built-in rollback — if reindexing doesn't improve shared deps it restores the original node state, so this is safe to call speculatively. Gated behind `config.loop_reindexing_after_fusion` (enabled by default).

## Test plan

Two new tests in `test/inductor/test_loop_ordering.py`:

- **`test_floordiv_broadcast_vertical_fusion`**: Standalone block reduction + FloorDiv broadcast pointwise → expects **1 kernel** (was 2).
- **`test_floordiv_broadcast_with_preceding_reduction`**: RMSNorm + block-wise quantization → expects **2 kernels** (was 3).

| Pattern | Before | After |
|---------|--------|-------|
| Block reduction + broadcast pointwise | 2 kernels | 1 kernel |
| RMSNorm + block-wise quantization | 3 kernels | 2 kernels |

Pull Request resolved: #183521
Approved by: https://github.com/jansel, https://github.com/eellison
pytorchmergebot pushed a commit to khushi-411/pytorch that referenced this pull request May 24, 2026
…uction-broadcast fusion (pytorch#183521)

Edited by claude.

## Motivation

While profiling Llama4-Maverick-17B-128E with TorchAO MXFP8 quantization, every RMSNorm + block-wise MXFP8 quant layer produces **3 kernels instead of 2**. The root cause is a `FloorDiv` index mismatch in vertical fusion: the block-amax reduction writes `buf[256*p0 + p1]` (`p1 ∈ [0, 256)`) but the fp8-quantize pointwise reads `buf[256*p0 + (p1 // 32)]` (`p1 ∈ [0, 8192)`). `fusable_read_and_write` in `can_fuse_vertical` rejects this with `"memory deps did not match"`.

The existing `_try_reindex_pointwise_for_reduction` (from pytorch#176927) can resolve this mismatch by rewriting the pointwise's iteration domain to match the reduction's. However, it currently only runs inside `shared_data_after_reordering_loop` (the scoring/loop-ordering path) — by then, `can_fuse_vertical` has already rejected the pair.

This affects any block-wise quantization pattern (MXFP8, MXFP4, etc.) where a per-block scale is broadcast back to element granularity via `unsqueeze`.

Fixes pytorch#183542

## Solution

In `can_fuse` (the top-level fusion entry point), when vertical fusion fails, attempt `_try_reindex_pointwise_for_reduction` as a fallback before giving up. If reindexing succeeds, retry the full `can_fuse_vertical` chain:

```python
if node1.get_operation_names() & node2.ancestors:
    # Try vertical fusion normally first
    if (
        self.can_fuse_vertical(node1, node2)
        and V.choices.can_fuse_vertical(...)
        and self.get_backend(device).can_fuse_vertical(...)
    ):
        return True

    # Vertical fusion failed — try reindexing pointwise to match
    # reduction's iteration domain (e.g. FloorDiv broadcast)
    if (
        config.loop_reindexing_after_fusion
        and self._try_reindex_pointwise_for_reduction(node1, node2)
    ):
        return (
            self.can_fuse_vertical(node1, node2)
            and V.choices.can_fuse_vertical(...)
            and self.get_backend(device).can_fuse_vertical(...)
        )

    return False
```

`_try_reindex_pointwise_for_reduction` has a built-in rollback — if reindexing doesn't improve shared deps it restores the original node state, so this is safe to call speculatively. Gated behind `config.loop_reindexing_after_fusion` (enabled by default).

## Test plan

Two new tests in `test/inductor/test_loop_ordering.py`:

- **`test_floordiv_broadcast_vertical_fusion`**: Standalone block reduction + FloorDiv broadcast pointwise → expects **1 kernel** (was 2).
- **`test_floordiv_broadcast_with_preceding_reduction`**: RMSNorm + block-wise quantization → expects **2 kernels** (was 3).

| Pattern | Before | After |
|---------|--------|-------|
| Block reduction + broadcast pointwise | 2 kernels | 1 kernel |
| RMSNorm + block-wise quantization | 3 kernels | 2 kernels |

Pull Request resolved: pytorch#183521
Approved by: https://github.com/jansel, https://github.com/eellison
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…torch#179090)

_try_reorder_loops_for_candidates picks the largest common buffer to guide loop reordering. When a shared read (e.g., an input to both kernels) is larger than a write→read dep, it gets picked. Instead, we should prioritize based on the dependencies that are blocking fusion.

This pr prioritizes those dependencies, and detects when loop re-ordering will not be able to successfully fix a failed fusion. In this case we do not reorder the node’s loops. Loop ordering after fusion was interfering with loop reindexing. Potential other approaches would be either saving a pre-modified node prior to loop reordering, or, finding a way to reverse the transformation.

This fixes an fp8 grouped quantization fusion where reshape changes the iteration domain (e.g., [8, 7168] vs [448, 128]). The reduction and pointwise share the input tensor (large, normalizes to match) but the reduction output (small, different factorization) blocks can_fuse_vertical.

Authored with Claude.

Pull Request resolved: pytorch#179090
Approved by: https://github.com/shunting314
ghstack dependencies: pytorch#176927
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…9091)

Pointwise cat evaluates every input's computation for each output element (masked), so fusing reductions in is normally wasteful. When cat inputs just recombine a reduction's output (e.g. qknorm → RoPE → cat), no computation is duplicated — exclude that specific reduction from the guard so pointwise cat can enable fusion.

Authored with Claude.

Pull Request resolved: pytorch#179091
Approved by: https://github.com/PaulZhang12
ghstack dependencies: pytorch#176927, pytorch#179090
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…ytorch#176927)

When a pointwise and reduction operate on the same data but with
different iteration spaces (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Motivation is to fuse qknorm.

Authored with Claude.

Pull Request resolved: pytorch#176927
Approved by: https://github.com/PaulZhang12, https://github.com/shunting314
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…torch#179090)

_try_reorder_loops_for_candidates picks the largest common buffer to guide loop reordering. When a shared read (e.g., an input to both kernels) is larger than a write→read dep, it gets picked. Instead, we should prioritize based on the dependencies that are blocking fusion.

This pr prioritizes those dependencies, and detects when loop re-ordering will not be able to successfully fix a failed fusion. In this case we do not reorder the node’s loops. Loop ordering after fusion was interfering with loop reindexing. Potential other approaches would be either saving a pre-modified node prior to loop reordering, or, finding a way to reverse the transformation.

This fixes an fp8 grouped quantization fusion where reshape changes the iteration domain (e.g., [8, 7168] vs [448, 128]). The reduction and pointwise share the input tensor (large, normalizes to match) but the reduction output (small, different factorization) blocks can_fuse_vertical.

Authored with Claude.

Pull Request resolved: pytorch#179090
Approved by: https://github.com/shunting314
ghstack dependencies: pytorch#176927
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…9091)

Pointwise cat evaluates every input's computation for each output element (masked), so fusing reductions in is normally wasteful. When cat inputs just recombine a reduction's output (e.g. qknorm → RoPE → cat), no computation is duplicated — exclude that specific reduction from the guard so pointwise cat can enable fusion.

Authored with Claude.

Pull Request resolved: pytorch#179091
Approved by: https://github.com/PaulZhang12
ghstack dependencies: pytorch#176927, pytorch#179090
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…uction-broadcast fusion (pytorch#183521)

Edited by claude.

## Motivation

While profiling Llama4-Maverick-17B-128E with TorchAO MXFP8 quantization, every RMSNorm + block-wise MXFP8 quant layer produces **3 kernels instead of 2**. The root cause is a `FloorDiv` index mismatch in vertical fusion: the block-amax reduction writes `buf[256*p0 + p1]` (`p1 ∈ [0, 256)`) but the fp8-quantize pointwise reads `buf[256*p0 + (p1 // 32)]` (`p1 ∈ [0, 8192)`). `fusable_read_and_write` in `can_fuse_vertical` rejects this with `"memory deps did not match"`.

The existing `_try_reindex_pointwise_for_reduction` (from pytorch#176927) can resolve this mismatch by rewriting the pointwise's iteration domain to match the reduction's. However, it currently only runs inside `shared_data_after_reordering_loop` (the scoring/loop-ordering path) — by then, `can_fuse_vertical` has already rejected the pair.

This affects any block-wise quantization pattern (MXFP8, MXFP4, etc.) where a per-block scale is broadcast back to element granularity via `unsqueeze`.

Fixes pytorch#183542

## Solution

In `can_fuse` (the top-level fusion entry point), when vertical fusion fails, attempt `_try_reindex_pointwise_for_reduction` as a fallback before giving up. If reindexing succeeds, retry the full `can_fuse_vertical` chain:

```python
if node1.get_operation_names() & node2.ancestors:
    # Try vertical fusion normally first
    if (
        self.can_fuse_vertical(node1, node2)
        and V.choices.can_fuse_vertical(...)
        and self.get_backend(device).can_fuse_vertical(...)
    ):
        return True

    # Vertical fusion failed — try reindexing pointwise to match
    # reduction's iteration domain (e.g. FloorDiv broadcast)
    if (
        config.loop_reindexing_after_fusion
        and self._try_reindex_pointwise_for_reduction(node1, node2)
    ):
        return (
            self.can_fuse_vertical(node1, node2)
            and V.choices.can_fuse_vertical(...)
            and self.get_backend(device).can_fuse_vertical(...)
        )

    return False
```

`_try_reindex_pointwise_for_reduction` has a built-in rollback — if reindexing doesn't improve shared deps it restores the original node state, so this is safe to call speculatively. Gated behind `config.loop_reindexing_after_fusion` (enabled by default).

## Test plan

Two new tests in `test/inductor/test_loop_ordering.py`:

- **`test_floordiv_broadcast_vertical_fusion`**: Standalone block reduction + FloorDiv broadcast pointwise → expects **1 kernel** (was 2).
- **`test_floordiv_broadcast_with_preceding_reduction`**: RMSNorm + block-wise quantization → expects **2 kernels** (was 3).

| Pattern | Before | After |
|---------|--------|-------|
| Block reduction + broadcast pointwise | 2 kernels | 1 kernel |
| RMSNorm + block-wise quantization | 3 kernels | 2 kernels |

Pull Request resolved: pytorch#183521
Approved by: https://github.com/jansel, https://github.com/eellison
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ytorch#176927)

When a pointwise and reduction operate on the same data but with
different iteration spaces (e.g., [M, N] vs [M*num_heads, head_dim]
after a reshape), they can't fuse because their MemoryDep index
expressions differ. This adds loop reindexing: re-expressing a
pointwise's iteration variables via FloorDiv/ModularIndexing of a flat
index to match the reduction's factorization.

Handles both single SchedulerNode and FusedSchedulerNode (multiple
fused pointwise ops).

Motivation is to fuse qknorm.

Authored with Claude.

Pull Request resolved: pytorch#176927
Approved by: https://github.com/PaulZhang12, https://github.com/shunting314
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…torch#179090)

_try_reorder_loops_for_candidates picks the largest common buffer to guide loop reordering. When a shared read (e.g., an input to both kernels) is larger than a write→read dep, it gets picked. Instead, we should prioritize based on the dependencies that are blocking fusion.

This pr prioritizes those dependencies, and detects when loop re-ordering will not be able to successfully fix a failed fusion. In this case we do not reorder the node’s loops. Loop ordering after fusion was interfering with loop reindexing. Potential other approaches would be either saving a pre-modified node prior to loop reordering, or, finding a way to reverse the transformation.

This fixes an fp8 grouped quantization fusion where reshape changes the iteration domain (e.g., [8, 7168] vs [448, 128]). The reduction and pointwise share the input tensor (large, normalizes to match) but the reduction output (small, different factorization) blocks can_fuse_vertical.

Authored with Claude.

Pull Request resolved: pytorch#179090
Approved by: https://github.com/shunting314
ghstack dependencies: pytorch#176927
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…9091)

Pointwise cat evaluates every input's computation for each output element (masked), so fusing reductions in is normally wasteful. When cat inputs just recombine a reduction's output (e.g. qknorm → RoPE → cat), no computation is duplicated — exclude that specific reduction from the guard so pointwise cat can enable fusion.

Authored with Claude.

Pull Request resolved: pytorch#179091
Approved by: https://github.com/PaulZhang12
ghstack dependencies: pytorch#176927, pytorch#179090
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…uction-broadcast fusion (pytorch#183521)

Edited by claude.

## Motivation

While profiling Llama4-Maverick-17B-128E with TorchAO MXFP8 quantization, every RMSNorm + block-wise MXFP8 quant layer produces **3 kernels instead of 2**. The root cause is a `FloorDiv` index mismatch in vertical fusion: the block-amax reduction writes `buf[256*p0 + p1]` (`p1 ∈ [0, 256)`) but the fp8-quantize pointwise reads `buf[256*p0 + (p1 // 32)]` (`p1 ∈ [0, 8192)`). `fusable_read_and_write` in `can_fuse_vertical` rejects this with `"memory deps did not match"`.

The existing `_try_reindex_pointwise_for_reduction` (from pytorch#176927) can resolve this mismatch by rewriting the pointwise's iteration domain to match the reduction's. However, it currently only runs inside `shared_data_after_reordering_loop` (the scoring/loop-ordering path) — by then, `can_fuse_vertical` has already rejected the pair.

This affects any block-wise quantization pattern (MXFP8, MXFP4, etc.) where a per-block scale is broadcast back to element granularity via `unsqueeze`.

Fixes pytorch#183542

## Solution

In `can_fuse` (the top-level fusion entry point), when vertical fusion fails, attempt `_try_reindex_pointwise_for_reduction` as a fallback before giving up. If reindexing succeeds, retry the full `can_fuse_vertical` chain:

```python
if node1.get_operation_names() & node2.ancestors:
    # Try vertical fusion normally first
    if (
        self.can_fuse_vertical(node1, node2)
        and V.choices.can_fuse_vertical(...)
        and self.get_backend(device).can_fuse_vertical(...)
    ):
        return True

    # Vertical fusion failed — try reindexing pointwise to match
    # reduction's iteration domain (e.g. FloorDiv broadcast)
    if (
        config.loop_reindexing_after_fusion
        and self._try_reindex_pointwise_for_reduction(node1, node2)
    ):
        return (
            self.can_fuse_vertical(node1, node2)
            and V.choices.can_fuse_vertical(...)
            and self.get_backend(device).can_fuse_vertical(...)
        )

    return False
```

`_try_reindex_pointwise_for_reduction` has a built-in rollback — if reindexing doesn't improve shared deps it restores the original node state, so this is safe to call speculatively. Gated behind `config.loop_reindexing_after_fusion` (enabled by default).

## Test plan

Two new tests in `test/inductor/test_loop_ordering.py`:

- **`test_floordiv_broadcast_vertical_fusion`**: Standalone block reduction + FloorDiv broadcast pointwise → expects **1 kernel** (was 2).
- **`test_floordiv_broadcast_with_preceding_reduction`**: RMSNorm + block-wise quantization → expects **2 kernels** (was 3).

| Pattern | Before | After |
|---------|--------|-------|
| Block reduction + broadcast pointwise | 2 kernels | 1 kernel |
| RMSNorm + block-wise quantization | 3 kernels | 2 kernels |

Pull Request resolved: pytorch#183521
Approved by: https://github.com/jansel, https://github.com/eellison
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 topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants