Skip to content

[MPS] Add complex support to c10/metal/reduction_utils.h - #180708

Closed
malfet wants to merge 3 commits into
gh/malfet/839/basefrom
gh/malfet/839/head
Closed

malfet wants to merge 3 commits into
gh/malfet/839/basefrom
gh/malfet/839/head

Conversation

@malfet

@malfet malfet commented Apr 17, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Add float2 simd_sum and simd_prod overloads to c10/metal/reduction_utils.h for complex reductions. simd_sum reduces real and imaginary parts independently; simd_prod simulates reduction using c10::metal::mul and simd_shuffle_and_fill_down.

Add OpMathType<half2> -> float2 specialization to c10/metal/utils.h so complex32 accumulation uses complex64 precision, that fixed prod op accuracy

Also fix a latent bug in LinearAlgebra.metal, when accumulation for torch.half (not used in prod yet) and torch.complex32 matrices were done over lower precision dtypes
Add test_reduction_utils_complex to test/test_mps.py covering simd_sum and simd_prod for float2 (complex64).

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Apr 17, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit c28f99e with merge base 296c570 (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 the ciflow/mps Run MPS tests (subset of trunk) label Apr 17, 2026
@pytorch-bot

pytorch-bot Bot commented Apr 17, 2026

Copy link
Copy Markdown

This PR needs a release notes: label

If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

@malfet malfet changed the title Prep for sum migration to Metal [MPS] Add complex support to c10/metal/reduction_utils.h Apr 17, 2026
[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the release notes: mps Release notes category label Apr 17, 2026
[ghstack-poisoned]
@malfet
malfet requested a review from mruberry as a code owner April 17, 2026 21:39
@malfet

malfet commented Apr 18, 2026

Copy link
Copy Markdown
Collaborator Author

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

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

Learn more about merging in the wiki.

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

Advanced Debugging
Check the merge workflow status
here

pytorchmergebot pushed a commit that referenced this pull request Apr 19, 2026
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: #180709
Approved by: https://github.com/Skylion007
ghstack dependencies: #180572, #180708
@github-actions
github-actions Bot deleted the gh/malfet/839/head branch May 18, 2026 02:27
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…80708)

Add float2 `simd_sum` and `simd_prod` overloads to `c10/metal/reduction_utils.h` for complex reductions. `simd_sum` reduces real and imaginary parts independently; `simd_prod` simulates reduction using  `c10::metal::mul` and `simd_shuffle_and_fill_down`.

Add `OpMathType<half2>` -> float2 specialization to `c10/metal/utils.h` so complex32 accumulation uses complex64 precision, that fixed prod op accuracy

Also fix a latent bug in `LinearAlgebra.metal`, when accumulation for `torch.half` (not used in prod yet) and `torch.complex32` matrices were done over lower precision dtypes
Add test_reduction_utils_complex to `test/test_mps.py` covering simd_sum and simd_prod for float2 (complex64).
Pull Request resolved: pytorch#180708
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180572
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…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
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…80708)

Add float2 `simd_sum` and `simd_prod` overloads to `c10/metal/reduction_utils.h` for complex reductions. `simd_sum` reduces real and imaginary parts independently; `simd_prod` simulates reduction using  `c10::metal::mul` and `simd_shuffle_and_fill_down`.

Add `OpMathType<half2>` -> float2 specialization to `c10/metal/utils.h` so complex32 accumulation uses complex64 precision, that fixed prod op accuracy

Also fix a latent bug in `LinearAlgebra.metal`, when accumulation for `torch.half` (not used in prod yet) and `torch.complex32` matrices were done over lower precision dtypes
Add test_reduction_utils_complex to `test/test_mps.py` covering simd_sum and simd_prod for float2 (complex64).
Pull Request resolved: pytorch#180708
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180572
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…80708)

Add float2 `simd_sum` and `simd_prod` overloads to `c10/metal/reduction_utils.h` for complex reductions. `simd_sum` reduces real and imaginary parts independently; `simd_prod` simulates reduction using  `c10::metal::mul` and `simd_shuffle_and_fill_down`.

Add `OpMathType<half2>` -> float2 specialization to `c10/metal/utils.h` so complex32 accumulation uses complex64 precision, that fixed prod op accuracy

Also fix a latent bug in `LinearAlgebra.metal`, when accumulation for `torch.half` (not used in prod yet) and `torch.complex32` matrices were done over lower precision dtypes
Add test_reduction_utils_complex to `test/test_mps.py` covering simd_sum and simd_prod for float2 (complex64).
Pull Request resolved: pytorch#180708
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#180572
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…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
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) Merged release notes: mps Release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants