Skip to content

[inductor] Forward live reduction lanes into persistent fixed-lane epilogues - #200466

Closed
eellison wants to merge 18 commits into
gh/eellison/1122/basefrom
gh/eellison/1122/head
Closed

eellison wants to merge 18 commits into
gh/eellison/1122/basefrom
gh/eellison/1122/head

Conversation

@eellison

@eellison eellison commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Author's note: When the reduction itself is the group, a persistent kernel already holds each group's tile, but fixed-lane epilogue reads forced the producer to be materialized. This plans those epilogues against the live tile and forces a persistent kernel only when the backend heuristic agrees, so the producer, reduction, and epilogue compile to one kernel.

The description below was drafted with an AI assistant (Claude):

A reduced-width epilogue that reads a fixed element of each reduction group
(e.g. v.amax(-1) + v[:, 7] with v of shape [N, G]) reads a value a
persistent reduction already holds in registers. Today that value is loaded
again, and if v is materialized in the same graph the epilogue cannot fuse:
it reads v at a different index than the producer writes it.

For persistent reductions with a static power-of-2 group (at most 128), the
scheduler now plans such epilogues as sub-parent stages whose lane reads are
resolved from the live tile (requires_persistent plans). The lanes of a group
must be live together; since the reduction is the group, that means a
persistent kernel, which SIMDScheduling forces for these plans (a looped
multi-kernel variant could not serve the lanes). Suggested review order:

  1. NestedReduction._persistent_lane_epilogue_candidates: which reductions
    and epilogues qualify.
  2. sub_parent_epilogue_plan: instead of the hoisting mutation check,
    persistent candidates (which have no mutations) only accept aliased
    outputs that are slices of a ConcatKernel they feed (e.g. the columns of
    torch.stack(words, -1)). Concat slices are disjoint and their stores keep
    their own indexing; a reader of the concat depends on the concat node and
    cannot join the group.
  3. The scheduler side: the existing index-equivalence fallback now also
    accepts reads of persistent plans; the sub-parent read proof maps a size-1
    child coordinate; the row-boundary check accepts a flat contiguous source
    over the whole frame; and can_fuse can prepend reduced epilogues to an
    existing FusedStagedReduction.

A reduction that an upstream reduction over the same full domain could own as
an outer + grouped nested pipeline is left to that planner.

Performance on MI300X, 16M elements, v materialized as an output:
v.abs().amax(-1) + v[:, G // 3] goes from 2 kernels to 1 and 1.12-1.14x for
G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
and faster beyond that (0.43-0.58x of the load time for all 32).

test_nested_reduction.py's even/odd consumer test now expects the fixed-lane
side output to fuse while the incompatible consumers keep their own kernel.

Test Plan:

python -m pytest test/inductor/test_persistent_reduction_lanes.py \
  test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
  test/inductor/test_inductor_scheduler.py

A randomized sweep of 173 generated lane graphs matched eager.
test_single_group_is_not_forwarded and test_dynamic_group_count cover a
single group and a symbolic group count, both declined (their epilogue ranges
are empty, or merge differently per node in merge_loops).
test_tiled_group_axes covers a GEMM scale tile whose first axis has size 1.

This change was prepared with an AI assistant.

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

🟡 AUTOMATED REVIEW - Changes requested:

The PR adds a persistent path for reduced-width epilogues that read fixed lanes
of a reduction group, planning them against the reduction's live tile so the
producer, reduction and epilogue compile to one kernel. Recommendation: Request
Changes. The blockers are: the default-on persistent path turns 1 kernel into 2
when no live lane is needed; the multi-kernel gate forces persistence without
the benchmark its scaled threshold relies on; Path 3 rejects fusions before the
backend gate can decline the plan; and the new tests are too weak and
misclassify hardware.

Findings (15):

[major] torch/_inductor/scheduler.py:813
Under default config, some graphs go from 1 kernel to 2. `requires_persistent =
grouping is None` sends every miss of the looped grouping to the persistent
planner, and the plan only needs a non-empty `source_relations`. Nothing
requires a relation with `requires_live_source and parent_lane is not None`.
Repro (traced, not run): `x` is a graph input `[B, 32]`, `s = x.sum(-1) - x[:,
0]` is realized, `y = x / s[:, None]`. (1) `{sum, s}` gets a persistent plan:
lane 0 of the input is proved through the new `child_coordinate = 0`, and
`fuse()` builds a `FusedStagedReduction`. (2) `can_fuse(FSR, y)` gets no plan
because `y` reads an epilogue output. (3) The guard passes because `live_lanes`
is False. (4) SIMD rejects with "staged reduction plan would be lost". No fusion
order avoids this; before the PR all three fused. These groups also lose combo
kernels, benchmark fusion and the looped multi-kernel variant. Fix: take the
persistent path only when some relation needs a live lane, or keep no-live-lane
groups as a plain `FusedSchedulerNode`. Add the regression test.

[major] torch/_inductor/codegen/simd.py:3184
With multi-kernel on, the fusion gate and the forced kernel disagree (here vs
`simd.py:4256-4257`). Under `triton.multi_kernel`,
`should_use_persistent_reduction` multiplies its threshold by 16
(`choices.py:549-550`) because multi-kernel will benchmark a looped fallback.
With a non-INNER hint the threshold becomes 1024, so every power-of-two group up
to 128 passes. But `override_persistent_reduction=True` makes
`add_multi_kernel_choices` skip the looped variant (`triton.py:9413-9415`), so
such a case is forced persistent and never benchmarked, e.g. G=128 with a
non-INNER hint, which the base heuristic (threshold 64) declines. The new test
class's `setUp` turns `multi_kernel` on, so its tests run in exactly this mode;
the one decline test has to set `multi_kernel=0`. Fix: evaluate the gate as if
multi-kernel were off.

[major] torch/_inductor/scheduler.py:10991
Path 3 can reject a fusion before the backend gate drops the plan: the Path 3
check (`:10976-10984`) runs before this gate (`:10991-10997`). When the backend
declines persistence, `{R, E}` fuses as an ordinary `FusedSchedulerNode`. A
later full-width consumer `Y` that does not read `E` then gets a persistent plan
for `{R, E, Y}` with `Y` as a parent node, and is rejected with "consumer is not
wholly in the sub-parent epilogue". Before the PR there was no plan and `Y`
fused ordinarily. This only happens when `{R, E}` fuses before `Y`, which is not
the usual score order. Fix: run the backend gate before the Path 3 check.

[major] test/inductor/test_persistent_reduction_lanes.py:121
Several tests cannot detect what they are named for:
- `test_three_output_asm_stack` passes `kernels=2`, which skips the `tl.load(`
count (`:65-66`), and has no `codegen_nested_reduction` assertion. Assert both.
- `test_internal_rounded_source` (`:79`) checks only that `"for r0_offset"` is
absent. It never shows that lanes come from the tile rather than being loaded
again.
- `test_transposed_internal_read_is_not_forwarded` (`:270-284`) does not assert
`codegen_nested_reduction == 0`.
- `test_cross_row_lane_is_not_forwarded[group=31]` (`:259`) is rejected by the
power-of-two gate (`scheduler.py:948`) before it reaches the cross-row logic.
Use 16 or 64.

(11 more not shown, see the review run)

Reviewed commit: 0509d62

Review run

🔗 Helpful Links

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

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

✅ No Failures

As of commit 0509d62 with merge base 4fb332d (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - PR was reverted - re-landing requires human review:

Green Light will not review this PR again, on this or any later commit; re-landing it needs a human approval.

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

[ghstack-poisoned]
eellison added a commit that referenced this pull request Oct 12, 2026
…ilogues

Author's note: TODO(author) -- why this change matters, what you reviewed and verified.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.


ghstack-source-id: 95291e5
Pull-Request: #200466
[ghstack-poisoned]
eellison added a commit that referenced this pull request Oct 12, 2026
…ilogues

Author's note: TODO(author) -- why this change matters, what you reviewed and verified.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.


ghstack-source-id: d19a2e1
Pull-Request: #200466
[ghstack-poisoned]
eellison added a commit that referenced this pull request Oct 12, 2026
…ilogues

Author's note: TODO(author) -- why this change matters, what you reviewed and verified.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.


ghstack-source-id: 9821967
Pull-Request: #200466
[ghstack-poisoned]
eellison added a commit that referenced this pull request Oct 12, 2026
…ilogues

Author's note: TODO(author) -- why this change matters, what you reviewed and verified.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.


ghstack-source-id: 9f6b536
Pull-Request: #200466
[ghstack-poisoned]
eellison added a commit that referenced this pull request Oct 12, 2026
…ilogues

Author's note (Claude draft, edit before review): When the reduction itself is the group, a persistent kernel already holds each group's tile, but fixed-lane epilogue reads forced the producer to be materialized. This plans those epilogues against the live tile and forces a persistent kernel only when the backend heuristic agrees, so the producer, reduction, and epilogue compile to one kernel.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.


ghstack-source-id: 2c246de
Pull-Request: #200466
@eellison
eellison marked this pull request as ready for review October 12, 2026 17:25
[ghstack-poisoned]
eellison added a commit that referenced this pull request Oct 12, 2026
…ilogues

Author's note (Claude draft, edit before review): When the reduction itself is the group, a persistent kernel already holds each group's tile, but fixed-lane epilogue reads forced the producer to be materialized. This plans those epilogues against the live tile and forces a persistent kernel only when the backend heuristic agrees, so the producer, reduction, and epilogue compile to one kernel.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.


ghstack-source-id: 29cf7f2
Pull-Request: #200466

MAX_INNER_R_GROUP_SIZE = 512
MAX_NON_INNER_GROUP_SIZE = 128
# Persistent lane forwarding keeps each whole group tile live in registers.

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.

so cap is for reg pressure?

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.

AI-drafted reply, reviewed and agreed by me:

Yes. Forwarding lanes keeps each whole group tile live in registers, plus a log2(G)-deep split tree over it, so the cap bounds that. It matches MAX_NON_INNER_GROUP_SIZE (128). The backend's persistent-reduction heuristic still has the final say: can_fuse now drops the plan when the backend won't emit a persistent kernel.

@drisspg

drisspg commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

@claude Please do a deep review focused on subtle correctness bugs and regressions that are easy for human reviewers to miss. Prioritize findings over summary. I dont care about anything that isnt a real bug drop all the noise but that, if you there isnt anything to report just say so with a small comment

@claude

claude Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Claude finished @drisspg's task in 7m 8s —— View job


I found two correctness bugs. Both can end with a plain fused kernel where a reduced-width epilogue reads a buffer stored in the same kernel at a different index (w[:, 7] vs w[n, g]).

Details

1. The persistent heuristic gate does not stop fusion, so the fused node can lose its plan

SIMDScheduling._sub_parent_epilogue_plan (torch/_inductor/codegen/simd.py:3150) returns None when should_use_persistent_reduction says no. Only the backend calls it, though.

  • Scheduler accepts the read. Scheduler.can_fuse (Path 3, scheduler.py:10894) builds the ungated plan with NestedReduction.sub_parent_epilogue_plan. It proves the epilogue's lane read through relation_matches, and _can_fuse_vertical_impl then accepts that read as an additional_match.
  • Backend accepts the fusion. The new epilogue nodes have the reduced width (numel, 1). In SIMDScheduling.can_fuse, the pointwise-to-reduction branch sets ordinary_fusion = numel1 == numel2, which is True, and returns at simd.py:3027 without reaching _sub_parent_epilogue_decision. Even if that function ran, _is_sub_parent_shaped is False for these nodes, so it would return DEFER, not REJECT. The older sub-parent epilogues were always sub-parent shaped, which is why they never hit this.
  • The fused node loses its plan. Scheduler.fuse (scheduler.py:13258) uses the gated has_sub_parent_epilogue. When the heuristic declines, it builds a plain FusedSchedulerNode.
  • Codegen is ordinary. The epilogue's load(w, x*G + 7) either hits cse.store_cache[w], which returns the full [XBLOCK, R0_BLOCK] tile and ignores the index (common.py:3141), or it reads global memory written by other threads in the same kernel with no barrier.

Trigger: any case where the scheduler-side persistent plan exists but the backend gate fails:

  • 64 < G <= 128 with a non-INNER reduction hint. The threshold is 64 unless the hint is INNER, e.g. v = y.t() with G = 128.
  • A parent whose tiling heuristic wants 3D, so _sub_parent_tiling_is_2d fails.

The tests only cover INNER cases with G <= 64.

Suggested fix: when plan.requires_persistent, the scheduler should not authorize the fusion unless the backend agrees. For example, in Scheduler.can_fuse, drop the plan or reject when not self.get_backend(device).has_sub_parent_epilogue(nodes). Alternatively, make the reduced-width ordinary branch in SIMDScheduling.can_fuse consult _sub_parent_epilogue_decision.

2. Path 4 can switch a persistent FusedStagedReduction to a looped plan without re-proving its lane readers

In sub_parent_epilogue_plan, requires_persistent = grouping is None is recomputed from the whole node set every time.

Sequence:

  1. {amax, w = x - amax, out1 = amax + w[:, 7]} fuses as a persistent FusedStagedReduction. out1 is a lane reader of w, which is computed in the kernel.
  2. Path 4 then appends a real sub-parent consumer such as out2 = w[:, 0::2] + w[:, 1::2].
  3. With out2 present, the non-persistent _sub_parent_epilogue_candidate_nodes succeeds, so requires_persistent becomes False. out1 now has the reduced domain, so it hits continue and becomes an ordinary parent node.
  4. _prove_staged_fusion_dependencies(node1, node2, plan) only checks node2.unmet_dependencies. out1's read of w, which only the persistent plan justified, is never checked again.
  5. The backend returns FUSE (type(reduction_node) is FusedStagedReduction).
  6. At codegen, _find_sub_parent_epilogue_plan rebuilds the non-persistent plan. out1 is emitted as a normal parent load of w at another index, which has the same problem as Matrix multiplication operator #1.

If out2 fuses first, the result is safe: out1 is rejected because requires_persistent is False at the fallback (scheduler.py:10512). So the result depends on fusion order.

Suggested fix: once a node set is persistent, keep it persistent; don't let the planner fall back to looped. Alternatively, check that every reduced-domain parent node reading a buffer written in the kernel still passes ordinary index matching.


I couldn't run anything here (no Python or GPU available), so both findings come from reading the code and neither has been reproduced. #1 is high confidence: I traced every step to a specific line. #2 is medium confidence: I didn't confirm that fusion scoring actually produces the out1-before-out2 order.

[ghstack-poisoned]
@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: GitHub GraphQL query failed: Something went wrong while executing your query on 2026-11-03T16:26:32Z. Please include F3C5:2F9DEA:7A2769:1912A60:6AEA0B31 when reporting this issue.

Details for Dev Infra team

Raised by workflow job

GraphQL variables:

{
  "name": "pytorch",
  "owner": "pytorch",
  "number": 200466,
  "cs_cursor": "Y3Vyc29yOnYyOpHPAAAAGked3Iw=",
  "cr_cursor": "Y3Vyc29yOnYyOpHPAAAAHVUoD0M="
}

GraphQL errors:

[
  {
    "message": "Something went wrong while executing your query on 2026-11-03T16:26:32Z. Please include `F3C5:2F9DEA:7A2769:1912A60:6AEA0B31` when reporting this issue."
  }
]

GraphQL query:

query ($owner: String!, $name: String!, $number: Int!, $cs_cursor: String, $cr_cursor: String!) {
  repository(name: $name, owner: $owner) {
    pullRequest(number: $number) {
      commits(last: 1) {
        nodes {
          commit {
            oid
            checkSuites(first: 1, after: $cs_cursor) {
              nodes {
                checkRuns(first: 100, after: $cr_cursor) {
                  nodes {
                    name
                    conclusion
                    detailsUrl
                    databaseId
                    title
                    summary
                  }
                  pageInfo {
                    endCursor
                    hasNextPage
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

@eellison

eellison commented Nov 3, 2026

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

Merge failed

Reason: Merge rule check failed for stacked PR #200460:

1 mandatory check(s) failed. The first few are:

Dig deeper by viewing the failures on hud

Details for Dev Infra team

Raised by workflow job

Failing merge rule: Core Maintainers

@eellison

eellison commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

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

The previous cherry-pick is now empty, possibly due to conflict resolution.
If you wish to commit it anyway, use:

    git commit --allow-empty

Otherwise, please use 'git cherry-pick --skip'
On branch main
Your branch is ahead of 'origin/main' by 1 commit.
  (use "git push" to publish your local commits)

You are currently cherry-picking commit 7e1d5366db1.
  (all conflicts fixed: run "git cherry-pick --continue")
  (use "git cherry-pick --skip" to skip this patch)
  (use "git cherry-pick --abort" to cancel the cherry-pick operation)

nothing to commit, working tree clean
Details for Dev Infra team

Raised by workflow job

@eellison

eellison commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

pytorchmergebot pushed a commit that referenced this pull request Nov 3, 2026
… lands only once (#203139)

**Impact:** merge bot (trymerge), CI only
**Risk:** low

## What
Before committing anything, `merge_changes_locally` now fetches the default branch (explicit refspec) and recreates it from the remote tip (`git checkout -B main refs/remotes/origin/main`). A merge attempt that fails partway can then no longer leave commits behind for the next retry. New end-to-end tests cover the retry, squash and `--check-mergeability` paths.

## Why
On 2026-11-02 the stack merge from #200466 landed #200459 four times, and the extra copies broke trunk lint (cleaned up in #203123). `merge_ghstack_into` cherry-picks each PR in the stack before checking the next one. When a higher PR still had pending checks, the lower PRs were already cherry-picked onto local main. `merge()` then retried on the same checkout without resetting it, so every retry added another copy, and the attempt that finally passed pushed all of them.

# Notes
- Doing the reset in `merge_changes_locally` instead of `merge()`'s retry loop also covers the regular squash path and `--check-mergeability`. Native stacks already build from the remote ref. Retry policy and check ordering are unchanged.
- The reset discards local commits on the branch. The docstring says so, which matters for anyone running the script against their own checkout.
- Test: `cd .github/scripts && python -m pytest test_trymerge.py test_native_stack.py -q`. On the old code, `TestMergeChangesLocallyEndToEnd`'s retry test lands #101 twice, the same way #200459 landed.
Pull Request resolved: #203139
Approved by: https://github.com/huydhn
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…ilogues (pytorch#200466)

Author's note: When the reduction itself is the group, a persistent kernel already holds each group's tile, but fixed-lane epilogue reads forced the producer to be materialized. This plans those epilogues against the live tile and forces a persistent kernel only when the backend heuristic agrees, so the producer, reduction, and epilogue compile to one kernel.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200466
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463, pytorch#200464, pytorch#200465
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…-lane epilogues (pytorch#200466)"

This reverts commit 4dd518d.

Reverted pytorch#200466 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#200459 (comment)))
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…ch#203123)

Trunk lint fails with ruff F811 on `test/inductor/test_static_triton_launcher.py`: the same test methods are defined three times.

Root cause: the merge bot landed pytorch#200459 four times (daca0c5, 6f29e2d, b3b5844, bb845a5). The stack merge from pytorch#200466 cherry-picked pytorch#200459 locally. It then failed the merge-rule check on pytorch#200460 because mandatory checks were still pending. trymerge retries that every 5 minutes without resetting the local branch to origin/main, so each retry cherry-picked pytorch#200459 again on top of the leftover copy, and the attempt that succeeded pushed all four. The autorevert of the stack (a67a74d) reverted only the last copy and left three.

This PR reverts daca0c5, 6f29e2d and b3b5844, which backs pytorch#200459 out fully, as the autorevert intended. Both files become byte-identical to their state at b85dea2, before the first copy landed. The trymerge retry bug gets a separate fix.

Test Plan:

```
for f in test/inductor/test_static_triton_launcher.py torch/_inductor/runtime/triton_heuristics.py; do git show b85dea2:$f | cmp - $f; done
```

`ruff check` (0.14.4) reports 4 F811 errors on main's copy of the test file and "All checks passed!" on this branch. Lint CI runs on this PR.

This PR was authored with an AI assistant (Claude Code).

Pull Request resolved: pytorch#203123
Approved by: https://github.com/georgehong, https://github.com/huydhn
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…ilogues (pytorch#200466)

Author's note: When the reduction itself is the group, a persistent kernel already holds each group's tile, but fixed-lane epilogue reads forced the producer to be materialized. This plans those epilogues against the live tile and forces a persistent kernel only when the backend heuristic agrees, so the producer, reduction, and epilogue compile to one kernel.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200466
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463, pytorch#200464, pytorch#200465
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
… lands only once (pytorch#203139)

**Impact:** merge bot (trymerge), CI only
**Risk:** low

## What
Before committing anything, `merge_changes_locally` now fetches the default branch (explicit refspec) and recreates it from the remote tip (`git checkout -B main refs/remotes/origin/main`). A merge attempt that fails partway can then no longer leave commits behind for the next retry. New end-to-end tests cover the retry, squash and `--check-mergeability` paths.

## Why
On 2026-11-02 the stack merge from pytorch#200466 landed pytorch#200459 four times, and the extra copies broke trunk lint (cleaned up in pytorch#203123). `merge_ghstack_into` cherry-picks each PR in the stack before checking the next one. When a higher PR still had pending checks, the lower PRs were already cherry-picked onto local main. `merge()` then retried on the same checkout without resetting it, so every retry added another copy, and the attempt that finally passed pushed all of them.

# Notes
- Doing the reset in `merge_changes_locally` instead of `merge()`'s retry loop also covers the regular squash path and `--check-mergeability`. Native stacks already build from the remote ref. Retry policy and check ordering are unchanged.
- The reset discards local commits on the branch. The docstring says so, which matters for anyone running the script against their own checkout.
- Test: `cd .github/scripts && python -m pytest test_trymerge.py test_native_stack.py -q`. On the old code, `TestMergeChangesLocallyEndToEnd`'s retry test lands pytorch#101 twice, the same way pytorch#200459 landed.
Pull Request resolved: pytorch#203139
Approved by: https://github.com/huydhn
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…ilogues (pytorch#200466)

Author's note: When the reduction itself is the group, a persistent kernel already holds each group's tile, but fixed-lane epilogue reads forced the producer to be materialized. This plans those epilogues against the live tile and forces a persistent kernel only when the backend heuristic agrees, so the producer, reduction, and epilogue compile to one kernel.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200466
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463, pytorch#200464, pytorch#200465
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…-lane epilogues (pytorch#200466)"

This reverts commit 4dd518d.

Reverted pytorch#200466 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#200459 (comment)))
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…ch#203123)

Trunk lint fails with ruff F811 on `test/inductor/test_static_triton_launcher.py`: the same test methods are defined three times.

Root cause: the merge bot landed pytorch#200459 four times (daca0c5, 6f29e2d, b3b5844, bb845a5). The stack merge from pytorch#200466 cherry-picked pytorch#200459 locally. It then failed the merge-rule check on pytorch#200460 because mandatory checks were still pending. trymerge retries that every 5 minutes without resetting the local branch to origin/main, so each retry cherry-picked pytorch#200459 again on top of the leftover copy, and the attempt that succeeded pushed all four. The autorevert of the stack (a67a74d) reverted only the last copy and left three.

This PR reverts daca0c5, 6f29e2d and b3b5844, which backs pytorch#200459 out fully, as the autorevert intended. Both files become byte-identical to their state at b85dea2, before the first copy landed. The trymerge retry bug gets a separate fix.

Test Plan:

```
for f in test/inductor/test_static_triton_launcher.py torch/_inductor/runtime/triton_heuristics.py; do git show b85dea2:$f | cmp - $f; done
```

`ruff check` (0.14.4) reports 4 F811 errors on main's copy of the test file and "All checks passed!" on this branch. Lint CI runs on this PR.

This PR was authored with an AI assistant (Claude Code).

Pull Request resolved: pytorch#203123
Approved by: https://github.com/georgehong, https://github.com/huydhn
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…ilogues (pytorch#200466)

Author's note: When the reduction itself is the group, a persistent kernel already holds each group's tile, but fixed-lane epilogue reads forced the producer to be materialized. This plans those epilogues against the live tile and forces a persistent kernel only when the backend heuristic agrees, so the producer, reduction, and epilogue compile to one kernel.

The description below was drafted with an AI assistant (Claude):

> A reduced-width epilogue that reads a fixed element of each reduction group
> (e.g. `v.amax(-1) + v[:, 7]` with `v` of shape `[N, G]`) reads a value a
> persistent reduction already holds in registers. Today that value is loaded
> again, and if `v` is materialized in the same graph the epilogue cannot fuse:
> it reads `v` at a different index than the producer writes it.
>
> For persistent reductions with a static power-of-2 group (at most 128), the
> scheduler now plans such epilogues as sub-parent stages whose lane reads are
> resolved from the live tile (`requires_persistent` plans). The lanes of a group
> must be live together; since the reduction is the group, that means a
> persistent kernel, which `SIMDScheduling` forces for these plans (a looped
> multi-kernel variant could not serve the lanes). Suggested review order:
>
> 1. `NestedReduction._persistent_lane_epilogue_candidates`: which reductions
>    and epilogues qualify.
> 2. `sub_parent_epilogue_plan`: instead of the hoisting mutation check,
>    persistent candidates (which have no mutations) only accept aliased
>    outputs that are slices of a `ConcatKernel` they feed (e.g. the columns of
>    `torch.stack(words, -1)`). Concat slices are disjoint and their stores keep
>    their own indexing; a reader of the concat depends on the concat node and
>    cannot join the group.
> 3. The scheduler side: the existing index-equivalence fallback now also
>    accepts reads of persistent plans; the sub-parent read proof maps a size-1
>    child coordinate; the row-boundary check accepts a flat contiguous source
>    over the whole frame; and `can_fuse` can prepend reduced epilogues to an
>    existing `FusedStagedReduction`.
>
> A reduction that an upstream reduction over the same full domain could own as
> an outer + grouped nested pipeline is left to that planner.
>
> Performance on MI300X, 16M elements, `v` materialized as an output:
> `v.abs().amax(-1) + v[:, G // 3]` goes from 2 kernels to 1 and 1.12-1.14x for
> G = 8, 32, 64. When the lane sources are graph inputs there is no kernel to
> remove; taking the lanes from the tile measured 0.93-1.01x for 1-2 of 32 lanes
> and faster beyond that (0.43-0.58x of the load time for all 32).
>
> `test_nested_reduction.py`'s even/odd consumer test now expects the fixed-lane
> side output to fuse while the incompatible consumers keep their own kernel.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_persistent_reduction_lanes.py \
>   test/inductor/test_nested_reduction_lanes.py test/inductor/test_nested_reduction.py \
>   test/inductor/test_inductor_scheduler.py
> ```
> A randomized sweep of 173 generated lane graphs matched eager.
> `test_single_group_is_not_forwarded` and `test_dynamic_group_count` cover a
> single group and a symbolic group count, both declined (their epilogue ranges
> are empty, or merge differently per node in `merge_loops`).
> `test_tiled_group_axes` covers a GEMM scale tile whose first axis has size 1.
>
> This change was prepared with an AI assistant.

Pull Request resolved: pytorch#200466
Approved by: https://github.com/drisspg
ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463, pytorch#200464, pytorch#200465
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
… lands only once (pytorch#203139)

**Impact:** merge bot (trymerge), CI only
**Risk:** low

## What
Before committing anything, `merge_changes_locally` now fetches the default branch (explicit refspec) and recreates it from the remote tip (`git checkout -B main refs/remotes/origin/main`). A merge attempt that fails partway can then no longer leave commits behind for the next retry. New end-to-end tests cover the retry, squash and `--check-mergeability` paths.

## Why
On 2026-11-02 the stack merge from pytorch#200466 landed pytorch#200459 four times, and the extra copies broke trunk lint (cleaned up in pytorch#203123). `merge_ghstack_into` cherry-picks each PR in the stack before checking the next one. When a higher PR still had pending checks, the lower PRs were already cherry-picked onto local main. `merge()` then retried on the same checkout without resetting it, so every retry added another copy, and the attempt that finally passed pushed all of them.

# Notes
- Doing the reset in `merge_changes_locally` instead of `merge()`'s retry loop also covers the regular squash path and `--check-mergeability`. Native stacks already build from the remote ref. Retry policy and check ordering are unchanged.
- The reset discards local commits on the branch. The docstring says so, which matters for anyone running the script against their own checkout.
- Test: `cd .github/scripts && python -m pytest test_trymerge.py test_native_stack.py -q`. On the old code, `TestMergeChangesLocallyEndToEnd`'s retry test lands pytorch#101 twice, the same way pytorch#200459 landed.
Pull Request resolved: pytorch#203139
Approved by: https://github.com/huydhn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request in progress PR is being worked on by the author, until the automated review accepts it Merged module: inductor Reverted topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants