Skip to content

[MPS] fix older gpu gen mac matmul failures - #183535

Closed
Isalia20 wants to merge 7 commits into
pytorch:mainfrom
Isalia20:fix-m2-linear-failure
Closed

Isalia20 wants to merge 7 commits into
pytorch:mainfrom
Isalia20:fix-m2-linear-failure

Conversation

@Isalia20

@Isalia20 Isalia20 commented May 13, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #177116

Another MPS Graph issue...

To explain it shortly: on M1/M2 (Apple7/8 GPUs), the MPSGraph matmul kernel reads past the end of the K (reduction) dimension once K > 32768, when both GEMM output dims M and N are >= 16. Each output element is a K-term dot product and the kernel sums a few extra terms beyond K, using whatever data happens to sit in memory past the operands.

Performance below is just to show that there are no regressions, any kind of speedup that we see below can just be attributed to noise since we are running effectively the same function for backwards (just dispatched with mm instead of having graph inside of the backward)

Performance for backward on base M2:
input shape weight shape bias function before us after us speedup
(128, 64) (32, 64) no _mps_linear_backward_input 39.3 39.7 0.99x
(128, 64) (32, 64) no _mps_linear_backward_weights 45.1 41.4 1.09x
(2, 3, 4, 5, 64) (32, 64) yes _mps_linear_backward_input 51.0 40.8 1.25x
(2, 3, 4, 5, 64) (32, 64) yes _mps_linear_backward_weights 50.9 46.4 1.10x
(32000, 128) (16, 128) yes _mps_linear_backward_input 176.2 176.5 1.00x
(32000, 128) (16, 128) yes _mps_linear_backward_weights 663.6 665.2 0.99x
(512, 1024) (1024, 1024) yes _mps_linear_backward_input 380.5 382.7 0.99x
(512, 1024) (1024, 1024) yes _mps_linear_backward_weights 411.7 406.9 1.01x
(64, 128) (256, 128) yes _mps_linear_backward_input 41.2 41.7 0.99x
(64, 128) (256, 128) yes _mps_linear_backward_weights 53.0 49.9 1.06x
(8, 128) (40000, 128) yes _mps_linear_backward_input 339.7 341.1 1.00x
(8, 128) (40000, 128) yes _mps_linear_backward_weights 577.9 578.9 1.00x
(8, 512, 768) (3072, 768) yes _mps_linear_backward_input 6530.9 6529.4 1.00x
(8, 512, 768) (3072, 768) yes _mps_linear_backward_weights 7304.7 7269.9 1.00x
(8, 512, 768) (768, 768) yes _mps_linear_backward_input 1692.4 1692.1 1.00x
(8, 512, 768) (768, 768) yes _mps_linear_backward_weights 1927.4 1880.9 1.02x
Performance for backward on M5 Pro:
input shape weight shape bias function before us after us speedup
(128, 64) (32, 64) no _mps_linear_backward_input 32.8 32.1 1.02x
(128, 64) (32, 64) no _mps_linear_backward_weights 38.2 33.9 1.13x
(2, 3, 4, 5, 64) (32, 64) yes _mps_linear_backward_input 36.7 33.2 1.11x
(2, 3, 4, 5, 64) (32, 64) yes _mps_linear_backward_weights 46.2 40.4 1.14x
(32000, 128) (16, 128) yes _mps_linear_backward_input 68.3 67.1 1.02x
(32000, 128) (16, 128) yes _mps_linear_backward_weights 142.2 135.5 1.05x
(512, 1024) (1024, 1024) yes _mps_linear_backward_input 213.6 212.9 1.00x
(512, 1024) (1024, 1024) yes _mps_linear_backward_weights 221.8 216.7 1.02x
(64, 128) (256, 128) yes _mps_linear_backward_input 33.6 34.1 0.98x
(64, 128) (256, 128) yes _mps_linear_backward_weights 45.4 40.0 1.14x
(8, 128) (40000, 128) yes _mps_linear_backward_input 227.6 230.4 0.99x
(8, 128) (40000, 128) yes _mps_linear_backward_weights 226.4 220.4 1.03x
(8, 512, 768) (768, 768) yes _mps_linear_backward_input 837.9 833.1 1.01x
(8, 512, 768) (768, 768) yes _mps_linear_backward_weights 912.6 908.6 1.00x
(8, 512, 768) (3072, 768) yes _mps_linear_backward_input 3270.6 3264.4 1.00x
(8, 512, 768) (3072, 768) yes _mps_linear_backward_weights 3490.9 3463.4 1.01x

@pytorch-bot pytorch-bot Bot added ciflow/mps Run MPS tests (subset of trunk) release notes: mps Release notes category labels May 13, 2026
@pytorch-bot

pytorch-bot Bot commented May 13, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ No Failures

As of commit 4c27440 with merge base 08fe091 (image):
💚 Looks good so far! There are no failures yet. 💚

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

@Isalia20
Isalia20 marked this pull request as ready for review May 27, 2026 21:21
@Isalia20
Isalia20 requested a review from malfet as a code owner May 27, 2026 21:21
@Isalia20 Isalia20 added the topic: bug fixes topic category label May 27, 2026
@drisspg drisspg added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 29, 2026

@malfet malfet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please don't land it as is, as linear operator expects weights to be in CM order, compared to MM where default order for both operands are probably RM

Isalia20 added 2 commits July 25, 2026 22:43
The "refusing to merge unrelated histories" error was a shallow-clone
artifact, not a genuine lack of common ancestry: this worktree's object
store was shallow, and main's history was truncated at 2026-06-08, a
month after this branch's base (681fe45, 2026-05-06). Deepening main
past the branch point exposed the real merge base.

Upstream landed eight commits on Linear.mm since the branch point,
including this branch's own AppleGPUFamily / is_apple_family_or_newer
helper and the is_macos_13_or_newer -> is_macos_at_least rename. The
resolution keeps this branch's at::mm routing (the M1/M2 K > 2^15 fix)
and layers upstream's orthogonal empty-tensor semantics on top. Three
resolution decisions worth reviewing, in this order:

In the forward path, upstream's in_features == 0 early-out is placed
before the K-overflow fallback; the two conditions are mutually
exclusive, so the order only matters for the degenerate shape.

In _mps_linear_backward_input, upstream's MPSGraph implementation is
dropped in favor of at::mm, but its empty guard is kept and widened to
cover an empty grad-input (in_features == 0), which at::mm cannot take.
Upstream's macOS 27 in-graph-reshape workaround goes away with the graph
it guarded.

In _mps_linear_backward_weights, the degenerate guard moves above the 2D
reshapes: this branch computed input_2d first, and reshape({-1, 0})
throws for a 0-element input. The bias gradient is still the sum over
leading dims when grad_output is non-empty.

use_metal_mm drops the now-dead is_macos_14_4_or_newer declaration that
this branch replaced with a GPU-family gate. Separately, the auto-merge
silently duplicated the AppleGPUFamily enum in MPSDevice.h, since both
sides added it at different offsets; the duplicate is removed.

Test Plan:

Not built or run yet. This merge brings in 3908 upstream commits, so it
needs a full rebuild before the MPS tests mean anything:

  pip install -e . -v --no-build-isolation
  cmake --install build --prefix $PWD/torch
  python test/test_mps.py -k linear
  python test/test_mps.py -k test_linear_large_K

Verified so far without building: no conflict markers remain, no stale
pre-rename API references (is_macos_13_or_newer, MACOS_VER_*_PLUS,
MTLGPUFamilyApple10), no duplicate definitions in the resolved files,
no merge-introduced duplicate test names in test_mps.py, clang
diagnostics clean on all four files, and lintrunner reports no issues.
@malfet malfet added the module: regression It used to work, and now it doesn't label Aug 7, 2026

@malfet malfet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please rebase and also run some sort of a benchmark on a newer MacOS that shows that those are somewhat comparable barring the bias

On Apple7/8 GPUs, MPSGraph matmul intermittently corrupts results when
the GEMM reduction dimension K exceeds 2^15 and both output dimensions
are at least 16. The corruption is allocator/session-state dependent
(the same shape can pass in one process and fail reproducibly in
another, with relative errors up to 2.3) and affects fully contiguous
operands as well as transposed ones. Shapes where only M or N is large,
or where either output dimension is below 16, never failed across
shape sweeps, repeated trials, and allocator-perturbed trials.

The previous condition diverted any operand with a size or stride over
2^15 to the Metal kernels, which routed many correct-on-MPSGraph shapes
(large batch rows in forward and grad_input, large out_features) to the
slower fallback: 3.3x on the issue-realistic grad_input, 6.8x on
large-N grad_input, ~19x on a small-output large-K forward. Narrowing
the trigger to K > 32768 && m >= 16 && n >= 16 keeps every previously
corrupt shape on the Metal path while returning the already-correct
shapes to MPSGraph (measured within noise of their pre-fallback
timings).

This also restores the pre-macOS-14.4 broad size-or-stride fallback for
all GPU families, which the earlier commit had replaced with the
GPU-family gate; before 14.4 the overflow bug is an OS-level issue that
is not limited to Apple7/8.

An alternative was to keep per-shape guards inside the linear backward
functions, but since those now route through at::mm unconditionally,
use_metal_mm is the single decision point and only the two predicates
needed to change. Note torch.bmm does not consult use_metal_mm and
still lacks a large-K fallback on Apple7/8; that pre-existing gap is
left for a follow-up.

The failure-region boundary was characterized empirically on an M2
(Apple8, macOS 26.3); the K boundary flips exactly at 32769, and the
min-output-dim boundary of 16 never produced a failure below it. M1
(Apple7) is assumed to behave the same but was not tested on hardware.

Test Plan:

```
python test/test_mps.py -k test_linear_large_K
python test/test_mps.py -k linear
```

2 passed; 178 passed, 12 skipped, 6 expected failures (identical to
baseline). Also verified on M2 hardware: an 84-case correctness matrix
over mm/linear forward and backward in fp32/fp16/bf16 including
boundary, empty, non-contiguous, and 5D shapes; a contiguous mm sweep
over K in {32769..66000} x m in {8..122} x n in {8..128} (35 failures
before, 0 after); 24 allocator-perturbed trials per boundary shape
(worst case 15/24 failures before, 0/24 after); and the issue pytorch#177116
reproduction (gradient ratio vs CPU 1.0000000393, loss error 0).

Authored with the assistance of an AI agent (Claude).
@Isalia20

Isalia20 commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -f "Lint and 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

ankitbhrdwj pushed a commit to ankitbhrdwj/pytorch that referenced this pull request Aug 12, 2026
Fixes pytorch#177116

Another MPS Graph issue...

To explain it shortly: on M1/M2 (Apple7/8 GPUs), the MPSGraph matmul kernel reads past the end of the K (reduction) dimension once K > 32768, when both GEMM output dims M and N are >= 16. Each output element is a K-term dot product and the kernel sums a few extra terms beyond K, using whatever data happens to sit in memory past the operands.

Performance below is just to show that there are no regressions, any kind of speedup that we see below can just be attributed to noise since we are running effectively the same function for backwards (just dispatched with mm instead of having graph inside of the backward)

<details>
<summary> Performance for backward on base M2:</summary>

| input shape | weight shape | bias | function | before us | after us | speedup |
|---|---|---|---|---|---|---|
| (128, 64) | (32, 64) | no | _mps_linear_backward_input | 39.3 | 39.7 | 0.99x |
| (128, 64) | (32, 64) | no | _mps_linear_backward_weights | 45.1 | 41.4 | 1.09x |
| (2, 3, 4, 5, 64) | (32, 64) | yes | _mps_linear_backward_input | 51.0 | 40.8 | 1.25x |
| (2, 3, 4, 5, 64) | (32, 64) | yes | _mps_linear_backward_weights | 50.9 | 46.4 | 1.10x |
| (32000, 128) | (16, 128) | yes | _mps_linear_backward_input | 176.2 | 176.5 | 1.00x |
| (32000, 128) | (16, 128) | yes | _mps_linear_backward_weights | 663.6 | 665.2 | 0.99x |
| (512, 1024) | (1024, 1024) | yes | _mps_linear_backward_input | 380.5 | 382.7 | 0.99x |
| (512, 1024) | (1024, 1024) | yes | _mps_linear_backward_weights | 411.7 | 406.9 | 1.01x |
| (64, 128) | (256, 128) | yes | _mps_linear_backward_input | 41.2 | 41.7 | 0.99x |
| (64, 128) | (256, 128) | yes | _mps_linear_backward_weights | 53.0 | 49.9 | 1.06x |
| (8, 128) | (40000, 128) | yes | _mps_linear_backward_input | 339.7 | 341.1 | 1.00x |
| (8, 128) | (40000, 128) | yes | _mps_linear_backward_weights | 577.9 | 578.9 | 1.00x |
| (8, 512, 768) | (3072, 768) | yes | _mps_linear_backward_input | 6530.9 | 6529.4 | 1.00x |
| (8, 512, 768) | (3072, 768) | yes | _mps_linear_backward_weights | 7304.7 | 7269.9 | 1.00x |
| (8, 512, 768) | (768, 768) | yes | _mps_linear_backward_input | 1692.4 | 1692.1 | 1.00x |
| (8, 512, 768) | (768, 768) | yes | _mps_linear_backward_weights | 1927.4 | 1880.9 | 1.02x |

</details>

<details>

<summary> Performance for backward on M5 Pro:</summary>

| input shape | weight shape | bias | function | before us | after us | speedup |
|---|---|---|---|---|---|---|
| (128, 64) | (32, 64) | no | _mps_linear_backward_input | 32.8 | 32.1 | 1.02x |
| (128, 64) | (32, 64) | no | _mps_linear_backward_weights | 38.2 | 33.9 | 1.13x |
| (2, 3, 4, 5, 64) | (32, 64) | yes | _mps_linear_backward_input | 36.7 | 33.2 | 1.11x |
| (2, 3, 4, 5, 64) | (32, 64) | yes | _mps_linear_backward_weights | 46.2 | 40.4 | 1.14x |
| (32000, 128) | (16, 128) | yes | _mps_linear_backward_input | 68.3 | 67.1 | 1.02x |
| (32000, 128) | (16, 128) | yes | _mps_linear_backward_weights | 142.2 | 135.5 | 1.05x |
| (512, 1024) | (1024, 1024) | yes | _mps_linear_backward_input | 213.6 | 212.9 | 1.00x |
| (512, 1024) | (1024, 1024) | yes | _mps_linear_backward_weights | 221.8 | 216.7 | 1.02x |
| (64, 128) | (256, 128) | yes | _mps_linear_backward_input | 33.6 | 34.1 | 0.98x |
| (64, 128) | (256, 128) | yes | _mps_linear_backward_weights | 45.4 | 40.0 | 1.14x |
| (8, 128) | (40000, 128) | yes | _mps_linear_backward_input | 227.6 | 230.4 | 0.99x |
| (8, 128) | (40000, 128) | yes | _mps_linear_backward_weights | 226.4 | 220.4 | 1.03x |
| (8, 512, 768) | (768, 768) | yes | _mps_linear_backward_input | 837.9 | 833.1 | 1.01x |
| (8, 512, 768) | (768, 768) | yes | _mps_linear_backward_weights | 912.6 | 908.6 | 1.00x |
| (8, 512, 768) | (3072, 768) | yes | _mps_linear_backward_input | 3270.6 | 3264.4 | 1.00x |
| (8, 512, 768) | (3072, 768) | yes | _mps_linear_backward_weights | 3490.9 | 3463.4 | 1.01x |

</details>
Pull Request resolved: pytorch#183535
Approved by: https://github.com/malfet
scott-kirila added a commit to scott-kirila/pytorch that referenced this pull request Aug 27, 2026
…0 on the Metal fallbacks

On M1/M2 (Apple7/8) the MPS matmul kernels can read past the end of both
operands when the reduction dimension is 32767 or longer, on the shapes that
use the tiled kernels (both output dims at least 16): the last K tile is not
clipped, so whatever sits in memory after the operands is summed into the
result. Most such shapes over-read; a few tile-aligned ones do not. Which calls
misbehave also depends on neighboring memory (freshly zeroed memory hides it),
so the failures look intermittent. pytorch#183535 routed the 2-D paths (mm/addmm/linear) to PyTorch's own
Metal kernels for this, but bmm/baddbmm/addbmm, and therefore 3-D matmul and
einsum, still go through MPSGraph and return silently wrong results on
current main. Its threshold (K > 32768) is also off by one: K = 32767 is
wrong by exactly one term on every kernel variant measured, and K = 32768
only passes because that value happens to split evenly.

The condition now lives in one inline helper, mps_matmul_overreads_k, used by
use_metal_mm, _mps_linear, bmm_out_mps_impl and addbmm_or_baddbmm_out_mps_impl,
with the threshold corrected to K >= 32767. Routing float shapes to
do_metal_addbmm_or_baddbmm exposed that the Metal fallbacks compute beta*bias
literally, so beta=0 propagated nan/inf from a bias that the documented
contract says is ignored (CPU and the MPSGraph path do ignore it); do_metal_addmm had the same hole for the default integer
alpha. Both now substitute a zero bias when beta is zero, and do_metal_addmm's
shortcut compares scalar values rather than scalar types.

Alternative considered: chunking K into <= 32766 pieces through MPSGraph and
summing measures at about the cost of the single MPSGraph call on the affected
shapes (0.6x-1.2x), against the naive Metal kernels' ~8x, so it is the faster
option. This change routes to the Metal kernels anyway: it keeps bmm/baddbmm
consistent with how pytorch#183535 already handles mm/addmm/linear, stays small, and
leaves one condition to relax if Apple fixes the kernels. Chunked-K is a
reasonable follow-up if the cost matters.

Affected shapes only (Apple7/8, K >= 32767, m, n >= 16), M2 Max, ms per call:
  bmm (2,25,40000)@(2,40000,25):    MPSGraph 0.32 (wrong) -> Metal 2.45
  bmm (2,256,50257)@(2,50257,768):  MPSGraph 4.4  (wrong) -> Metal 36
  bmm (8,512,40000)@(8,40000,64):   MPSGraph 2.3  (wrong) -> Metal 20

Fixes pytorch#193487. Related: pytorch#177116, pytorch#183535. Apple Feedback FB24518264.
Kernel-level analysis and a standalone reproducer:
https://scottkirila.studio.site/blog/kernel-bug

Test Plan:

On an M2 Max, macOS 26.6.2, source build of this branch:

```
python test/test_mps.py -k test_batched_matmul_large_K -k test_linear_large_K -k test_matmul_large_K_beta_zero -v
```

9/9 pass. The body of test_batched_matmul_large_K, run against the unpatched
2.15.0.dev20260821 nightly, fails all four cases (max abs diff 17.6 against a
1e-3 tolerance), and the addmm case of test_matmul_large_K_beta_zero returns
nan there. The batched test relies on a 20 MB fill buffer landing after the
operands, which cannot be guaranteed from Python, so on some allocator states
it may pass without the fix; the beta=0 test is deterministic.

```
python test/test_mps.py -k bmm -k matmul -k einsum -k linear -k addmm -k test_mm -k mv -k tensordot
```

516 tests, one failure: TestConsistencyMPS.test_mm_stride_zero_mps, which
fails identically on the unpatched nightly (K = 1, not touched by this change;
the pytorch#180201 fix appears not to hold on macOS 26.6.2).

Also checked against CPU on the routed path: fp16/bf16, transposed and
broadcast batch operands, alpha/beta values, batch=64, K=32766 (unrouted),
autograd through bmm; and a 124M-parameter GPT-2 training run whose
output-layer gradient (K = 50257) previously diverged now matches CPU to
6e-7 relative error.

Written with the help of an AI assistant (Claude); the author reviewed and
tested every change.

Co-Authored-By: Claude Fable 5 <[email protected]>
scott-kirila added a commit to scott-kirila/pytorch that referenced this pull request Aug 28, 2026
On M1/M2 (Apple7/8) the MPS matmul kernels can read past the end of both
operands when the reduction dimension is 32767 or longer, on the shapes that
use the tiled kernels (both output dims at least 16): the last K tile is not
clipped, so whatever sits in memory after the operands is summed into the
result. Most such shapes over-read; a few tile-aligned ones do not. Which calls
misbehave also depends on neighboring memory (freshly zeroed memory hides it),
so the failures look intermittent. pytorch#183535 routed the 2-D paths (mm/addmm/linear) to PyTorch's own
Metal kernels for this, but bmm/baddbmm/addbmm, and therefore 3-D matmul and
einsum, still go through MPSGraph and return silently wrong results on
current main. Its threshold (K > 32768) is also off by one: K = 32767 is
wrong by exactly one term on every kernel variant measured, and K = 32768
only passes because that value happens to split evenly.

The condition now lives in one inline helper, mps_matmul_overreads_k, used by
use_metal_mm, _mps_linear, bmm_out_mps_impl and addbmm_or_baddbmm_out_mps_impl,
with the threshold corrected to K >= 32767.

Alternative considered: chunking K into <= 32766 pieces through MPSGraph and
summing measures at about the cost of the single MPSGraph call on the affected
shapes (0.6x-1.2x), against the naive Metal kernels' ~8x, so it is the faster
option. This change routes to the Metal kernels anyway: it keeps bmm/baddbmm
consistent with how pytorch#183535 already handles mm/addmm/linear, stays small, and
leaves one condition to relax if Apple fixes the kernels. Chunked-K is a
reasonable follow-up if the cost matters.

Affected shapes only (Apple7/8, K >= 32767, m, n >= 16), M2 Max, ms per call:
  bmm (2,25,40000)@(2,40000,25):    MPSGraph 0.32 (wrong) -> Metal 2.45
  bmm (2,256,50257)@(2,50257,768):  MPSGraph 4.4  (wrong) -> Metal 36
  bmm (8,512,40000)@(8,40000,64):   MPSGraph 2.3  (wrong) -> Metal 20

Fixes pytorch#195163. Related: pytorch#193487, pytorch#177116, pytorch#183535. Apple Feedback FB24518264.
Kernel-level analysis and a standalone reproducer:
https://scottkirila.studio.site/blog/kernel-bug

Test Plan:

On an M2 Max, macOS 26.6.2, source build of this branch:

```
python test/test_mps.py -k test_batched_matmul_large_K -k test_linear_large_K -v
```

6/6 pass. The body of test_batched_matmul_large_K, run against the unpatched
2.15.0.dev20260821 nightly, fails all four cases (max abs diff 17.6 against a
1e-3 tolerance). The batched test relies on a 20 MB fill buffer landing after
the operands, which cannot be guaranteed from Python, so on some allocator
states it may pass without the fix.

```
python test/test_mps.py -k bmm -k matmul -k einsum -k linear -k addmm -k test_mm -k mv -k tensordot
```

516 tests, one failure: TestConsistencyMPS.test_mm_stride_zero_mps, which
fails identically on the unpatched nightly (K = 1, not touched by this change;
the pytorch#180201 fix appears not to hold on macOS 26.6.2).

Also checked against CPU on the routed path: fp16/bf16, transposed and
broadcast batch operands, alpha/beta values, batch=64, K=32766 (unrouted),
autograd through bmm; and a 124M-parameter GPT-2 training run whose
output-layer gradient (K = 50257) previously diverged now matches CPU to
6e-7 relative error.

Written with the help of an AI assistant (Claude); the author reviewed and
tested every change.

Co-Authored-By: Claude Fable 5 <[email protected]>
scott-kirila added a commit to scott-kirila/pytorch that referenced this pull request Aug 28, 2026
On M1/M2 (Apple7/8) the MPS matmul kernels can read past the end of both
operands when the reduction dimension is 32767 or longer, on the shapes that
use the tiled kernels (both output dims at least 16): the last K tile is not
clipped, so whatever sits in memory after the operands is summed into the
result. Most such shapes over-read; a few tile-aligned ones do not. Which calls
misbehave also depends on neighboring memory (freshly zeroed memory hides it),
so the failures look intermittent. pytorch#183535 routed the 2-D paths (mm/addmm/linear) to PyTorch's own
Metal kernels for this, but bmm/baddbmm/addbmm, and therefore 3-D matmul and
einsum, still go through MPSGraph and return silently wrong results on
current main. Its threshold (K > 32768) is also off by one: K = 32767 is
wrong by exactly one term on every kernel variant measured, and K = 32768
only passes because that value happens to split evenly.

The condition now lives in one inline helper, mps_matmul_overreads_k, used by
use_metal_mm, _mps_linear, bmm_out_mps_impl and addbmm_or_baddbmm_out_mps_impl,
with the threshold corrected to K >= 32767.

Alternative considered: chunking K into <= 32766 pieces through MPSGraph and
summing measures at about the cost of the single MPSGraph call on the affected
shapes (1.0x-1.3x), against the naive Metal kernels' ~8x, so it is the faster
option. This change routes to the Metal kernels anyway: it keeps bmm/baddbmm
consistent with how pytorch#183535 already handles mm/addmm/linear, stays small, and
leaves one condition to relax if Apple fixes the kernels. Chunked-K is a
reasonable follow-up if the cost matters.

Affected shapes only (Apple7/8, K >= 32767, m, n >= 16), M2 Max, ms per call:
  bmm (2,25,40000)@(2,40000,25):    MPSGraph 0.32 (wrong) -> Metal 2.45
  bmm (2,256,50257)@(2,50257,768):  MPSGraph 4.4  (wrong) -> Metal 36
  bmm (8,512,40000)@(8,40000,64):   MPSGraph 2.3  (wrong) -> Metal 20

Fixes pytorch#195163. Related: pytorch#193487, pytorch#177116, pytorch#183535. Apple Feedback FB24518264.
Kernel-level analysis and a standalone reproducer:
https://scottkirila.studio.site/blog/kernel-bug

Test Plan:

On an M2 Max, macOS 26.6.2, source build of this branch:

```
python test/test_mps.py -k test_batched_matmul_large_K -k test_linear_large_K -v
```

6/6 pass. The body of test_batched_matmul_large_K, run against the unpatched
2.15.0.dev20260821 nightly, fails all four cases (max abs diff 17.6 against a
1e-3 tolerance). The batched test relies on a 20 MB fill buffer landing after
the operands, which cannot be guaranteed from Python, so on some allocator
states it may pass without the fix.

```
python test/test_mps.py -k bmm -k matmul -k einsum -k linear -k addmm -k test_mm -k mv -k tensordot
```

513 tests, one failure: TestConsistencyMPS.test_mm_stride_zero_mps, which
fails identically on the unpatched nightly (K = 1, not touched by this change;
the pytorch#180201 fix appears not to hold on macOS 26.6.2).

Also checked against CPU on the routed path: fp16/bf16, transposed and
broadcast batch operands, alpha/beta values, batch=64, K=32766 (unrouted),
autograd through bmm; and a 124M-parameter GPT-2 training run whose
output-layer gradient (K = 50257) previously diverged now matches CPU to
6e-7 relative error.

Written with the help of an AI assistant (Claude); the author reviewed and
tested every change.

Co-Authored-By: Claude Fable 5 <[email protected]>
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 module: regression It used to work, and now it doesn't open source release notes: mps Release notes category topic: bug fixes topic category triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MPS: catastrophically wrong gradients in backward pass (>32K elements)

5 participants