Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/180709
Note: Links to docs will display an error until the docs builds have been completed. ⏳ No Failures, 15 PendingAs of commit 21dbb92 with merge base b4a129a ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
Use custom Metal shaders for torch.sum() on MPS instead of MPSGraph's reductionSumWithTensor, with four specialized paths: 1. Full reduction (output is scalar): two-pass multi-TG approach that splits work across 512 threadgroups with float32 partials. 2. Outer-dim reduction (e.g. dim=0 on contiguous): 2D threadgroup kernel (32x32) with coalesced column reads and shared memory reduction across row-workers. 3. Inner-dim reduction (e.g. dim=1 on contiguous): one SIMD group per row, 8 rows per threadgroup, simd_sum for intra-row reduction. No shared memory needed. 4. General reduction (multi-dim, non-contiguous): per-TG base+stride for single reduced dims, get_input_offset fallback for multi-dim. All kernels use multiple independent accumulation chains (NCHAINS=4) for instruction-level parallelism, and accumulate in opmath_t. Supports all MPS dtypes natively — no MPSGraph fallback needed. Route MPS through the common sum_out dispatch path via sum_stub (matching CPU/CUDA) instead of a separate sum_out_mps function. ghstack-source-id: 4ee479f Pull-Request: #180709
Attention! native_functions.yaml was changedIf 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: |
Use custom Metal shaders for torch.sum() on MPS instead of MPSGraph's reductionSumWithTensor, with four specialized paths: 1. Full reduction (output is scalar): two-pass multi-TG approach that splits work across 512 threadgroups with float32 partials. 2. Outer-dim reduction (e.g. dim=0 on contiguous): 2D threadgroup kernel (32x32) with coalesced column reads and shared memory reduction across row-workers. 3. Inner-dim reduction (e.g. dim=1 on contiguous): one SIMD group per row, 8 rows per threadgroup, simd_sum for intra-row reduction. No shared memory needed. 4. General reduction (multi-dim, non-contiguous): per-TG base+stride for single reduced dims, get_input_offset fallback for multi-dim. All kernels use multiple independent accumulation chains (NCHAINS=4) for instruction-level parallelism, and accumulate in opmath_t. Supports all MPS dtypes natively — no MPSGraph fallback needed. Route MPS through the common sum_out dispatch path via sum_stub (matching CPU/CUDA) instead of a separate sum_out_mps function. ghstack-source-id: f836ac6 Pull-Request: #180709
Use custom Metal shaders for torch.sum() on MPS instead of MPSGraph's reductionSumWithTensor, with four specialized paths: 1. Full reduction (output is scalar): two-pass multi-TG approach that splits work across 512 threadgroups with float32 partials. 2. Outer-dim reduction (e.g. dim=0 on contiguous): 2D threadgroup kernel (32x32) with coalesced column reads and shared memory reduction across row-workers. 3. Inner-dim reduction (e.g. dim=1 on contiguous): one SIMD group per row, 8 rows per threadgroup, simd_sum for intra-row reduction. No shared memory needed. 4. General reduction (multi-dim, non-contiguous): per-TG base+stride for single reduced dims, get_input_offset fallback for multi-dim. All kernels use multiple independent accumulation chains (NCHAINS=4) for instruction-level parallelism, and accumulate in opmath_t. Supports all MPS dtypes natively — no MPSGraph fallback needed. Route MPS through the common sum_out dispatch path via sum_stub (matching CPU/CUDA) instead of a separate sum_out_mps function. ghstack-source-id: 967bc5e Pull-Request: #180709
Use custom Metal shaders for torch.sum() on MPS instead of MPSGraph's reductionSumWithTensor, with four specialized paths: 1. Full reduction (output is scalar): two-pass multi-TG approach that splits work across 512 threadgroups with float32 partials. 2. Outer-dim reduction (e.g. dim=0 on contiguous): 2D threadgroup kernel (32x32) with coalesced column reads and shared memory reduction across row-workers. 3. Inner-dim reduction (e.g. dim=1 on contiguous): one SIMD group per row, 8 rows per threadgroup, simd_sum for intra-row reduction. No shared memory needed. 4. General reduction (multi-dim, non-contiguous): per-TG base+stride for single reduced dims, get_input_offset fallback for multi-dim. All kernels use multiple independent accumulation chains (NCHAINS=4) for instruction-level parallelism, and accumulate in opmath_t. Supports all MPS dtypes natively — no MPSGraph fallback needed. Route MPS through the common sum_out dispatch path via sum_stub (matching CPU/CUDA) instead of a separate sum_out_mps function. ghstack-source-id: 967bc5e Pull-Request: #180709
Use custom Metal shaders for torch.sum() on MPS instead of MPSGraph's reductionSumWithTensor, with four specialized paths: 1. Full reduction (output is scalar): two-pass multi-TG approach that splits work across 512 threadgroups with float32 partials. 2. Outer-dim reduction (e.g. dim=0 on contiguous): 2D threadgroup kernel (32x32) with coalesced column reads and shared memory reduction across row-workers. 3. Inner-dim reduction (e.g. dim=1 on contiguous): one SIMD group per row, 8 rows per threadgroup, simd_sum for intra-row reduction. No shared memory needed. 4. General reduction (multi-dim, non-contiguous): per-TG base+stride for single reduced dims, get_input_offset fallback for multi-dim. All kernels use multiple independent accumulation chains (NCHAINS=4) for instruction-level parallelism, and accumulate in opmath_t. Supports all MPS dtypes natively — no MPSGraph fallback needed. Route MPS through the common sum_out dispatch path via sum_stub (matching CPU/CUDA) instead of a separate sum_out_mps function. ghstack-source-id: 1cc57a7 Pull-Request: #180709
Use custom Metal shaders for torch.sum() on MPS instead of MPSGraph's reductionSumWithTensor, with four specialized paths: 1. Full reduction (output is scalar): two-pass multi-TG approach that splits work across 512 threadgroups with float32 partials. 2. Outer-dim reduction (e.g. dim=0 on contiguous): 2D threadgroup kernel (32x32) with coalesced column reads and shared memory reduction across row-workers. 3. Inner-dim reduction (e.g. dim=1 on contiguous): one SIMD group per row, 8 rows per threadgroup, simd_sum for intra-row reduction. No shared memory needed. 4. General reduction (multi-dim, non-contiguous): per-TG base+stride for single reduced dims, get_input_offset fallback for multi-dim. All kernels use multiple independent accumulation chains (NCHAINS=4) for instruction-level parallelism, and accumulate in opmath_t. Supports all MPS dtypes natively — no MPSGraph fallback needed. Route MPS through the common sum_out dispatch path via sum_stub (matching CPU/CUDA) instead of a separate sum_out_mps function. ghstack-source-id: 5f701a4 Pull-Request: #180709
|
This PR partially fixes #178497 |
|
@pytorchbot merge -f "Lint + MPS are green" |
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.
Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: `LOAD_IDENTITY` (sum), `LOAD_NAN_TO_ZERO` (nansum), and `LOAD_NONZERO` (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation. Even though output is 64-bit integer, accumulates partial counts in `uint32` rather than `long` as tensor dimension is always less that in32 on Metal.
Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"
Remove `MPSReductionType::COUNT_NONZERO` and its MPSGraph branch.
Tweaked the two-pass full-reduction path to always dispatch pass 2 with `LOAD_IDENTITY` (plain sum), regardless of pass-1 mode: pass 1 has already applied the load-mode transform (NaN-to-zero, nonzero-as-one), so pass 2 only needs to combine the partials.
Benchmark vs torch 2.11 MPSGraph (median us, M4 Max):
| shape | op | dtype | 2.11 | new | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,) | full | float32 | 14.0 | 8.1 | 1.73x |
| (1000000,) | full | float32 | 14.2 | 10.8 | 1.31x |
| (1024,1024) | full | float32 | 16.4 | 11.6 | 1.41x |
| (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | 2.18x |
| (1024,1024) | dim=1 | float32 | 12.9 | 4.9 | 2.62x |
| (4096,4096) | full | float32 |131.2 |121.9 | 1.08x |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x |
| (1024,1024) | full | int64 | 15.5 | 12.8 | 1.21x |
| (1024,1024) | dim=0 | int64 | 12.9 | 7.6 | 1.70x |
| (1024,1024) | dim=0 | float16 | 14.7 | 4.7 | 3.13x |
| (1024,1024) | full | bool | 15.1 | 11.2 | 1.34x |
| (1024,1024) | dim=0 | bool | 13.2 | 4.8 | 2.76x |
| (4096,4096) | dim=0 | bool | 48.8 | 26.2 | 1.86x |
Dim reductions see parity or 1.7–3x speedups across dtypes.
<details>
<summary>Benchmark script</summary>
```python
import torch
import torch.utils.benchmark as benchmark
import itertools
shapes_and_dims = [
((10_000,), None),
((1_000_000,), None),
((1024, 1024), None),
((1024, 1024), 0),
((1024, 1024), 1),
((4096, 4096), None),
((4096, 4096), 0),
((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]
def make_input(shape, sparsity, dtype, device):
if dtype == torch.bool:
return torch.rand(shape, device=device) < sparsity
x = torch.randn(shape, device=device, dtype=dtype)
mask = torch.rand(shape, device=device) >= sparsity
x[mask] = 0
return x
def bench(x, dim):
stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
for _ in range(2):
result = t.timeit(500)
return result.median
for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
x = make_input(shape, sparsity, torch.float32, "mps")
m = bench(x, dim) * 1e6
print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>
Pull Request resolved: #180725
Approved by: https://github.com/Skylion007
ghstack dependencies: #180709
…torch#180709)" This reverts commit 10a41bb. Reverted pytorch#180709 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#180709 (comment)))
…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
…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
…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
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** | <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: #180752 Approved by: https://github.com/Skylion007
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.
…0709) Use Metal shaders for torch.sum/nansum/mean instead of MPSGraph's `reductionSumWithTensor:` Route `torch.sum`, `torch.nansum`, and `torch.mean` on MPS through custom Metal shaders via the common `sum_stub` / `nansum_stub` / `mean_stub` dispatch path (matching CPU/CUDA), instead of separate `sum_out_mps` / `nansum_mps` / `mean_out_mps` MPSGraph wrappers. ## Kernel design Four specialized paths selected per-call inside `sum_nansum_kernel_mps`: 1. **Full reduction** (scalar output) for large inputs (`reduction_size > 1024`): two-pass multi-threadgroup. Pass 1 splits the input into `num_groups` equal contiguous slices (each TG reduces one slice into a float32 partial); pass 2 reduces `num_groups` partials to the final scalar. `num_groups` is adjusted so that `num_groups * elems_per_group == reduction_size` exactly - the last TG must not read past the logical end, otherwise the MPS caching allocator can place the `partials` buffer in the OOB region and subsequent `sum()` calls accumulate stale data. 2. **Outer-dim reduction** (e.g. `dim=0` on a contiguous tensor): 32×32 threadgroup with coalesced column reads and a shared-memory reduction across row-workers. 3. **Inner-dim reduction** (e.g. `dim=-1` on a contiguous tensor): one SIMD group per row, 8 rows per threadgroup, `simd_sum` for intra-row reduction - no shared memory needed. 4. **General reduction** (multi-dim, non-contiguous): `NormParams`-based kernel; for the single-reduced-dim case uses per-TG `input_base` plus `reduction_stride`, otherwise falls back to `get_input_offset` per element. All three operators (`sum_reduction`, `sum_reduction_outer`, `sum_reduction_inner`) share the same reduction kernel code with different prologue (for `nansum`) and epilogue (for `mean`). Accumulation is always in `opmath_t<TO>` (e.g. `float` for fp16/bfloat16, `float2` for `half2`), with 8 independent accumulation chains per thread for ILP. ## Benchmark Median latency over 500 iterations on M4 Max (PyTorch 2.11 MPSGraph baseline vs this change). Script at the end. ### Sum | shape | op | dtype | 2.11 (µs) | new (µs) | speedup | |---|---|---|---:|---:|---| | (1024,1024) | full | float32 | 15.3 | 13.2 | **1.24x** | | (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | **2.18x** | | (1024,1024) | dim=1 | float32 | 12.9 | 5.1 | **2.55x** | | (4096,4096) | full | float32 | 131 | 122 | 1.08x | | (4096,4096) | dim=0 | float32 | 132 | 127 | 1.04x | | (4096,4096) | dim=0 | float16 | 81.9 | 49.2 | **1.66x** | | (4096,4096) | dim=0 | bfloat16 | 78.9 | 47.2 | **1.67x** | | (1024,1024) | full | int64 | 29.8 | 13.1 | **2.28x** | | (1024,1024) | dim=0 | int64 | 23.4 | 7.4 | **3.16x** | Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable to 1.4x faster on every tested shape. ## Correctness Adds two regression tests to `test/test_mps.py` (that were already detected by inductor tests): - `test_mean_low_prec_order` — fp16/bfloat16/complex32 mean matches the fp32-intermediate reference; catches cast/divide order regressions. - `test_sum_full_reduction_repeated` — repeated `sum()` calls on the same tensor are stable; catches the two-pass OOB regression where the `partials` buffer could alias the input's trailing bytes. Pull Request resolved: pytorch#180709 Approved by: https://github.com/Skylion007 ghstack dependencies: pytorch#180572, pytorch#180708
…torch#180709)" This reverts commit 10a41bb. Reverted pytorch#180709 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#180709 (comment)))
…0709) Use Metal shaders for torch.sum/nansum/mean instead of MPSGraph's `reductionSumWithTensor:` Route `torch.sum`, `torch.nansum`, and `torch.mean` on MPS through custom Metal shaders via the common `sum_stub` / `nansum_stub` / `mean_stub` dispatch path (matching CPU/CUDA), instead of separate `sum_out_mps` / `nansum_mps` / `mean_out_mps` MPSGraph wrappers. ## Kernel design Four specialized paths selected per-call inside `sum_nansum_kernel_mps`: 1. **Full reduction** (scalar output) for large inputs (`reduction_size > 1024`): two-pass multi-threadgroup. Pass 1 splits the input into `num_groups` equal contiguous slices (each TG reduces one slice into a float32 partial); pass 2 reduces `num_groups` partials to the final scalar. `num_groups` is adjusted so that `num_groups * elems_per_group == reduction_size` exactly - the last TG must not read past the logical end, otherwise the MPS caching allocator can place the `partials` buffer in the OOB region and subsequent `sum()` calls accumulate stale data. 2. **Outer-dim reduction** (e.g. `dim=0` on a contiguous tensor): 32×32 threadgroup with coalesced column reads and a shared-memory reduction across row-workers. 3. **Inner-dim reduction** (e.g. `dim=-1` on a contiguous tensor): one SIMD group per row, 8 rows per threadgroup, `simd_sum` for intra-row reduction - no shared memory needed. 4. **General reduction** (multi-dim, non-contiguous): `NormParams`-based kernel; for the single-reduced-dim case uses per-TG `input_base` plus `reduction_stride`, otherwise falls back to `get_input_offset` per element. All three operators (`sum_reduction`, `sum_reduction_outer`, `sum_reduction_inner`) share the same reduction kernel code with different prologue (for `nansum`) and epilogue (for `mean`). Accumulation is always in `opmath_t<TO>` (e.g. `float` for fp16/bfloat16, `float2` for `half2`), with 8 independent accumulation chains per thread for ILP. ## Benchmark Median latency over 500 iterations on M4 Max (PyTorch 2.11 MPSGraph baseline vs this change). Script at the end. ### Sum | shape | op | dtype | 2.11 (µs) | new (µs) | speedup | |---|---|---|---:|---:|---| | (1024,1024) | full | float32 | 15.3 | 13.2 | **1.24x** | | (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | **2.18x** | | (1024,1024) | dim=1 | float32 | 12.9 | 5.1 | **2.55x** | | (4096,4096) | full | float32 | 131 | 122 | 1.08x | | (4096,4096) | dim=0 | float32 | 132 | 127 | 1.04x | | (4096,4096) | dim=0 | float16 | 81.9 | 49.2 | **1.66x** | | (4096,4096) | dim=0 | bfloat16 | 78.9 | 47.2 | **1.67x** | | (1024,1024) | full | int64 | 29.8 | 13.1 | **2.28x** | | (1024,1024) | dim=0 | int64 | 23.4 | 7.4 | **3.16x** | Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable to 1.4x faster on every tested shape. ## Correctness Adds two regression tests to `test/test_mps.py` (that were already detected by inductor tests): - `test_mean_low_prec_order` — fp16/bfloat16/complex32 mean matches the fp32-intermediate reference; catches cast/divide order regressions. - `test_sum_full_reduction_repeated` — repeated `sum()` calls on the same tensor are stable; catches the two-pass OOB regression where the `partials` buffer could alias the input's trailing bytes. Pull Request resolved: pytorch#180709 Approved by: https://github.com/Skylion007
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.
Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: `LOAD_IDENTITY` (sum), `LOAD_NAN_TO_ZERO` (nansum), and `LOAD_NONZERO` (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation. Even though output is 64-bit integer, accumulates partial counts in `uint32` rather than `long` as tensor dimension is always less that in32 on Metal.
Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"
Remove `MPSReductionType::COUNT_NONZERO` and its MPSGraph branch.
Tweaked the two-pass full-reduction path to always dispatch pass 2 with `LOAD_IDENTITY` (plain sum), regardless of pass-1 mode: pass 1 has already applied the load-mode transform (NaN-to-zero, nonzero-as-one), so pass 2 only needs to combine the partials.
Benchmark vs torch 2.11 MPSGraph (median us, M4 Max):
| shape | op | dtype | 2.11 | new | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,) | full | float32 | 14.0 | 8.1 | 1.73x |
| (1000000,) | full | float32 | 14.2 | 10.8 | 1.31x |
| (1024,1024) | full | float32 | 16.4 | 11.6 | 1.41x |
| (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | 2.18x |
| (1024,1024) | dim=1 | float32 | 12.9 | 4.9 | 2.62x |
| (4096,4096) | full | float32 |131.2 |121.9 | 1.08x |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x |
| (1024,1024) | full | int64 | 15.5 | 12.8 | 1.21x |
| (1024,1024) | dim=0 | int64 | 12.9 | 7.6 | 1.70x |
| (1024,1024) | dim=0 | float16 | 14.7 | 4.7 | 3.13x |
| (1024,1024) | full | bool | 15.1 | 11.2 | 1.34x |
| (1024,1024) | dim=0 | bool | 13.2 | 4.8 | 2.76x |
| (4096,4096) | dim=0 | bool | 48.8 | 26.2 | 1.86x |
Dim reductions see parity or 1.7–3x speedups across dtypes.
<details>
<summary>Benchmark script</summary>
```python
import torch
import torch.utils.benchmark as benchmark
import itertools
shapes_and_dims = [
((10_000,), None),
((1_000_000,), None),
((1024, 1024), None),
((1024, 1024), 0),
((1024, 1024), 1),
((4096, 4096), None),
((4096, 4096), 0),
((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]
def make_input(shape, sparsity, dtype, device):
if dtype == torch.bool:
return torch.rand(shape, device=device) < sparsity
x = torch.randn(shape, device=device, dtype=dtype)
mask = torch.rand(shape, device=device) >= sparsity
x[mask] = 0
return x
def bench(x, dim):
stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
for _ in range(2):
result = t.timeit(500)
return result.median
for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
x = make_input(shape, sparsity, torch.float32, "mps")
m = bench(x, dim) * 1e6
print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>
Pull Request resolved: pytorch#180725
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180709
pytorch#180709 moved sum/nansum/mean off MPSGraph onto native Metal kernels that assign one 32-lane simdgroup per output element. When the reduced extent N is small, that geometry inverts: the vectorized loop needs N >= 32 * SUM_NCHAINS = 256 to execute at all, 30 of 32 lanes idle in the tail loop for N < 32, and a full simd shuffle is paid to add a handful of values across numel/N simdgroups, so cost scales with the output size instead of the work. The backward of expand/broadcast is exactly this reduction (sum over the expanded dims, extent = the expansion factor, typically 2): on an M4 Max, sum(dim=-1) at extent 2 over 33.5M elements reads 25.6 ms vs 0.93 ms on torch 2.12, and an expand-upsample backward reads 97.4 ms vs 2.4 ms. Middle-dim and multi-dim reductions (what sum_to_size emits) additionally had no fast path at any extent and fell to a generic kernel paying a div/mod chain per element. The fix keeps the simdgroup kernels for their intended regime and adds thread-per-output kernels (sum_reduction_small, sum_reduction_inner_small) where that geometry is wrong: each thread serially accumulates its own N elements with no shuffles or barriers. reduction_dispatch_mps routes to them when the reduced extent is below SUM_SMALL_REDUCTION_THRESHOLD (256, the structural point where the simdgroup kernel's vectorized loop starts running), and also routes contiguous single middle-dim reductions of any extent there when the output has at least SUM_THREAD_PER_OUTPUT_MIN_OUTPUTS elements to fill the machine. Dispatch first drops size-1 dims and merges stride-compatible adjacent dims, and the kernel walks up to two reduced dims affinely, so the expand-backward pattern avoids per-element div/mod entirely. Only sum/nansum/mean/count_nonzero opt in via a has_small_variants flag; min/max/all/any/norm dispatch is unchanged, and above the threshold dispatch is byte-identical to before. The alternative of routing small N back to MPSGraph was rejected: the native kernel beats MPSGraph at large extents, and the same thread-per-output geometry matches or beats MPSGraph at small extents too, so there is no regime left where the graph path wins. Results (M4 Max, 33.5M elements, reduced extent 2): sum(dim=-1) 25.65 -> 1.05 ms, sum(dim=1) 30.52 -> 1.07 ms (now flat across extents), extent 1024 unchanged at 0.26 ms, expand-upsample backward 97.4 -> 2.74 ms (torch 2.12 parity; the reduction itself is at its bandwidth floor). Test Plan: Correctness, on this build (285 passed / 5 xfailed, and 152 passed / 4 xfailed respectively): ``` python -m pytest test/test_mps.py -k "sum or mean or nansum" -q python -m pytest test/test_mps.py -k "count_nonzero or amax or amin or any or all" -q ``` Plus 12/12 CPU-parity spot checks covering interleaved multi-dim sum/mean, adjacent-dim collapse, three reduced dims, keepdim, non-contiguous, permuted, nansum, half, bool, and complex64 inputs. Performance, the characterising sweep (total elements fixed at 33.5M, reduced extent varied over 2..1024 for dim=-1 and a middle dim) and the expand-backward repro from the report, run before and after on the same source build with an idle GPU: ``` python agent_space/bench_sum_sweep.py python agent_space/bench_expand_backward.py ``` Authored with the assistance of an AI coding tool (Claude Code). Co-Authored-By: Claude Fable 5 <[email protected]>
pytorch#180709 moved sum/nansum/mean off MPSGraph onto native Metal kernels that assign one 32-lane simdgroup per output element. That geometry fails at both ends of the output-size spectrum: Tiny reduced extent, huge output: the vectorized loop needs N >= 32 * SUM_NCHAINS = 256 to execute at all, 30 of 32 lanes idle in the tail loop for N < 32, and a full simd shuffle is paid per output across numel/N simdgroups, so cost scales with output size instead of work. The backward of expand/broadcast is exactly this reduction (extent = the expansion factor, typically 2): sum(dim=-1) at extent 2 over 33.5M elements reads 25.6 ms vs 0.93 ms on torch 2.12 (M4 Max), and an expand-upsample backward reads 97.4 ms vs 2.4 ms. Huge reduced extent, tiny output: one simdgroup per output gives 32 simdgroups for a 33M-element tensor, leaving the GPU idle. sum(dim=(0,2,3)) on [1,32,1024,1024] - the parameter-gradient reduction for every per-channel broadcast (conv bias, FiLM, AdaIN) - reads 2.4 ms vs 0.32 ms on 2.12. The existing output.numel() == 1 split path does the right thing but was only reached for full reductions. Middle-dim and multi-dim reductions (what sum_to_size emits) additionally had no fast path at any extent and fell to a generic kernel paying a div/mod chain per element. The fix keeps the simdgroup kernels for their intended regime and adds two dispatch paths around them: Small extents go to new thread-per-output kernels (sum_reduction_small, sum_reduction_inner_small): each thread serially accumulates its own N elements, no shuffles or barriers. Routed below SUM_SMALL_REDUCTION_THRESHOLD (256, the structural point where the simdgroup kernel's vectorized loop starts running), plus contiguous single middle-dim reductions of any extent when the output has at least SUM_THREAD_PER_OUTPUT_MIN_OUTPUTS elements. Tiny outputs with large extents (output.numel() < SUM_SPLIT_MAX_OUTPUTS and extent > MAX_THREADGROUP_SIZE * NCHAINS) generalize the output.numel() == 1 two-pass split: the largest collapsed reduced dim is split into chunks targeting SUM_SPLIT_TARGET_TGS pass-1 threadgroups (pass 1 reduces a single dim with direct strides, fully coalesced), and pass 2 collapses the partials. Mean's divisor is applied once in pass 2, nansum's NaN-to-zero happens at pass-1 load, and min/max/all/any reuse the same split since they share the dispatcher's split fields. Both paths first drop size-1 dims and merge stride-compatible adjacent dims, and the small and generic kernels walk up to two reduced dims affinely, so the sum_to_size pattern avoids per-element div/mod entirely. Only sum/nansum/mean/count_nonzero opt in to the small path via a has_small_variants flag; above the thresholds dispatch is unchanged. Routing these regimes back to MPSGraph was considered and rejected: the native kernel beats MPSGraph at large extents, and the new geometries match or beat MPSGraph in their regimes, so no regime remains where the graph path wins. Results (M4 Max, 33.5M elements): sum(dim=-1) extent 2 25.65 -> 1.06 ms, sum(dim=1) extent 2 30.52 -> 1.07 ms (flat across extents), extent 1024 unchanged, expand-upsample backward 97.4 -> 2.70 ms, sum(dim=(0,2,3)) on [1,32,1024,1024] 2.40 -> 0.26 ms (2.12: 0.32), and an output-size sweep (1 to 16M outputs, total elements fixed) is flat at both ends for inner, outer, middle, and multi-dim layouts. Known residual: outer/middle layouts at 8-256 outputs sit at 0.45-0.93 ms (~3x off bandwidth); a batched outer kernel could close this later. Test Plan: Correctness on this source build (285 passed / 5 xfailed, and 152 passed / 4 xfailed respectively): ``` python -m pytest test/test_mps.py -k "sum or mean or nansum" -q python -m pytest test/test_mps.py -k "count_nonzero or amax or amin or any or all" -q ``` Plus 12/12 CPU-parity spot checks for the small path (interleaved multi-dim sum/mean, adjacent-dim collapse, three reduced dims, keepdim, non-contiguous, permuted, nansum, half, bool, complex64) and 17/17 for the split path (sum/mean/nansum with NaNs, non-power-of-2 batches, strided, permuted, half, complex, int64, count_nonzero, amax/amin/any/all). Performance: extent sweep, output-size sweep, and the expand-backward repro, run before and after on the same source build with an idle GPU and a clone() control: ``` python agent_space/bench_sum_sweep.py python agent_space/bench_output_sweep.py python agent_space/bench_expand_backward.py ``` Authored with the assistance of an AI coding tool (Claude Code). Co-Authored-By: Claude Fable 5 <[email protected]>
…0709) Use Metal shaders for torch.sum/nansum/mean instead of MPSGraph's `reductionSumWithTensor:` Route `torch.sum`, `torch.nansum`, and `torch.mean` on MPS through custom Metal shaders via the common `sum_stub` / `nansum_stub` / `mean_stub` dispatch path (matching CPU/CUDA), instead of separate `sum_out_mps` / `nansum_mps` / `mean_out_mps` MPSGraph wrappers. ## Kernel design Four specialized paths selected per-call inside `sum_nansum_kernel_mps`: 1. **Full reduction** (scalar output) for large inputs (`reduction_size > 1024`): two-pass multi-threadgroup. Pass 1 splits the input into `num_groups` equal contiguous slices (each TG reduces one slice into a float32 partial); pass 2 reduces `num_groups` partials to the final scalar. `num_groups` is adjusted so that `num_groups * elems_per_group == reduction_size` exactly - the last TG must not read past the logical end, otherwise the MPS caching allocator can place the `partials` buffer in the OOB region and subsequent `sum()` calls accumulate stale data. 2. **Outer-dim reduction** (e.g. `dim=0` on a contiguous tensor): 32×32 threadgroup with coalesced column reads and a shared-memory reduction across row-workers. 3. **Inner-dim reduction** (e.g. `dim=-1` on a contiguous tensor): one SIMD group per row, 8 rows per threadgroup, `simd_sum` for intra-row reduction - no shared memory needed. 4. **General reduction** (multi-dim, non-contiguous): `NormParams`-based kernel; for the single-reduced-dim case uses per-TG `input_base` plus `reduction_stride`, otherwise falls back to `get_input_offset` per element. All three operators (`sum_reduction`, `sum_reduction_outer`, `sum_reduction_inner`) share the same reduction kernel code with different prologue (for `nansum`) and epilogue (for `mean`). Accumulation is always in `opmath_t<TO>` (e.g. `float` for fp16/bfloat16, `float2` for `half2`), with 8 independent accumulation chains per thread for ILP. ## Benchmark Median latency over 500 iterations on M4 Max (PyTorch 2.11 MPSGraph baseline vs this change). Script at the end. ### Sum | shape | op | dtype | 2.11 (µs) | new (µs) | speedup | |---|---|---|---:|---:|---| | (1024,1024) | full | float32 | 15.3 | 13.2 | **1.24x** | | (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | **2.18x** | | (1024,1024) | dim=1 | float32 | 12.9 | 5.1 | **2.55x** | | (4096,4096) | full | float32 | 131 | 122 | 1.08x | | (4096,4096) | dim=0 | float32 | 132 | 127 | 1.04x | | (4096,4096) | dim=0 | float16 | 81.9 | 49.2 | **1.66x** | | (4096,4096) | dim=0 | bfloat16 | 78.9 | 47.2 | **1.67x** | | (1024,1024) | full | int64 | 29.8 | 13.1 | **2.28x** | | (1024,1024) | dim=0 | int64 | 23.4 | 7.4 | **3.16x** | Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable to 1.4x faster on every tested shape. ## Correctness Adds two regression tests to `test/test_mps.py` (that were already detected by inductor tests): - `test_mean_low_prec_order` — fp16/bfloat16/complex32 mean matches the fp32-intermediate reference; catches cast/divide order regressions. - `test_sum_full_reduction_repeated` — repeated `sum()` calls on the same tensor are stable; catches the two-pass OOB regression where the `partials` buffer could alias the input's trailing bytes. Pull Request resolved: pytorch#180709 Approved by: https://github.com/Skylion007 ghstack dependencies: pytorch#180572, pytorch#180708
…torch#180709)" This reverts commit 10a41bb. Reverted pytorch#180709 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#180709 (comment)))
…0709) Use Metal shaders for torch.sum/nansum/mean instead of MPSGraph's `reductionSumWithTensor:` Route `torch.sum`, `torch.nansum`, and `torch.mean` on MPS through custom Metal shaders via the common `sum_stub` / `nansum_stub` / `mean_stub` dispatch path (matching CPU/CUDA), instead of separate `sum_out_mps` / `nansum_mps` / `mean_out_mps` MPSGraph wrappers. ## Kernel design Four specialized paths selected per-call inside `sum_nansum_kernel_mps`: 1. **Full reduction** (scalar output) for large inputs (`reduction_size > 1024`): two-pass multi-threadgroup. Pass 1 splits the input into `num_groups` equal contiguous slices (each TG reduces one slice into a float32 partial); pass 2 reduces `num_groups` partials to the final scalar. `num_groups` is adjusted so that `num_groups * elems_per_group == reduction_size` exactly - the last TG must not read past the logical end, otherwise the MPS caching allocator can place the `partials` buffer in the OOB region and subsequent `sum()` calls accumulate stale data. 2. **Outer-dim reduction** (e.g. `dim=0` on a contiguous tensor): 32×32 threadgroup with coalesced column reads and a shared-memory reduction across row-workers. 3. **Inner-dim reduction** (e.g. `dim=-1` on a contiguous tensor): one SIMD group per row, 8 rows per threadgroup, `simd_sum` for intra-row reduction - no shared memory needed. 4. **General reduction** (multi-dim, non-contiguous): `NormParams`-based kernel; for the single-reduced-dim case uses per-TG `input_base` plus `reduction_stride`, otherwise falls back to `get_input_offset` per element. All three operators (`sum_reduction`, `sum_reduction_outer`, `sum_reduction_inner`) share the same reduction kernel code with different prologue (for `nansum`) and epilogue (for `mean`). Accumulation is always in `opmath_t<TO>` (e.g. `float` for fp16/bfloat16, `float2` for `half2`), with 8 independent accumulation chains per thread for ILP. ## Benchmark Median latency over 500 iterations on M4 Max (PyTorch 2.11 MPSGraph baseline vs this change). Script at the end. ### Sum | shape | op | dtype | 2.11 (µs) | new (µs) | speedup | |---|---|---|---:|---:|---| | (1024,1024) | full | float32 | 15.3 | 13.2 | **1.24x** | | (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | **2.18x** | | (1024,1024) | dim=1 | float32 | 12.9 | 5.1 | **2.55x** | | (4096,4096) | full | float32 | 131 | 122 | 1.08x | | (4096,4096) | dim=0 | float32 | 132 | 127 | 1.04x | | (4096,4096) | dim=0 | float16 | 81.9 | 49.2 | **1.66x** | | (4096,4096) | dim=0 | bfloat16 | 78.9 | 47.2 | **1.67x** | | (1024,1024) | full | int64 | 29.8 | 13.1 | **2.28x** | | (1024,1024) | dim=0 | int64 | 23.4 | 7.4 | **3.16x** | Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable to 1.4x faster on every tested shape. ## Correctness Adds two regression tests to `test/test_mps.py` (that were already detected by inductor tests): - `test_mean_low_prec_order` — fp16/bfloat16/complex32 mean matches the fp32-intermediate reference; catches cast/divide order regressions. - `test_sum_full_reduction_repeated` — repeated `sum()` calls on the same tensor are stable; catches the two-pass OOB regression where the `partials` buffer could alias the input's trailing bytes. Pull Request resolved: pytorch#180709 Approved by: https://github.com/Skylion007
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.
Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: `LOAD_IDENTITY` (sum), `LOAD_NAN_TO_ZERO` (nansum), and `LOAD_NONZERO` (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation. Even though output is 64-bit integer, accumulates partial counts in `uint32` rather than `long` as tensor dimension is always less that in32 on Metal.
Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"
Remove `MPSReductionType::COUNT_NONZERO` and its MPSGraph branch.
Tweaked the two-pass full-reduction path to always dispatch pass 2 with `LOAD_IDENTITY` (plain sum), regardless of pass-1 mode: pass 1 has already applied the load-mode transform (NaN-to-zero, nonzero-as-one), so pass 2 only needs to combine the partials.
Benchmark vs torch 2.11 MPSGraph (median us, M4 Max):
| shape | op | dtype | 2.11 | new | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,) | full | float32 | 14.0 | 8.1 | 1.73x |
| (1000000,) | full | float32 | 14.2 | 10.8 | 1.31x |
| (1024,1024) | full | float32 | 16.4 | 11.6 | 1.41x |
| (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | 2.18x |
| (1024,1024) | dim=1 | float32 | 12.9 | 4.9 | 2.62x |
| (4096,4096) | full | float32 |131.2 |121.9 | 1.08x |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x |
| (1024,1024) | full | int64 | 15.5 | 12.8 | 1.21x |
| (1024,1024) | dim=0 | int64 | 12.9 | 7.6 | 1.70x |
| (1024,1024) | dim=0 | float16 | 14.7 | 4.7 | 3.13x |
| (1024,1024) | full | bool | 15.1 | 11.2 | 1.34x |
| (1024,1024) | dim=0 | bool | 13.2 | 4.8 | 2.76x |
| (4096,4096) | dim=0 | bool | 48.8 | 26.2 | 1.86x |
Dim reductions see parity or 1.7–3x speedups across dtypes.
<details>
<summary>Benchmark script</summary>
```python
import torch
import torch.utils.benchmark as benchmark
import itertools
shapes_and_dims = [
((10_000,), None),
((1_000_000,), None),
((1024, 1024), None),
((1024, 1024), 0),
((1024, 1024), 1),
((4096, 4096), None),
((4096, 4096), 0),
((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]
def make_input(shape, sparsity, dtype, device):
if dtype == torch.bool:
return torch.rand(shape, device=device) < sparsity
x = torch.randn(shape, device=device, dtype=dtype)
mask = torch.rand(shape, device=device) >= sparsity
x[mask] = 0
return x
def bench(x, dim):
stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
for _ in range(2):
result = t.timeit(500)
return result.median
for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
x = make_input(shape, sparsity, torch.float32, "mps")
m = bench(x, dim) * 1e6
print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>
Pull Request resolved: pytorch#180725
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180709
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
…0709) Use Metal shaders for torch.sum/nansum/mean instead of MPSGraph's `reductionSumWithTensor:` Route `torch.sum`, `torch.nansum`, and `torch.mean` on MPS through custom Metal shaders via the common `sum_stub` / `nansum_stub` / `mean_stub` dispatch path (matching CPU/CUDA), instead of separate `sum_out_mps` / `nansum_mps` / `mean_out_mps` MPSGraph wrappers. ## Kernel design Four specialized paths selected per-call inside `sum_nansum_kernel_mps`: 1. **Full reduction** (scalar output) for large inputs (`reduction_size > 1024`): two-pass multi-threadgroup. Pass 1 splits the input into `num_groups` equal contiguous slices (each TG reduces one slice into a float32 partial); pass 2 reduces `num_groups` partials to the final scalar. `num_groups` is adjusted so that `num_groups * elems_per_group == reduction_size` exactly - the last TG must not read past the logical end, otherwise the MPS caching allocator can place the `partials` buffer in the OOB region and subsequent `sum()` calls accumulate stale data. 2. **Outer-dim reduction** (e.g. `dim=0` on a contiguous tensor): 32×32 threadgroup with coalesced column reads and a shared-memory reduction across row-workers. 3. **Inner-dim reduction** (e.g. `dim=-1` on a contiguous tensor): one SIMD group per row, 8 rows per threadgroup, `simd_sum` for intra-row reduction - no shared memory needed. 4. **General reduction** (multi-dim, non-contiguous): `NormParams`-based kernel; for the single-reduced-dim case uses per-TG `input_base` plus `reduction_stride`, otherwise falls back to `get_input_offset` per element. All three operators (`sum_reduction`, `sum_reduction_outer`, `sum_reduction_inner`) share the same reduction kernel code with different prologue (for `nansum`) and epilogue (for `mean`). Accumulation is always in `opmath_t<TO>` (e.g. `float` for fp16/bfloat16, `float2` for `half2`), with 8 independent accumulation chains per thread for ILP. ## Benchmark Median latency over 500 iterations on M4 Max (PyTorch 2.11 MPSGraph baseline vs this change). Script at the end. ### Sum | shape | op | dtype | 2.11 (µs) | new (µs) | speedup | |---|---|---|---:|---:|---| | (1024,1024) | full | float32 | 15.3 | 13.2 | **1.24x** | | (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | **2.18x** | | (1024,1024) | dim=1 | float32 | 12.9 | 5.1 | **2.55x** | | (4096,4096) | full | float32 | 131 | 122 | 1.08x | | (4096,4096) | dim=0 | float32 | 132 | 127 | 1.04x | | (4096,4096) | dim=0 | float16 | 81.9 | 49.2 | **1.66x** | | (4096,4096) | dim=0 | bfloat16 | 78.9 | 47.2 | **1.67x** | | (1024,1024) | full | int64 | 29.8 | 13.1 | **2.28x** | | (1024,1024) | dim=0 | int64 | 23.4 | 7.4 | **3.16x** | Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable to 1.4x faster on every tested shape. ## Correctness Adds two regression tests to `test/test_mps.py` (that were already detected by inductor tests): - `test_mean_low_prec_order` — fp16/bfloat16/complex32 mean matches the fp32-intermediate reference; catches cast/divide order regressions. - `test_sum_full_reduction_repeated` — repeated `sum()` calls on the same tensor are stable; catches the two-pass OOB regression where the `partials` buffer could alias the input's trailing bytes. Pull Request resolved: pytorch#180709 Approved by: https://github.com/Skylion007 ghstack dependencies: pytorch#180572, pytorch#180708
…torch#180709)" This reverts commit 10a41bb. Reverted pytorch#180709 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#180709 (comment)))
…0709) Use Metal shaders for torch.sum/nansum/mean instead of MPSGraph's `reductionSumWithTensor:` Route `torch.sum`, `torch.nansum`, and `torch.mean` on MPS through custom Metal shaders via the common `sum_stub` / `nansum_stub` / `mean_stub` dispatch path (matching CPU/CUDA), instead of separate `sum_out_mps` / `nansum_mps` / `mean_out_mps` MPSGraph wrappers. ## Kernel design Four specialized paths selected per-call inside `sum_nansum_kernel_mps`: 1. **Full reduction** (scalar output) for large inputs (`reduction_size > 1024`): two-pass multi-threadgroup. Pass 1 splits the input into `num_groups` equal contiguous slices (each TG reduces one slice into a float32 partial); pass 2 reduces `num_groups` partials to the final scalar. `num_groups` is adjusted so that `num_groups * elems_per_group == reduction_size` exactly - the last TG must not read past the logical end, otherwise the MPS caching allocator can place the `partials` buffer in the OOB region and subsequent `sum()` calls accumulate stale data. 2. **Outer-dim reduction** (e.g. `dim=0` on a contiguous tensor): 32×32 threadgroup with coalesced column reads and a shared-memory reduction across row-workers. 3. **Inner-dim reduction** (e.g. `dim=-1` on a contiguous tensor): one SIMD group per row, 8 rows per threadgroup, `simd_sum` for intra-row reduction - no shared memory needed. 4. **General reduction** (multi-dim, non-contiguous): `NormParams`-based kernel; for the single-reduced-dim case uses per-TG `input_base` plus `reduction_stride`, otherwise falls back to `get_input_offset` per element. All three operators (`sum_reduction`, `sum_reduction_outer`, `sum_reduction_inner`) share the same reduction kernel code with different prologue (for `nansum`) and epilogue (for `mean`). Accumulation is always in `opmath_t<TO>` (e.g. `float` for fp16/bfloat16, `float2` for `half2`), with 8 independent accumulation chains per thread for ILP. ## Benchmark Median latency over 500 iterations on M4 Max (PyTorch 2.11 MPSGraph baseline vs this change). Script at the end. ### Sum | shape | op | dtype | 2.11 (µs) | new (µs) | speedup | |---|---|---|---:|---:|---| | (1024,1024) | full | float32 | 15.3 | 13.2 | **1.24x** | | (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | **2.18x** | | (1024,1024) | dim=1 | float32 | 12.9 | 5.1 | **2.55x** | | (4096,4096) | full | float32 | 131 | 122 | 1.08x | | (4096,4096) | dim=0 | float32 | 132 | 127 | 1.04x | | (4096,4096) | dim=0 | float16 | 81.9 | 49.2 | **1.66x** | | (4096,4096) | dim=0 | bfloat16 | 78.9 | 47.2 | **1.67x** | | (1024,1024) | full | int64 | 29.8 | 13.1 | **2.28x** | | (1024,1024) | dim=0 | int64 | 23.4 | 7.4 | **3.16x** | Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable to 1.4x faster on every tested shape. ## Correctness Adds two regression tests to `test/test_mps.py` (that were already detected by inductor tests): - `test_mean_low_prec_order` — fp16/bfloat16/complex32 mean matches the fp32-intermediate reference; catches cast/divide order regressions. - `test_sum_full_reduction_repeated` — repeated `sum()` calls on the same tensor are stable; catches the two-pass OOB regression where the `partials` buffer could alias the input's trailing bytes. Pull Request resolved: pytorch#180709 Approved by: https://github.com/Skylion007
Migrate count_nonzero to native Metal by extending the existing sum reduction kernels with a third LoadMode variant that counts nonzero elements.
Refactor the NAN_TO_ZERO bool template parameter in ReduceOps.metal to a LoadMode enum with three values: `LOAD_IDENTITY` (sum), `LOAD_NAN_TO_ZERO` (nansum), and `LOAD_NONZERO` (count_nonzero — contributes 1 per nonzero, 0 otherwise). The sum_reduction, sum_reduction_outer, and sum_reduction_inner templates all share the same load dispatch; the compiler eliminates dead branches per instantiation. Even though output is 64-bit integer, accumulates partial counts in `uint32` rather than `long` as tensor dimension is always less that in32 on Metal.
Register count_nonzero_{,_outer,_inner}_<TI>_long kernels for all supported input dtypes (float/half/bfloat/{int,long,short,char,uchar}/bool/float2/half2). Host-side count_nonzero_mps now builds a TensorIterator via make_reduction and dispatches to sum_nansum_kernel_mps with prefix "count_nonzero_"
Remove `MPSReductionType::COUNT_NONZERO` and its MPSGraph branch.
Tweaked the two-pass full-reduction path to always dispatch pass 2 with `LOAD_IDENTITY` (plain sum), regardless of pass-1 mode: pass 1 has already applied the load-mode transform (NaN-to-zero, nonzero-as-one), so pass 2 only needs to combine the partials.
Benchmark vs torch 2.11 MPSGraph (median us, M4 Max):
| shape | op | dtype | 2.11 | new | speedup |
|-------------|-------|---------|------|------|---------|
| (10000,) | full | float32 | 14.0 | 8.1 | 1.73x |
| (1000000,) | full | float32 | 14.2 | 10.8 | 1.31x |
| (1024,1024) | full | float32 | 16.4 | 11.6 | 1.41x |
| (1024,1024) | dim=0 | float32 | 13.0 | 6.0 | 2.18x |
| (1024,1024) | dim=1 | float32 | 12.9 | 4.9 | 2.62x |
| (4096,4096) | full | float32 |131.2 |121.9 | 1.08x |
| (4096,4096) | dim=0 | float32 |132.4 |127.1 | 1.04x |
| (1024,1024) | full | int64 | 15.5 | 12.8 | 1.21x |
| (1024,1024) | dim=0 | int64 | 12.9 | 7.6 | 1.70x |
| (1024,1024) | dim=0 | float16 | 14.7 | 4.7 | 3.13x |
| (1024,1024) | full | bool | 15.1 | 11.2 | 1.34x |
| (1024,1024) | dim=0 | bool | 13.2 | 4.8 | 2.76x |
| (4096,4096) | dim=0 | bool | 48.8 | 26.2 | 1.86x |
Dim reductions see parity or 1.7–3x speedups across dtypes.
<details>
<summary>Benchmark script</summary>
```python
import torch
import torch.utils.benchmark as benchmark
import itertools
shapes_and_dims = [
((10_000,), None),
((1_000_000,), None),
((1024, 1024), None),
((1024, 1024), 0),
((1024, 1024), 1),
((4096, 4096), None),
((4096, 4096), 0),
((4096, 4096), 1),
]
sparsities = [0.2, 0.5, 0.8]
def make_input(shape, sparsity, dtype, device):
if dtype == torch.bool:
return torch.rand(shape, device=device) < sparsity
x = torch.randn(shape, device=device, dtype=dtype)
mask = torch.rand(shape, device=device) >= sparsity
x[mask] = 0
return x
def bench(x, dim):
stmt = "torch.count_nonzero(x)" if dim is None else "torch.count_nonzero(x, dim=d)"
t = benchmark.Timer(stmt=stmt, globals={"torch": torch, "x": x, "d": dim}, num_threads=1)
for _ in range(2):
result = t.timeit(500)
return result.median
for (shape, dim), sparsity in itertools.product(shapes_and_dims, sparsities):
x = make_input(shape, sparsity, torch.float32, "mps")
m = bench(x, dim) * 1e6
print(f"{str(shape):>14} {str(dim):>5} {sparsity:>5.2f} {m:>12.2f}")
```
</details>
Pull Request resolved: pytorch#180725
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180709
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
Stack from ghstack (oldest at bottom):
Use Metal shaders for torch.sum/nansum/mean instead of MPSGraph's
reductionSumWithTensor:Route
torch.sum,torch.nansum, andtorch.meanon MPS through customMetal shaders via the common
sum_stub/nansum_stub/mean_stubdispatch path (matching CPU/CUDA), instead of separate
sum_out_mps/nansum_mps/mean_out_mpsMPSGraph wrappers.Kernel design
Four specialized paths selected per-call inside
sum_nansum_kernel_mps:reduction_size > 1024): two-pass multi-threadgroup. Pass 1 splits the input intonum_groupsequal contiguous slices (each TG reduces one slice into a float32 partial);pass 2 reduces
num_groupspartials to the final scalar.num_groupsis adjusted so thatnum_groups * elems_per_group == reduction_sizeexactly - the last TG must not read past the logical end, otherwise the MPS caching allocator can place thepartialsbuffer in the OOB region and subsequentsum()calls accumulate stale data.dim=0on a contiguous tensor): 32×32 threadgroup with coalesced column reads and a shared-memory reduction across row-workers.dim=-1on a contiguous tensor): one SIMD group per row, 8 rows per threadgroup,simd_sumfor intra-row reduction - no shared memory needed.NormParams-based kernel; for the single-reduced-dim case uses per-TGinput_baseplusreduction_stride, otherwise falls back toget_input_offsetper element.All three operators (
sum_reduction,sum_reduction_outer,sum_reduction_inner) share the same reduction kernel code with different prologue (fornansum) and epilogue (formean).Accumulation is always in
opmath_t<TO>(e.g.floatfor fp16/bfloat16,float2forhalf2), with 8 independent accumulation chains per thread for ILP.Benchmark
Median latency over 500 iterations on M4 Max (PyTorch 2.11 MPSGraph baseline vs this change). Script at the end.
Sum
Dim reductions see 2–4x speedups across dtypes. Full reductions are comparable to 1.4x faster on every tested shape.
Correctness
Adds two regression tests to
test/test_mps.py(that were already detected by inductor tests):test_mean_low_prec_order— fp16/bfloat16/complex32 mean matches the fp32-intermediate reference; catches cast/divide order regressions.test_sum_full_reduction_repeated— repeatedsum()calls on the same tensor are stable; catches the two-pass OOB regression where thepartialsbuffer could alias the input's trailing bytes.