Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". 🟡 AUTOMATED REVIEW - Changes requested:
Findings (14): Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/200464
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 45dceb2 with merge base 4fb332d ( 🟡 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. |
|
Starting merge as part of PR stack under #200465 |
Blocking findings addressed earlier in this stack (miscompile fix, backend gate, precision fix, test fixes); remaining items are coverage/perf follow-ups. Approved by human reviewer.
|
Starting merge as part of PR stack under #200466 |
There was a problem hiding this comment.
Automated review of 45dceb2: changes requested before human review.
The PR changes how Inductor extracts sub-parent tile lanes: it adds tile-wide to_dtype_bitcast synthesis, packed uint32 splitting of 16-bit lanes, contiguous-halves splits via tl.permute for looped kernels, and a liveness-only check_sources. The bit-level logic is correct, but the review recommends Request Changes. It is blocked on four things: no end-to-end tests of the new paths, a double split when a source has both bitcast and raw readers, MI350X-tuned heuristics applied ungated on every backend, and hw_classification/only_for misuse.
🔴 5 blocking findings are attached to the code below.
⚪ 9 non-blocking findings
pytorch/torch/_inductor/codegen/simd.py
Line 2738 in 45dceb2
The check_sources docstring is wrong. It says "split lanes when a consumer needs them", but the method only checks contains_value; splitting happens in materialize_source and _resolve_pending. The check is weaker than the old _materialize(value) is not None: a live source that cannot be split now passes here and fails later in resolve_load (simd.py:2846) with "sub-parent stage lost required source". The docstring should say so. Restore the deleted note, which is still true: external sources are skipped, and their lanes split lazily or reload when expired. test_inductor_scheduler.py:1311-1313 now covers only the dead-source case. The live-but-unsplittable case was deleted, and the success path is untested.
pytorch/torch/_inductor/lowering.py
Line 1041 in 45dceb2
Registering to_dtype_bitcast as a pointwise op does more than enable the fold, because registered_pointwise_ops is also read at simd.py:2419, 2547 and 2591. It changes _PointwiseRemapHandler._operation_preserves_group_width / _default (2414-2442), so a bitcast of a group-width value (e.g. an e8m0 scale) now stays at group width instead of first being widened by _materialize_group_width. It also records every parent-resolution bitcast as a parent twin (2547-2555). Both are semantically sound but alter codegen for existing sub-parent kernels, whereas the PR body says the registration is only for the fold. Document both effects and cover the group-width case with a test.
pytorch/torch/_inductor/codegen/simd.py
Line 2588 in 45dceb2
The _try_fold_lane_op docstring (2585-2589) is inaccurate. "Fully consumed sources" really means "all lanes planned", not "all lanes read through the bitcast". It omits the other conditions: the source must be an original recorded source (not a cast chain), live, and not already split. Because the not self._parent_twins early return was removed (2593), the fold can now create its own parent value, so "When the same op ran on the same operands at parent resolution" no longer describes the only path.
pytorch/torch/_inductor/codegen/triton.py
Line 7066 in 45dceb2
Two docstrings are stale (triton.py:7044 and :7088). _emit_recursive_split now reads self.persistent_reduction and switches lane layout between contiguous halves (via tl.permute) and even/odd interleave. Its docstring should say so, and should state that names\[i\] always receives lane i; the test stub already had to fake persistent_reduction because of this hidden dependency. The emit_split_via_reshape docstring does not mention the packed 16-bit path. That path is chosen from the CSE dtype, so with the default codegen_upcast_to_fp32 a bf16 load (an fp32 CSE var) never takes it; only the synthesized int16 tile does.
test_storage_bits (66-116) is expensive and cannot tell which path ran. It has 2259 = 180 variants per device, each JIT-compiling a Triton kernel through PyCodeCache.load. Yet int16/uint16/fp16/bf16 share one code path, the four fp8 dtypes share another, and persistent has no effect at factor 2 (or at factor 4 for 16-bit dtypes). It checks only a bit-exact round trip, so if the packed branch were deleted, the fallback recursive split would still pass. Fix: use one dtype per path, and assert on the emitted code for 16-bit dtypes with factor > 2.
test_no_unused_splits (253-278) can pass vacuously: if no tl.split( is emitted, unused == \[\]. For lanes=(0, 1, 2, 3) it should assert an exact split count. Nothing checks that persistent actually produced a persistent or looped kernel (e.g. tl.permute( in the looped case), so the new contiguous-halves path isn't known to have been hit. The b{name}b search runs over every later kernel and the wrapper. Because tmpN numbering restarts per kernel, a reused name can hide an unused lane. Restrict the search to the kernel that contains the split.
_SplitCodegen (31-42) is a fragile stub. It copies unbound TritonKernel methods and fakes cse, compute, persistent_reduction, create_cse_var and index_to_str. Any new self.* access in the split helpers would break both stub-based classes for reasons unrelated to the change. Build a real TritonKernel(..., features=SIMDKernelFeatures(...), override_persistent_reduction=persistent, override_cooperative_reduction=False) under MockGraphHandler, as test_simd_range_trees.py:37-44 and test_codegen_triton.py:323 do.
NestedLaneTestCase.compare (129-167) overlaps _choices_context / get_unnested_reference / check_nested_matches_unnested in test/inductor/test_nested_reduction.py:44-59, 90-100, but uses a different persistence filter (only when reduction_numel == x.shape\[-1\]), so the two will drift apart. Its exact=False branch has no caller. Extend and reuse one helper.
pytorch/test/inductor/test_nested_reduction.py
Line 1413 in 45dceb2
The new load-count assertion (1411-1414) is unexplained: 3 if self.force_persistent_outer_reduction is False else 2 has no comment. Add one saying it guards against lazy lane splitting reloading the source; otherwise any unrelated load-CSE change will look like a regression.
Please address the findings and push; a new commit normally gets a fresh automated review.
This review is AI-generated and advisory. Each new automated review replaces the previous one.
| if lane is None: | ||
| return None | ||
| parent_value = self._parent_twins.get(self._twin_key(name, parent_args, kwargs)) | ||
| if parent_value is None and name == "to_dtype_bitcast": |
There was a problem hiding this comment.
🔴 No test shows that either new codegen path runs (bitcast synthesis at simd.py:2618-2634, packed 16-bit split at triton.py:7094-7129). test_no_unused_splits reads lanes with .float(), and under the default upcast its bf16 source is an fp32 CSE var, so it hits neither branch. The packed path is reached only through the _SplitCodegen stub. test_inline_asm_elementwise.py:1084-1102 is CUDA-only, not in the test plan, and asserts nothing about which branch ran. Also untested: the sparse-reader synthesis guard, the second-split guard, the mixed bitcast/raw case, and removal of the not self._parent_twins early return. Fix: add persistent and looped tests in test_nested_reduction_lanes.py that read all G=32 lanes of a realized bf16 group through .view(torch.int16) (the MXFP6 shape). Assert exact equality, codegen_nested_reduction == 1, the exact tl.split( count, and the presence of << 16 / tl.uint32. Add negative tests for the sparse-reader and mixed cases.
| ): | ||
| return None | ||
| # An already split source would gain a second, full split. | ||
| if parent_args[0] in self._materialized or not ( |
There was a problem hiding this comment.
🔴 A source can be split twice. The synthesis trigger (2621-2627) only checks that planned parent_lanes covers every lane, not that those lanes are read through the bitcast. The guard parent_args\[0\] in self._materialized only catches a raw split that was already emitted, and deferred pending lanes from materialize_source never enter _materialized. If the bitcast reader comes first, the tile bitcast and its split are emitted; a later raw-lane reader that doesn't fold then goes _default _resolve_pending _materialize(source) and emits a second full split. The same happens if a raw pending lane is still unresolved when the bitcast reader arrives. At G=32 that is a 16-split packed tree plus a 31-split tree, the very cost this PR exists to remove. The comment at 2628 implies the guard prevents this, but it doesn't fully. Fix: mark the source as covered once its bitcast twin is recorded, or require every planned lane read to go through the bitcast.
| return | ||
| half = factor // 2 | ||
| split_shape = (*shape[:-1], half, 2) | ||
| # Contiguous halves help looped kernels but regress persistent kernels. |
There was a problem hiding this comment.
🔴 Two layout heuristics measured only on MI350X change default codegen on every Triton backend: contiguous halves via tl.permute for looped kernels (7065-7071), and packed uint32 pairing for 16-bit lanes (7094-7098). config.triton.nested_reduction defaults to True, and TritonScheduling serves CUDA, ROCm and XPU. triton.py already gates ROCm-specific codegen on torch.version.hip (lines 970, 2265, 7604). tl.permute appears nowhere else in Inductor's non-template codegen (N-d permutes use tl.trans, line 768). The looped path emits one permute per recursion level above factor 2, which on NVIDIA may force shared-memory layout conversions. At factor 4 the packed path saves one tl.split but adds pack/unpack ops, and no measurement is given for that size. The comment states one GPU's result as a general rule. Fix: post NVIDIA (and XPU if possible) measurements or gate both heuristics to ROCm, then reword both comments to name the hardware.
|
|
||
|
|
||
| class TestRecursiveLaneSplit(TestCase): | ||
| hw_classification = HardwareClassification.CUDA |
There was a problem hiding this comment.
🔴 TestRecursiveLaneSplit is misclassified (test/REVIEW.md Rules 1/2/4). It is labelled HardwareClassification.CUDA and instantiated with only_for="cuda" (line 281), but it is a plain Triton kernel launch with nothing CUDA-specific. It is accelerator-agnostic and should be ACCELERATOR, using except_for (Rule 4) or a Triton-availability skip; dropping only_for alone would instantiate a CPU variant. As written, it silently drops the 16-bit and fp32 cases on XPU.
|
|
||
|
|
||
| class TestNestedLaneSplits(NestedLaneTestCase): | ||
| hw_classification = HardwareClassification.CUDA |
There was a problem hiding this comment.
🔴 Labels don't match instantiation. TestNestedLaneSplits (253-254, 283) and TestPitchedLaneSources (170-171, 282; whole-file scope) are labelled CUDA but instantiated with only_for=GPU_TYPE, which is xpu or mtia on those runners. Both are accelerator-agnostic compile tests and should be ACCELERATOR without only_for.
Blocking findings addressed earlier in this stack (miscompile fix, backend gate, precision fix, test fixes); remaining items are coverage/perf follow-ups. Approved by human reviewer.
|
Starting merge as part of PR stack under #200466 |
3 similar comments
|
Starting merge as part of PR stack under #200466 |
|
Starting merge as part of PR stack under #200466 |
|
Starting merge as part of PR stack under #200466 |
Author's note: In outer-plus-grouped nested reductions (layer norm followed by a per-group pack), a consumer reading fixed lanes of each group broke the fusion, so the normalized tensor was written to memory and read back. This proves when such a read is a lane of the live group tile; the MXFP6 layer-norm preparation then compiles to one kernel.
The description below was drafted with an AI assistant (Claude):
> In an outer + grouped nested reduction, a reduced-width consumer in the grouped
> stage may read one fixed element of each group, e.g. the per-group inputs of
> a multi-output `inline_asm_elementwise` call. The cross-stage check
> (`_r_grouped_stage_accesses_match`) required every internal read to address
> the same element its producer writes, so such a consumer broke the plan and
> the value was materialized and reloaded in a second kernel.
>
> `_try_get_r_grouped_lane_accesses` now also accepts a read that selects a
> fixed lane of the producer's local group, and returns it as a
> `SubParentAccessRelation`. It requires a unique, unit-stride, non-reduction,
> non-atomic write, a constant lane in `[0, G)`, a group base that is a multiple
> of `G`, and row-preserving indices on both sides. The writer must belong to
> the local stage, or compute a full-width value from the grouped reduction's
> output; a writer outside the plan's pointwise domains belongs to the parent
> stage, which a looped parent flushes before the grouped stage runs. The
> relations are stored on `NestedReductionStage.lane_accesses`; the scheduler's
> dependency check accepts exactly those read/write pairs, and
> codegen resolves them through `_SubParentValueResolver` at the local
> reduction factor, whose derived family now sizes its child block from the
> reduced block for nested stages.
>
> Also included: a `why("nested reduction plan declined")` fusion log, and the
> nested-reduction internals tests now enable `loop_ordering_after_fusion` in
> `setUp` (nested reductions assume it).
>
> End to end, this makes a whole MXFP6 layer-norm preparation one kernel. The
> preparation graphs pad K to a 192-element tile. Written the obvious way (layer
> norm over K, then pad the packed payload with zeros and the scales with 127),
> the padding tail and the GEMM scale layout need a second kernel. Written with
> the input padded instead (two-pass statistics that keep the true K, padded
> values masked to zero), the padded groups flow through the same nested
> reduction and a small-M or medium-K preparation compiles to one kernel. On
> MI350X this form is faster than the hand-written kernel for both layer-norm
> shapes (K=1056, M=128: 4.43 vs 5.11 us; K=22592: 28.5 vs 40.1 us). Inductor
> cannot rewrite the first form into the second: the payload padding is zero
> only because the FP6 conversion maps zero inputs to zero, which is hidden
> inside inline assembly. `test_padded_two_pass_layer_norm` locks in the
> one-kernel structure for the input-padded form, and the packed 16-split lane
> extraction the performance depends on.
>
> Test Plan:
> ```
> python -m pytest test/inductor/test_nested_reduction_lanes.py \
> test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py
> ```
> `test_nested_reduction_lanes.py` covers lanes read from the parent stage, source
> lifetimes, and the previous commit's shared source bitcast and packed 16-bit
> split, with exact split counts (these graphs only reach the resolver once their
> lanes are forwarded). `test_pitched_layer_norm_lanes` covers a producer with a
> row pitch wider than its width. The acceptance conditions are tested directly in
> `test_inductor_scheduler.py` (`test_nested_grouped_lane_access_conditions`,
> `test_nested_plan_restricts_lane_sources`,
> `test_nested_dependency_matches_require_planned_lane`); each negative case fails
> if its condition is removed. `test_parent_full_lane_source` covers lanes of a
> value computed from the grouped reduction's output, and
> `test_padded_two_pass_layer_norm` the whole padded MXFP6 layer-norm
> preparation (one kernel, 16 packed splits).
>
> This change was prepared with an AI assistant.
Pull Request resolved: #200465
Approved by: https://github.com/drisspg
ghstack dependencies: #200459, #200460, #200461, #200462, #200463, #200464
…ilogues (#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: #200466 Approved by: https://github.com/drisspg ghstack dependencies: #200459, #200460, #200461, #200462, #200463, #200464, #200465
…ytorch#200464) Author's note: Reading fixed lanes of a live tile used to round and bitcast every lane separately after a 31-way split, which is slow on MI350X. Now the bitcast runs once on the whole tile and 16-bit lanes are split as packed 32-bit pairs (16 splits); I verified MI350X performance natively. The description below was drafted with an AI assistant (Claude): > Sub-parent epilogues read fixed lanes of a group tile: lane k of a > `[..., groups, G]` tile is extracted with a reshape and a `tl.split` tree. > Inductor inlines the pointwise chain between the source and each lane read > into every lane's consumer. For the MXFP6 pack (`bits(v[2j]) | > bits(v[2j+1]) << 16` over a group of 32 bf16 values), each lane is split out > as fp32 and then rounded to bf16 and bitcast on its own. The split lanes have > replicated layouts, so every thread repeats that work for each lane, and on > MI350X the 32 separate 16-bit lanes also cost extra layout conversions. > > Three changes, all local to the existing split path: > > - When every lane of a source is read, a `to_dtype_bitcast` of the source is > emitted once at parent width, so the existing parent-twin fold collapses > each lane's cast chain into a split of the integer tile. > `to_dtype_bitcast` is registered as a pointwise op for that fold. > - `emit_split_via_reshape` moves 16-bit lanes (int16/fp16/bf16, power-of-two > factor > 2) in pairs: split even/odd once, pack each pair into a uint32, > run the existing recursive split on the packed tile (16 splits instead of > 31 at G=32), and unpack each lane to its original name and dtype. > - In looped kernels the recursive split takes contiguous halves (via > `tl.permute`) instead of even/odd lanes, which needs fewer layout > conversions there; persistent kernels keep even/odd, which is faster for > them. > > Sources are no longer split eagerly before the epilogue: `check_sources` only > checks that required sources are live, and a split is emitted when a > consumer needs a lane. > > This changes how existing sub-parent epilogues are emitted; which graphs fuse > is unchanged. It matters once the next two commits route the MXFP6 preparation > graphs through the resolver. On native MI350X, a fused MXFP6 preparation > kernel (an elementwise producer followed by a per-group pack) is about 1.3x > slower with only the tile bitcast and no packed split, and falls behind a > hand-written kernel. With this change it beats that kernel on both the > elementwise-producer and the padded layer-norm preparation graphs. > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction_lanes.py \ > test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py > ``` > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200464 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463
…0465) Author's note: In outer-plus-grouped nested reductions (layer norm followed by a per-group pack), a consumer reading fixed lanes of each group broke the fusion, so the normalized tensor was written to memory and read back. This proves when such a read is a lane of the live group tile; the MXFP6 layer-norm preparation then compiles to one kernel. The description below was drafted with an AI assistant (Claude): > In an outer + grouped nested reduction, a reduced-width consumer in the grouped > stage may read one fixed element of each group, e.g. the per-group inputs of > a multi-output `inline_asm_elementwise` call. The cross-stage check > (`_r_grouped_stage_accesses_match`) required every internal read to address > the same element its producer writes, so such a consumer broke the plan and > the value was materialized and reloaded in a second kernel. > > `_try_get_r_grouped_lane_accesses` now also accepts a read that selects a > fixed lane of the producer's local group, and returns it as a > `SubParentAccessRelation`. It requires a unique, unit-stride, non-reduction, > non-atomic write, a constant lane in `[0, G)`, a group base that is a multiple > of `G`, and row-preserving indices on both sides. The writer must belong to > the local stage, or compute a full-width value from the grouped reduction's > output; a writer outside the plan's pointwise domains belongs to the parent > stage, which a looped parent flushes before the grouped stage runs. The > relations are stored on `NestedReductionStage.lane_accesses`; the scheduler's > dependency check accepts exactly those read/write pairs, and > codegen resolves them through `_SubParentValueResolver` at the local > reduction factor, whose derived family now sizes its child block from the > reduced block for nested stages. > > Also included: a `why("nested reduction plan declined")` fusion log, and the > nested-reduction internals tests now enable `loop_ordering_after_fusion` in > `setUp` (nested reductions assume it). > > End to end, this makes a whole MXFP6 layer-norm preparation one kernel. The > preparation graphs pad K to a 192-element tile. Written the obvious way (layer > norm over K, then pad the packed payload with zeros and the scales with 127), > the padding tail and the GEMM scale layout need a second kernel. Written with > the input padded instead (two-pass statistics that keep the true K, padded > values masked to zero), the padded groups flow through the same nested > reduction and a small-M or medium-K preparation compiles to one kernel. On > MI350X this form is faster than the hand-written kernel for both layer-norm > shapes (K=1056, M=128: 4.43 vs 5.11 us; K=22592: 28.5 vs 40.1 us). Inductor > cannot rewrite the first form into the second: the payload padding is zero > only because the FP6 conversion maps zero inputs to zero, which is hidden > inside inline assembly. `test_padded_two_pass_layer_norm` locks in the > one-kernel structure for the input-padded form, and the packed 16-split lane > extraction the performance depends on. > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction_lanes.py \ > test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py > ``` > `test_nested_reduction_lanes.py` covers lanes read from the parent stage, source > lifetimes, and the previous commit's shared source bitcast and packed 16-bit > split, with exact split counts (these graphs only reach the resolver once their > lanes are forwarded). `test_pitched_layer_norm_lanes` covers a producer with a > row pitch wider than its width. The acceptance conditions are tested directly in > `test_inductor_scheduler.py` (`test_nested_grouped_lane_access_conditions`, > `test_nested_plan_restricts_lane_sources`, > `test_nested_dependency_matches_require_planned_lane`); each negative case fails > if its condition is removed. `test_parent_full_lane_source` covers lanes of a > value computed from the grouped reduction's output, and > `test_padded_two_pass_layer_norm` the whole padded MXFP6 layer-norm > preparation (one kernel, 16 packed splits). > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200465 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463, pytorch#200464
…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
…t pairs (pytorch#200464)" This reverts commit 438c7f3. Reverted pytorch#200464 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)))
…ytorch#200464) Author's note: Reading fixed lanes of a live tile used to round and bitcast every lane separately after a 31-way split, which is slow on MI350X. Now the bitcast runs once on the whole tile and 16-bit lanes are split as packed 32-bit pairs (16 splits); I verified MI350X performance natively. The description below was drafted with an AI assistant (Claude): > Sub-parent epilogues read fixed lanes of a group tile: lane k of a > `[..., groups, G]` tile is extracted with a reshape and a `tl.split` tree. > Inductor inlines the pointwise chain between the source and each lane read > into every lane's consumer. For the MXFP6 pack (`bits(v[2j]) | > bits(v[2j+1]) << 16` over a group of 32 bf16 values), each lane is split out > as fp32 and then rounded to bf16 and bitcast on its own. The split lanes have > replicated layouts, so every thread repeats that work for each lane, and on > MI350X the 32 separate 16-bit lanes also cost extra layout conversions. > > Three changes, all local to the existing split path: > > - When every lane of a source is read, a `to_dtype_bitcast` of the source is > emitted once at parent width, so the existing parent-twin fold collapses > each lane's cast chain into a split of the integer tile. > `to_dtype_bitcast` is registered as a pointwise op for that fold. > - `emit_split_via_reshape` moves 16-bit lanes (int16/fp16/bf16, power-of-two > factor > 2) in pairs: split even/odd once, pack each pair into a uint32, > run the existing recursive split on the packed tile (16 splits instead of > 31 at G=32), and unpack each lane to its original name and dtype. > - In looped kernels the recursive split takes contiguous halves (via > `tl.permute`) instead of even/odd lanes, which needs fewer layout > conversions there; persistent kernels keep even/odd, which is faster for > them. > > Sources are no longer split eagerly before the epilogue: `check_sources` only > checks that required sources are live, and a split is emitted when a > consumer needs a lane. > > This changes how existing sub-parent epilogues are emitted; which graphs fuse > is unchanged. It matters once the next two commits route the MXFP6 preparation > graphs through the resolver. On native MI350X, a fused MXFP6 preparation > kernel (an elementwise producer followed by a per-group pack) is about 1.3x > slower with only the tile bitcast and no packed split, and falls behind a > hand-written kernel. With this change it beats that kernel on both the > elementwise-producer and the padded layer-norm preparation graphs. > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction_lanes.py \ > test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py > ``` > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200464 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463
…0465) Author's note: In outer-plus-grouped nested reductions (layer norm followed by a per-group pack), a consumer reading fixed lanes of each group broke the fusion, so the normalized tensor was written to memory and read back. This proves when such a read is a lane of the live group tile; the MXFP6 layer-norm preparation then compiles to one kernel. The description below was drafted with an AI assistant (Claude): > In an outer + grouped nested reduction, a reduced-width consumer in the grouped > stage may read one fixed element of each group, e.g. the per-group inputs of > a multi-output `inline_asm_elementwise` call. The cross-stage check > (`_r_grouped_stage_accesses_match`) required every internal read to address > the same element its producer writes, so such a consumer broke the plan and > the value was materialized and reloaded in a second kernel. > > `_try_get_r_grouped_lane_accesses` now also accepts a read that selects a > fixed lane of the producer's local group, and returns it as a > `SubParentAccessRelation`. It requires a unique, unit-stride, non-reduction, > non-atomic write, a constant lane in `[0, G)`, a group base that is a multiple > of `G`, and row-preserving indices on both sides. The writer must belong to > the local stage, or compute a full-width value from the grouped reduction's > output; a writer outside the plan's pointwise domains belongs to the parent > stage, which a looped parent flushes before the grouped stage runs. The > relations are stored on `NestedReductionStage.lane_accesses`; the scheduler's > dependency check accepts exactly those read/write pairs, and > codegen resolves them through `_SubParentValueResolver` at the local > reduction factor, whose derived family now sizes its child block from the > reduced block for nested stages. > > Also included: a `why("nested reduction plan declined")` fusion log, and the > nested-reduction internals tests now enable `loop_ordering_after_fusion` in > `setUp` (nested reductions assume it). > > End to end, this makes a whole MXFP6 layer-norm preparation one kernel. The > preparation graphs pad K to a 192-element tile. Written the obvious way (layer > norm over K, then pad the packed payload with zeros and the scales with 127), > the padding tail and the GEMM scale layout need a second kernel. Written with > the input padded instead (two-pass statistics that keep the true K, padded > values masked to zero), the padded groups flow through the same nested > reduction and a small-M or medium-K preparation compiles to one kernel. On > MI350X this form is faster than the hand-written kernel for both layer-norm > shapes (K=1056, M=128: 4.43 vs 5.11 us; K=22592: 28.5 vs 40.1 us). Inductor > cannot rewrite the first form into the second: the payload padding is zero > only because the FP6 conversion maps zero inputs to zero, which is hidden > inside inline assembly. `test_padded_two_pass_layer_norm` locks in the > one-kernel structure for the input-padded form, and the packed 16-split lane > extraction the performance depends on. > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction_lanes.py \ > test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py > ``` > `test_nested_reduction_lanes.py` covers lanes read from the parent stage, source > lifetimes, and the previous commit's shared source bitcast and packed 16-bit > split, with exact split counts (these graphs only reach the resolver once their > lanes are forwarded). `test_pitched_layer_norm_lanes` covers a producer with a > row pitch wider than its width. The acceptance conditions are tested directly in > `test_inductor_scheduler.py` (`test_nested_grouped_lane_access_conditions`, > `test_nested_plan_restricts_lane_sources`, > `test_nested_dependency_matches_require_planned_lane`); each negative case fails > if its condition is removed. `test_parent_full_lane_source` covers lanes of a > value computed from the grouped reduction's output, and > `test_padded_two_pass_layer_norm` the whole padded MXFP6 layer-norm > preparation (one kernel, 16 packed splits). > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200465 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463, pytorch#200464
…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
…ytorch#200464) Author's note: Reading fixed lanes of a live tile used to round and bitcast every lane separately after a 31-way split, which is slow on MI350X. Now the bitcast runs once on the whole tile and 16-bit lanes are split as packed 32-bit pairs (16 splits); I verified MI350X performance natively. The description below was drafted with an AI assistant (Claude): > Sub-parent epilogues read fixed lanes of a group tile: lane k of a > `[..., groups, G]` tile is extracted with a reshape and a `tl.split` tree. > Inductor inlines the pointwise chain between the source and each lane read > into every lane's consumer. For the MXFP6 pack (`bits(v[2j]) | > bits(v[2j+1]) << 16` over a group of 32 bf16 values), each lane is split out > as fp32 and then rounded to bf16 and bitcast on its own. The split lanes have > replicated layouts, so every thread repeats that work for each lane, and on > MI350X the 32 separate 16-bit lanes also cost extra layout conversions. > > Three changes, all local to the existing split path: > > - When every lane of a source is read, a `to_dtype_bitcast` of the source is > emitted once at parent width, so the existing parent-twin fold collapses > each lane's cast chain into a split of the integer tile. > `to_dtype_bitcast` is registered as a pointwise op for that fold. > - `emit_split_via_reshape` moves 16-bit lanes (int16/fp16/bf16, power-of-two > factor > 2) in pairs: split even/odd once, pack each pair into a uint32, > run the existing recursive split on the packed tile (16 splits instead of > 31 at G=32), and unpack each lane to its original name and dtype. > - In looped kernels the recursive split takes contiguous halves (via > `tl.permute`) instead of even/odd lanes, which needs fewer layout > conversions there; persistent kernels keep even/odd, which is faster for > them. > > Sources are no longer split eagerly before the epilogue: `check_sources` only > checks that required sources are live, and a split is emitted when a > consumer needs a lane. > > This changes how existing sub-parent epilogues are emitted; which graphs fuse > is unchanged. It matters once the next two commits route the MXFP6 preparation > graphs through the resolver. On native MI350X, a fused MXFP6 preparation > kernel (an elementwise producer followed by a per-group pack) is about 1.3x > slower with only the tile bitcast and no packed split, and falls behind a > hand-written kernel. With this change it beats that kernel on both the > elementwise-producer and the padded layer-norm preparation graphs. > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction_lanes.py \ > test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py > ``` > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200464 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463
…0465) Author's note: In outer-plus-grouped nested reductions (layer norm followed by a per-group pack), a consumer reading fixed lanes of each group broke the fusion, so the normalized tensor was written to memory and read back. This proves when such a read is a lane of the live group tile; the MXFP6 layer-norm preparation then compiles to one kernel. The description below was drafted with an AI assistant (Claude): > In an outer + grouped nested reduction, a reduced-width consumer in the grouped > stage may read one fixed element of each group, e.g. the per-group inputs of > a multi-output `inline_asm_elementwise` call. The cross-stage check > (`_r_grouped_stage_accesses_match`) required every internal read to address > the same element its producer writes, so such a consumer broke the plan and > the value was materialized and reloaded in a second kernel. > > `_try_get_r_grouped_lane_accesses` now also accepts a read that selects a > fixed lane of the producer's local group, and returns it as a > `SubParentAccessRelation`. It requires a unique, unit-stride, non-reduction, > non-atomic write, a constant lane in `[0, G)`, a group base that is a multiple > of `G`, and row-preserving indices on both sides. The writer must belong to > the local stage, or compute a full-width value from the grouped reduction's > output; a writer outside the plan's pointwise domains belongs to the parent > stage, which a looped parent flushes before the grouped stage runs. The > relations are stored on `NestedReductionStage.lane_accesses`; the scheduler's > dependency check accepts exactly those read/write pairs, and > codegen resolves them through `_SubParentValueResolver` at the local > reduction factor, whose derived family now sizes its child block from the > reduced block for nested stages. > > Also included: a `why("nested reduction plan declined")` fusion log, and the > nested-reduction internals tests now enable `loop_ordering_after_fusion` in > `setUp` (nested reductions assume it). > > End to end, this makes a whole MXFP6 layer-norm preparation one kernel. The > preparation graphs pad K to a 192-element tile. Written the obvious way (layer > norm over K, then pad the packed payload with zeros and the scales with 127), > the padding tail and the GEMM scale layout need a second kernel. Written with > the input padded instead (two-pass statistics that keep the true K, padded > values masked to zero), the padded groups flow through the same nested > reduction and a small-M or medium-K preparation compiles to one kernel. On > MI350X this form is faster than the hand-written kernel for both layer-norm > shapes (K=1056, M=128: 4.43 vs 5.11 us; K=22592: 28.5 vs 40.1 us). Inductor > cannot rewrite the first form into the second: the payload padding is zero > only because the FP6 conversion maps zero inputs to zero, which is hidden > inside inline assembly. `test_padded_two_pass_layer_norm` locks in the > one-kernel structure for the input-padded form, and the packed 16-split lane > extraction the performance depends on. > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction_lanes.py \ > test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py > ``` > `test_nested_reduction_lanes.py` covers lanes read from the parent stage, source > lifetimes, and the previous commit's shared source bitcast and packed 16-bit > split, with exact split counts (these graphs only reach the resolver once their > lanes are forwarded). `test_pitched_layer_norm_lanes` covers a producer with a > row pitch wider than its width. The acceptance conditions are tested directly in > `test_inductor_scheduler.py` (`test_nested_grouped_lane_access_conditions`, > `test_nested_plan_restricts_lane_sources`, > `test_nested_dependency_matches_require_planned_lane`); each negative case fails > if its condition is removed. `test_parent_full_lane_source` covers lanes of a > value computed from the grouped reduction's output, and > `test_padded_two_pass_layer_norm` the whole padded MXFP6 layer-norm > preparation (one kernel, 16 packed splits). > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200465 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463, pytorch#200464
…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
…t pairs (pytorch#200464)" This reverts commit 438c7f3. Reverted pytorch#200464 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)))
…ytorch#200464) Author's note: Reading fixed lanes of a live tile used to round and bitcast every lane separately after a 31-way split, which is slow on MI350X. Now the bitcast runs once on the whole tile and 16-bit lanes are split as packed 32-bit pairs (16 splits); I verified MI350X performance natively. The description below was drafted with an AI assistant (Claude): > Sub-parent epilogues read fixed lanes of a group tile: lane k of a > `[..., groups, G]` tile is extracted with a reshape and a `tl.split` tree. > Inductor inlines the pointwise chain between the source and each lane read > into every lane's consumer. For the MXFP6 pack (`bits(v[2j]) | > bits(v[2j+1]) << 16` over a group of 32 bf16 values), each lane is split out > as fp32 and then rounded to bf16 and bitcast on its own. The split lanes have > replicated layouts, so every thread repeats that work for each lane, and on > MI350X the 32 separate 16-bit lanes also cost extra layout conversions. > > Three changes, all local to the existing split path: > > - When every lane of a source is read, a `to_dtype_bitcast` of the source is > emitted once at parent width, so the existing parent-twin fold collapses > each lane's cast chain into a split of the integer tile. > `to_dtype_bitcast` is registered as a pointwise op for that fold. > - `emit_split_via_reshape` moves 16-bit lanes (int16/fp16/bf16, power-of-two > factor > 2) in pairs: split even/odd once, pack each pair into a uint32, > run the existing recursive split on the packed tile (16 splits instead of > 31 at G=32), and unpack each lane to its original name and dtype. > - In looped kernels the recursive split takes contiguous halves (via > `tl.permute`) instead of even/odd lanes, which needs fewer layout > conversions there; persistent kernels keep even/odd, which is faster for > them. > > Sources are no longer split eagerly before the epilogue: `check_sources` only > checks that required sources are live, and a split is emitted when a > consumer needs a lane. > > This changes how existing sub-parent epilogues are emitted; which graphs fuse > is unchanged. It matters once the next two commits route the MXFP6 preparation > graphs through the resolver. On native MI350X, a fused MXFP6 preparation > kernel (an elementwise producer followed by a per-group pack) is about 1.3x > slower with only the tile bitcast and no packed split, and falls behind a > hand-written kernel. With this change it beats that kernel on both the > elementwise-producer and the padded layer-norm preparation graphs. > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction_lanes.py \ > test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py > ``` > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200464 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463
…0465) Author's note: In outer-plus-grouped nested reductions (layer norm followed by a per-group pack), a consumer reading fixed lanes of each group broke the fusion, so the normalized tensor was written to memory and read back. This proves when such a read is a lane of the live group tile; the MXFP6 layer-norm preparation then compiles to one kernel. The description below was drafted with an AI assistant (Claude): > In an outer + grouped nested reduction, a reduced-width consumer in the grouped > stage may read one fixed element of each group, e.g. the per-group inputs of > a multi-output `inline_asm_elementwise` call. The cross-stage check > (`_r_grouped_stage_accesses_match`) required every internal read to address > the same element its producer writes, so such a consumer broke the plan and > the value was materialized and reloaded in a second kernel. > > `_try_get_r_grouped_lane_accesses` now also accepts a read that selects a > fixed lane of the producer's local group, and returns it as a > `SubParentAccessRelation`. It requires a unique, unit-stride, non-reduction, > non-atomic write, a constant lane in `[0, G)`, a group base that is a multiple > of `G`, and row-preserving indices on both sides. The writer must belong to > the local stage, or compute a full-width value from the grouped reduction's > output; a writer outside the plan's pointwise domains belongs to the parent > stage, which a looped parent flushes before the grouped stage runs. The > relations are stored on `NestedReductionStage.lane_accesses`; the scheduler's > dependency check accepts exactly those read/write pairs, and > codegen resolves them through `_SubParentValueResolver` at the local > reduction factor, whose derived family now sizes its child block from the > reduced block for nested stages. > > Also included: a `why("nested reduction plan declined")` fusion log, and the > nested-reduction internals tests now enable `loop_ordering_after_fusion` in > `setUp` (nested reductions assume it). > > End to end, this makes a whole MXFP6 layer-norm preparation one kernel. The > preparation graphs pad K to a 192-element tile. Written the obvious way (layer > norm over K, then pad the packed payload with zeros and the scales with 127), > the padding tail and the GEMM scale layout need a second kernel. Written with > the input padded instead (two-pass statistics that keep the true K, padded > values masked to zero), the padded groups flow through the same nested > reduction and a small-M or medium-K preparation compiles to one kernel. On > MI350X this form is faster than the hand-written kernel for both layer-norm > shapes (K=1056, M=128: 4.43 vs 5.11 us; K=22592: 28.5 vs 40.1 us). Inductor > cannot rewrite the first form into the second: the payload padding is zero > only because the FP6 conversion maps zero inputs to zero, which is hidden > inside inline assembly. `test_padded_two_pass_layer_norm` locks in the > one-kernel structure for the input-padded form, and the packed 16-split lane > extraction the performance depends on. > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction_lanes.py \ > test/inductor/test_inductor_scheduler.py test/inductor/test_nested_reduction.py > ``` > `test_nested_reduction_lanes.py` covers lanes read from the parent stage, source > lifetimes, and the previous commit's shared source bitcast and packed 16-bit > split, with exact split counts (these graphs only reach the resolver once their > lanes are forwarded). `test_pitched_layer_norm_lanes` covers a producer with a > row pitch wider than its width. The acceptance conditions are tested directly in > `test_inductor_scheduler.py` (`test_nested_grouped_lane_access_conditions`, > `test_nested_plan_restricts_lane_sources`, > `test_nested_dependency_matches_require_planned_lane`); each negative case fails > if its condition is removed. `test_parent_full_lane_source` covers lanes of a > value computed from the grouped reduction's output, and > `test_padded_two_pass_layer_norm` the whole padded MXFP6 layer-norm > preparation (one kernel, 16 packed splits). > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200465 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462, pytorch#200463, pytorch#200464
…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
Stack from ghstack (oldest at bottom):
Author's note: Reading fixed lanes of a live tile used to round and bitcast every lane separately after a 31-way split, which is slow on MI350X. Now the bitcast runs once on the whole tile and 16-bit lanes are split as packed 32-bit pairs (16 splits); I verified MI350X performance natively.
The description below was drafted with an AI assistant (Claude):
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo