Skip to content

[Inductor] Reindex pointwise before can_fuse_vertical to enable reduction-broadcast fusion - #183521

Closed
hoshibara wants to merge 9 commits into
pytorch:mainfrom
hoshibara:mxfp8-quant-fuse
Closed

hoshibara wants to merge 9 commits into
pytorch:mainfrom
hoshibara:mxfp8-quant-fuse

Conversation

@hoshibara

@hoshibara hoshibara commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

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:

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

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

@pytorch-bot

pytorch-bot Bot commented May 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (4 Unrelated Failures)

As of commit a3d849a with merge base ef303cd (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

UNSTABLE - The following jobs are marked as unstable, possibly due to flakiness on trunk:

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

@pytorch-bot

pytorch-bot Bot commented May 13, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@pytorch-bot

pytorch-bot Bot commented May 13, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/inductor
  • ciflow/torchtitan

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@hoshibara
hoshibara marked this pull request as draft May 13, 2026 07:18
@hoshibara

Copy link
Copy Markdown
Contributor Author

@pytorchbot label "topic: not user facing"

@etaf

etaf commented May 14, 2026

Copy link
Copy Markdown
Collaborator

Please add UT.

Test block-wise quantization pattern where reduction writes with
index buf[G*p0 + p1] but pointwise reads with FloorDiv broadcast
buf[G*p0 + (p1 // block_size)].

Two tests:
- Standalone block reduction + broadcast: expects 1 kernel
- RMSNorm + block quantization: expects 2 kernels (not 3)

Regression test for pytorch#183542
@etaf
etaf marked this pull request as ready for review May 14, 2026 03:49
@etaf
etaf requested a review from eellison May 14, 2026 03:49
@jansel

jansel commented May 14, 2026

Copy link
Copy Markdown
Contributor

@claude review these changes

@claude

claude Bot commented May 14, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 3m 8s —— View job


Code Review

  • Read the diff and changed files
  • Review torch/_inductor/scheduler.py changes
  • Review test/inductor/test_loop_ordering.py changes
  • Post review feedback

Overall: The approach is sound and well-structured. The key insight — trying reindexing only as a fallback after normal vertical fusion fails — is the right design. The previous commit (374ab38) that unconditionally reindexed before can_fuse_vertical was problematic because it could silently mutate nodes even when normal fusion would have succeeded. The current version correctly avoids that.

torch/_inductor/scheduler.py

Correctness: Good. The rollback safety is well-handled:

  • _try_reindex_pointwise_for_reduction has its own internal rollback (via _LoopStateSnapshot) when reindexing doesn't improve shared deps.
  • The outer _LoopMutationTracker in can_fuse() (line 7049) captures state before any mutation and rolls back if the overall fusion decision is False — so even if reindexing succeeds but the subsequent can_fuse_vertical retry fails, the state is properly restored.

Observation on the first can_fuse_vertical call: can_fuse_vertical itself is read-only (no loop mutations), so calling it first as a fast path before attempting reindexing is safe and efficient for the common case where iteration domains already match.

Minor nit: The comment uses a Unicode em dash (—) on line 7320. The project's CLAUDE.md says "ASCII only in newly added code comments." Since this is a new comment, it should use -- instead. Same on line 7323.

Fix this →

test/inductor/test_loop_ordering.py

Test quality: Good coverage. The two tests target the specific pattern described in the PR:

  1. test_floordiv_broadcast_vertical_fusion — isolated FloorDiv broadcast case
  2. test_floordiv_broadcast_with_preceding_reduction — end-to-end RMSNorm + block quant

Suggestion for the second test: test_floordiv_broadcast_with_preceding_reduction (line 609) manually calls torch._dynamo.reset() and metrics.reset() even though setUp() (line 242) already resets metrics. The dynamo reset is defensive (fine to keep), but the explicit metrics.reset() is unnecessary since setUp runs before each test. Not a blocker, just a style inconsistency with the first test.

Observation on the comment from @etaf ("Please add UT"): The tests were already added in commit e010e4e — this concern appears resolved.

Summary

This is a clean, well-motivated change. The only actionable feedback is the Unicode em dash in the comments (per repo coding style). The logic is correct, the rollback semantics are preserved, and the tests cover the regression case well.


@zou3519 zou3519 added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 14, 2026

@eellison eellison 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.

One comment about alternative approach

):
return True

# Vertical fusion failed — the iteration domains may not

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.

Thanks for the PR! After a bit of investigation with Codex, the root cause is that the two incompatible
SchedulerNodes don't attempt to reindex because they already share a common MemoryDep, arg0_1.

This PR adds a second round of reindexing when vertical fusion fails, after we already looked at doing
reindexing during shared-data scoring. This succeeds where the first path returned early.

The alternative way of fixing this would be to do something along the lines of
#179090: prioritize mismatching read/write deps in loop reindexing,
even if there already exists a shared read.

This should cover the test you've added.

Also, after #182897, we'll be able to fuse the MXFP8 casts in the
norm too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion. I tested this on a source build after #182897 with clean Inductor/Triton caches, and the reproducer still shows the same gap:

  • RMSNorm + MXFP8: still 3 kernels for M>=4 (expected 2)
  • Standalone MXFP8: still 2 kernels at M=32 (expected 1)

So #182897 does not resolve this FloorDiv-broadcast fusion case. The reindex-fallback retry in this PR is still needed.

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.

I wasn't suggesting doing #182897 directly. I will share the patch along what I'm suggesting.

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.

This is what I am suggesting:

diff --git a/torch/_inductor/scheduler.py b/torch/_inductor/scheduler.py
index 9f8c6ca4f76..b603bf973c8 100644
--- a/torch/_inductor/scheduler.py
+++ b/torch/_inductor/scheduler.py
@@ -6832,17 +6832,7 @@ class Scheduler:
             pw_node.group = snodes[0].group
             refresh_group_node_dependencies(pw_node)
 
-        # Verify reindexing actually increases shared deps.
-        common_names = (
-            node1.read_writes.buffer_names() & node2.read_writes.buffer_names()
-        )
-        n1_deps = {dep.name: dep for dep in node1.read_writes.reads_and_writes()}
-        n2_deps = {dep.name: dep for dep in node2.read_writes.reads_and_writes()}
-        has_benefit = any(
-            self.deps_match_normalized(n1_deps[name], n2_deps[name])
-            for name in common_names
-        )
-        if not has_benefit:
+        if not self._reindexing_has_dependency_benefit(node1, node2):
             rollback_snapshot.restore()
             return False
 
@@ -6859,6 +6849,50 @@ class Scheduler:
 
         return True
 
+    def _reindexing_has_dependency_benefit(
+        self,
+        node1: BaseSchedulerNode,
+        node2: BaseSchedulerNode,
+    ) -> bool:
+        def mem_deps(deps: typing.Iterable[Dep]) -> list[MemoryDep]:
+            return [dep for dep in deps if isinstance(dep, MemoryDep)]
+
+        n1_reads = mem_deps(node1.read_writes.reads)
+        n1_writes = mem_deps(node1.read_writes.writes)
+        n2_reads = mem_deps(node2.read_writes.reads)
+        n2_writes = mem_deps(node2.read_writes.writes)
+        n1_deps = n1_reads + n1_writes
+        n2_deps = n2_reads + n2_writes
+
+        # Prioritize write/read deps: for vertical fusion, shared reads can
+        # improve the memory score but do not satisfy the consumer's dependency
+        # on the producer output. Final legality is still checked later.
+        producer_writes, consumer_reads = (), ()
+        if node1.get_operation_names() & node2.ancestors:
+            producer_writes, consumer_reads = n1_writes, n2_reads
+        elif node2.get_operation_names() & node1.ancestors:
+            producer_writes, consumer_reads = n2_writes, n1_reads
+
+        writes_by_name: defaultdict[str, list[MemoryDep]] = defaultdict(list)
+        for write in producer_writes:
+            writes_by_name[write.name].append(write)
+        for read in consumer_reads:
+            matching_writes = writes_by_name.get(read.name)
+            if matching_writes and not any(
+                self.deps_match_normalized(write, read) for write in matching_writes
+            ):
+                return False
+
+        n1_deps_by_name: defaultdict[str, list[MemoryDep]] = defaultdict(list)
+        for dep in n1_deps:
+            n1_deps_by_name[dep.name].append(dep)
+
+        return any(
+            self.deps_match_normalized(dep1, dep2)
+            for dep2 in n2_deps
+            for dep1 in n1_deps_by_name.get(dep2.name, ())
+        )
+
     def unfusable_node(self, node: BaseSchedulerNode) -> bool:
         """
         Is this node unfusable under any conditions.

@hoshibara
hoshibara requested a review from eellison May 15, 2026 08:11

@jansel jansel 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.

fix merge conflicts

@hoshibara
hoshibara requested a review from a team as a code owner May 15, 2026 08:52
@hoshibara
hoshibara marked this pull request as draft May 15, 2026 08:53
# Conflicts:
#	torch/_inductor/scheduler.py
@hoshibara
hoshibara marked this pull request as ready for review May 15, 2026 08:57
@hoshibara
hoshibara requested a review from jansel May 15, 2026 09:00
@EikanWang

Copy link
Copy Markdown
Collaborator

@hoshibara , please rebase this PR for the green signal.

@hoshibara

Copy link
Copy Markdown
Contributor Author

@hoshibara , please rebase this PR for the green signal.

Hi @EikanWang, CI passed

@hoshibara

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot

pytorch-bot Bot commented May 21, 2026

Copy link
Copy Markdown

This PR has pending changes requested. Please address the comments and update the PR before merging.

@hoshibara

hoshibara commented May 21, 2026 •

Copy link
Copy Markdown
Contributor Author

fix merge conflicts

Hi @jansel, conflict has been resolved. Could you review it again?

@jansel

jansel commented May 21, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label May 21, 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

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@hoshibara

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 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
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
…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
anijain2305 added a commit that referenced this pull request Aug 20, 2026
can_fuse had a second chance for vertical fusion: when the checks failed, it
reindexed the pointwise to the reduction's iteration domain and ran them again.
This PR originally kept that retry and added a pre-check to skip it when graph
topology already ruled the fusion out, because most retries were wasted - 560 of
576 on one model's backward graph.

Per review, the retry itself is no longer needed: the case it was added for
(#183521) is handled by the original loop-transform path, and that PR's own
tests, test_floordiv_broadcast_vertical_fusion and
test_floordiv_broadcast_with_preceding_reduction, pass without it. So delete the
retry rather than optimize it, and with it the pre-check this PR had added.

Note what stays. _try_reindex_pointwise_for_reduction is still live: it is called
from shared_data_after_reordering_loop, which is the loop-transform path the
review suggested handling this in. config.loop_reindexing_after_fusion still
gates that call and the score threshold above it. Only the retry in can_fuse and
its pre-check go away.

No compile-time claim this time. The workload the earlier numbers came from is
nondeterministic - it fabricates random inputs, and three runs of *identical*
code produced 96, 100 and 101 triton kernels in 46.24s, 45.76s and 48.40s - so a
difference of a second or two between the two variants cannot be resolved on it,
and the measurements I took disagreed with each other. The justification here is
that the code path is unnecessary, not that removing it is faster.

Test plan:

```
python test/inductor/test_loop_ordering.py
```

124 tests, OK, and the failure set is identical to a run with the retry still in
place. Both tests from #183521 pass individually.

This PR was authored with the assistance of an AI coding agent.

ghstack-source-id: 8b4573a
Pull-Request: #193158
anijain2305 added a commit that referenced this pull request Aug 20, 2026
can_fuse had a second chance for vertical fusion: when the checks failed, it
reindexed the pointwise to the reduction's iteration domain and ran them again.
This PR originally kept that retry and added a pre-check to skip it when graph
topology already ruled the fusion out, because most retries were wasted - 560 of
576 on one model's backward graph.

Per review, the retry itself is no longer needed: the case it was added for
(#183521) is handled by the original loop-transform path, and that PR's own
tests, test_floordiv_broadcast_vertical_fusion and
test_floordiv_broadcast_with_preceding_reduction, pass without it. So delete the
retry rather than optimize it, and with it the pre-check this PR had added.

Note what stays. _try_reindex_pointwise_for_reduction is still live: it is called
from shared_data_after_reordering_loop, which is the loop-transform path the
review suggested handling this in. config.loop_reindexing_after_fusion still
gates that call and the score threshold above it. Only the retry in can_fuse and
its pre-check go away.

No compile-time claim this time. The workload the earlier numbers came from is
nondeterministic - it fabricates random inputs, and three runs of *identical*
code produced 96, 100 and 101 triton kernels in 46.24s, 45.76s and 48.40s - so a
difference of a second or two between the two variants cannot be resolved on it,
and the measurements I took disagreed with each other. The justification here is
that the code path is unnecessary, not that removing it is faster.

Test plan:

```
python test/inductor/test_loop_ordering.py
```

124 tests, OK, and the failure set is identical to a run with the retry still in
place. Both tests from #183521 pass individually.

This PR was authored with the assistance of an AI coding agent.

ghstack-source-id: 8b4573a
Pull-Request: #193158
anijain2305 added a commit that referenced this pull request Aug 20, 2026
can_fuse had a second chance for vertical fusion: when the checks failed, it
reindexed the pointwise to the reduction's iteration domain and ran them again.
This PR originally kept that retry and added a pre-check to skip it when graph
topology already ruled the fusion out, because most retries were wasted - 560 of
576 on one model's backward graph.

Per review, the retry itself is no longer needed: the case it was added for
(#183521) is handled by the original loop-transform path, and that PR's own
tests, test_floordiv_broadcast_vertical_fusion and
test_floordiv_broadcast_with_preceding_reduction, pass without it. So delete the
retry rather than optimize it, and with it the pre-check this PR had added.

Note what stays. _try_reindex_pointwise_for_reduction is still live: it is called
from shared_data_after_reordering_loop, which is the loop-transform path the
review suggested handling this in. config.loop_reindexing_after_fusion still
gates that call and the score threshold above it. Only the retry in can_fuse and
its pre-check go away.

No compile-time claim this time. The workload the earlier numbers came from is
nondeterministic - it fabricates random inputs, and three runs of *identical*
code produced 96, 100 and 101 triton kernels in 46.24s, 45.76s and 48.40s - so a
difference of a second or two between the two variants cannot be resolved on it,
and the measurements I took disagreed with each other. The justification here is
that the code path is unnecessary, not that removing it is faster.

Test plan:

```
python test/inductor/test_loop_ordering.py
```

124 tests, OK, and the failure set is identical to a run with the retry still in
place. Both tests from #183521 pass individually.

This PR was authored with the assistance of an AI coding agent.

ghstack-source-id: f8e9fdc
Pull-Request: #193158
pytorchmergebot pushed a commit that referenced this pull request Aug 20, 2026
can_fuse had a second chance for vertical fusion: when the checks failed, it
reindexed the pointwise to the reduction's iteration domain and ran them again.
This PR originally kept that retry and added a pre-check to skip it when graph
topology already ruled the fusion out, because most retries were wasted - 560 of
576 on one model's backward graph.

Per review, the retry itself is no longer needed: the case it was added for
(#183521) is handled by the original loop-transform path, and that PR's own
tests, test_floordiv_broadcast_vertical_fusion and
test_floordiv_broadcast_with_preceding_reduction, pass without it. So delete the
retry rather than optimize it, and with it the pre-check this PR had added.

Note what stays. _try_reindex_pointwise_for_reduction is still live: it is called
from shared_data_after_reordering_loop, which is the loop-transform path the
review suggested handling this in. config.loop_reindexing_after_fusion still
gates that call and the score threshold above it. Only the retry in can_fuse and
its pre-check go away.

No compile-time claim this time. The workload the earlier numbers came from is
nondeterministic - it fabricates random inputs, and three runs of *identical*
code produced 96, 100 and 101 triton kernels in 46.24s, 45.76s and 48.40s - so a
difference of a second or two between the two variants cannot be resolved on it,
and the measurements I took disagreed with each other. The justification here is
that the code path is unnecessary, not that removing it is faster.

Test plan:

```
python test/inductor/test_loop_ordering.py
```

124 tests, OK, and the failure set is identical to a run with the retry still in
place. Both tests from #183521 pass individually.

This PR was authored with the assistance of an AI coding agent.

Pull Request resolved: #193158
Approved by: https://github.com/eellison
orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
can_fuse had a second chance for vertical fusion: when the checks failed, it
reindexed the pointwise to the reduction's iteration domain and ran them again.
This PR originally kept that retry and added a pre-check to skip it when graph
topology already ruled the fusion out, because most retries were wasted - 560 of
576 on one model's backward graph.

Per review, the retry itself is no longer needed: the case it was added for
(pytorch#183521) is handled by the original loop-transform path, and that PR's own
tests, test_floordiv_broadcast_vertical_fusion and
test_floordiv_broadcast_with_preceding_reduction, pass without it. So delete the
retry rather than optimize it, and with it the pre-check this PR had added.

Note what stays. _try_reindex_pointwise_for_reduction is still live: it is called
from shared_data_after_reordering_loop, which is the loop-transform path the
review suggested handling this in. config.loop_reindexing_after_fusion still
gates that call and the score threshold above it. Only the retry in can_fuse and
its pre-check go away.

No compile-time claim this time. The workload the earlier numbers came from is
nondeterministic - it fabricates random inputs, and three runs of *identical*
code produced 96, 100 and 101 triton kernels in 46.24s, 45.76s and 48.40s - so a
difference of a second or two between the two variants cannot be resolved on it,
and the measurements I took disagreed with each other. The justification here is
that the code path is unnecessary, not that removing it is faster.

Test plan:

```
python test/inductor/test_loop_ordering.py
```

124 tests, OK, and the failure set is identical to a run with the retry still in
place. Both tests from pytorch#183521 pass individually.

This PR was authored with the assistance of an AI coding agent.

Pull Request resolved: pytorch#193158
Approved by: 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 ciflow/xpu Run XPU CI tasks Merged module: inductor open source topic: not user facing topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

[Inductor] Block-wise quantization (MXFP8) fusion rejects FloorDiv broadcast index before reindex runs

9 participants