Skip to content

[Metal] Binary tensor iterator fixes/improvements - #183055

Closed
malfet wants to merge 8 commits into
gh/malfet/896/basefrom
gh/malfet/896/head
Closed

malfet wants to merge 8 commits into
gh/malfet/896/basefrom
gh/malfet/896/head

Conversation

@malfet

@malfet malfet commented May 9, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Several MPS binary TensorIterator dispatcher fixes, plus tests.

Scalar promotion shortcut restricted to lossless int-scalar→float-common only. Was building wrong kernel names (mul_dense_scalar_float2_float for complex_convolution) and rounding float scalars on the host before launch (float16 CrossEntropyLoss drift). The cast_suffix_type selection now uses iter.common_dtype() (with a kBool branch for comparison ops) so cast-kernel name lookups match the post-promotion template instantiation. Fixes cosine_similarity mps_float16 (half.clamp_min_(float)).

natural_output_dtype contract on exec_binary_kernel + new binary_strided_castout kernel template (with a store_at_offs helper). Default natural = iter.dtype(0), so arithmetic ops dispatch through the existing <DTYPEO>_<DTYPEI> cast-kernel matrix as before. Ops whose kernel produces a fixed natural that may diverge from iter.dtype(0) (comparisons → kBool) declare it via the new parameter; the dispatcher then routes through _strided_castout_<DTYPEO>_<DTYPEI>, which computes at compile-time precision and runtime-casts on store. Castout is explicit opt-in via a separate REGISTER_BINARY_CASTOUT_OP(NAME, DTYPEI, DTYPEO) macro -- arithmetic ops don't pay binary size for unused kernels. Missing combos fail loudly via getPipelineStateForFunc rather than silent corruption. The contract is used by the comparison-ops migration in #183019 to fix cdist mps_float32 (linalg_vector_norm(p=0) → ne_outf(float, 0, float_out)) and inductor test_complex_from_real_imag_mps.

C10_METAL_ALL_TYPES_FUNCTOR extended to (EnumName, EnumValue, MetalType). val_at_offs and store_at_offs are generated from the same X-macro instead of hand-written per-type switches.

Caller-tunable ILP threshold via a new ilp_threshold parameter. Float-output default kept at 256K; non-float defaults off. binary_dense_ilp is unsigned ILP-templated and the unroll width appears in host names (add_dense_ilp4_float_float) so future ilp8/ilp16 can coexist.

Tests: new TestBinaryIteratorConformance (two synthetic functors -- simple_add and simple_ge -- compiled via MetalShaderLibrary and dispatched through the same path real ops use; simple_ge opts into castout). Plus test_binary_kernels regressions for scalar precision and in-place narrowing.

Authored with assistance from Claude.

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 9, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 0eeb6ff with merge base e775750 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@pytorch-bot pytorch-bot Bot added ciflow/mps Run MPS tests (subset of trunk) release notes: mps Release notes category labels May 9, 2026
@malfet
malfet requested a review from Skylion007 May 9, 2026 17:57
Comment thread test/test_mps.py Resolved
[ghstack-poisoned]
@malfet

malfet commented May 9, 2026

Copy link
Copy Markdown
Collaborator Author

@claude review this

@malfet malfet changed the title [MPS] Fix mixed-dtype scalar binary ops and broaden ILP override [Metal] Binary tensor iterator fixes/improvements May 9, 2026
@claude

claude Bot commented May 9, 2026 •

Copy link
Copy Markdown

Claude finished @malfet's task in 1m 36s —— View job


Review of PR #183055

  • Gather context and read changed files
  • Review aten/src/ATen/native/mps/OperationUtils.mm
  • Review aten/src/ATen/native/mps/MetalShaderLibrary.h
  • Review c10/metal/common.h and c10/metal/indexing.h
  • Review test/test_mps.py
  • Post review summary

This is a solid fix for a real correctness bug in the MPS scalar binary op path, with a clean ILP gating refactor on top. The changes are well-motivated and the test coverage targets the exact failure modes. A few observations:

Scalar promotion fix (OperationUtils.mm:1152-1186) -- looks correct

The core bug is clear: when a float tensor is multiplied by a complex scalar, common_dtype = complex but the tensor stays float. The old code promoted the scalar to common and then tried to look up a non-cast scalar kernel with mismatched types (mul_dense_scalar_float2_float), which doesn't exist.

The fix gate (safe_host_promote at line 1176-1177) is appropriately conservative:

tensor_dtype == common && c10::isIntegralType(scalar_dtype, /*includeBool=*/true) && common == kFloat;

Only fires for the one case where host-side .to() is provably bit-identical to the GPU cast kernel's op_math_t promotion. The comment explaining why half/bfloat cases are excluded (lines 1166-1171) is valuable given how easy it would be to "optimize" this gate later and break numerics.

Scalar rebind (OperationUtils.mm:1271-1274) -- looks correct

After host-promotion, the scalar tensor's Metal buffer has changed (.to() creates a new tensor), so rebinding is necessary. The "harmless when we didn't promote" claim is correct -- it just rebinds the same buffer that bind_iter_tensors already set.

Cast suffix type (OperationUtils.mm:1221)

Switching from scalarToMetalTypeString(out) to scalarToMetalTypeString(iter.common_dtype()) is semantically more correct. For current arithmetic ops these are identical, but this future-proofs for comparison ops returning bool. The comment at lines 1215-1220 makes this rationale clear.

ILP gating refactor

Clean separation of concerns: ilp_applicable (shape compatibility) vs threshold-based default (dtype-dependent). The caller-provided ilp_threshold parameter in the API is a nice touch for ops with different bandwidth profiles, and PYTORCH_BINARY_FORCE_FLAVOR now works for all applicable dtypes, matching the unary path.

Kernel name versioning (dense_ilp -> dense_ilp4)

The C10_METAL_ILP_PER_THREAD_STR macro with the static_assert guard at indexing.h:381-383 is the right way to keep the compile-time string and the runtime constant in sync. The template parameterization of binary_dense_ilp with unsigned ILP = ILP_PER_THREAD prepares for future unroll-width variants without requiring changes to existing registration.

Tests (test_mps.py:8765-8788)

Good coverage of the exact failure modes:

  • float x complex scalar (line 8770-8773): the original crash case
  • int x float scalar (line 8774-8776): exercises the safe_host_promote path
  • half precision regression (lines 8785-8788): verifies contiguous/strided parity for non-representable float scalars, guarding against future over-aggressive promotion

Agree with @Skylion007's nit about with self.subTest -- would make failure diagnosis easier, but not blocking.

Minor observations (non-blocking)

  1. Comment density in the promotion block (lines 1152-1171): 20-line comment for ~10 lines of code is heavy, but given this is a subtle numeric correctness invariant that would be easy to accidentally relax, I think it's justified here.

  2. tensor_operand unused in cast path: At line 1224, tensor_operand is declared but only used in the else (non-cast) branch of the scalar kernel name construction. This is pre-existing and fine (the compiler will optimize it out), just noting it.

Overall: the fix is correct, the test coverage is targeted, and the ILP refactor is a clean improvement. LGTM.

malfet added 6 commits May 10, 2026 14:24
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #183019

pytorchmergebot pushed a commit that referenced this pull request May 11, 2026
…al (#183019)

Used the metal-kernel skill to port the boolean comparison binary ops (`eq`, `ne`, `lt`, `le`, `gt`, `ge`) to native Metal kernels via the existing TensorIterator stub-dispatch path, dropping the MPSGraph-based implementations.

Each stub passes `kBool` as `natural_output_dtype` (the new contract introduced in #183055) so non-bool `out=` is correctly routed through the strided castout path. Stubs also pass `ilp_threshold = 1u << 18`, matching the floating-point default — measurably faster for small/medium tensors and avoids the 2b-param dispatch cliff in MPSGraph.

`torch.eq(a, b, out=c)` on M-series, default dispatcher (us/call, lower is better):

| numel | torch 2.11 (MPSGraph) | this PR | speedup |
|---|---|---|---|
| float32, 65K | 16.6 | 12.7 | 1.3x |
| float32, 262K | 111.5 | 18.6 | 6.0x |
| float32, 1M | 43.1 | 42.3 | 1.0x |
| float32, 16M | 601.7 | 632.6 | 0.95x |
| int32, 65K | 16.3 | 3.7 | 4.4x |
| int32, 262K | 16.4 | 5.2 | 3.2x |
| int32, 1M | 23.3 | 24.4 | 1.0x |
| int32, 16M | 613.1 | 606.2 | 1.0x |

Authored with assistance from Claude.
Pull Request resolved: #183019
Approved by: https://github.com/Skylion007
ghstack dependencies: #183055
dsashidh pushed a commit to dsashidh/pytorch that referenced this pull request May 13, 2026
Several MPS binary TensorIterator dispatcher fixes, plus tests.

**Scalar promotion shortcut** restricted to lossless int-scalar→float-common only. Was building wrong kernel names (`mul_dense_scalar_float2_float` for `complex_convolution`) and rounding float scalars on the host before launch (float16 CrossEntropyLoss drift). The `cast_suffix_type` selection now uses `iter.common_dtype()` (with a `kBool` branch for comparison ops) so cast-kernel name lookups match the post-promotion template instantiation. Fixes `cosine_similarity` `mps_float16` (`half.clamp_min_(float)`).

**`natural_output_dtype` contract on `exec_binary_kernel`** + new `binary_strided_castout` kernel template (with a `store_at_offs` helper). Default natural = `iter.dtype(0)`, so arithmetic ops dispatch through the existing `<DTYPEO>_<DTYPEI>` cast-kernel matrix as before. Ops whose kernel produces a fixed natural that may diverge from `iter.dtype(0)` (comparisons → `kBool`) declare it via the new parameter; the dispatcher then routes through `_strided_castout_<DTYPEO>_<DTYPEI>`, which computes at compile-time precision and runtime-casts on store. Castout is explicit opt-in via a separate `REGISTER_BINARY_CASTOUT_OP(NAME, DTYPEI, DTYPEO)` macro -- arithmetic ops don't pay binary size for unused kernels. Missing combos fail loudly via `getPipelineStateForFunc` rather than silent corruption. The contract is used by the comparison-ops migration in pytorch#183019 to fix `cdist` `mps_float32` (`linalg_vector_norm(p=0)` → `ne_outf(float, 0, float_out)`) and inductor `test_complex_from_real_imag_mps`.

**`C10_METAL_ALL_TYPES_FUNCTOR` extended** to `(EnumName, EnumValue, MetalType)`. `val_at_offs` and `store_at_offs` are generated from the same X-macro instead of hand-written per-type switches.

**Caller-tunable ILP threshold** via a new `ilp_threshold` parameter. Float-output default kept at 256K; non-float defaults off. `binary_dense_ilp` is `unsigned ILP`-templated and the unroll width appears in host names (`add_dense_ilp4_float_float`) so future `ilp8`/`ilp16` can coexist.

Tests: new `TestBinaryIteratorConformance` (two synthetic functors -- `simple_add` and `simple_ge` -- compiled via `MetalShaderLibrary` and dispatched through the same path real ops use; `simple_ge` opts into castout). Plus `test_binary_kernels` regressions for scalar precision and in-place narrowing.

Authored with assistance from Claude.
Pull Request resolved: pytorch#183055
Approved by: https://github.com/Skylion007
dsashidh pushed a commit to dsashidh/pytorch that referenced this pull request May 13, 2026
…al (pytorch#183019)

Used the metal-kernel skill to port the boolean comparison binary ops (`eq`, `ne`, `lt`, `le`, `gt`, `ge`) to native Metal kernels via the existing TensorIterator stub-dispatch path, dropping the MPSGraph-based implementations.

Each stub passes `kBool` as `natural_output_dtype` (the new contract introduced in pytorch#183055) so non-bool `out=` is correctly routed through the strided castout path. Stubs also pass `ilp_threshold = 1u << 18`, matching the floating-point default — measurably faster for small/medium tensors and avoids the 2b-param dispatch cliff in MPSGraph.

`torch.eq(a, b, out=c)` on M-series, default dispatcher (us/call, lower is better):

| numel | torch 2.11 (MPSGraph) | this PR | speedup |
|---|---|---|---|
| float32, 65K | 16.6 | 12.7 | 1.3x |
| float32, 262K | 111.5 | 18.6 | 6.0x |
| float32, 1M | 43.1 | 42.3 | 1.0x |
| float32, 16M | 601.7 | 632.6 | 0.95x |
| int32, 65K | 16.3 | 3.7 | 4.4x |
| int32, 262K | 16.4 | 5.2 | 3.2x |
| int32, 1M | 23.3 | 24.4 | 1.0x |
| int32, 16M | 613.1 | 606.2 | 1.0x |

Authored with assistance from Claude.
Pull Request resolved: pytorch#183019
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#183055
Alokksinha00 pushed a commit to Alokksinha00/pytorch that referenced this pull request May 15, 2026
Several MPS binary TensorIterator dispatcher fixes, plus tests.

**Scalar promotion shortcut** restricted to lossless int-scalar→float-common only. Was building wrong kernel names (`mul_dense_scalar_float2_float` for `complex_convolution`) and rounding float scalars on the host before launch (float16 CrossEntropyLoss drift). The `cast_suffix_type` selection now uses `iter.common_dtype()` (with a `kBool` branch for comparison ops) so cast-kernel name lookups match the post-promotion template instantiation. Fixes `cosine_similarity` `mps_float16` (`half.clamp_min_(float)`).

**`natural_output_dtype` contract on `exec_binary_kernel`** + new `binary_strided_castout` kernel template (with a `store_at_offs` helper). Default natural = `iter.dtype(0)`, so arithmetic ops dispatch through the existing `<DTYPEO>_<DTYPEI>` cast-kernel matrix as before. Ops whose kernel produces a fixed natural that may diverge from `iter.dtype(0)` (comparisons → `kBool`) declare it via the new parameter; the dispatcher then routes through `_strided_castout_<DTYPEO>_<DTYPEI>`, which computes at compile-time precision and runtime-casts on store. Castout is explicit opt-in via a separate `REGISTER_BINARY_CASTOUT_OP(NAME, DTYPEI, DTYPEO)` macro -- arithmetic ops don't pay binary size for unused kernels. Missing combos fail loudly via `getPipelineStateForFunc` rather than silent corruption. The contract is used by the comparison-ops migration in pytorch#183019 to fix `cdist` `mps_float32` (`linalg_vector_norm(p=0)` → `ne_outf(float, 0, float_out)`) and inductor `test_complex_from_real_imag_mps`.

**`C10_METAL_ALL_TYPES_FUNCTOR` extended** to `(EnumName, EnumValue, MetalType)`. `val_at_offs` and `store_at_offs` are generated from the same X-macro instead of hand-written per-type switches.

**Caller-tunable ILP threshold** via a new `ilp_threshold` parameter. Float-output default kept at 256K; non-float defaults off. `binary_dense_ilp` is `unsigned ILP`-templated and the unroll width appears in host names (`add_dense_ilp4_float_float`) so future `ilp8`/`ilp16` can coexist.

Tests: new `TestBinaryIteratorConformance` (two synthetic functors -- `simple_add` and `simple_ge` -- compiled via `MetalShaderLibrary` and dispatched through the same path real ops use; `simple_ge` opts into castout). Plus `test_binary_kernels` regressions for scalar precision and in-place narrowing.

Authored with assistance from Claude.
Pull Request resolved: pytorch#183055
Approved by: https://github.com/Skylion007
Alokksinha00 pushed a commit to Alokksinha00/pytorch that referenced this pull request May 15, 2026
…al (pytorch#183019)

Used the metal-kernel skill to port the boolean comparison binary ops (`eq`, `ne`, `lt`, `le`, `gt`, `ge`) to native Metal kernels via the existing TensorIterator stub-dispatch path, dropping the MPSGraph-based implementations.

Each stub passes `kBool` as `natural_output_dtype` (the new contract introduced in pytorch#183055) so non-bool `out=` is correctly routed through the strided castout path. Stubs also pass `ilp_threshold = 1u << 18`, matching the floating-point default — measurably faster for small/medium tensors and avoids the 2b-param dispatch cliff in MPSGraph.

`torch.eq(a, b, out=c)` on M-series, default dispatcher (us/call, lower is better):

| numel | torch 2.11 (MPSGraph) | this PR | speedup |
|---|---|---|---|
| float32, 65K | 16.6 | 12.7 | 1.3x |
| float32, 262K | 111.5 | 18.6 | 6.0x |
| float32, 1M | 43.1 | 42.3 | 1.0x |
| float32, 16M | 601.7 | 632.6 | 0.95x |
| int32, 65K | 16.3 | 3.7 | 4.4x |
| int32, 262K | 16.4 | 5.2 | 3.2x |
| int32, 1M | 23.3 | 24.4 | 1.0x |
| int32, 16M | 613.1 | 606.2 | 1.0x |

Authored with assistance from Claude.
Pull Request resolved: pytorch#183019
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#183055
@github-actions
github-actions Bot deleted the gh/malfet/896/head branch June 12, 2026 02:32
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
Several MPS binary TensorIterator dispatcher fixes, plus tests.

**Scalar promotion shortcut** restricted to lossless int-scalar→float-common only. Was building wrong kernel names (`mul_dense_scalar_float2_float` for `complex_convolution`) and rounding float scalars on the host before launch (float16 CrossEntropyLoss drift). The `cast_suffix_type` selection now uses `iter.common_dtype()` (with a `kBool` branch for comparison ops) so cast-kernel name lookups match the post-promotion template instantiation. Fixes `cosine_similarity` `mps_float16` (`half.clamp_min_(float)`).

**`natural_output_dtype` contract on `exec_binary_kernel`** + new `binary_strided_castout` kernel template (with a `store_at_offs` helper). Default natural = `iter.dtype(0)`, so arithmetic ops dispatch through the existing `<DTYPEO>_<DTYPEI>` cast-kernel matrix as before. Ops whose kernel produces a fixed natural that may diverge from `iter.dtype(0)` (comparisons → `kBool`) declare it via the new parameter; the dispatcher then routes through `_strided_castout_<DTYPEO>_<DTYPEI>`, which computes at compile-time precision and runtime-casts on store. Castout is explicit opt-in via a separate `REGISTER_BINARY_CASTOUT_OP(NAME, DTYPEI, DTYPEO)` macro -- arithmetic ops don't pay binary size for unused kernels. Missing combos fail loudly via `getPipelineStateForFunc` rather than silent corruption. The contract is used by the comparison-ops migration in pytorch#183019 to fix `cdist` `mps_float32` (`linalg_vector_norm(p=0)` → `ne_outf(float, 0, float_out)`) and inductor `test_complex_from_real_imag_mps`.

**`C10_METAL_ALL_TYPES_FUNCTOR` extended** to `(EnumName, EnumValue, MetalType)`. `val_at_offs` and `store_at_offs` are generated from the same X-macro instead of hand-written per-type switches.

**Caller-tunable ILP threshold** via a new `ilp_threshold` parameter. Float-output default kept at 256K; non-float defaults off. `binary_dense_ilp` is `unsigned ILP`-templated and the unroll width appears in host names (`add_dense_ilp4_float_float`) so future `ilp8`/`ilp16` can coexist.

Tests: new `TestBinaryIteratorConformance` (two synthetic functors -- `simple_add` and `simple_ge` -- compiled via `MetalShaderLibrary` and dispatched through the same path real ops use; `simple_ge` opts into castout). Plus `test_binary_kernels` regressions for scalar precision and in-place narrowing.

Authored with assistance from Claude.
Pull Request resolved: pytorch#183055
Approved by: https://github.com/Skylion007
aperson30 pushed a commit to aperson30/pytorch that referenced this pull request Jun 20, 2026
…al (pytorch#183019)

Used the metal-kernel skill to port the boolean comparison binary ops (`eq`, `ne`, `lt`, `le`, `gt`, `ge`) to native Metal kernels via the existing TensorIterator stub-dispatch path, dropping the MPSGraph-based implementations.

Each stub passes `kBool` as `natural_output_dtype` (the new contract introduced in pytorch#183055) so non-bool `out=` is correctly routed through the strided castout path. Stubs also pass `ilp_threshold = 1u << 18`, matching the floating-point default — measurably faster for small/medium tensors and avoids the 2b-param dispatch cliff in MPSGraph.

`torch.eq(a, b, out=c)` on M-series, default dispatcher (us/call, lower is better):

| numel | torch 2.11 (MPSGraph) | this PR | speedup |
|---|---|---|---|
| float32, 65K | 16.6 | 12.7 | 1.3x |
| float32, 262K | 111.5 | 18.6 | 6.0x |
| float32, 1M | 43.1 | 42.3 | 1.0x |
| float32, 16M | 601.7 | 632.6 | 0.95x |
| int32, 65K | 16.3 | 3.7 | 4.4x |
| int32, 262K | 16.4 | 5.2 | 3.2x |
| int32, 1M | 23.3 | 24.4 | 1.0x |
| int32, 16M | 613.1 | 606.2 | 1.0x |

Authored with assistance from Claude.
Pull Request resolved: pytorch#183019
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#183055
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Several MPS binary TensorIterator dispatcher fixes, plus tests.

**Scalar promotion shortcut** restricted to lossless int-scalar→float-common only. Was building wrong kernel names (`mul_dense_scalar_float2_float` for `complex_convolution`) and rounding float scalars on the host before launch (float16 CrossEntropyLoss drift). The `cast_suffix_type` selection now uses `iter.common_dtype()` (with a `kBool` branch for comparison ops) so cast-kernel name lookups match the post-promotion template instantiation. Fixes `cosine_similarity` `mps_float16` (`half.clamp_min_(float)`).

**`natural_output_dtype` contract on `exec_binary_kernel`** + new `binary_strided_castout` kernel template (with a `store_at_offs` helper). Default natural = `iter.dtype(0)`, so arithmetic ops dispatch through the existing `<DTYPEO>_<DTYPEI>` cast-kernel matrix as before. Ops whose kernel produces a fixed natural that may diverge from `iter.dtype(0)` (comparisons → `kBool`) declare it via the new parameter; the dispatcher then routes through `_strided_castout_<DTYPEO>_<DTYPEI>`, which computes at compile-time precision and runtime-casts on store. Castout is explicit opt-in via a separate `REGISTER_BINARY_CASTOUT_OP(NAME, DTYPEI, DTYPEO)` macro -- arithmetic ops don't pay binary size for unused kernels. Missing combos fail loudly via `getPipelineStateForFunc` rather than silent corruption. The contract is used by the comparison-ops migration in pytorch#183019 to fix `cdist` `mps_float32` (`linalg_vector_norm(p=0)` → `ne_outf(float, 0, float_out)`) and inductor `test_complex_from_real_imag_mps`.

**`C10_METAL_ALL_TYPES_FUNCTOR` extended** to `(EnumName, EnumValue, MetalType)`. `val_at_offs` and `store_at_offs` are generated from the same X-macro instead of hand-written per-type switches.

**Caller-tunable ILP threshold** via a new `ilp_threshold` parameter. Float-output default kept at 256K; non-float defaults off. `binary_dense_ilp` is `unsigned ILP`-templated and the unroll width appears in host names (`add_dense_ilp4_float_float`) so future `ilp8`/`ilp16` can coexist.

Tests: new `TestBinaryIteratorConformance` (two synthetic functors -- `simple_add` and `simple_ge` -- compiled via `MetalShaderLibrary` and dispatched through the same path real ops use; `simple_ge` opts into castout). Plus `test_binary_kernels` regressions for scalar precision and in-place narrowing.

Authored with assistance from Claude.
Pull Request resolved: pytorch#183055
Approved by: https://github.com/Skylion007
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
…al (pytorch#183019)

Used the metal-kernel skill to port the boolean comparison binary ops (`eq`, `ne`, `lt`, `le`, `gt`, `ge`) to native Metal kernels via the existing TensorIterator stub-dispatch path, dropping the MPSGraph-based implementations.

Each stub passes `kBool` as `natural_output_dtype` (the new contract introduced in pytorch#183055) so non-bool `out=` is correctly routed through the strided castout path. Stubs also pass `ilp_threshold = 1u << 18`, matching the floating-point default — measurably faster for small/medium tensors and avoids the 2b-param dispatch cliff in MPSGraph.

`torch.eq(a, b, out=c)` on M-series, default dispatcher (us/call, lower is better):

| numel | torch 2.11 (MPSGraph) | this PR | speedup |
|---|---|---|---|
| float32, 65K | 16.6 | 12.7 | 1.3x |
| float32, 262K | 111.5 | 18.6 | 6.0x |
| float32, 1M | 43.1 | 42.3 | 1.0x |
| float32, 16M | 601.7 | 632.6 | 0.95x |
| int32, 65K | 16.3 | 3.7 | 4.4x |
| int32, 262K | 16.4 | 5.2 | 3.2x |
| int32, 1M | 23.3 | 24.4 | 1.0x |
| int32, 16M | 613.1 | 606.2 | 1.0x |

Authored with assistance from Claude.
Pull Request resolved: pytorch#183019
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#183055
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Several MPS binary TensorIterator dispatcher fixes, plus tests.

**Scalar promotion shortcut** restricted to lossless int-scalar→float-common only. Was building wrong kernel names (`mul_dense_scalar_float2_float` for `complex_convolution`) and rounding float scalars on the host before launch (float16 CrossEntropyLoss drift). The `cast_suffix_type` selection now uses `iter.common_dtype()` (with a `kBool` branch for comparison ops) so cast-kernel name lookups match the post-promotion template instantiation. Fixes `cosine_similarity` `mps_float16` (`half.clamp_min_(float)`).

**`natural_output_dtype` contract on `exec_binary_kernel`** + new `binary_strided_castout` kernel template (with a `store_at_offs` helper). Default natural = `iter.dtype(0)`, so arithmetic ops dispatch through the existing `<DTYPEO>_<DTYPEI>` cast-kernel matrix as before. Ops whose kernel produces a fixed natural that may diverge from `iter.dtype(0)` (comparisons → `kBool`) declare it via the new parameter; the dispatcher then routes through `_strided_castout_<DTYPEO>_<DTYPEI>`, which computes at compile-time precision and runtime-casts on store. Castout is explicit opt-in via a separate `REGISTER_BINARY_CASTOUT_OP(NAME, DTYPEI, DTYPEO)` macro -- arithmetic ops don't pay binary size for unused kernels. Missing combos fail loudly via `getPipelineStateForFunc` rather than silent corruption. The contract is used by the comparison-ops migration in pytorch#183019 to fix `cdist` `mps_float32` (`linalg_vector_norm(p=0)` → `ne_outf(float, 0, float_out)`) and inductor `test_complex_from_real_imag_mps`.

**`C10_METAL_ALL_TYPES_FUNCTOR` extended** to `(EnumName, EnumValue, MetalType)`. `val_at_offs` and `store_at_offs` are generated from the same X-macro instead of hand-written per-type switches.

**Caller-tunable ILP threshold** via a new `ilp_threshold` parameter. Float-output default kept at 256K; non-float defaults off. `binary_dense_ilp` is `unsigned ILP`-templated and the unroll width appears in host names (`add_dense_ilp4_float_float`) so future `ilp8`/`ilp16` can coexist.

Tests: new `TestBinaryIteratorConformance` (two synthetic functors -- `simple_add` and `simple_ge` -- compiled via `MetalShaderLibrary` and dispatched through the same path real ops use; `simple_ge` opts into castout). Plus `test_binary_kernels` regressions for scalar precision and in-place narrowing.

Authored with assistance from Claude.
Pull Request resolved: pytorch#183055
Approved by: https://github.com/Skylion007
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…al (pytorch#183019)

Used the metal-kernel skill to port the boolean comparison binary ops (`eq`, `ne`, `lt`, `le`, `gt`, `ge`) to native Metal kernels via the existing TensorIterator stub-dispatch path, dropping the MPSGraph-based implementations.

Each stub passes `kBool` as `natural_output_dtype` (the new contract introduced in pytorch#183055) so non-bool `out=` is correctly routed through the strided castout path. Stubs also pass `ilp_threshold = 1u << 18`, matching the floating-point default — measurably faster for small/medium tensors and avoids the 2b-param dispatch cliff in MPSGraph.

`torch.eq(a, b, out=c)` on M-series, default dispatcher (us/call, lower is better):

| numel | torch 2.11 (MPSGraph) | this PR | speedup |
|---|---|---|---|
| float32, 65K | 16.6 | 12.7 | 1.3x |
| float32, 262K | 111.5 | 18.6 | 6.0x |
| float32, 1M | 43.1 | 42.3 | 1.0x |
| float32, 16M | 601.7 | 632.6 | 0.95x |
| int32, 65K | 16.3 | 3.7 | 4.4x |
| int32, 262K | 16.4 | 5.2 | 3.2x |
| int32, 1M | 23.3 | 24.4 | 1.0x |
| int32, 16M | 613.1 | 606.2 | 1.0x |

Authored with assistance from Claude.
Pull Request resolved: pytorch#183019
Approved by: https://github.com/Skylion007
ghstack dependencies: pytorch#183055
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