Skip to content

[MPS] Migrate argmin/argmax from MPSGraph to Metal kernels - #187304

Closed
malfet wants to merge 5 commits into
gh/malfet/954/basefrom
gh/malfet/954/head
Closed

malfet wants to merge 5 commits into
gh/malfet/954/basefrom
gh/malfet/954/head

Conversation

@malfet

@malfet malfet commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Replaces the MPSGraph-based argmax/argmin implementation with three native Metal kernels mirroring the value_reduction layout introduced for amax/amin/all/any in #180752: a generic NormParams kernel for arbitrary reduction patterns, an inner-dim kernel (one simdgroup per row, simd_arg_reduce collapse) for contiguous reductions over the last dim, and an outer-dim kernel (TG_X x TG_Y tile, shared-mem pair tree reduce) for contiguous reductions over dim 0. The host-side dispatcher in ReduceOps.mm picks inner/outer when the input and output are contiguous and exactly one of those dims is reduced, and falls back to the generic kernel otherwise; full reduction (dim=None) is handled via a contiguous flatten so the returned linear index matches the standard as-if-contiguous convention.

The MPSGraph path used to cast bfloat16 to float32 before the reduction, so bf16 is where the migration wins the most (e.g. 4096x4096 dim=0 argmax goes 1518us -> 294us = 5.17x on M4 Max); fp16/fp32 dim=0 hit 2.4-3.5x and dim=1 hit 1.1-1.3x.

Correctness: the natural simd_argmax(val, idx) helper ties on lowest LANE, but when a single lane scans multiple positions its stored idx is not necessarily the lowest one carrying the winning value, so the kernels do a two-step simd_max + simd_min-on-eff_idx pattern instead (NaN lanes count as winners so first-NaN-in-source-order wins). The shared-memory tree reduction in the outer kernel uses the same strict-better-or-equal-with-lower-idx predicate. The NaN-propagating "should-replace" predicates argmax_replace / argmin_replace are factored into c10/metal/reduction_utils.h so they sit next to simd_argmax/simd_argmin, which already encode the same NaN-as-winner logic via simd_ballot.

TODO: argmin/argmax and amin/amax now share the (general, inner, outer) kernel shape, the per-thread-scan + simd-collapse skeleton, and the address-math helpers. Unifying them under a single Reducer concept (per-thread accumulator + finalize hook, with NCHAINS as a property of the reducer) would let the three kernel grids be written once and instantiated for both ValueReducer<Op, Load, NCHAINS=8> and ArgReducer<Op, NCHAINS=1>. Worth doing in a follow-up.

Benchmark (median of 500 iters on M4 Max, agent_space/bench_argminmax_pr.py):

op shape dtype mode baseline (us) new (us) speedup
argmax 4096x4096 bfloat16 dim0 1518 294 5.17x
argmax 4096x4096 bfloat16 dim1 991 315 3.15x
argmax 4096x4096 float16 dim0 1024 290 3.53x
argmin 4096x4096 float16 dim0 1014 326 3.11x
argmax 4096x4096 float32 dim0 1009 424 2.38x
argmin 4096x4096 int64 dim0 1075 740 1.45x
argmax 1024x1024 bfloat16 dim0 192 100 1.92x
argmax 1024x1024 float32 dim0 194 120 1.61x
argmax 4096x4096 float32 full 5044 4926 1.02x

Authored with Claude.

Fixes #130295

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jun 15, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❌ 1 New Failure, 3 Pending, 2 Unrelated Failures

As of commit f9e4d1f with merge base 40e21dc (image):

NEW FAILURE - The following job has failed:

FLAKY - The following job failed but was likely due to flakiness present on trunk:

BROKEN TRUNK - The following job failed but was present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

return T(-INFINITY);
}
template <typename T>
static inline bool better(T cand, T cur) {

@kurtamohler kurtamohler Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit: Why not call it "replace" or "reduce" instead of "better"?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Sure, let me come up with better name. Also, do you think it would be better if I'll split this one into two: one that moves inlined primitives from torch.compile to use c10::metal::argmax_replace and then next one that uses the same primitives from the kernel?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

TBH I don't really understand the question. I'm not very familiar with compile primitives

@malfet malfet added the topic: improvements topic category label Jun 16, 2026
[ghstack-poisoned]
[ghstack-poisoned]
malfet added a commit that referenced this pull request Jun 17, 2026
Replaces the MPSGraph-based argmax/argmin implementation with three native Metal kernels mirroring the value_reduction layout introduced for amax/amin/all/any in #180752: a generic NormParams kernel for arbitrary reduction patterns, an inner-dim kernel (one simdgroup per row, simd_arg_reduce collapse) for contiguous reductions over the last dim, and an outer-dim kernel (TG_X x TG_Y tile, shared-mem pair tree reduce) for contiguous reductions over dim 0. The host-side dispatcher in ReduceOps.mm picks inner/outer when the input and output are contiguous and exactly one of those dims is reduced, and falls back to the generic kernel otherwise; full reduction (dim=None) is handled via a contiguous flatten so the returned linear index matches the standard as-if-contiguous convention.

The MPSGraph path used to cast bfloat16 to float32 before the reduction, so bf16 is where the migration wins the most (e.g. 4096x4096 dim=0 argmax goes 1518us -> 294us = 5.17x on M4 Max); fp16/fp32 dim=0 hit 2.4-3.5x and dim=1 hit 1.1-1.3x.

Correctness: the natural simd_argmax(val, idx) helper ties on lowest LANE, but when a single lane scans multiple positions its stored idx is not necessarily the lowest one carrying the winning value, so the kernels do a two-step simd_max + simd_min-on-eff_idx pattern instead (NaN lanes count as winners so first-NaN-in-source-order wins). The shared-memory tree reduction in the outer kernel uses the same strict-better-or-equal-with-lower-idx predicate. The kernels template directly on the shared c10::metal::MaxOp / MinOp introduced in the previous commit, so the strict NaN-propagating "should-replace" predicate is the same one used for the inductor MPS codegen's per-thread arg scan.

TODO: argmin/argmax and amin/amax now share the (general, inner, outer) kernel shape, the per-thread-scan + simd-collapse skeleton, and the address-math helpers. Unifying them under a single Reducer concept (per-thread accumulator + finalize hook, with NCHAINS as a property of the reducer) would let the three kernel grids be written once and instantiated for both ValueReducer<Op, Load, NCHAINS=8> and ArgReducer<Op, NCHAINS=1>. Worth doing in a follow-up.

Benchmark (median of 500 iters on M4 Max, agent_space/bench_argminmax_pr.py):

| op     | shape     | dtype    | mode | baseline (us) | new (us) | speedup |
|--------|-----------|----------|------|--------------:|---------:|--------:|
| argmax | 4096x4096 | bfloat16 | dim0 |          1518 |      294 |  5.17x  |
| argmax | 4096x4096 | bfloat16 | dim1 |           991 |      315 |  3.15x  |
| argmax | 4096x4096 | float16  | dim0 |          1024 |      290 |  3.53x  |
| argmin | 4096x4096 | float16  | dim0 |          1014 |      326 |  3.11x  |
| argmax | 4096x4096 | float32  | dim0 |          1009 |      424 |  2.38x  |
| argmin | 4096x4096 | int64    | dim0 |          1075 |      740 |  1.45x  |
| argmax | 1024x1024 | bfloat16 | dim0 |           192 |      100 |  1.92x  |
| argmax | 1024x1024 | float32  | dim0 |           194 |      120 |  1.61x  |
| argmax | 4096x4096 | float32  | full |          5044 |     4926 |  1.02x  |

Authored with Claude.
ghstack-source-id: a1f9a57
Pull-Request: #187304
[ghstack-poisoned]
malfet added a commit that referenced this pull request Jun 17, 2026
Replaces the MPSGraph-based argmax/argmin implementation with three native Metal kernels mirroring the value_reduction layout introduced for amax/amin/all/any in #180752: a generic NormParams kernel for arbitrary reduction patterns, an inner-dim kernel (one simdgroup per row, simd_arg_reduce collapse) for contiguous reductions over the last dim, and an outer-dim kernel (TG_X x TG_Y tile, shared-mem pair tree reduce) for contiguous reductions over dim 0. The host-side dispatcher in ReduceOps.mm picks inner/outer when the input and output are contiguous and exactly one of those dims is reduced, and falls back to the generic kernel otherwise; full reduction (dim=None) is handled via a contiguous flatten so the returned linear index matches the standard as-if-contiguous convention.

The MPSGraph path used to cast bfloat16 to float32 before the reduction, so bf16 is where the migration wins the most (e.g. 4096x4096 dim=0 argmax goes 1518us -> 294us = 5.17x on M4 Max); fp16/fp32 dim=0 hit 2.4-3.5x and dim=1 hit 1.1-1.3x.

Correctness: the natural simd_argmax(val, idx) helper ties on lowest LANE, but when a single lane scans multiple positions its stored idx is not necessarily the lowest one carrying the winning value, so the kernels do a two-step simd_max + simd_min-on-eff_idx pattern instead (NaN lanes count as winners so first-NaN-in-source-order wins). The shared-memory tree reduction in the outer kernel uses the same strict-better-or-equal-with-lower-idx predicate. The kernels template directly on the shared c10::metal::MaxOp / MinOp introduced in the previous commit, so the strict NaN-propagating "should-replace" predicate is the same one used for the inductor MPS codegen's per-thread arg scan.

TODO: argmin/argmax and amin/amax now share the (general, inner, outer) kernel shape, the per-thread-scan + simd-collapse skeleton, and the address-math helpers. Unifying them under a single Reducer concept (per-thread accumulator + finalize hook, with NCHAINS as a property of the reducer) would let the three kernel grids be written once and instantiated for both ValueReducer<Op, Load, NCHAINS=8> and ArgReducer<Op, NCHAINS=1>. Worth doing in a follow-up.

Benchmark (median of 500 iters on M4 Max, agent_space/bench_argminmax_pr.py):

| op     | shape     | dtype    | mode | baseline (us) | new (us) | speedup |
|--------|-----------|----------|------|--------------:|---------:|--------:|
| argmax | 4096x4096 | bfloat16 | dim0 |          1518 |      294 |  5.17x  |
| argmax | 4096x4096 | bfloat16 | dim1 |           991 |      315 |  3.15x  |
| argmax | 4096x4096 | float16  | dim0 |          1024 |      290 |  3.53x  |
| argmin | 4096x4096 | float16  | dim0 |          1014 |      326 |  3.11x  |
| argmax | 4096x4096 | float32  | dim0 |          1009 |      424 |  2.38x  |
| argmin | 4096x4096 | int64    | dim0 |          1075 |      740 |  1.45x  |
| argmax | 1024x1024 | bfloat16 | dim0 |           192 |      100 |  1.92x  |
| argmax | 1024x1024 | float32  | dim0 |           194 |      120 |  1.61x  |
| argmax | 4096x4096 | float32  | full |          5044 |     4926 |  1.02x  |

Authored with Claude.
ghstack-source-id: ffe08ff
Pull-Request: #187304
malfet added a commit that referenced this pull request Jun 17, 2026
Replaces the MPSGraph-based argmax/argmin implementation with three native Metal kernels mirroring the value_reduction layout introduced for amax/amin/all/any in #180752: a generic NormParams kernel for arbitrary reduction patterns, an inner-dim kernel (one simdgroup per row, simd_arg_reduce collapse) for contiguous reductions over the last dim, and an outer-dim kernel (TG_X x TG_Y tile, shared-mem pair tree reduce) for contiguous reductions over dim 0. The host-side dispatcher in ReduceOps.mm picks inner/outer when the input and output are contiguous and exactly one of those dims is reduced, and falls back to the generic kernel otherwise; full reduction (dim=None) is handled via a contiguous flatten so the returned linear index matches the standard as-if-contiguous convention.

The MPSGraph path used to cast bfloat16 to float32 before the reduction, so bf16 is where the migration wins the most (e.g. 4096x4096 dim=0 argmax goes 1518us -> 294us = 5.17x on M4 Max); fp16/fp32 dim=0 hit 2.4-3.5x and dim=1 hit 1.1-1.3x.

Correctness: the natural simd_argmax(val, idx) helper ties on lowest LANE, but when a single lane scans multiple positions its stored idx is not necessarily the lowest one carrying the winning value, so the kernels do a two-step simd_max + simd_min-on-eff_idx pattern instead (NaN lanes count as winners so first-NaN-in-source-order wins). The shared-memory tree reduction in the outer kernel uses the same strict-better-or-equal-with-lower-idx predicate. The kernels template directly on the shared c10::metal::MaxOp / MinOp introduced in the previous commit, so the strict NaN-propagating "should-replace" predicate is the same one used for the inductor MPS codegen's per-thread arg scan.

TODO: argmin/argmax and amin/amax now share the (general, inner, outer) kernel shape, the per-thread-scan + simd-collapse skeleton, and the address-math helpers. Unifying them under a single Reducer concept (per-thread accumulator + finalize hook, with NCHAINS as a property of the reducer) would let the three kernel grids be written once and instantiated for both ValueReducer<Op, Load, NCHAINS=8> and ArgReducer<Op, NCHAINS=1>. Worth doing in a follow-up.

Benchmark (median of 500 iters on M4 Max, agent_space/bench_argminmax_pr.py):

| op     | shape     | dtype    | mode | baseline (us) | new (us) | speedup |
|--------|-----------|----------|------|--------------:|---------:|--------:|
| argmax | 4096x4096 | bfloat16 | dim0 |          1518 |      294 |  5.17x  |
| argmax | 4096x4096 | bfloat16 | dim1 |           991 |      315 |  3.15x  |
| argmax | 4096x4096 | float16  | dim0 |          1024 |      290 |  3.53x  |
| argmin | 4096x4096 | float16  | dim0 |          1014 |      326 |  3.11x  |
| argmax | 4096x4096 | float32  | dim0 |          1009 |      424 |  2.38x  |
| argmin | 4096x4096 | int64    | dim0 |          1075 |      740 |  1.45x  |
| argmax | 1024x1024 | bfloat16 | dim0 |           192 |      100 |  1.92x  |
| argmax | 1024x1024 | float32  | dim0 |           194 |      120 |  1.61x  |
| argmax | 4096x4096 | float32  | full |          5044 |     4926 |  1.02x  |

Authored with Claude.
ghstack-source-id: ffe08ff
Pull-Request: #187304
[ghstack-poisoned]
malfet added a commit that referenced this pull request Jun 17, 2026
Replaces the MPSGraph-based argmax/argmin implementation with three native Metal kernels mirroring the value_reduction layout introduced for amax/amin/all/any in #180752: a generic NormParams kernel for arbitrary reduction patterns, an inner-dim kernel (one simdgroup per row, simd_arg_reduce collapse) for contiguous reductions over the last dim, and an outer-dim kernel (TG_X x TG_Y tile, shared-mem pair tree reduce) for contiguous reductions over dim 0. The host-side dispatcher in ReduceOps.mm picks inner/outer when the input and output are contiguous and exactly one of those dims is reduced, and falls back to the generic kernel otherwise; full reduction (dim=None) is handled via a contiguous flatten so the returned linear index matches the standard as-if-contiguous convention.

The MPSGraph path used to cast bfloat16 to float32 before the reduction, so bf16 is where the migration wins the most (e.g. 4096x4096 dim=0 argmax goes 1518us -> 294us = 5.17x on M4 Max); fp16/fp32 dim=0 hit 2.4-3.5x and dim=1 hit 1.1-1.3x.

Correctness: the natural simd_argmax(val, idx) helper ties on lowest LANE, but when a single lane scans multiple positions its stored idx is not necessarily the lowest one carrying the winning value, so the kernels do a two-step simd_max + simd_min-on-eff_idx pattern instead (NaN lanes count as winners so first-NaN-in-source-order wins). The shared-memory tree reduction in the outer kernel uses the same strict-better-or-equal-with-lower-idx predicate. The kernels template directly on the shared c10::metal::MaxOp / MinOp introduced in the previous commit, so the strict NaN-propagating "should-replace" predicate is the same one used for the inductor MPS codegen's per-thread arg scan.

TODO: argmin/argmax and amin/amax now share the (general, inner, outer) kernel shape, the per-thread-scan + simd-collapse skeleton, and the address-math helpers. Unifying them under a single Reducer concept (per-thread accumulator + finalize hook, with NCHAINS as a property of the reducer) would let the three kernel grids be written once and instantiated for both ValueReducer<Op, Load, NCHAINS=8> and ArgReducer<Op, NCHAINS=1>. Worth doing in a follow-up.

Benchmark (median of 500 iters on M4 Max, agent_space/bench_argminmax_pr.py):

| op     | shape     | dtype    | mode | baseline (us) | new (us) | speedup |
|--------|-----------|----------|------|--------------:|---------:|--------:|
| argmax | 4096x4096 | bfloat16 | dim0 |          1518 |      294 |  5.17x  |
| argmax | 4096x4096 | bfloat16 | dim1 |           991 |      315 |  3.15x  |
| argmax | 4096x4096 | float16  | dim0 |          1024 |      290 |  3.53x  |
| argmin | 4096x4096 | float16  | dim0 |          1014 |      326 |  3.11x  |
| argmax | 4096x4096 | float32  | dim0 |          1009 |      424 |  2.38x  |
| argmin | 4096x4096 | int64    | dim0 |          1075 |      740 |  1.45x  |
| argmax | 1024x1024 | bfloat16 | dim0 |           192 |      100 |  1.92x  |
| argmax | 1024x1024 | float32  | dim0 |           194 |      120 |  1.61x  |
| argmax | 4096x4096 | float32  | full |          5044 |     4926 |  1.02x  |

Authored with Claude.
ghstack-source-id: 2a75a50
Pull-Request: #187304
@malfet

malfet commented Jun 17, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "Lint + MPS are green"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: Approvers from one of the following sets are needed:

  • Metamates (8Keep, aditvenk, AmesingFlank, andrewor14, andyanwang, ...)
  • Core Reviewers (mruberry, lezcano, Skylion007, ngimel, peterbell10, ...)
  • Core Maintainers (soumith, gchanan, ezyang, malfet, albanD, ...)
Details for Dev Infra team Raised by workflow job

Failing merge rule: Core Maintainers

@malfet

malfet commented Jun 17, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "Lint + MPS are green"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@atalman atalman added this to the 2.13.0 milestone Jun 18, 2026
atalman pushed a commit that referenced this pull request Jun 25, 2026
* [MPS] Refactor inlined Metal reduction logic into shared header (#187541)

Pulls the open-coded identity / replace / combine / simd_reduce / threadgroup_reduce helpers used by the Metal min/max value-reduction kernels (and by the inductor MPS codegen's max/min and argmin/argmax paths) into shared `c10::metal::MaxOp<T>` / `MinOp<T>` structs in `c10/metal/reduction_utils.h`. The follow-up change migrating argmin/argmax will reuse those primitives as well.

Fix latent bug in MPSInducotr when min/max would not identify -INFINITY, as identity used to be `-FLT_MIN` in inductor inlined reduction code, that allows one to remove xfails from bunch of dynamic shapes reduction tests

Authored with Claude.

Pull Request resolved: #187541
Approved by: https://github.com/Skylion007

* [MPS] Migrate argmin/argmax from MPSGraph to Metal kernels (#187304)

Replaces the MPSGraph-based argmax/argmin implementation with three native Metal kernels mirroring the value_reduction layout introduced for amax/amin/all/any in #180752: a generic NormParams kernel for arbitrary reduction patterns, an inner-dim kernel (one simdgroup per row, simd_arg_reduce collapse) for contiguous reductions over the last dim, and an outer-dim kernel (TG_X x TG_Y tile, shared-mem pair tree reduce) for contiguous reductions over dim 0. The host-side dispatcher in ReduceOps.mm picks inner/outer when the input and output are contiguous and exactly one of those dims is reduced, and falls back to the generic kernel otherwise; full reduction (dim=None) is handled via a contiguous flatten so the returned linear index matches the standard as-if-contiguous convention.

The MPSGraph path used to cast bfloat16 to float32 before the reduction, so bf16 is where the migration wins the most (e.g. 4096x4096 dim=0 argmax goes 1518us -> 294us = 5.17x on M4 Max); fp16/fp32 dim=0 hit 2.4-3.5x and dim=1 hit 1.1-1.3x.

Correctness: the natural simd_argmax(val, idx) helper ties on lowest LANE, but when a single lane scans multiple positions its stored idx is not necessarily the lowest one carrying the winning value, so the kernels do a two-step simd_max + simd_min-on-eff_idx pattern instead (NaN lanes count as winners so first-NaN-in-source-order wins). The shared-memory tree reduction in the outer kernel uses the same strict-better-or-equal-with-lower-idx predicate. The NaN-propagating "should-replace" predicates argmax_replace / argmin_replace are factored into c10/metal/reduction_utils.h so they sit next to simd_argmax/simd_argmin, which already encode the same NaN-as-winner logic via simd_ballot.

TODO: argmin/argmax and amin/amax now share the (general, inner, outer) kernel shape, the per-thread-scan + simd-collapse skeleton, and the address-math helpers. Unifying them under a single Reducer concept (per-thread accumulator + finalize hook, with NCHAINS as a property of the reducer) would let the three kernel grids be written once and instantiated for both ValueReducer<Op, Load, NCHAINS=8> and ArgReducer<Op, NCHAINS=1>. Worth doing in a follow-up.

Benchmark (median of 500 iters on M4 Max, agent_space/bench_argminmax_pr.py):

| op     | shape     | dtype    | mode | baseline (us) | new (us) | speedup |
|--------|-----------|----------|------|--------------:|---------:|--------:|
| argmax | 4096x4096 | bfloat16 | dim0 |          1518 |      294 |  5.17x  |
| argmax | 4096x4096 | bfloat16 | dim1 |           991 |      315 |  3.15x  |
| argmax | 4096x4096 | float16  | dim0 |          1024 |      290 |  3.53x  |
| argmin | 4096x4096 | float16  | dim0 |          1014 |      326 |  3.11x  |
| argmax | 4096x4096 | float32  | dim0 |          1009 |      424 |  2.38x  |
| argmin | 4096x4096 | int64    | dim0 |          1075 |      740 |  1.45x  |
| argmax | 1024x1024 | bfloat16 | dim0 |           192 |      100 |  1.92x  |
| argmax | 1024x1024 | float32  | dim0 |           194 |      120 |  1.61x  |
| argmax | 4096x4096 | float32  | full |          5044 |     4926 |  1.02x  |

Authored with Claude.

Fixes  #130295

Pull Request resolved: #187304
Approved by: https://github.com/kurtamohler, https://github.com/seemethere, https://github.com/izaitsevfb
ghstack dependencies: #187541
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…87304)

Replaces the MPSGraph-based argmax/argmin implementation with three native Metal kernels mirroring the value_reduction layout introduced for amax/amin/all/any in pytorch#180752: a generic NormParams kernel for arbitrary reduction patterns, an inner-dim kernel (one simdgroup per row, simd_arg_reduce collapse) for contiguous reductions over the last dim, and an outer-dim kernel (TG_X x TG_Y tile, shared-mem pair tree reduce) for contiguous reductions over dim 0. The host-side dispatcher in ReduceOps.mm picks inner/outer when the input and output are contiguous and exactly one of those dims is reduced, and falls back to the generic kernel otherwise; full reduction (dim=None) is handled via a contiguous flatten so the returned linear index matches the standard as-if-contiguous convention.

The MPSGraph path used to cast bfloat16 to float32 before the reduction, so bf16 is where the migration wins the most (e.g. 4096x4096 dim=0 argmax goes 1518us -> 294us = 5.17x on M4 Max); fp16/fp32 dim=0 hit 2.4-3.5x and dim=1 hit 1.1-1.3x.

Correctness: the natural simd_argmax(val, idx) helper ties on lowest LANE, but when a single lane scans multiple positions its stored idx is not necessarily the lowest one carrying the winning value, so the kernels do a two-step simd_max + simd_min-on-eff_idx pattern instead (NaN lanes count as winners so first-NaN-in-source-order wins). The shared-memory tree reduction in the outer kernel uses the same strict-better-or-equal-with-lower-idx predicate. The NaN-propagating "should-replace" predicates argmax_replace / argmin_replace are factored into c10/metal/reduction_utils.h so they sit next to simd_argmax/simd_argmin, which already encode the same NaN-as-winner logic via simd_ballot.

TODO: argmin/argmax and amin/amax now share the (general, inner, outer) kernel shape, the per-thread-scan + simd-collapse skeleton, and the address-math helpers. Unifying them under a single Reducer concept (per-thread accumulator + finalize hook, with NCHAINS as a property of the reducer) would let the three kernel grids be written once and instantiated for both ValueReducer<Op, Load, NCHAINS=8> and ArgReducer<Op, NCHAINS=1>. Worth doing in a follow-up.

Benchmark (median of 500 iters on M4 Max, agent_space/bench_argminmax_pr.py):

| op     | shape     | dtype    | mode | baseline (us) | new (us) | speedup |
|--------|-----------|----------|------|--------------:|---------:|--------:|
| argmax | 4096x4096 | bfloat16 | dim0 |          1518 |      294 |  5.17x  |
| argmax | 4096x4096 | bfloat16 | dim1 |           991 |      315 |  3.15x  |
| argmax | 4096x4096 | float16  | dim0 |          1024 |      290 |  3.53x  |
| argmin | 4096x4096 | float16  | dim0 |          1014 |      326 |  3.11x  |
| argmax | 4096x4096 | float32  | dim0 |          1009 |      424 |  2.38x  |
| argmin | 4096x4096 | int64    | dim0 |          1075 |      740 |  1.45x  |
| argmax | 1024x1024 | bfloat16 | dim0 |           192 |      100 |  1.92x  |
| argmax | 1024x1024 | float32  | dim0 |           194 |      120 |  1.61x  |
| argmax | 4096x4096 | float32  | full |          5044 |     4926 |  1.02x  |

Authored with Claude.

Fixes  pytorch#130295

Pull Request resolved: pytorch#187304
Approved by: https://github.com/kurtamohler, https://github.com/seemethere, https://github.com/izaitsevfb
ghstack dependencies: pytorch#187541
@github-actions
github-actions Bot deleted the gh/malfet/954/head branch July 19, 2026 02:24
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…87304)

Replaces the MPSGraph-based argmax/argmin implementation with three native Metal kernels mirroring the value_reduction layout introduced for amax/amin/all/any in pytorch#180752: a generic NormParams kernel for arbitrary reduction patterns, an inner-dim kernel (one simdgroup per row, simd_arg_reduce collapse) for contiguous reductions over the last dim, and an outer-dim kernel (TG_X x TG_Y tile, shared-mem pair tree reduce) for contiguous reductions over dim 0. The host-side dispatcher in ReduceOps.mm picks inner/outer when the input and output are contiguous and exactly one of those dims is reduced, and falls back to the generic kernel otherwise; full reduction (dim=None) is handled via a contiguous flatten so the returned linear index matches the standard as-if-contiguous convention.

The MPSGraph path used to cast bfloat16 to float32 before the reduction, so bf16 is where the migration wins the most (e.g. 4096x4096 dim=0 argmax goes 1518us -> 294us = 5.17x on M4 Max); fp16/fp32 dim=0 hit 2.4-3.5x and dim=1 hit 1.1-1.3x.

Correctness: the natural simd_argmax(val, idx) helper ties on lowest LANE, but when a single lane scans multiple positions its stored idx is not necessarily the lowest one carrying the winning value, so the kernels do a two-step simd_max + simd_min-on-eff_idx pattern instead (NaN lanes count as winners so first-NaN-in-source-order wins). The shared-memory tree reduction in the outer kernel uses the same strict-better-or-equal-with-lower-idx predicate. The NaN-propagating "should-replace" predicates argmax_replace / argmin_replace are factored into c10/metal/reduction_utils.h so they sit next to simd_argmax/simd_argmin, which already encode the same NaN-as-winner logic via simd_ballot.

TODO: argmin/argmax and amin/amax now share the (general, inner, outer) kernel shape, the per-thread-scan + simd-collapse skeleton, and the address-math helpers. Unifying them under a single Reducer concept (per-thread accumulator + finalize hook, with NCHAINS as a property of the reducer) would let the three kernel grids be written once and instantiated for both ValueReducer<Op, Load, NCHAINS=8> and ArgReducer<Op, NCHAINS=1>. Worth doing in a follow-up.

Benchmark (median of 500 iters on M4 Max, agent_space/bench_argminmax_pr.py):

| op     | shape     | dtype    | mode | baseline (us) | new (us) | speedup |
|--------|-----------|----------|------|--------------:|---------:|--------:|
| argmax | 4096x4096 | bfloat16 | dim0 |          1518 |      294 |  5.17x  |
| argmax | 4096x4096 | bfloat16 | dim1 |           991 |      315 |  3.15x  |
| argmax | 4096x4096 | float16  | dim0 |          1024 |      290 |  3.53x  |
| argmin | 4096x4096 | float16  | dim0 |          1014 |      326 |  3.11x  |
| argmax | 4096x4096 | float32  | dim0 |          1009 |      424 |  2.38x  |
| argmin | 4096x4096 | int64    | dim0 |          1075 |      740 |  1.45x  |
| argmax | 1024x1024 | bfloat16 | dim0 |           192 |      100 |  1.92x  |
| argmax | 1024x1024 | float32  | dim0 |           194 |      120 |  1.61x  |
| argmax | 4096x4096 | float32  | full |          5044 |     4926 |  1.02x  |

Authored with Claude.

Fixes  pytorch#130295

Pull Request resolved: pytorch#187304
Approved by: https://github.com/kurtamohler, https://github.com/seemethere, https://github.com/izaitsevfb
ghstack dependencies: pytorch#187541
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/mps Run MPS tests (subset of trunk) Merged module: inductor release notes: mps Release notes category topic: improvements topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants