Skip to content

[MPS] Migrate amax/amin/aminmax/all/any to Metal - #180752

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

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

Conversation

@malfet

@malfet malfet commented Apr 19, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Migration of trace, amax/amin, aminmax, and all/any from MPSGraph to native Metal kernels, following the pattern established by the sum migration (#180709):

  • Dedicated outer- and inner- reduction kernels
  • Two-stage reduction for large full reductions
  • Reuse c10::metal primitive for threadgroup reduction and nan propagation
  • Shared host-side dispatch with the sum/mean migration
  • aminmax fans out to at::amin_outf + at::amax_outf, which is not great but same as before
  • any/all are expressed as max/min on a predicate load (nonzero or NaN -> 1, zero -> 0)
  • native_functions.yaml now routes abovementioned to shared dispatc
  • Enables test_aminmax and test_invalid_0dim_aminmax on MPS

Benchmark

Median latency over 500 iterations on M4 Max, torch 2.12 (MPSGraph baseline) vs this PR.
Times averaged across min/max (which are the same op with a flipped functor) and all/any. Script at the end.

amin / amax

shape dtype mode 2.12 (µs) new (µs) speedup
1024x1024 float32 full 138 115 1.20x
1024x1024 float32 dim0 113 90 1.25x
1024x1024 float32 dim1 108 90 1.20x
1024x1024 float16 full 123 100 1.23x
1024x1024 float16 dim0 113 91 1.24x
1024x1024 float16 dim1 109 91 1.20x
1024x1024 bfloat16 full 117 102 1.14x
1024x1024 bfloat16 dim0 109 90 1.21x
1024x1024 bfloat16 dim1 108 92 1.18x
1024x1024 int64 full 139 105 1.32x
1024x1024 int64 dim0 142 101 1.41x
1024x1024 int64 dim1 125 100 1.26x
4096x4096 float32 full 273 234 1.16x
4096x4096 float32 dim0 269 238 1.13x
4096x4096 float32 dim1 260 229 1.13x
4096x4096 float16 full 177 142 1.25x
4096x4096 float16 dim0 194 140 1.39x
4096x4096 float16 dim1 168 130 1.30x
4096x4096 bfloat16 full 177 151 1.17x
4096x4096 bfloat16 dim0 197 147 1.34x
4096x4096 bfloat16 dim1 164 144 1.14x
4096x4096 int64 full 406 376 1.08x
4096x4096 int64 dim0 418 392 1.07x
4096x4096 int64 dim1 424 401 1.06x

all / any

shape dtype mode 2.12 (µs) new (µs) speedup
1024x1024 bool full 144 106 1.36x
1024x1024 bool dim0 137 92 1.48x
1024x1024 bool dim1 135 91 1.49x
1024x1024 int64 full 131 100 1.31x
1024x1024 int64 dim0 127 99 1.29x
1024x1024 int64 dim1 125 99 1.26x
1024x1024 float32 full 127 99 1.28x
1024x1024 float32 dim0 123 89 1.38x
1024x1024 float32 dim1 120 89 1.34x
1024x1024 float16 full 124 98 1.26x
1024x1024 float16 dim0 119 88 1.35x
1024x1024 float16 dim1 113 90 1.26x
4096x4096 bool full 446 125 3.55x
4096x4096 bool dim0 444 116 3.82x
4096x4096 bool dim1 463 112 4.14x
4096x4096 int64 full 434 369 1.18x
4096x4096 int64 dim0 440 396 1.11x
4096x4096 int64 dim1 417 399 1.05x
4096x4096 float32 full 294 264 1.11x
4096x4096 float32 dim0 290 270 1.07x
4096x4096 float32 dim1 292 260 1.12x
4096x4096 float16 full 206 159 1.30x
4096x4096 float16 dim0 218 135 1.62x
4096x4096 float16 dim1 195 130 1.50x
Benchmark script
import json, time, torch
SHAPES = [(1024, 1024), (4096, 4096)]
DV = [torch.float32, torch.float16, torch.bfloat16, torch.int64]
DP = [torch.bool, torch.int64, torch.float32, torch.float16]
OPS = [('amax', torch.amax, DV), ('amin', torch.amin, DV),
       ('all', torch.all, DP), ('any', torch.any, DP)]

def bench(fn, n=500):
    for _ in range(20): fn()
    s = []
    for _ in range(n):
        torch.mps.synchronize(); t0 = time.perf_counter()
        fn(); torch.mps.synchronize()
        s.append((time.perf_counter() - t0) * 1e6)
    return sorted(s)[n // 2]

def mkx(shape, dt):
    if dt == torch.bool:
        return torch.randint(0, 2, shape, dtype=dt, device='mps')
    if dt == torch.int64:
        return torch.randint(-100, 100, shape, dtype=dt, device='mps')
    return torch.randn(shape, dtype=dt, device='mps')

for op, fn, dts in OPS:
    for shape in SHAPES:
        for dt in dts:
            x = mkx(shape, dt)
            for mode, call in [('full', lambda: fn(x)),
                               ('dim0', lambda: fn(x, dim=0)),
                               ('dim1', lambda: fn(x, dim=1))]:
                print(json.dumps({'op': op, 'shape': shape,
                                  'dtype': str(dt).split('.')[1],
                                  'mode': mode, 'us': round(bench(call), 1)}))

Authored with Claude.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 19, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

⏳ No Failures, 14 Pending

As of commit 6ae47e4 with merge base 642b8f8 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added ciflow/mps Run MPS tests (subset of trunk) release notes: mps Release notes category labels Apr 19, 2026
malfet added a commit that referenced this pull request Apr 19, 2026
- trace now implemented as self.diagonal().sum() (reuses sum kernel).
- amax/amin now dispatch to a generic Metal value_reduction kernel
  parameterised on MaxOp/MinOp, mirroring the NormParams 2D layout
  used by sum_reduction. Registered for float, half, bfloat, long,
  int, short, uchar; char/bool promote to short via tensor cast.
- Adds int_lowest/int_highest helpers per integer dtype and
  NaN-propagating max_combine/min_combine (avoids metal::max
  overload-resolution ambiguity with c10::metal::max).
- Drops the TRACE MPSReductionType enum entry and the amax_out_mps/
  amin_out_mps MPSGraph wrappers (native_functions.yaml now routes
  amax.out/amin.out through CPU,CUDA,MPS: amax_out/amin_out).


ghstack-source-id: 4b4d90b
Pull-Request: #180752
@github-actions

Copy link
Copy Markdown
Contributor

Attention! native_functions.yaml was changed

If you are adding a new function or defaulted argument to native_functions.yaml, you cannot use it from pre-existing Python frontend code until our FC window passes (two weeks). Split your PR into two PRs, one which adds the new C++ functionality, and one that makes use of it from Python, and land them two weeks apart. See https://github.com/pytorch/pytorch/wiki/PyTorch's-Python-Frontend-Backward-and-Forward-Compatibility-Policy#forwards-compatibility-fc for more info.


Caused by:

@Skylion007 Skylion007 left a comment

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.

What aminmax kernel while you are at it?

@Skylion007 Skylion007 left a comment

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.

Add the missing constexpr and looks good

[ghstack-poisoned]
malfet added a commit that referenced this pull request May 14, 2026
- trace now implemented as self.diagonal().sum() (reuses sum kernel).
- amax/amin now dispatch to a generic Metal value_reduction kernel
  parameterised on MaxOp/MinOp, mirroring the NormParams 2D layout
  used by sum_reduction. Registered for float, half, bfloat, long,
  int, short, uchar; char/bool promote to short via tensor cast.
- Adds int_lowest/int_highest helpers per integer dtype and
  NaN-propagating max_combine/min_combine (avoids metal::max
  overload-resolution ambiguity with c10::metal::max).
- Drops the TRACE MPSReductionType enum entry and the amax_out_mps/
  amin_out_mps MPSGraph wrappers (native_functions.yaml now routes
  amax.out/amin.out through CPU,CUDA,MPS: amax_out/amin_out).


ghstack-source-id: 91331ef
Pull-Request: #180752
@pytorch-bot

pytorch-bot Bot commented May 14, 2026

Copy link
Copy Markdown

Attention! native_functions.yaml was changed

If you are adding a new function or defaulted argument to native_functions.yaml, you cannot use it from pre-existing Python frontend code until our FC window passes (two weeks). Split your PR into two PRs, one which adds the new C++ functionality, and one that makes use of it from Python, and land them two weeks apart. See https://github.com/pytorch/pytorch/wiki/PyTorch's-Python-Frontend-Backward-and-Forward-Compatibility-Policy#forwards-compatibility-fc for more info.

[ghstack-poisoned]
@malfet
malfet requested a review from mruberry as a code owner May 15, 2026 06:04
malfet added a commit that referenced this pull request May 15, 2026
…rnels

- trace now implemented as self.diagonal().sum() (reuses sum kernel).
- amax/amin and all/any share a single Metal value_reduction kernel
  parameterised on (Op, Load, TI, TO) where:
    * MaxOp/MinOp delegate combine() to c10::metal::max/min and
      threadgroup_reduce() to c10::metal::threadgroup_max/min, both
      NaN-propagating via isunordered. Identity values use
      metal::numeric_limits<T>::lowest()/max() for integers and
      +/-INFINITY for floats.
    * IdentityLoad keeps the input value (min/max);
      PredicateLoad maps nonzero (and NaN) -> 1, zero -> 0 (all/any).
  So any == max-of-bool, all == min-of-bool: register MaxOp +
  PredicateLoad as "any_reduction_<TI>" and MinOp + PredicateLoad as
  "all_reduction_<TI>". The kernel is decorated with
  max_total_threads_per_threadgroup(MAX_THREADGROUP_SIZE) so the
  compiler can bound the runtime tptg and constant-fold the
  size-vs-simdgroup_size branch inside threadgroup_min/max.
- For min/max, bool input dispatches the char kernel via host-side
  kernel-name remap (no buffer cast, since bool and char share
  1-byte 0/1 layout). Registered for float/half/bfloat/long/int/
  short/char/uchar. any/all register a dedicated bool kernel plus
  complex (float2/half2), since their reduction is on uchar
  regardless of input type.
- aminmax_out_mps removed; aminmax.out now routes through the shared
  CPU/CUDA/MPS aminmax_out impl via two new MPS dispatch stubs that
  fan out to at::amin_outf / at::amax_outf.
- All four MPSGraph all/any wrappers (all_out_mps, any_out_mps,
  all_all_out_mps, any_all_out_mps) and the all_any_common_impl_mps
  helper are removed. native_functions.yaml now routes all.out,
  all.all_out, any.out, any.all_out through CPU,CUDA,MPS shared
  impls, registered for MPS via the new and/or stubs.
  get_allany_iter() adds MPS to its no-upfront-cast fast path
  (alongside CUDA), since our kernel reads input directly without
  iter-based casting.
- Drops the TRACE/AMIN/AMAX MPSReductionType enum entries and the
  amax_out_mps/amin_out_mps MPSGraph wrappers (native_functions.yaml
  now routes amax.out/amin.out/aminmax.out through
  CPU,CUDA,MPS: amax_out/amin_out/aminmax_out).
- Enables test_aminmax and test_invalid_0dim_aminmax on MPS
  (excluding float64/complex128 which MPS doesn't support).

Authored by Claude.

ghstack-source-id: c396552
Pull-Request: #180752
@malfet malfet added the ciflow/trunk Trigger trunk jobs on your pull request label May 15, 2026
@malfet malfet changed the title Replace MPSGraph trace/amax/amin with custom Metal kernels Migrate any/all/amax/amin to Metal kernels May 15, 2026
[ghstack-poisoned]
@malfet malfet changed the title Migrate any/all/amax/amin to Metal kernels Replace MPSGraph trace/amax/amin/aminmax/all/any with custom Metal kernels May 15, 2026
malfet added a commit that referenced this pull request May 15, 2026
…rnels

Migration of `trace`, `amax`/`amin`, `aminmax`, and `all`/`any` from MPSGraph
to native Metal kernels, following the pattern established by the sum
migration (#180709):

- **Dedicated outer-reduction kernel** (32x32 TG, coalesced column reads,
  shared-memory cross-row collapse) for the `dim=0` contiguous case.
- **Dedicated inner-reduction kernel** (one SIMD group per row, 8 rows per
  TG, `simd_reduce` for intra-row collapse) for the last-dim contiguous
  case.
- **Two-stage reduction** for large full reductions (output is scalar):
  pass 1 splits the input into <=512 contiguous slices reduced in parallel;
  pass 2 collapses the partials into the final scalar.
- **Reuses c10/metal primitives**: `c10::metal::threadgroup_max`/`min`
  for the simd->threadgroup collapse, `c10::metal::simd_max`/`min` for
  the SIMD-group reduction, and `c10::metal::max`/`min` (NaN-propagating
  via `isunordered`) as the per-element combiner.
- **Shared host-side dispatch** with the sum migration: a single
  `reduction_dispatch_mps` helper selects among outer-dim / inner-dim /
  two-pass-full / generic-single-pass code paths, and both
  `sum_nansum_kernel_mps` and `value_reduction_kernel_mps` collapse to
  thin wrappers (~25 LOC each) that just configure the helper opts.
  Kernel names follow a unified `<prefix>reduction_<variant>_<TI>_<TO>`
  pattern across sum/min/max/all/any.

`trace` collapses to `self.diagonal().sum()`. `aminmax` fans out to
`at::amin_outf` + `at::amax_outf`. `any`/`all` are expressed as
max/min on a predicate load (nonzero or NaN -> 1, zero -> 0):
`any == max-of-bool`, `all == min-of-bool` -- so a single
`value_reduction<Op, Load, TI, TO>` template covers all four ops via two
load functors (`IdentityLoad` for min/max, `PredicateLoad` for all/any).
For min/max, bool input dispatches the char kernel via host-side
kernel-name remap (no buffer cast, since bool and char share 1-byte 0/1
layout); for all/any, bool and complex (float2/half2) are registered
directly since the reduction is on uchar regardless of input type.

native_functions.yaml now routes trace.out, amax.out, amin.out,
aminmax.out, all.{out,all_out}, any.{out,all_out} through the shared
CPU/CUDA/MPS implementations. MPSGraph wrappers (`all_out_mps`,
`any_out_mps`, `all_all_out_mps`, `any_all_out_mps`, `aminmax_out_mps`,
`amax_out_mps`, `amin_out_mps`, plus the `all_any_common_impl_mps`
helper, plus the `TRACE`/`AMIN`/`AMAX` `MPSReductionType` enum entries)
are deleted. `get_allany_iter()` adds MPS to its no-upfront-cast fast
path (alongside CUDA) since our kernel reads input directly without
iter-based casting.

Also enables `test_aminmax` and `test_invalid_0dim_aminmax` on MPS
(excluding float64/complex128 which MPS doesn't support).

## Benchmark

Median latency over 500 iterations on M-series Mac, torch 2.12 (MPSGraph
baseline) vs this PR. Times averaged across min/max (which are the same
op with a flipped functor) and across all/any. Script at the end.

### amin / amax

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | float32 | full | 138 | 115 | 1.20x |
| 1024x1024 | float32 | dim0 | 113 | 90 | 1.25x |
| 1024x1024 | float32 | dim1 | 108 | 90 | 1.20x |
| 1024x1024 | float16 | full | 123 | 100 | 1.23x |
| 1024x1024 | float16 | dim0 | 113 | 91 | 1.24x |
| 1024x1024 | float16 | dim1 | 109 | 91 | 1.20x |
| 1024x1024 | bfloat16 | full | 117 | 102 | 1.14x |
| 1024x1024 | bfloat16 | dim0 | 109 | 90 | 1.21x |
| 1024x1024 | bfloat16 | dim1 | 108 | 92 | 1.18x |
| 1024x1024 | int64 | full | 139 | 105 | 1.32x |
| 1024x1024 | int64 | dim0 | 142 | 101 | 1.41x |
| 1024x1024 | int64 | dim1 | 125 | 100 | 1.26x |
| 4096x4096 | float32 | full | 273 | 234 | 1.16x |
| 4096x4096 | float32 | dim0 | 269 | 238 | 1.13x |
| 4096x4096 | float32 | dim1 | 260 | 229 | 1.13x |
| 4096x4096 | float16 | full | 177 | 142 | 1.25x |
| 4096x4096 | float16 | dim0 | 194 | 140 | 1.39x |
| 4096x4096 | float16 | dim1 | 168 | 130 | 1.30x |
| 4096x4096 | bfloat16 | full | 177 | 151 | 1.17x |
| 4096x4096 | bfloat16 | dim0 | 197 | 147 | 1.34x |
| 4096x4096 | bfloat16 | dim1 | 164 | 144 | 1.14x |
| 4096x4096 | int64 | full | 406 | 376 | 1.08x |
| 4096x4096 | int64 | dim0 | 418 | 392 | 1.07x |
| 4096x4096 | int64 | dim1 | 424 | 401 | 1.06x |

### all / any

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | bool | full | 144 | 106 | 1.36x |
| 1024x1024 | bool | dim0 | 137 | 92 | 1.48x |
| 1024x1024 | bool | dim1 | 135 | 91 | 1.49x |
| 1024x1024 | int64 | full | 131 | 100 | 1.31x |
| 1024x1024 | int64 | dim0 | 127 | 99 | 1.29x |
| 1024x1024 | int64 | dim1 | 125 | 99 | 1.26x |
| 1024x1024 | float32 | full | 127 | 99 | 1.28x |
| 1024x1024 | float32 | dim0 | 123 | 89 | 1.38x |
| 1024x1024 | float32 | dim1 | 120 | 89 | 1.34x |
| 1024x1024 | float16 | full | 124 | 98 | 1.26x |
| 1024x1024 | float16 | dim0 | 119 | 88 | 1.35x |
| 1024x1024 | float16 | dim1 | 113 | 90 | 1.26x |
| 4096x4096 | bool | full | 446 | 125 | **3.55x** |
| 4096x4096 | bool | dim0 | 444 | 116 | **3.82x** |
| 4096x4096 | bool | dim1 | 463 | 112 | **4.14x** |
| 4096x4096 | int64 | full | 434 | 369 | 1.18x |
| 4096x4096 | int64 | dim0 | 440 | 396 | 1.11x |
| 4096x4096 | int64 | dim1 | 417 | 399 | 1.05x |
| 4096x4096 | float32 | full | 294 | 264 | 1.11x |
| 4096x4096 | float32 | dim0 | 290 | 270 | 1.07x |
| 4096x4096 | float32 | dim1 | 292 | 260 | 1.12x |
| 4096x4096 | float16 | full | 206 | 159 | 1.30x |
| 4096x4096 | float16 | dim0 | 218 | 135 | **1.62x** |
| 4096x4096 | float16 | dim1 | 195 | 130 | **1.50x** |

<details>
<summary>Benchmark script</summary>

```python
import json, time, torch
SHAPES = [(1024, 1024), (4096, 4096)]
DV = [torch.float32, torch.float16, torch.bfloat16, torch.int64]
DP = [torch.bool, torch.int64, torch.float32, torch.float16]
OPS = [('amax', torch.amax, DV), ('amin', torch.amin, DV),
       ('all', torch.all, DP), ('any', torch.any, DP)]

def bench(fn, n=500):
    for _ in range(20): fn()
    s = []
    for _ in range(n):
        torch.mps.synchronize(); t0 = time.perf_counter()
        fn(); torch.mps.synchronize()
        s.append((time.perf_counter() - t0) * 1e6)
    return sorted(s)[n // 2]

def mkx(shape, dt):
    if dt == torch.bool:
        return torch.randint(0, 2, shape, dtype=dt, device='mps')
    if dt == torch.int64:
        return torch.randint(-100, 100, shape, dtype=dt, device='mps')
    return torch.randn(shape, dtype=dt, device='mps')

for op, fn, dts in OPS:
    for shape in SHAPES:
        for dt in dts:
            x = mkx(shape, dt)
            for mode, call in [('full', lambda: fn(x)),
                               ('dim0', lambda: fn(x, dim=0)),
                               ('dim1', lambda: fn(x, dim=1))]:
                print(json.dumps({'op': op, 'shape': shape,
                                  'dtype': str(dt).split('.')[1],
                                  'mode': mode, 'us': round(bench(call), 1)}))
```

</details>

Authored by Claude.

ghstack-source-id: 0a56c3c
Pull-Request: #180752
@malfet

malfet commented May 15, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review this

@claude

claude Bot commented May 15, 2026 •

Copy link
Copy Markdown

Claude finished @malfet's task in 8m 15s —— View job


Review: Replace MPSGraph reductions with custom Metal kernels

  • Gather context and read changed files
  • Review Metal kernel code (ReduceOps.metal)
  • Review host-side dispatch (ReduceOps.mm)
  • Review native_functions.yaml changes
  • Review C++ dispatch changes (ReduceOps.cpp)
  • Review test changes
  • Post review feedback

PR Review: #180752

Summary

Migrates trace, amax/amin, aminmax, all/any from MPSGraph to native Metal kernels, sharing infrastructure with the existing sum/mean reduction kernels. The refactoring into ReductionDispatch is clean and the kernel structure (general / outer / inner) mirrors the sum kernels well. Overall this is solid work with nice performance wins, especially for all/any on large tensors. One potential correctness issue found in the two-pass path.

Code Quality

Missing simd round-up in two-pass path — ReduceOps.mm:1021

The single-pass fallback correctly rounds threads_per_group up to a simdgroup boundary (line 1054):

const auto threads_per_group = std::min(MAX_THREADGROUP_SIZE, c10::metal::round_up(reduction_size, 32u));

with a comment explaining that inactive SIMD lanes carry register-zero, corrupting min/max.

But the two-pass path does not round up for pass 2 (line 1021):

auto tpg2 = std::min(MAX_THREADGROUP_SIZE, num_groups);

This is reachable: for reduction_size = 16384, num_groups = 2, so tpg2 = 2. Pass 2 dispatches the min_reduction_uchar_uchar or max_reduction_uchar_uchar kernel with 2 threads — far below the 32-lane simdgroup. Inactive lanes contribute register-zero to simd_min/simd_max, corrupting the result. For all (min), simd_min(1, 1, 0, 0, ...) = 0 would incorrectly return false.

Suggested fix:

auto tpg2 = std::min(MAX_THREADGROUP_SIZE, c10::metal::round_up(num_groups, 32u));

Pass 1 (line 1013) has the same issue but elems_per_group is always reduction_size / num_groups ≥ 4097 when the two-pass path is entered, so in practice it's always ≥ 32. Still worth rounding for consistency:

auto tpg1 = std::min(MAX_THREADGROUP_SIZE, c10::metal::round_up(elems_per_group, 32u));

Fix this →


Reviewer's constexpr request — @Skylion007 noted the identity() methods in MaxOp/MinOp (lines 735, 744, 769, 775 of ReduceOps.metal) should be constexpr. These return compile-time constants (numeric_limits::lowest(), -INFINITY, etc.) and marking them constexpr is both correct for MSL and consistent with best practice. This was approved as the only remaining request.

Testing

Enabling test_aminmax and test_invalid_0dim_aminmax on MPS is good. The dtypesIfMPS annotations at test_reductions.py:1296 and test_reductions.py:1310 are appropriate.

The new min_values_stub/max_values_stub/and_stub/or_stub registrations route through the shared structured kernel infrastructure, so existing OpInfo-based tests for amax, amin, all, any should cover MPS automatically (via instantiate_device_type_tests). No missing test coverage detected.

Backward Compatibility

The native_functions.yaml changes consolidate MPS into the shared CPU, CUDA, MPS dispatch entries, removing per-op MPS-specific implementations. This is BC-safe: the Python-level API doesn't change, and the FC warning from the bot is about adding new functions (not applicable here — these are existing ops getting a new backend dispatch route).

The aminmax implementation delegates to at::amin_outf + at::amax_outf rather than doing a fused kernel. This matches the old behavior (which also called the graph twice). PR description acknowledges this isn't ideal but is no regression.

Performance

The ReduceOps.cpp change (line 1653: self.is_cuda() || self.is_mps()) lets MPS skip the make_reduction_from_out_ty cast-to-bool for all/any, avoiding an extra copy. This is a correct optimization since the Metal kernel reads input in its original dtype and applies the predicate load in-kernel.

Recommendation

Request Changes

The simd round-up issue in the two-pass path is a correctness bug that can produce wrong results for all/any/amin/amax on inputs with numel > 8192. It should be fixed before merging. The constexpr nit from @Skylion007 should also be addressed.


malfet added a commit that referenced this pull request May 15, 2026
…rnels

Migration of `trace`, `amax`/`amin`, `aminmax`, and `all`/`any` from MPSGraph
to native Metal kernels, following the pattern established by the sum
migration (#180709):

- **Dedicated outer-reduction kernel** (32x32 TG, coalesced column reads,
  shared-memory cross-row collapse) for the `dim=0` contiguous case.
- **Dedicated inner-reduction kernel** (one SIMD group per row, 8 rows per
  TG, `simd_reduce` for intra-row collapse) for the last-dim contiguous
  case.
- **Two-stage reduction** for large full reductions (output is scalar):
  pass 1 splits the input into <=512 contiguous slices reduced in parallel;
  pass 2 collapses the partials into the final scalar.
- **Reuses c10/metal primitives**: `c10::metal::threadgroup_max`/`min`
  for the simd->threadgroup collapse, `c10::metal::simd_max`/`min` for
  the SIMD-group reduction, and `c10::metal::max`/`min` (NaN-propagating
  via `isunordered`) as the per-element combiner.
- **Shared host-side dispatch** with the sum migration: a single
  `reduction_dispatch_mps` helper selects among outer-dim / inner-dim /
  two-pass-full / generic-single-pass code paths, and both
  `sum_nansum_kernel_mps` and `value_reduction_kernel_mps` collapse to
  thin wrappers (~25 LOC each) that just configure the helper opts.
  Kernel names follow a unified `<prefix>reduction_<variant>_<TI>_<TO>`
  pattern across sum/min/max/all/any.

`trace` collapses to `self.diagonal().sum()`. `aminmax` fans out to
`at::amin_outf` + `at::amax_outf`. `any`/`all` are expressed as
max/min on a predicate load (nonzero or NaN -> 1, zero -> 0):
`any == max-of-bool`, `all == min-of-bool` -- so a single
`value_reduction<Op, Load, TI, TO>` template covers all four ops via two
load functors (`IdentityLoad` for min/max, `PredicateLoad` for all/any).
For min/max, bool input dispatches the char kernel via host-side
kernel-name remap (no buffer cast, since bool and char share 1-byte 0/1
layout); for all/any, bool and complex (float2/half2) are registered
directly since the reduction is on uchar regardless of input type.

native_functions.yaml now routes trace.out, amax.out, amin.out,
aminmax.out, all.{out,all_out}, any.{out,all_out} through the shared
CPU/CUDA/MPS implementations. MPSGraph wrappers (`all_out_mps`,
`any_out_mps`, `all_all_out_mps`, `any_all_out_mps`, `aminmax_out_mps`,
`amax_out_mps`, `amin_out_mps`, plus the `all_any_common_impl_mps`
helper, plus the `TRACE`/`AMIN`/`AMAX` `MPSReductionType` enum entries)
are deleted. `get_allany_iter()` adds MPS to its no-upfront-cast fast
path (alongside CUDA) since our kernel reads input directly without
iter-based casting.

Also enables `test_aminmax` and `test_invalid_0dim_aminmax` on MPS
(excluding float64/complex128 which MPS doesn't support).

## Benchmark

Median latency over 500 iterations on M-series Mac, torch 2.12 (MPSGraph
baseline) vs this PR. Times averaged across min/max (which are the same
op with a flipped functor) and across all/any. Script at the end.

### amin / amax

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | float32 | full | 138 | 115 | 1.20x |
| 1024x1024 | float32 | dim0 | 113 | 90 | 1.25x |
| 1024x1024 | float32 | dim1 | 108 | 90 | 1.20x |
| 1024x1024 | float16 | full | 123 | 100 | 1.23x |
| 1024x1024 | float16 | dim0 | 113 | 91 | 1.24x |
| 1024x1024 | float16 | dim1 | 109 | 91 | 1.20x |
| 1024x1024 | bfloat16 | full | 117 | 102 | 1.14x |
| 1024x1024 | bfloat16 | dim0 | 109 | 90 | 1.21x |
| 1024x1024 | bfloat16 | dim1 | 108 | 92 | 1.18x |
| 1024x1024 | int64 | full | 139 | 105 | 1.32x |
| 1024x1024 | int64 | dim0 | 142 | 101 | 1.41x |
| 1024x1024 | int64 | dim1 | 125 | 100 | 1.26x |
| 4096x4096 | float32 | full | 273 | 234 | 1.16x |
| 4096x4096 | float32 | dim0 | 269 | 238 | 1.13x |
| 4096x4096 | float32 | dim1 | 260 | 229 | 1.13x |
| 4096x4096 | float16 | full | 177 | 142 | 1.25x |
| 4096x4096 | float16 | dim0 | 194 | 140 | 1.39x |
| 4096x4096 | float16 | dim1 | 168 | 130 | 1.30x |
| 4096x4096 | bfloat16 | full | 177 | 151 | 1.17x |
| 4096x4096 | bfloat16 | dim0 | 197 | 147 | 1.34x |
| 4096x4096 | bfloat16 | dim1 | 164 | 144 | 1.14x |
| 4096x4096 | int64 | full | 406 | 376 | 1.08x |
| 4096x4096 | int64 | dim0 | 418 | 392 | 1.07x |
| 4096x4096 | int64 | dim1 | 424 | 401 | 1.06x |

### all / any

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | bool | full | 144 | 106 | 1.36x |
| 1024x1024 | bool | dim0 | 137 | 92 | 1.48x |
| 1024x1024 | bool | dim1 | 135 | 91 | 1.49x |
| 1024x1024 | int64 | full | 131 | 100 | 1.31x |
| 1024x1024 | int64 | dim0 | 127 | 99 | 1.29x |
| 1024x1024 | int64 | dim1 | 125 | 99 | 1.26x |
| 1024x1024 | float32 | full | 127 | 99 | 1.28x |
| 1024x1024 | float32 | dim0 | 123 | 89 | 1.38x |
| 1024x1024 | float32 | dim1 | 120 | 89 | 1.34x |
| 1024x1024 | float16 | full | 124 | 98 | 1.26x |
| 1024x1024 | float16 | dim0 | 119 | 88 | 1.35x |
| 1024x1024 | float16 | dim1 | 113 | 90 | 1.26x |
| 4096x4096 | bool | full | 446 | 125 | **3.55x** |
| 4096x4096 | bool | dim0 | 444 | 116 | **3.82x** |
| 4096x4096 | bool | dim1 | 463 | 112 | **4.14x** |
| 4096x4096 | int64 | full | 434 | 369 | 1.18x |
| 4096x4096 | int64 | dim0 | 440 | 396 | 1.11x |
| 4096x4096 | int64 | dim1 | 417 | 399 | 1.05x |
| 4096x4096 | float32 | full | 294 | 264 | 1.11x |
| 4096x4096 | float32 | dim0 | 290 | 270 | 1.07x |
| 4096x4096 | float32 | dim1 | 292 | 260 | 1.12x |
| 4096x4096 | float16 | full | 206 | 159 | 1.30x |
| 4096x4096 | float16 | dim0 | 218 | 135 | **1.62x** |
| 4096x4096 | float16 | dim1 | 195 | 130 | **1.50x** |

<details>
<summary>Benchmark script</summary>

```python
import json, time, torch
SHAPES = [(1024, 1024), (4096, 4096)]
DV = [torch.float32, torch.float16, torch.bfloat16, torch.int64]
DP = [torch.bool, torch.int64, torch.float32, torch.float16]
OPS = [('amax', torch.amax, DV), ('amin', torch.amin, DV),
       ('all', torch.all, DP), ('any', torch.any, DP)]

def bench(fn, n=500):
    for _ in range(20): fn()
    s = []
    for _ in range(n):
        torch.mps.synchronize(); t0 = time.perf_counter()
        fn(); torch.mps.synchronize()
        s.append((time.perf_counter() - t0) * 1e6)
    return sorted(s)[n // 2]

def mkx(shape, dt):
    if dt == torch.bool:
        return torch.randint(0, 2, shape, dtype=dt, device='mps')
    if dt == torch.int64:
        return torch.randint(-100, 100, shape, dtype=dt, device='mps')
    return torch.randn(shape, dtype=dt, device='mps')

for op, fn, dts in OPS:
    for shape in SHAPES:
        for dt in dts:
            x = mkx(shape, dt)
            for mode, call in [('full', lambda: fn(x)),
                               ('dim0', lambda: fn(x, dim=0)),
                               ('dim1', lambda: fn(x, dim=1))]:
                print(json.dumps({'op': op, 'shape': shape,
                                  'dtype': str(dt).split('.')[1],
                                  'mode': mode, 'us': round(bench(call), 1)}))
```

</details>

Authored by Claude.

ghstack-source-id: 0a56c3c
Pull-Request: #180752
@malfet malfet changed the title Replace MPSGraph trace/amax/amin/aminmax/all/any with custom Metal kernels [MPS] Migrate amax/amin/aminmax/all/any to Metal May 15, 2026
[ghstack-poisoned]
malfet added a commit that referenced this pull request May 15, 2026
…rnels

Migration of `trace`, `amax`/`amin`, `aminmax`, and `all`/`any` from MPSGraph
to native Metal kernels, following the pattern established by the sum
migration (#180709):

- **Dedicated outer-reduction kernel** (32x32 TG, coalesced column reads,
  shared-memory cross-row collapse) for the `dim=0` contiguous case.
- **Dedicated inner-reduction kernel** (one SIMD group per row, 8 rows per
  TG, `simd_reduce` for intra-row collapse) for the last-dim contiguous
  case.
- **Two-stage reduction** for large full reductions (output is scalar):
  pass 1 splits the input into <=512 contiguous slices reduced in parallel;
  pass 2 collapses the partials into the final scalar.
- **Reuses c10/metal primitives**: `c10::metal::threadgroup_max`/`min`
  for the simd->threadgroup collapse, `c10::metal::simd_max`/`min` for
  the SIMD-group reduction, and `c10::metal::max`/`min` (NaN-propagating
  via `isunordered`) as the per-element combiner.
- **Shared host-side dispatch** with the sum migration: a single
  `reduction_dispatch_mps` helper selects among outer-dim / inner-dim /
  two-pass-full / generic-single-pass code paths, and both
  `sum_nansum_kernel_mps` and `value_reduction_kernel_mps` collapse to
  thin wrappers (~25 LOC each) that just configure the helper opts.
  Kernel names follow a unified `<prefix>reduction_<variant>_<TI>_<TO>`
  pattern across sum/min/max/all/any.

`trace` collapses to `self.diagonal().sum()`. `aminmax` fans out to
`at::amin_outf` + `at::amax_outf`. `any`/`all` are expressed as
max/min on a predicate load (nonzero or NaN -> 1, zero -> 0):
`any == max-of-bool`, `all == min-of-bool` -- so a single
`value_reduction<Op, Load, TI, TO>` template covers all four ops via two
load functors (`IdentityLoad` for min/max, `PredicateLoad` for all/any).
For min/max, bool input dispatches the char kernel via host-side
kernel-name remap (no buffer cast, since bool and char share 1-byte 0/1
layout); for all/any, bool and complex (float2/half2) are registered
directly since the reduction is on uchar regardless of input type.

native_functions.yaml now routes trace.out, amax.out, amin.out,
aminmax.out, all.{out,all_out}, any.{out,all_out} through the shared
CPU/CUDA/MPS implementations. MPSGraph wrappers (`all_out_mps`,
`any_out_mps`, `all_all_out_mps`, `any_all_out_mps`, `aminmax_out_mps`,
`amax_out_mps`, `amin_out_mps`, plus the `all_any_common_impl_mps`
helper, plus the `TRACE`/`AMIN`/`AMAX` `MPSReductionType` enum entries)
are deleted. `get_allany_iter()` adds MPS to its no-upfront-cast fast
path (alongside CUDA) since our kernel reads input directly without
iter-based casting.

Also enables `test_aminmax` and `test_invalid_0dim_aminmax` on MPS
(excluding float64/complex128 which MPS doesn't support).

## Benchmark

Median latency over 500 iterations on M-series Mac, torch 2.12 (MPSGraph
baseline) vs this PR. Times averaged across min/max (which are the same
op with a flipped functor) and across all/any. Script at the end.

### amin / amax

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | float32 | full | 138 | 115 | 1.20x |
| 1024x1024 | float32 | dim0 | 113 | 90 | 1.25x |
| 1024x1024 | float32 | dim1 | 108 | 90 | 1.20x |
| 1024x1024 | float16 | full | 123 | 100 | 1.23x |
| 1024x1024 | float16 | dim0 | 113 | 91 | 1.24x |
| 1024x1024 | float16 | dim1 | 109 | 91 | 1.20x |
| 1024x1024 | bfloat16 | full | 117 | 102 | 1.14x |
| 1024x1024 | bfloat16 | dim0 | 109 | 90 | 1.21x |
| 1024x1024 | bfloat16 | dim1 | 108 | 92 | 1.18x |
| 1024x1024 | int64 | full | 139 | 105 | 1.32x |
| 1024x1024 | int64 | dim0 | 142 | 101 | 1.41x |
| 1024x1024 | int64 | dim1 | 125 | 100 | 1.26x |
| 4096x4096 | float32 | full | 273 | 234 | 1.16x |
| 4096x4096 | float32 | dim0 | 269 | 238 | 1.13x |
| 4096x4096 | float32 | dim1 | 260 | 229 | 1.13x |
| 4096x4096 | float16 | full | 177 | 142 | 1.25x |
| 4096x4096 | float16 | dim0 | 194 | 140 | 1.39x |
| 4096x4096 | float16 | dim1 | 168 | 130 | 1.30x |
| 4096x4096 | bfloat16 | full | 177 | 151 | 1.17x |
| 4096x4096 | bfloat16 | dim0 | 197 | 147 | 1.34x |
| 4096x4096 | bfloat16 | dim1 | 164 | 144 | 1.14x |
| 4096x4096 | int64 | full | 406 | 376 | 1.08x |
| 4096x4096 | int64 | dim0 | 418 | 392 | 1.07x |
| 4096x4096 | int64 | dim1 | 424 | 401 | 1.06x |

### all / any

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | bool | full | 144 | 106 | 1.36x |
| 1024x1024 | bool | dim0 | 137 | 92 | 1.48x |
| 1024x1024 | bool | dim1 | 135 | 91 | 1.49x |
| 1024x1024 | int64 | full | 131 | 100 | 1.31x |
| 1024x1024 | int64 | dim0 | 127 | 99 | 1.29x |
| 1024x1024 | int64 | dim1 | 125 | 99 | 1.26x |
| 1024x1024 | float32 | full | 127 | 99 | 1.28x |
| 1024x1024 | float32 | dim0 | 123 | 89 | 1.38x |
| 1024x1024 | float32 | dim1 | 120 | 89 | 1.34x |
| 1024x1024 | float16 | full | 124 | 98 | 1.26x |
| 1024x1024 | float16 | dim0 | 119 | 88 | 1.35x |
| 1024x1024 | float16 | dim1 | 113 | 90 | 1.26x |
| 4096x4096 | bool | full | 446 | 125 | **3.55x** |
| 4096x4096 | bool | dim0 | 444 | 116 | **3.82x** |
| 4096x4096 | bool | dim1 | 463 | 112 | **4.14x** |
| 4096x4096 | int64 | full | 434 | 369 | 1.18x |
| 4096x4096 | int64 | dim0 | 440 | 396 | 1.11x |
| 4096x4096 | int64 | dim1 | 417 | 399 | 1.05x |
| 4096x4096 | float32 | full | 294 | 264 | 1.11x |
| 4096x4096 | float32 | dim0 | 290 | 270 | 1.07x |
| 4096x4096 | float32 | dim1 | 292 | 260 | 1.12x |
| 4096x4096 | float16 | full | 206 | 159 | 1.30x |
| 4096x4096 | float16 | dim0 | 218 | 135 | **1.62x** |
| 4096x4096 | float16 | dim1 | 195 | 130 | **1.50x** |

<details>
<summary>Benchmark script</summary>

```python
import json, time, torch
SHAPES = [(1024, 1024), (4096, 4096)]
DV = [torch.float32, torch.float16, torch.bfloat16, torch.int64]
DP = [torch.bool, torch.int64, torch.float32, torch.float16]
OPS = [('amax', torch.amax, DV), ('amin', torch.amin, DV),
       ('all', torch.all, DP), ('any', torch.any, DP)]

def bench(fn, n=500):
    for _ in range(20): fn()
    s = []
    for _ in range(n):
        torch.mps.synchronize(); t0 = time.perf_counter()
        fn(); torch.mps.synchronize()
        s.append((time.perf_counter() - t0) * 1e6)
    return sorted(s)[n // 2]

def mkx(shape, dt):
    if dt == torch.bool:
        return torch.randint(0, 2, shape, dtype=dt, device='mps')
    if dt == torch.int64:
        return torch.randint(-100, 100, shape, dtype=dt, device='mps')
    return torch.randn(shape, dtype=dt, device='mps')

for op, fn, dts in OPS:
    for shape in SHAPES:
        for dt in dts:
            x = mkx(shape, dt)
            for mode, call in [('full', lambda: fn(x)),
                               ('dim0', lambda: fn(x, dim=0)),
                               ('dim1', lambda: fn(x, dim=1))]:
                print(json.dumps({'op': op, 'shape': shape,
                                  'dtype': str(dt).split('.')[1],
                                  'mode': mode, 'us': round(bench(call), 1)}))
```

</details>

Authored by Claude.

ghstack-source-id: 4bf8fcf
Pull-Request: #180752
@malfet

malfet commented May 15, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "Lint + MPS are green, perf numbers looks good"

@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

anagnorisis2peripeteia added a commit to anagnorisis2peripeteia/pytorch that referenced this pull request May 27, 2026
Migrates the remaining MPSGraph-based reduce ops to hand-written Metal
kernels: prod, var, std, var_mean, std_mean, argmax, argmin, and
max/min (with indices). Follows the pattern of the sum/mean (pytorch#180709)
and amax/amin/aminmax/all/any (pytorch#180752) migrations and builds on the
shared reduction dispatch, eliminating the per-shape MPSGraph graph
caching for these ops.

Kernel layouts (selected per reduction shape):
- inner (last dim): one SIMD group per row for many short rows; a wide
  one-threadgroup-per-row variant for few/huge rows (small M, large N).
- outer (dim 0): 2D threadgroup tiles with per-column tree reduction;
  a simdgroup_matrix (tensor-core) Welford for small M.
- all-reduce: fused two-pass (parallel per-group partials, then combine).

argmax/argmin/max/min carry indices with lowest-index / NaN-propagating
tie-breaking matching CPU/CUDA. Variance uses Welford (shifted
sum/sum-of-squares in the all-reduce pass to avoid a per-element
division). Bench harness: benchmarks/sweep_reduce.py.
@github-actions
github-actions Bot deleted the gh/malfet/842/head branch June 15, 2026 02:29
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
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
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
pytorchmergebot pushed 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 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
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
Migration of `trace`, `amax`/`amin`, `aminmax`, and `all`/`any` from MPSGraph to native Metal kernels, following the pattern established by the sum migration (pytorch#180709):

- Dedicated outer- and inner- reduction kernels
- Two-stage reduction for large full reductions
- Reuse `c10::metal` primitive for threadgroup reduction and nan propagation
- Shared host-side dispatch with the sum/mean migration
- `aminmax` fans out to `at::amin_outf` + `at::amax_outf`, which is not great but same as before
- `any`/`all` are expressed as max/min on a predicate load (nonzero or NaN -> 1, zero -> 0)
- `native_functions.yaml` now routes abovementioned to shared dispatc
- Enables `test_aminmax` and `test_invalid_0dim_aminmax` on MPS

## Benchmark

Median latency over 500 iterations on M4 Max, torch 2.12 (MPSGraph baseline) vs this PR.
Times averaged across min/max (which are the same op with a flipped functor) and all/any. Script at the end.

### amin / amax

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | float32 | full | 138 | 115 | 1.20x |
| 1024x1024 | float32 | dim0 | 113 | 90 | 1.25x |
| 1024x1024 | float32 | dim1 | 108 | 90 | 1.20x |
| 1024x1024 | float16 | full | 123 | 100 | 1.23x |
| 1024x1024 | float16 | dim0 | 113 | 91 | 1.24x |
| 1024x1024 | float16 | dim1 | 109 | 91 | 1.20x |
| 1024x1024 | bfloat16 | full | 117 | 102 | 1.14x |
| 1024x1024 | bfloat16 | dim0 | 109 | 90 | 1.21x |
| 1024x1024 | bfloat16 | dim1 | 108 | 92 | 1.18x |
| 1024x1024 | int64 | full | 139 | 105 | 1.32x |
| 1024x1024 | int64 | dim0 | 142 | 101 | 1.41x |
| 1024x1024 | int64 | dim1 | 125 | 100 | 1.26x |
| 4096x4096 | float32 | full | 273 | 234 | 1.16x |
| 4096x4096 | float32 | dim0 | 269 | 238 | 1.13x |
| 4096x4096 | float32 | dim1 | 260 | 229 | 1.13x |
| 4096x4096 | float16 | full | 177 | 142 | 1.25x |
| 4096x4096 | float16 | dim0 | 194 | 140 | 1.39x |
| 4096x4096 | float16 | dim1 | 168 | 130 | 1.30x |
| 4096x4096 | bfloat16 | full | 177 | 151 | 1.17x |
| 4096x4096 | bfloat16 | dim0 | 197 | 147 | 1.34x |
| 4096x4096 | bfloat16 | dim1 | 164 | 144 | 1.14x |
| 4096x4096 | int64 | full | 406 | 376 | 1.08x |
| 4096x4096 | int64 | dim0 | 418 | 392 | 1.07x |
| 4096x4096 | int64 | dim1 | 424 | 401 | 1.06x |

### all / any

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | bool | full | 144 | 106 | 1.36x |
| 1024x1024 | bool | dim0 | 137 | 92 | 1.48x |
| 1024x1024 | bool | dim1 | 135 | 91 | 1.49x |
| 1024x1024 | int64 | full | 131 | 100 | 1.31x |
| 1024x1024 | int64 | dim0 | 127 | 99 | 1.29x |
| 1024x1024 | int64 | dim1 | 125 | 99 | 1.26x |
| 1024x1024 | float32 | full | 127 | 99 | 1.28x |
| 1024x1024 | float32 | dim0 | 123 | 89 | 1.38x |
| 1024x1024 | float32 | dim1 | 120 | 89 | 1.34x |
| 1024x1024 | float16 | full | 124 | 98 | 1.26x |
| 1024x1024 | float16 | dim0 | 119 | 88 | 1.35x |
| 1024x1024 | float16 | dim1 | 113 | 90 | 1.26x |
| 4096x4096 | bool | full | 446 | 125 | **3.55x** |
| 4096x4096 | bool | dim0 | 444 | 116 | **3.82x** |
| 4096x4096 | bool | dim1 | 463 | 112 | **4.14x** |
| 4096x4096 | int64 | full | 434 | 369 | 1.18x |
| 4096x4096 | int64 | dim0 | 440 | 396 | 1.11x |
| 4096x4096 | int64 | dim1 | 417 | 399 | 1.05x |
| 4096x4096 | float32 | full | 294 | 264 | 1.11x |
| 4096x4096 | float32 | dim0 | 290 | 270 | 1.07x |
| 4096x4096 | float32 | dim1 | 292 | 260 | 1.12x |
| 4096x4096 | float16 | full | 206 | 159 | 1.30x |
| 4096x4096 | float16 | dim0 | 218 | 135 | **1.62x** |
| 4096x4096 | float16 | dim1 | 195 | 130 | **1.50x** |

<details>
<summary>Benchmark script</summary>

```python
import json, time, torch
SHAPES = [(1024, 1024), (4096, 4096)]
DV = [torch.float32, torch.float16, torch.bfloat16, torch.int64]
DP = [torch.bool, torch.int64, torch.float32, torch.float16]
OPS = [('amax', torch.amax, DV), ('amin', torch.amin, DV),
       ('all', torch.all, DP), ('any', torch.any, DP)]

def bench(fn, n=500):
    for _ in range(20): fn()
    s = []
    for _ in range(n):
        torch.mps.synchronize(); t0 = time.perf_counter()
        fn(); torch.mps.synchronize()
        s.append((time.perf_counter() - t0) * 1e6)
    return sorted(s)[n // 2]

def mkx(shape, dt):
    if dt == torch.bool:
        return torch.randint(0, 2, shape, dtype=dt, device='mps')
    if dt == torch.int64:
        return torch.randint(-100, 100, shape, dtype=dt, device='mps')
    return torch.randn(shape, dtype=dt, device='mps')

for op, fn, dts in OPS:
    for shape in SHAPES:
        for dt in dts:
            x = mkx(shape, dt)
            for mode, call in [('full', lambda: fn(x)),
                               ('dim0', lambda: fn(x, dim=0)),
                               ('dim1', lambda: fn(x, dim=1))]:
                print(json.dumps({'op': op, 'shape': shape,
                                  'dtype': str(dt).split('.')[1],
                                  'mode': mode, 'us': round(bench(call), 1)}))
```

</details>

Authored with Claude.
Pull Request resolved: pytorch#180752
Approved by: https://github.com/Skylion007
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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Migration of `trace`, `amax`/`amin`, `aminmax`, and `all`/`any` from MPSGraph to native Metal kernels, following the pattern established by the sum migration (pytorch#180709):

- Dedicated outer- and inner- reduction kernels
- Two-stage reduction for large full reductions
- Reuse `c10::metal` primitive for threadgroup reduction and nan propagation
- Shared host-side dispatch with the sum/mean migration
- `aminmax` fans out to `at::amin_outf` + `at::amax_outf`, which is not great but same as before
- `any`/`all` are expressed as max/min on a predicate load (nonzero or NaN -> 1, zero -> 0)
- `native_functions.yaml` now routes abovementioned to shared dispatc
- Enables `test_aminmax` and `test_invalid_0dim_aminmax` on MPS

## Benchmark

Median latency over 500 iterations on M4 Max, torch 2.12 (MPSGraph baseline) vs this PR.
Times averaged across min/max (which are the same op with a flipped functor) and all/any. Script at the end.

### amin / amax

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | float32 | full | 138 | 115 | 1.20x |
| 1024x1024 | float32 | dim0 | 113 | 90 | 1.25x |
| 1024x1024 | float32 | dim1 | 108 | 90 | 1.20x |
| 1024x1024 | float16 | full | 123 | 100 | 1.23x |
| 1024x1024 | float16 | dim0 | 113 | 91 | 1.24x |
| 1024x1024 | float16 | dim1 | 109 | 91 | 1.20x |
| 1024x1024 | bfloat16 | full | 117 | 102 | 1.14x |
| 1024x1024 | bfloat16 | dim0 | 109 | 90 | 1.21x |
| 1024x1024 | bfloat16 | dim1 | 108 | 92 | 1.18x |
| 1024x1024 | int64 | full | 139 | 105 | 1.32x |
| 1024x1024 | int64 | dim0 | 142 | 101 | 1.41x |
| 1024x1024 | int64 | dim1 | 125 | 100 | 1.26x |
| 4096x4096 | float32 | full | 273 | 234 | 1.16x |
| 4096x4096 | float32 | dim0 | 269 | 238 | 1.13x |
| 4096x4096 | float32 | dim1 | 260 | 229 | 1.13x |
| 4096x4096 | float16 | full | 177 | 142 | 1.25x |
| 4096x4096 | float16 | dim0 | 194 | 140 | 1.39x |
| 4096x4096 | float16 | dim1 | 168 | 130 | 1.30x |
| 4096x4096 | bfloat16 | full | 177 | 151 | 1.17x |
| 4096x4096 | bfloat16 | dim0 | 197 | 147 | 1.34x |
| 4096x4096 | bfloat16 | dim1 | 164 | 144 | 1.14x |
| 4096x4096 | int64 | full | 406 | 376 | 1.08x |
| 4096x4096 | int64 | dim0 | 418 | 392 | 1.07x |
| 4096x4096 | int64 | dim1 | 424 | 401 | 1.06x |

### all / any

| shape | dtype | mode | 2.12 (µs) | new (µs) | speedup |
|---|---|---|---:|---:|---|
| 1024x1024 | bool | full | 144 | 106 | 1.36x |
| 1024x1024 | bool | dim0 | 137 | 92 | 1.48x |
| 1024x1024 | bool | dim1 | 135 | 91 | 1.49x |
| 1024x1024 | int64 | full | 131 | 100 | 1.31x |
| 1024x1024 | int64 | dim0 | 127 | 99 | 1.29x |
| 1024x1024 | int64 | dim1 | 125 | 99 | 1.26x |
| 1024x1024 | float32 | full | 127 | 99 | 1.28x |
| 1024x1024 | float32 | dim0 | 123 | 89 | 1.38x |
| 1024x1024 | float32 | dim1 | 120 | 89 | 1.34x |
| 1024x1024 | float16 | full | 124 | 98 | 1.26x |
| 1024x1024 | float16 | dim0 | 119 | 88 | 1.35x |
| 1024x1024 | float16 | dim1 | 113 | 90 | 1.26x |
| 4096x4096 | bool | full | 446 | 125 | **3.55x** |
| 4096x4096 | bool | dim0 | 444 | 116 | **3.82x** |
| 4096x4096 | bool | dim1 | 463 | 112 | **4.14x** |
| 4096x4096 | int64 | full | 434 | 369 | 1.18x |
| 4096x4096 | int64 | dim0 | 440 | 396 | 1.11x |
| 4096x4096 | int64 | dim1 | 417 | 399 | 1.05x |
| 4096x4096 | float32 | full | 294 | 264 | 1.11x |
| 4096x4096 | float32 | dim0 | 290 | 270 | 1.07x |
| 4096x4096 | float32 | dim1 | 292 | 260 | 1.12x |
| 4096x4096 | float16 | full | 206 | 159 | 1.30x |
| 4096x4096 | float16 | dim0 | 218 | 135 | **1.62x** |
| 4096x4096 | float16 | dim1 | 195 | 130 | **1.50x** |

<details>
<summary>Benchmark script</summary>

```python
import json, time, torch
SHAPES = [(1024, 1024), (4096, 4096)]
DV = [torch.float32, torch.float16, torch.bfloat16, torch.int64]
DP = [torch.bool, torch.int64, torch.float32, torch.float16]
OPS = [('amax', torch.amax, DV), ('amin', torch.amin, DV),
       ('all', torch.all, DP), ('any', torch.any, DP)]

def bench(fn, n=500):
    for _ in range(20): fn()
    s = []
    for _ in range(n):
        torch.mps.synchronize(); t0 = time.perf_counter()
        fn(); torch.mps.synchronize()
        s.append((time.perf_counter() - t0) * 1e6)
    return sorted(s)[n // 2]

def mkx(shape, dt):
    if dt == torch.bool:
        return torch.randint(0, 2, shape, dtype=dt, device='mps')
    if dt == torch.int64:
        return torch.randint(-100, 100, shape, dtype=dt, device='mps')
    return torch.randn(shape, dtype=dt, device='mps')

for op, fn, dts in OPS:
    for shape in SHAPES:
        for dt in dts:
            x = mkx(shape, dt)
            for mode, call in [('full', lambda: fn(x)),
                               ('dim0', lambda: fn(x, dim=0)),
                               ('dim1', lambda: fn(x, dim=1))]:
                print(json.dumps({'op': op, 'shape': shape,
                                  'dtype': str(dt).split('.')[1],
                                  'mode': mode, 'us': round(bench(call), 1)}))
```

</details>

Authored with Claude.
Pull Request resolved: pytorch#180752
Approved by: https://github.com/Skylion007
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/mps Run MPS tests (subset of trunk) ciflow/trunk Trigger trunk jobs on your pull request Merged release notes: mps Release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants