Repository navigation
Conversation
PR Status: Approved 🚀Please fix all CI failures and trigger merge by commenting "@pytorchbot merge". ✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:
Reviewed commit: 🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/200459
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 903736d 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. |
drisspg
left a comment
There was a problem hiding this comment.
Makes sense; failures look real though
|
Starting merge as part of PR stack under #200465 |
There was a problem hiding this comment.
Automated review of 558cd8c: nothing blocking; ready for human review.
The PR stops make_launcher from calling reload_cubin_path when the kernel is already loaded (function is not None). Before, a second launch after the Triton cache dir changed raised a spurious RuntimeError. load_kernel already returns early in that case, so the guard only removes a pointless reload, and the device-agnostic, close() and unpickle paths behave as before. The new regression test fails on the old code, and a companion test checks that an unloaded kernel with a missing binary still errors. The only maintainer review is an approval, whose note about CI failures is outside this review's scope.
This review is AI-generated and advisory. Each new automated review replaces the previous one.
|
Starting merge as part of PR stack under #200466 |
|
@pytorchbot merge |
Merge startedYour 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 |
…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: #200464 Approved by: https://github.com/drisspg ghstack dependencies: #200459, #200460, #200461, #200462, #200463
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
… 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
…ytorch#203016) Summary: When the Triton config chosen for a kernel exceeds shared memory at launcher creation, _make_launchers retries via compile_by_disabling_pipelining (num_stages=1). For kernels with a PrecomputedGrid, GridExpr.generate then looked for an exact config match including num_stages, so the retry died with "Precomputed grid not found for {..., num_stages: 1}" instead of launching with the precomputed grid. Candidate matching in PrecomputedGrid.generate is tiered: an exact config match first (a user grid can depend on num_warps/num_stages, so candidates differing only in those values may carry different grids), then a retry tier that accepts a different num_stages/NUM_STAGES only when the lookup value is 1, which is exactly what compile_by_disabling_pipelining produces. Different BLOCK sizes still reject. Update addressing automated GitHub review comments: candidate matching now lives in the shared PrecomputedGrid.find_candidate_index helper, used by PrecomputedGrid.generate, run_triton_kernel_with_autotune, and generate_aoti_kernel_config_header. Matching is tiered as described above, so a user grid that depends on num_warps/num_stages still selects its own candidate, while the pipelining-disabled retry (num_stages and NUM_STAGES lowered to 1) reuses the chosen candidate. The two lazy paths raise when no candidate matches instead of leaving config_index unset or emitting CONFIG_INDEX=-1, and the generated PrecomputedGrid switch throws std::runtime_error on an unknown config_index rather than silently launching a wrong grid or skipping the launch. Repro (fresh compile, B200): an APS deterministic NE training graph failed compiling its backward embedding kernel with Precomputed grid not found for {BLOCK_EMB_1: 64, BLOCK_EMB_2: 64, BLOCK_EMB_3: 64, num_warps: 8, num_stages: 1} in [{config: {..., num_warps: 4, num_stages: 2}, ...}, {config: {..., num_warps: 8, num_stages: 2}, ...}] Test Plan: Unit tests (focused, this diff): buck2 test fbcode//caffe2/test/inductor:triton_heuristics -- --regex 'TestPrecomputedGridConfigMatching' Latest result: Tests finished: Pass 10. Fail 0. EXIT=0. The TestPrecomputedGridConfigMatching class has 9 tests; buck also counts the target listing entry in the Pass total. (Earlier combined run with the static-launcher suite: Pass 13, testrun 20829148341781464.) - test_exact_match_selects_warps_dependent_grid: candidates with distinct num_warps-dependent grids select their own candidate on an exact config. - test_exact_match_distinguishes_num_stages: candidates differing only in num_stages select their own candidate; the exact tier is not relaxed onto the first candidate. - test_retry_tier_matches_num_stages_kwarg_only_at_one: the NUM_STAGES kwarg relaxes only at the retry-produced value 1; NUM_STAGES=2 finds no candidate. - test_matches_pipelining_disabled_retry_config: the num_stages=1 retry config still selects the num_warps=8 candidate (index 1). - test_candidate_order_does_not_change_result: candidate order does not change the selected candidate or grid. - test_still_rejects_different_block_sizes: a BLOCK mismatch still raises AssertionError / returns None. - test_aoti_config_header_matches_pipelining_disabled_config: the AOTI lazy header emits CONFIG_INDEX 1 for a num_stages=1, num_warps=8 config. - test_aoti_config_header_rejects_unmatched_config: the AOTI lazy path raises when no candidate matches. - test_from_meta_with_retried_config: drives GridExpr.from_meta (the entry point make_launcher uses) with candidates stored from a NUM_STAGES=3 pre-retry config and the retried num_stages/NUM_STAGES=1 lookup. (A fuller retry-chain test in test_static_triton_launcher.py was removed from this diff: that file's GitHub base lacks the anchoring test from the closed-unmerged PR pytorch#200459, so ShipIt could not apply the patch; see below.) End-to-end (earlier version): with this change, the B200 deterministic NE graph that previously failed fresh compilation with "Precomputed grid not found for {..., num_stages: 1}" compiles and runs. Re-run on version 463077376 stack (D128589853@c49463b671): B200 NE E2E on RE, testrun 18577348527581008, RE session reSessionID-4515d0f8-7324-493b-bbef-22851e574ff6, ran 997s, Infra Failure 0, Fatal 0; the single failure is the B200 NE numerical comparison, the same single failure D128589853 CI reports for this target/baseline, unrelated to grid selection. arc lint -a on all changed files: ok, no issues. arc pyrefly check-owning-targets: typing is not enabled for these targets, so no type check was performed. Rebased onto trunk (master@bf4054759a76) after the GitHub export failed to apply the patch to test/inductor/test_static_triton_launcher.py on the stale base; rebase merged cleanly. Focused tests re-run on the rebased commit 30389e9bdf11: Pass 13, Fail 0 (testrun 15762598912051375). Export note: the GitHub export of version 464127200 failed in CodeSync because the added test in test_static_triton_launcher.py anchors after test_tensor_memory_autotuner_retries_without_pipelining, which exists in fbsource trunk (from PR pytorch#200459) but that PR is closed-unmerged on GitHub, so the patch context does not exist on GitHub main. Rebasing inside fbsource cannot fix an fbsource<->GitHub base divergence, so that file is no longer touched by this diff. Differential Revision: D128937194
…ytorch#203016) Summary: When the Triton config chosen for a kernel exceeds shared memory at launcher creation, _make_launchers retries via compile_by_disabling_pipelining (num_stages=1). For kernels with a PrecomputedGrid, GridExpr.generate then looked for an exact config match including num_stages, so the retry died with "Precomputed grid not found for {..., num_stages: 1}" instead of launching with the precomputed grid. Candidate matching in PrecomputedGrid.generate is tiered: an exact config match first (a user grid can depend on num_warps/num_stages, so candidates differing only in those values may carry different grids), then a retry tier that accepts a different num_stages/NUM_STAGES only when the lookup value is 1, which is exactly what compile_by_disabling_pipelining produces. Different BLOCK sizes still reject. Update addressing automated GitHub review comments: candidate matching now lives in the shared PrecomputedGrid.find_candidate_index helper, used by PrecomputedGrid.generate, run_triton_kernel_with_autotune, and generate_aoti_kernel_config_header. Matching is tiered as described above, so a user grid that depends on num_warps/num_stages still selects its own candidate, while the pipelining-disabled retry (num_stages and NUM_STAGES lowered to 1) rebinds to a stored candidate. The relaxed tier cannot tell which candidate the retried config came from, so when several relaxed matches carry different grids it raises instead of silently picking the first; a stored grid is reused as-is (a grid that reads NUM_STAGES is not recomputed for the retried config). The two lazy paths raise when no candidate matches instead of leaving config_index unset or emitting CONFIG_INDEX=-1, and the generated PrecomputedGrid switch throws std::runtime_error on an unknown config_index rather than silently launching a wrong grid or skipping the launch. Repro (fresh compile, B200): an APS deterministic NE training graph failed compiling its backward embedding kernel with Precomputed grid not found for {BLOCK_EMB_1: 64, BLOCK_EMB_2: 64, BLOCK_EMB_3: 64, num_warps: 8, num_stages: 1} in [{config: {..., num_warps: 4, num_stages: 2}, ...}, {config: {..., num_warps: 8, num_stages: 2}, ...}] Test Plan: Unit tests (focused, this diff): buck2 test fbcode//caffe2/test/inductor:triton_heuristics -- --regex 'TestPrecomputedGridConfigMatching' Latest result: Tests finished: Pass 14. Fail 0. EXIT=0 (testrun 15762598912076552). The TestPrecomputedGridConfigMatching class has 13 tests; buck also counts the target listing entry in the Pass total. (Earlier combined run with the static-launcher suite: Pass 13, testrun 20829148341781464.) - test_exact_match_selects_warps_dependent_grid: candidates with distinct num_warps-dependent grids select their own candidate on an exact config. - test_exact_match_distinguishes_num_stages: candidates differing only in num_stages select their own candidate; the exact tier is not relaxed onto the first candidate. - test_retry_tier_matches_num_stages_kwarg_only_at_one: the NUM_STAGES kwarg relaxes only at the retry-produced value 1; NUM_STAGES=2 finds no candidate. - test_matches_pipelining_disabled_retry_config: the num_stages=1 retry config still selects the num_warps=8 candidate (index 1). - test_candidate_order_does_not_change_result: candidate order does not change the selected candidate or grid. - test_still_rejects_different_block_sizes: a BLOCK mismatch still raises AssertionError / returns None. - test_aoti_config_header_matches_pipelining_disabled_config: the AOTI lazy header emits CONFIG_INDEX 1 for a num_stages=1, num_warps=8 config. - test_aoti_config_header_rejects_unmatched_config: the AOTI lazy path raises when no candidate matches. - test_make_launchers_retries_with_precomputed_grid: drives the real chain _make_launchers -> compile_by_disabling_pipelining -> make_launcher -> GridExpr.from_meta with a real triton.Config (so from_meta's config_to_dict conversion runs) and candidates built by config_to_dict, mirroring wrapper.py; the retry produces the num_warps=8 candidate's grid. - test_exact_tier_wins_over_relaxed_tier: a num_stages=1 lookup with an exact candidate selects it over an earlier num_stages=3 candidate. - test_relaxed_tier_raises_on_ambiguous_grids / test_relaxed_tier_accepts_identical_grids: relaxed matches with different grids raise; identical grids return the first match. - test_from_meta_with_retried_config: drives GridExpr.from_meta with hand-written dicts as a lightweight complement. End-to-end (earlier version): with this change, the B200 deterministic NE graph that previously failed fresh compilation with "Precomputed grid not found for {..., num_stages: 1}" compiles and runs. Re-run on version 463077376 stack (D128589853@c49463b671): B200 NE E2E on RE, testrun 18577348527581008, RE session reSessionID-4515d0f8-7324-493b-bbef-22851e574ff6, ran 997s, Infra Failure 0, Fatal 0; the single failure is the B200 NE numerical comparison, the same single failure D128589853 CI reports for this target/baseline, unrelated to grid selection. arc lint -a on all changed files: ok, no issues. arc pyrefly check-owning-targets: typing is not enabled for these targets, so no type check was performed. Rebased onto trunk (master@bf4054759a76) after the GitHub export failed to apply the patch to test/inductor/test_static_triton_launcher.py on the stale base; rebase merged cleanly. Focused tests re-run on the rebased commit 30389e9bdf11: Pass 13, Fail 0 (testrun 15762598912051375). Export note: the GitHub export of version 464127200 failed in CodeSync because the added test in test_static_triton_launcher.py anchors after test_tensor_memory_autotuner_retries_without_pipelining, which exists in fbsource trunk (from PR pytorch#200459) but that PR is closed-unmerged on GitHub, so the patch context does not exist on GitHub main. Rebasing inside fbsource cannot fix an fbsource<->GitHub base divergence, so that file is no longer touched by this diff. Differential Revision: D128937194
…ytorch#203016) Summary: When the Triton config chosen for a kernel exceeds shared memory at launcher creation, _make_launchers retries via compile_by_disabling_pipelining (num_stages=1). For kernels with a PrecomputedGrid, GridExpr.generate then looked for an exact config match including num_stages, so the retry died with "Precomputed grid not found for {..., num_stages: 1}" instead of launching with the precomputed grid. Candidate matching in PrecomputedGrid.generate is tiered: an exact config match first (a user grid can depend on num_warps/num_stages, so candidates differing only in those values may carry different grids), then a retry tier that accepts a different num_stages/NUM_STAGES only when the lookup value is 1, which is exactly what compile_by_disabling_pipelining produces. Different BLOCK sizes still reject. Update addressing automated GitHub review comments: candidate matching now lives in the shared PrecomputedGrid.find_candidate_index helper, used by PrecomputedGrid.generate, run_triton_kernel_with_autotune, and generate_aoti_kernel_config_header. Matching is tiered as described above, so a user grid that depends on num_warps/num_stages still selects its own candidate, while the pipelining-disabled retry (num_stages and NUM_STAGES lowered to 1) rebinds to a stored candidate. The relaxed tier cannot tell which candidate the retried config came from, so when several relaxed matches carry different grids it raises instead of silently picking the first; a stored grid is reused as-is (a grid that reads NUM_STAGES is not recomputed for the retried config). The two lazy paths raise when no candidate matches instead of leaving config_index unset or emitting CONFIG_INDEX=-1, and the generated PrecomputedGrid switch throws std::runtime_error on an unknown config_index rather than silently launching a wrong grid or skipping the launch. Repro (fresh compile, B200): an APS deterministic NE training graph failed compiling its backward embedding kernel with Precomputed grid not found for {BLOCK_EMB_1: 64, BLOCK_EMB_2: 64, BLOCK_EMB_3: 64, num_warps: 8, num_stages: 1} in [{config: {..., num_warps: 4, num_stages: 2}, ...}, {config: {..., num_warps: 8, num_stages: 2}, ...}] Test Plan: Unit tests (focused, this diff): buck2 test fbcode//caffe2/test/inductor:triton_heuristics -- --regex 'TestPrecomputedGridConfigMatching' Latest result: Tests finished: Pass 14. Fail 0. EXIT=0 (testrun 15762598912076552). The TestPrecomputedGridConfigMatching class has 13 tests; buck also counts the target listing entry in the Pass total. (Earlier combined run with the static-launcher suite: Pass 13, testrun 20829148341781464.) - test_exact_match_selects_warps_dependent_grid: candidates with distinct num_warps-dependent grids select their own candidate on an exact config. - test_exact_match_distinguishes_num_stages: candidates differing only in num_stages select their own candidate; the exact tier is not relaxed onto the first candidate. - test_retry_tier_matches_num_stages_kwarg_only_at_one: the NUM_STAGES kwarg relaxes only at the retry-produced value 1; NUM_STAGES=2 finds no candidate. - test_matches_pipelining_disabled_retry_config: the num_stages=1 retry config still selects the num_warps=8 candidate (index 1). - test_candidate_order_does_not_change_result: candidate order does not change the selected candidate or grid. - test_still_rejects_different_block_sizes: a BLOCK mismatch still raises AssertionError / returns None. - test_aoti_config_header_matches_pipelining_disabled_config: the AOTI lazy header emits CONFIG_INDEX 1 for a num_stages=1, num_warps=8 config. - test_aoti_config_header_rejects_unmatched_config: the AOTI lazy path raises when no candidate matches. - test_make_launchers_retries_with_precomputed_grid: drives the real chain _make_launchers -> compile_by_disabling_pipelining -> make_launcher -> GridExpr.from_meta with a real triton.Config (so from_meta's config_to_dict conversion runs) and candidates built by config_to_dict, mirroring wrapper.py; the retry produces the num_warps=8 candidate's grid. - test_exact_tier_wins_over_relaxed_tier: a num_stages=1 lookup with an exact candidate selects it over an earlier num_stages=3 candidate. - test_relaxed_tier_raises_on_ambiguous_grids / test_relaxed_tier_accepts_identical_grids: relaxed matches with different grids raise; identical grids return the first match. - test_from_meta_with_retried_config: drives GridExpr.from_meta with hand-written dicts as a lightweight complement. End-to-end (earlier version): with this change, the B200 deterministic NE graph that previously failed fresh compilation with "Precomputed grid not found for {..., num_stages: 1}" compiles and runs. Re-run on version 463077376 stack (D128589853@c49463b671): B200 NE E2E on RE, testrun 18577348527581008, RE session reSessionID-4515d0f8-7324-493b-bbef-22851e574ff6, ran 997s, Infra Failure 0, Fatal 0; the single failure is the B200 NE numerical comparison, the same single failure D128589853 CI reports for this target/baseline, unrelated to grid selection. arc lint -a on all changed files: ok, no issues. arc pyrefly check-owning-targets: typing is not enabled for these targets, so no type check was performed. Rebased onto trunk (master@bf4054759a76) after the GitHub export failed to apply the patch to test/inductor/test_static_triton_launcher.py on the stale base; rebase merged cleanly. Focused tests re-run on the rebased commit 30389e9bdf11: Pass 13, Fail 0 (testrun 15762598912051375). Export note: the GitHub export of version 464127200 failed in CodeSync because the added test in test_static_triton_launcher.py anchors after test_tensor_memory_autotuner_retries_without_pipelining, which exists in fbsource trunk (from PR pytorch#200459) but that PR is closed-unmerged on GitHub, so the patch context does not exist on GitHub main. Rebasing inside fbsource cannot fix an fbsource<->GitHub base divergence, so that file is no longer touched by this diff. Differential Revision: D128937194
…ytorch#203016) Summary: When the Triton config chosen for a kernel exceeds shared memory at launcher creation, _make_launchers retries via compile_by_disabling_pipelining (num_stages=1). For kernels with a PrecomputedGrid, GridExpr.generate then looked for an exact config match including num_stages, so the retry died with "Precomputed grid not found for {..., num_stages: 1}" instead of launching with the precomputed grid. Candidate matching in PrecomputedGrid.generate is tiered: an exact config match first (a user grid can depend on num_warps/num_stages, so candidates differing only in those values may carry different grids), then a retry tier that accepts a different num_stages/NUM_STAGES only when the lookup value is 1, which is exactly what compile_by_disabling_pipelining produces. Different BLOCK sizes still reject. Update addressing automated GitHub review comments: candidate matching now lives in the shared PrecomputedGrid.find_candidate_index helper, used by PrecomputedGrid.generate, run_triton_kernel_with_autotune, and generate_aoti_kernel_config_header. Matching is tiered as described above, so a user grid that depends on num_warps/num_stages still selects its own candidate, while the pipelining-disabled retry (num_stages lowered to 1) rebinds to a stored candidate. Only num_stages is relaxed: the NUM_STAGES kwarg is a user kernel kwarg a grid can read, so it must match exactly and such kernels fail loudly on the retry instead of reusing a stale grid. The relaxed tier cannot tell which candidate the retried config came from, so when several relaxed matches carry different grids it raises instead of silently picking the first; a stored grid is reused as-is and is not recomputed for the retried config. The two lazy paths raise when no candidate matches instead of leaving config_index unset or emitting CONFIG_INDEX=-1, and the generated PrecomputedGrid switch throws std::runtime_error on an unknown config_index rather than silently launching a wrong grid or skipping the launch. Repro (fresh compile, B200): an APS deterministic NE training graph failed compiling its backward embedding kernel with Precomputed grid not found for {BLOCK_EMB_1: 64, BLOCK_EMB_2: 64, BLOCK_EMB_3: 64, num_warps: 8, num_stages: 1} in [{config: {..., num_warps: 4, num_stages: 2}, ...}, {config: {..., num_warps: 8, num_stages: 2}, ...}] Test Plan: Unit tests (focused, this diff): buck2 test fbcode//caffe2/test/inductor:triton_heuristics -- --regex 'TestPrecomputedGridConfigMatching' Latest result: Tests finished: Pass 14. Fail 0. EXIT=0 (latest run this session; earlier testrun 15762598912076552). The TestPrecomputedGridConfigMatching class has 13 tests; buck also counts the target listing entry in the Pass total. (Earlier combined run with the static-launcher suite: Pass 13, testrun 20829148341781464.) - test_exact_match_selects_warps_dependent_grid: candidates with distinct num_warps-dependent grids select their own candidate on an exact config. - test_exact_match_distinguishes_num_stages: candidates differing only in num_stages select their own candidate; the exact tier is not relaxed onto the first candidate. - test_num_stages_kwarg_is_not_relaxed: the NUM_STAGES kwarg must match exactly; a retried NUM_STAGES=1 lookup finds no candidate, and the stage keys do not relax independently (the relaxed tier is gated on lookup num_stages == 1). - test_matches_pipelining_disabled_retry_config: the num_stages=1 retry config still selects the num_warps=8 candidate (index 1). - test_candidate_order_does_not_change_result: candidate order does not change the selected candidate or grid. - test_still_rejects_different_block_sizes: a BLOCK mismatch still raises AssertionError / returns None. - test_aoti_config_header_matches_pipelining_disabled_config: the AOTI lazy header emits CONFIG_INDEX 1 for a num_stages=1, num_warps=8 config. - test_aoti_config_header_rejects_unmatched_config: the AOTI lazy path raises when no candidate matches. - test_make_launchers_retries_with_precomputed_grid: drives the real chain _make_launchers -> compile_by_disabling_pipelining -> make_launcher -> GridExpr.from_meta with a real triton.Config (so from_meta's config_to_dict conversion runs) and candidates built by config_to_dict, mirroring wrapper.py; the retry produces the num_warps=8 candidate's grid. - test_exact_tier_wins_over_relaxed_tier: a num_stages=1 lookup with an exact candidate selects it over an earlier num_stages=3 candidate. - test_relaxed_tier_raises_on_ambiguous_grids / test_relaxed_tier_accepts_identical_grids: relaxed matches with different grids raise; identical grids return the first match. - test_from_meta_with_retried_config: drives GridExpr.from_meta with hand-written dicts as a lightweight complement. End-to-end (earlier version): with this change, the B200 deterministic NE graph that previously failed fresh compilation with "Precomputed grid not found for {..., num_stages: 1}" compiles and runs. Re-run on version 463077376 stack (D128589853@c49463b671): B200 NE E2E on RE, testrun 18577348527581008, RE session reSessionID-4515d0f8-7324-493b-bbef-22851e574ff6, ran 997s, Infra Failure 0, Fatal 0; the single failure is the B200 NE numerical comparison, the same single failure D128589853 CI reports for this target/baseline, unrelated to grid selection. arc lint -a on all changed files: ok, no issues. arc pyrefly check-owning-targets: typing is not enabled for these targets, so no type check was performed. Rebased onto trunk (master@bf4054759a76) after the GitHub export failed to apply the patch to test/inductor/test_static_triton_launcher.py on the stale base; rebase merged cleanly. Focused tests re-run on the rebased commit 30389e9bdf11: Pass 13, Fail 0 (testrun 15762598912051375). Export note: the GitHub export of version 464127200 failed in CodeSync because the added test in test_static_triton_launcher.py anchors after test_tensor_memory_autotuner_retries_without_pipelining, which exists in fbsource trunk (from PR pytorch#200459) but that PR is closed-unmerged on GitHub, so the patch context does not exist on GitHub main. Rebasing inside fbsource cannot fix an fbsource<->GitHub base divergence, so that file is no longer touched by this diff. Differential Revision: D128937194
…ytorch#203016) Summary: When the Triton config chosen for a kernel exceeds shared memory at launcher creation, _make_launchers retries via compile_by_disabling_pipelining (num_stages=1). For kernels with a PrecomputedGrid, GridExpr.generate then looked for an exact config match including num_stages, so the retry died with "Precomputed grid not found for {..., num_stages: 1}" instead of launching with the precomputed grid. Candidate matching in PrecomputedGrid.generate is tiered: an exact config match first (a user grid can depend on num_warps/num_stages, so candidates differing only in those values may carry different grids), then a retry tier that accepts a different num_stages/NUM_STAGES only when the lookup value is 1, which is exactly what compile_by_disabling_pipelining produces. Different BLOCK sizes still reject. Update addressing automated GitHub review comments: candidate matching now lives in the shared PrecomputedGrid.find_candidate_index helper, used by PrecomputedGrid.generate, run_triton_kernel_with_autotune, and generate_aoti_kernel_config_header. Matching is tiered as described above, so a user grid that depends on num_warps/num_stages still selects its own candidate, while the pipelining-disabled retry (num_stages lowered to 1) rebinds to a stored candidate. Only num_stages is relaxed: the NUM_STAGES kwarg is a user kernel kwarg a grid can read, so it must match exactly and such kernels fail loudly on the retry instead of reusing a stale grid. The relaxed tier cannot tell which candidate the retried config came from, so when several relaxed matches carry different grids it raises instead of silently picking the first; a stored grid is reused as-is and is not recomputed for the retried config. The two lazy paths raise when no candidate matches instead of leaving config_index unset or emitting CONFIG_INDEX=-1, and the generated PrecomputedGrid switch throws std::runtime_error on an unknown config_index rather than silently launching a wrong grid or skipping the launch. Repro (fresh compile, B200): an APS deterministic NE training graph failed compiling its backward embedding kernel with Precomputed grid not found for {BLOCK_EMB_1: 64, BLOCK_EMB_2: 64, BLOCK_EMB_3: 64, num_warps: 8, num_stages: 1} in [{config: {..., num_warps: 4, num_stages: 2}, ...}, {config: {..., num_warps: 8, num_stages: 2}, ...}] Test Plan: Unit tests (focused, this diff): buck2 test fbcode//caffe2/test/inductor:triton_heuristics -- --regex 'TestPrecomputedGridConfigMatching' Latest result: Tests finished: Pass 14. Fail 0. EXIT=0 (latest run this session; earlier testrun 15762598912076552). The TestPrecomputedGridConfigMatching class has 13 tests; buck also counts the target listing entry in the Pass total. (Earlier combined run with the static-launcher suite: Pass 13, testrun 20829148341781464.) - test_exact_match_selects_warps_dependent_grid: candidates with distinct num_warps-dependent grids select their own candidate on an exact config. - test_exact_match_distinguishes_num_stages: candidates differing only in num_stages select their own candidate; the exact tier is not relaxed onto the first candidate. - test_num_stages_kwarg_is_not_relaxed: the NUM_STAGES kwarg must match exactly; a retried NUM_STAGES=1 lookup finds no candidate, and the stage keys do not relax independently (the relaxed tier is gated on lookup num_stages == 1). - test_matches_pipelining_disabled_retry_config: the num_stages=1 retry config still selects the num_warps=8 candidate (index 1). - test_candidate_order_does_not_change_result: candidate order does not change the selected candidate or grid. - test_still_rejects_different_block_sizes: a BLOCK mismatch still raises AssertionError / returns None. - test_aoti_config_header_matches_pipelining_disabled_config: the AOTI lazy header emits CONFIG_INDEX 1 for a num_stages=1, num_warps=8 config. - test_aoti_config_header_rejects_unmatched_config: the AOTI lazy path raises when no candidate matches. - test_make_launchers_retries_with_precomputed_grid: drives the real chain _make_launchers -> compile_by_disabling_pipelining -> make_launcher -> GridExpr.from_meta with a real triton.Config (so from_meta's config_to_dict conversion runs) and candidates built by config_to_dict, mirroring wrapper.py; the retry produces the num_warps=8 candidate's grid. - test_exact_tier_wins_over_relaxed_tier: a num_stages=1 lookup with an exact candidate selects it over an earlier num_stages=3 candidate. - test_relaxed_tier_raises_on_ambiguous_grids / test_relaxed_tier_accepts_identical_grids: relaxed matches with different grids raise; identical grids return the first match. - test_from_meta_with_retried_config: drives GridExpr.from_meta with hand-written dicts as a lightweight complement. End-to-end (earlier version): with this change, the B200 deterministic NE graph that previously failed fresh compilation with "Precomputed grid not found for {..., num_stages: 1}" compiles and runs. Re-run on version 463077376 stack (D128589853@c49463b671): B200 NE E2E on RE, testrun 18577348527581008, RE session reSessionID-4515d0f8-7324-493b-bbef-22851e574ff6, ran 997s, Infra Failure 0, Fatal 0; the single failure is the B200 NE numerical comparison, the same single failure D128589853 CI reports for this target/baseline, unrelated to grid selection. arc lint -a on all changed files: ok, no issues. arc pyrefly check-owning-targets: typing is not enabled for these targets, so no type check was performed. Rebased onto trunk (master@bf4054759a76) after the GitHub export failed to apply the patch to test/inductor/test_static_triton_launcher.py on the stale base; rebase merged cleanly. Focused tests re-run on the rebased commit 30389e9bdf11: Pass 13, Fail 0 (testrun 15762598912051375). Export note: the GitHub export of version 464127200 failed in CodeSync because the added test in test_static_triton_launcher.py anchors after test_tensor_memory_autotuner_retries_without_pipelining, which exists in fbsource trunk (from PR pytorch#200459) but that PR is closed-unmerged on GitHub, so the patch context does not exist on GitHub main. Rebasing inside fbsource cannot fix an fbsource<->GitHub base divergence, so that file is no longer touched by this diff. Differential Revision: D128937194
…ytorch#200459) Author's note: A second `make_launcher` on the same static compile result tried to reload a cubin that the first load had already cleared, which either raised "Cubin file saved by TritonBundler not found" or did redundant I/O. I reviewed the 1-line guard; the new unit tests fail without it and cover the still-erroring case. The description below was drafted with an AI assistant (Claude): > `StaticTritonCompileResult.make_launcher` reloads the kernel binary whenever > `kernel.cubin_path` is unset. The first `load_kernel` call clears > `cubin_path`/`cubin_raw` after loading, so a second `make_launcher` on the same > result, which `_dynamic_scale_rblock` triggers through `_make_launchers()`, > tries to reload a binary that is no longer there. Depending on the cache > directory at that point this either raises "Cubin file saved by TritonBundler > not found" or does redundant file I/O. > > Skip the reload when a device-bound kernel function is already loaded. > Device-agnostic kernels keep `function` unset, so they still load per device. > > Test Plan: > ``` > python -m pytest test/inductor/test_static_triton_launcher.py -k make_launcher > ``` > `test_make_launcher_reuses_loaded_kernel_after_cache_context` fails without the > fix; `test_make_launcher_missing_unloaded_binary_still_errors` checks that an > unloaded kernel with no binary still errors. > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200459 Approved by: https://github.com/drisspg
…ytorch#200459) Author's note: A second `make_launcher` on the same static compile result tried to reload a cubin that the first load had already cleared, which either raised "Cubin file saved by TritonBundler not found" or did redundant I/O. I reviewed the 1-line guard; the new unit tests fail without it and cover the still-erroring case. The description below was drafted with an AI assistant (Claude): > `StaticTritonCompileResult.make_launcher` reloads the kernel binary whenever > `kernel.cubin_path` is unset. The first `load_kernel` call clears > `cubin_path`/`cubin_raw` after loading, so a second `make_launcher` on the same > result, which `_dynamic_scale_rblock` triggers through `_make_launchers()`, > tries to reload a binary that is no longer there. Depending on the cache > directory at that point this either raises "Cubin file saved by TritonBundler > not found" or does redundant file I/O. > > Skip the reload when a device-bound kernel function is already loaded. > Device-agnostic kernels keep `function` unset, so they still load per device. > > Test Plan: > ``` > python -m pytest test/inductor/test_static_triton_launcher.py -k make_launcher > ``` > `test_make_launcher_reuses_loaded_kernel_after_cache_context` fails without the > fix; `test_make_launcher_missing_unloaded_binary_still_errors` checks that an > unloaded kernel with no binary still errors. > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200459 Approved by: https://github.com/drisspg
…ytorch#200459) Author's note: A second `make_launcher` on the same static compile result tried to reload a cubin that the first load had already cleared, which either raised "Cubin file saved by TritonBundler not found" or did redundant I/O. I reviewed the 1-line guard; the new unit tests fail without it and cover the still-erroring case. The description below was drafted with an AI assistant (Claude): > `StaticTritonCompileResult.make_launcher` reloads the kernel binary whenever > `kernel.cubin_path` is unset. The first `load_kernel` call clears > `cubin_path`/`cubin_raw` after loading, so a second `make_launcher` on the same > result, which `_dynamic_scale_rblock` triggers through `_make_launchers()`, > tries to reload a binary that is no longer there. Depending on the cache > directory at that point this either raises "Cubin file saved by TritonBundler > not found" or does redundant file I/O. > > Skip the reload when a device-bound kernel function is already loaded. > Device-agnostic kernels keep `function` unset, so they still load per device. > > Test Plan: > ``` > python -m pytest test/inductor/test_static_triton_launcher.py -k make_launcher > ``` > `test_make_launcher_reuses_loaded_kernel_after_cache_context` fails without the > fix; `test_make_launcher_missing_unloaded_binary_still_errors` checks that an > unloaded kernel with no binary still errors. > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200459 Approved by: https://github.com/drisspg
…ytorch#200459) Author's note: A second `make_launcher` on the same static compile result tried to reload a cubin that the first load had already cleared, which either raised "Cubin file saved by TritonBundler not found" or did redundant I/O. I reviewed the 1-line guard; the new unit tests fail without it and cover the still-erroring case. The description below was drafted with an AI assistant (Claude): > `StaticTritonCompileResult.make_launcher` reloads the kernel binary whenever > `kernel.cubin_path` is unset. The first `load_kernel` call clears > `cubin_path`/`cubin_raw` after loading, so a second `make_launcher` on the same > result, which `_dynamic_scale_rblock` triggers through `_make_launchers()`, > tries to reload a binary that is no longer there. Depending on the cache > directory at that point this either raises "Cubin file saved by TritonBundler > not found" or does redundant file I/O. > > Skip the reload when a device-bound kernel function is already loaded. > Device-agnostic kernels keep `function` unset, so they still load per device. > > Test Plan: > ``` > python -m pytest test/inductor/test_static_triton_launcher.py -k make_launcher > ``` > `test_make_launcher_reuses_loaded_kernel_after_cache_context` fails without the > fix; `test_make_launcher_missing_unloaded_binary_still_errors` checks that an > unloaded kernel with no binary still errors. > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200459 Approved by: https://github.com/drisspg
…UDA graphs (pytorch#200460) Author's note: With CUDA-graph autotune benchmarking, multi-kernel candidates launched on the wrong stream and nested lazy-autotune benchmarks were timed eagerly, so the wrong candidate could win. Each fix has a test that fails without it, and both match how `CachingAutotuner.bench` already handles the stream. The description below was drafted with an AI assistant (Claude): > With `max_autotune` and `autotune_cudagraph_benchmarking`, two bugs make > candidates that launch through multi-kernel, or that autotune on their first > launch, escape graph timing: they are timed eagerly with launch overhead, or > not at all. Either way the wrong candidate can win. > > 1. `MultiKernelCall.benchmark_sub_kernels` forwards the `stream` kwarg it was > called with to every candidate launch. The benchmarker captures the callable > on a side stream, so the launch escapes the capture: the graph is empty and > the candidate times as nearly free, or the capture errors and falls back to > eager timing. The stream is now resolved at call time, as > `CachingAutotuner.bench` already does (pytorch#179246). Outside of capture the > current stream is the one that was passed in, so eager benchmarking is > unchanged. > > 2. `InductorBenchmarker.benchmark_gpu` times GPU callables through > `benchmark_gpu_with_cuda_graph`: warmup, capture, then > `self.benchmark_gpu(cuda_graph.replay)`. `_in_cudagraph_benchmark` (a > thread-local depth since pytorch#194649) exists so that last call times the replay > directly instead of capturing it again, but the `InductorBenchmarker` > override raised it for the whole method, warmup included. A callable that autotunes on its first launch benchmarks other > callables during that warmup, and those nested benchmarks saw the flag and > were timed eagerly. Two callers hit this: > `MultiKernelCall.benchmark_sub_kernels`, which times `CachingAutotuner.run` > on sub-kernels that have not picked a config yet, and > `SubgraphChoiceCaller.benchmark`, which times a compiled module whose > kernels autotune on first call and calls `benchmark_gpu_with_cuda_graph` > directly. The thread-local depth now moves to the base `Benchmarker`, and > `benchmark_gpu_with_cuda_graph` raises it only around the replay timing; > the `InductorBenchmarker` override is dropped. > > An alternative is running the callable once before entering the graph path, > so lazy autotuning finishes first. That adds a launch to every graph-mode > benchmark and misses the direct `benchmark_gpu_with_cuda_graph` caller. > > Test Plan: > ``` > python -m pytest test/inductor/test_benchmarking.py test/inductor/test_multi_kernel.py test/inductor/test_static_triton_launcher.py test/inductor/test_custom_op_autotune.py > ``` > `test_benchmark_sub_kernels_captures_on_current_stream` captures a candidate in > a real CUDA graph and checks that replay runs it; it fails without fix 1. > `test_benchmark_gpu_with_cuda_graph_nested_benchmark_uses_graph` fails when the > flag covers the whole method (the nested benchmark is timed eagerly). On > MI300X, compiling a softmax with `triton.multi_kernel=1`, the 10 sub-kernel > config benchmarks run eagerly before this change and through graph capture > after it. > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200460 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459
…rs (pytorch#200461) Author's note: Behind an off-by-default flag, a stacked computed buffer is copied by a kernel fused into its producer instead of being re-read by a pointwise cat, which saves a kernel per stack in the MXFP6 preparation graphs. It's off by default because a broad benchmark sweep found regressions when the destination is transposed; the real fix (size-1 views not freezing their base) will replace the flag. The description below was drafted with an AI assistant (Claude): > `torch.stack(ts, -1)` decomposes to `cat([t.unsqueeze(-1) ...], -1)`. When a > stacked input is already realized, its unsqueeze builds a `ReinterpretView`, > which freezes the buffer's layout, so `ConcatKernel` cannot place it in the > output and it has to be copied. `cat` then treats that input as needing a copy > kernel anyway; if every input does, it lowers the whole cat as one > `pointwise_cat` kernel that re-reads the realized buffer. That kernel iterates > over the stacked output, so it cannot fuse with the input's producer, and the > producer's buffer is written and read back. > > A per-input copy through `ConcatKernel` has the same shape as the input, so the > scheduler can fuse it into the producer, which then stores straight into the > output slice; the intermediate buffer is removed when nothing else reads it. > So in `should_lower_cat_input`, do not count an input as needing a copy when > it is all of a buffer Inductor computes (and not a no-op such as > `torch.empty`, which has nothing to fuse into). > > This is behind `config.cat_fuse_computed_input_copies`, off by default. > Whether fusing the copy is profitable depends on the destination layout > relative to the producer's iteration order, which the lowering does not know: > on a broad benchmark sweep it removed bytes and kernels in most changed > graphs, but a padded *transposed* output made the fused stores uncoalesced > (1.6-1.9x slower on two cross-entropy gradients). Workloads where it is a win > (MXFP6 preparation: one kernel instead of two) opt in. The flag is > temporary: a size-1 view (the stack's unsqueeze) should not freeze its base, > since it is valid under any base layout; with that, cat places the buffer in > its output with no copy for everyone, and this flag can be removed. > > Alternatives considered: not freezing on size-1 views (a lazy unsqueeze view > that `ConcatKernel` sees through) is the real fix, but lazy views currently > claim their base's layout while having no strides, which some lowerings trip > over; that needs fixing first (and pytorch#193860's freeze discipline). A layout > derived from another layout would be the general form; that is a larger IR > change. > > Test Plan: > ``` > python -m pytest test/inductor/test_torchinductor.py -k "cat or stack" > python -m pytest test/inductor/test_inline_asm_concat.py > ``` > With the flag on, `test_stack_realized_inputs` generates 1 kernel on GPU instead of 2; > `test_stack_realized_input_twice` copies one realized buffer into two > slices. `test_inline_asm_concat.py` stacks the outputs of multi-output > `inline_asm_elementwise` calls; without this change, the six-output > `test_stack_outputs` case and the `use_asm` cases of > `test_normal_choices_stack_reshape` get a separate stack kernel. > `test_unrelated_asm_outputs` and `TestPointwisePackingChoices` cover stacks that > already compile to one kernel. On the MXFP6 preparation benchmark graphs, the > generated Triton kernels match those of the lazy-view approach (same kernel > count, loads and stores). > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200461 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460
…writes (pytorch#200462) Author's note: Forwarding a producer's live values required dense writes, so padded producers (row pitch wider than width) couldn't fuse. I reviewed the conservative non-overlap proof, which only declines on unknown sizes; it was also checked against brute-force address enumeration. The description below was drafted with an AI assistant (Claude): > Fusing a consumer that forwards a producer's live values requires knowing the > producer writes each address from exactly one iteration. The existing check > only accepts dense (contiguous) writes, so a producer whose logical rows are > narrower than their storage pitch (e.g. width 1056, pitch 1088, from a padded > output) is rejected even though its rows never overlap. > > Add `MemoryDep.is_non_overlapping`: the index must equal its affine > reconstruction `offset + sum(stride_i * var_i)`, and with axes ordered by > stride, each stride must exceed the largest displacement the inner axes can > reach. Size hints only choose the order; every inequality is checked with > `statically_known_*`, so a wrong hint can only make the proof decline. Offsets > containing indirect (TMP) symbols vary per iteration and decline too. > > This only replaces the density clause of > `_memory_dep_supports_index_equivalence`; callers still prove that each read > matches the write of the same iteration. > > Test Plan: > ``` > python -m pytest test/inductor/test_dependencies.py test/inductor/test_inductor_scheduler.py > python -m pytest test/inductor/test_nested_reduction_lanes.py -k pitched_group_lanes > ``` > `test_non_overlapping_addresses` checks every accepted map against its > enumerated addresses; a separate brute-force sweep over 18k rank-1..3 maps > found no accepted map with repeated addresses. > `test_pitched_group_lanes_and_aliases` reads a fixed lane of a producer whose > row pitch is wider than its width; its `escape` and `dynamic` cases fail > without this change. > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200462 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461
…stages (pytorch#200463) Author's note: A grouped reduction over fp16 labeled its fp32 tile as fp16, so a later bitcast emitted an invalid Triton cast and compilation failed; this is an upstream bug found by fuzzing. The reshape now keeps the input's dtype and the result uses the same accumulation type as `TritonKernel.reduction`. The description below was drafted with an AI assistant (Claude): > `_GroupedReductionOpsHandler.reduction` reshapes and reduces a grouped stage > value with the source dtype, but like `TritonKernel.reduction` the tile is > computed in float32 for float16/bfloat16 inputs. The reduced value is then > labelled float16 while holding a float32 tile, so a later bitcast emits > `<fp32 tile>.to(tl.int16, bitcast=True)`, which Triton rejects. Use the upcast > compute type for both the reshape and the reduce. > > Found by fuzzing the nested-reduction lane paths; it reproduces on upstream > main without them (`amin` over fp16 groups, then `.view(torch.int16) + 1`). > > Test Plan: > ``` > python -m pytest test/inductor/test_nested_reduction.py -k half_grouped_reduction_bitcast > ``` > `test_half_grouped_reduction_bitcast_epilogue` fails with a Triton compilation > error without the fix (persistent and looped variants) and passes with it. > > This change was prepared with an AI assistant. Pull Request resolved: pytorch#200463 Approved by: https://github.com/drisspg ghstack dependencies: pytorch#200459, pytorch#200460, pytorch#200461, pytorch#200462
…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
…-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)))
…torch#200465)" This reverts commit 671e030. Reverted pytorch#200465 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)))
…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)))
… nested stages (pytorch#200463)" This reverts commit 3da914e. Reverted pytorch#200463 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)))
Stack from ghstack (oldest at bottom):
Author's note: A second
make_launcheron the same static compile result tried to reload a cubin that the first load had already cleared, which either raised "Cubin file saved by TritonBundler not found" or did redundant I/O. I reviewed the 1-line guard; the new unit tests fail without it and cover the still-erroring case.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