#4522·kornia

MPS on torch nightly 2.15: missing linalg_eig, a clamp_min process abort, uint16 comparisons, linalg.qr hang, and the kernels slower than the M1 CPU (findings for the PyTorch MPS team)

Author: ducha-aikiCreated Sep 14, 2026Updated Sep 28, 2026

Summary

Findings from a kornia-wide audit of Apple MPS on torch nightly 2.15.0.dev20260913 (Apple M1, 8 GB, macOS 26.5.1, PYTORCH_ENABLE_MPS_FALLBACK unset, kornia 633951bd7), collected here for the PyTorch MPS team. Two methods: (1) a TorchDispatchMode pytest plugin ran kornia's whole CPU suite at float32 and float64 and replayed every new aten signature on MPS — 365 aten overloads, 66,244 distinct (op, shapes, dtypes, scalars) signatures, each replay classified as ok / NotImplementedError / other exception / numeric mismatch; (2) 292 public kornia ops were timed on CPU and MPS at 2–4 shapes each (924 device pairs, torch.utils.benchmark medians, mps.synchronize inside the timed region), every large-shape loss was attributed to individual aten calls by replaying them in isolation, and each culprit kernel was reproduced standalone at several sizes. Every non-ok replay and every headline timing was re-checked in a fresh process. The kornia-side follow-ups (device bugs, avoidable slow paths in kornia code) are in #4521; this issue is only what PyTorch could act on.

1. Missing or broken

# aten op MPS nightly CPU how kornia reaches it
1 aten::linalg_eig, aten::_linalg_eigvals NotImplementedError: The operator 'aten::linalg_eig' is not currently implemented for the MPS device fine find_essential (5-point Nistér, non-symmetric (B,10,10) companion matrix, complex eigenvalues), RANSAC(model_type="essential"). The only op the whole suite found missing outright.
2 aten::clamp_min (and clamp/clamp_max) with a Python float outside float32 range on a float32 tensor libc++abi: terminating due to uncaught exception of type std::runtime_error: value cannot be converted to type float without overflow → SIGABRT, the process dies raises a catchable RuntimeError with the same text any float64-derived bound such as torch.finfo(torch.float64).min meeting a float32 tensor. torch.full_like(x_f32, 1.8e308) raises cleanly on both devices, so the throw escapes only from the clamp kernel's scalar conversion.
3 uint16 comparisons: aten::eq, aten::ne, aten::lt, torch.equal RuntimeError: Failed to create function state object for: eq_dense_bool_ushort (also eq_strided_bool_ushort, ne_…, lt_…) fine 16-bit PNG/TIFF loaded with ImageLoadType.UNCHANGED and moved to MPS. uint8 / int16 / int32 comparisons work.
4 aten::linalg_qr pathologically slow, then hangs, wrong result at one size, and the machine hard-reset — see below fine 4-point homography minimal path (complete QR of (B, 9, 8)), solve_pnp_dlt (3x3 RQ), nn.init.orthogonal_ in HardNet8 when constructed on MPS

Repros for 2 and 3:

python
import torch
x = torch.zeros(3, device="mps")
torch.full_like(x, 1.7976931348623157e+308)   # RuntimeError on cpu and mps alike
x.clamp_min(-1.7976931348623157e+308)         # cpu: RuntimeError; mps: libc++abi terminate -> SIGABRT

a = torch.randint(0, 100, (3, 4, 5), dtype=torch.int32).to(torch.uint16).to("mps")
torch.eq(a, a.clone())                        # RuntimeError: Failed to create function state object for: eq_dense_bool_ushort

torch.linalg.qr — observed, not fully characterised (it reset the machine)

Float32 contiguous torch.randn(m, n, device="mps"), one process per size:

| shape | wall time | max|QR − A| | |---|---|---| | (512, 512) | 14.1 s (CPU ≈ 10 ms) | 3.6e-5 | | (2048, 512) | killed by a 90 s timer | – | | (8192, 512) | killed by a 90 s timer | – | | (16384, 512) | 66 s | 5.47 — wrong (randn input; CPU ≈ 1e-5) | | next 512² matmul, fresh process | machine hard-reset | – |

Inside the pytest replay the same op on a non-contiguous (16384, 512) tensor sat at 0 % CPU for over 10 minutes and a different process's .to("mps") of a 2x2 tensor blocked for the duration, i.e. the GPU queue was wedged machine-wide. The large shape finishing faster than the medium ones, with garbage, suggests a size-dependent path switch. Reproducer, smallest size first, one size per process, on a machine you can afford to lose for a minute:

python
# qr_probe.py  —  perl -e 'alarm shift; exec @ARGV' 120 python qr_probe.py 512,512
import sys, time, warnings, torch
m, n = (int(v) for v in sys.argv[1].split(","))
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    a = torch.randn(m, n, device="mps"); torch.mps.synchronize()
    t = time.time(); q, r = torch.linalg.qr(a); torch.mps.synchronize(); dt = time.time() - t
    err = (q @ r - a).abs().max().item()
print(f"({m},{n}) mps qr {dt:.3f} s  recon max|QR-A| {err:.3g}", [str(x.message)[:120] for x in w])

The small batched shapes kornia actually uses ((B, 9, 8) mode="complete" with B ≤ 2048, (B, 3, 3)) were not timed after the reset and may be fine.

2. Per-kernel launch cost (why every small op loses to the M1 CPU)

(1,3,64,64) float32, torch.utils.benchmark medians:

measurement MPS CPU
torch.mps.synchronize() with nothing queued 0.1 µs –
one x + 1 + synchronize 268–332 µs 2.7 µs
10 chained adds + one synchronize 525 µs (52 µs / kernel) 29 µs
100 chained adds + one synchronize 1694 µs (17 µs / kernel) 283 µs

≈ 250 µs per command-buffer commit + wait and ≈ 15–20 µs per additional encoded kernel, versus ≈ 3 µs per op on the CPU. 485 of the 924 (kornia op, shape) pairs were slower on MPS, and almost all of them are simply < 1–2 ms of CPU work at 64²/256². Everything below is what remains after discounting that floor: kernels slower than the CPU on the same inputs at sizes where the CPU takes ≥ 1 ms.

3. Kernels slower than the M1 CPU (standalone repros, fresh processes)

kernel standalone evidence (MPS vs CPU) kornia op that hits it (largest shape measured)
aten::bincount with few bins minlength=16: 96–120x slower at 64k / 1M / 8M elements (757 ms at 8M); minlength=1024: 2–3.6x. Atomic contention on a handful of bins. metrics.confusion_matrix, mean_iou (4 classes, 1024²): 2.8 ms → 92.7 ms
aten::histc 256 bins: 20–29x slower at 64k–1M; a 1024-element histogram costs 359 µs (CPU 5 µs); 8M elements: Invalid buffer size: 8.00 GiB enhance.equalize_clahe 1024²: 36.5 ms → 244 ms (192 tile histograms per 256² RGB image)
reduction over the trailing two dims x.sum(dim=(-2,-1)) on (1,3,1024,1024): 5.05 ms vs 0.21 ms (24x), while x.sum() = 0.51 ms and x.sum(dim=-1) = 0.50 ms on MPS; 70x at 256². amax(dim=(4,5)) on a (1,3,S,S,k,k) window tensor: 60–71x on both stride-preserved and contiguous layouts. losses.total_variation 1024²: 5.5 ms → 11.7 ms; morphology unfold engine
single-dim reduction with a short innermost dim max(dim=4) on (1,3,256,256,k,k): 1.8–3.9x slower on the stride-preserved add output, 1.1–5x on a contiguous copy when the innermost dim is 3–7 wide; the same reduction with a 65536-long inner dim ((1,3,49,65536), dim=2) is 10x faster on MPS morphology.dilation/erosion/... 1024² k3–k15: 1.5–2.1x slower
aten::median.dim / sort along a short last dim 9-wide rows, 3M rows: 500 ms ≈ 18 ns/element vs 373 ms CPU; 49- and 121-wide rows: 35–45 ms ≈ 1.5–2 ns/element, 4–17x faster than CPU — a large per-row cost filters.median_blur k3 at every shape 1.1–1.5x slower; k7/k11 3–5x faster
aten::mean.dim over two dims of a 6-D strided view x.view(1,2,S/2,2,S/2,2).mean(dim=(3,5)): 83.7 ms vs 9.1 ms at 1024² (9.2x); F.avg_pool2d(x, 2) computes the same in 0.62 ms color.rgb_to_yuv420 1024²: 10.9 ms → 84.7 ms
batched small-matrix LU family: linalg_inv_ex, _linalg_solve_ex, linalg_det B=65536: inv 2x2 / 3x3 / 4x4 10.4x / 7.7x / 6.3x slower (≈ 0.9–1 µs per matrix vs 0.09–0.17 µs CPU), solve 3x3 7.9x, det 2.4x; B=4096: 9–12x; B=256: 1.4 ms flat. Contrast: batched eigh and svd 3x3 are 3–5x faster on MPS at B ≥ 4096. geometry.invert_affine_transform (65536): 8.5 ms → 64 ms; filters.guided_blur (per-pixel 3x3 solve) 1024²: 793 ms → 1.07 s; 7-point find_fundamental 1.5x
depthwise 3-D aten::convolution F.conv3d C=1 k3: 2.8x slower at 64³, 2.1x at 128³; k7 parity; a full 8→8 conv3d is 6x faster on MPS filters.filter3d k3 128³: 39 ms → 125 ms; motion_blur3d, 3-D augmentations
tall-skinny aten::mm (65536,64)@(64,64): 3.0x slower; (65536,64)ᵀ@(65536,64): 8.7x slower; 1024² and 4096² square GEMMs are faster on MPS enhance.zca_whiten (65536×64): 7.6 ms → 17.9 ms
small-k aten::topk on long rows topk(k=2, dim=-1) on (n,n): 1.3x (2048), 1.76x (4096) slower, 0.82x at 8192; min(dim=-1) is 2.3x faster and _euclidean_dist 1.7x faster feature.match_nn/snn/smnn/fginn 4096 descriptors: 1.2–1.9x slower
small per-call kernels reflection_pad2d 4.1x (0.5 ms per call at 256²), constant_pad_nd 9x (0.3 ms), any.dim on (1,1,256,256) 0.77 ms per call, nonzero on 4k elements 470 µs (host round trip; 3x faster than CPU at 1M), randperm(16) 231 µs, unique on 4k 605 µs canny (16 eq, 4 any.dim), guided_blur, KMeans, RandomJigsaw

Standalone microbenchmark for the table (CPU vs MPS, medians, sizes stay under ~200 MB per tensor):

python
import torch, torch.nn.functional as F, torch.utils.benchmark as bench
def t(fn, dev):
    s = torch.mps.synchronize if dev == "mps" else (lambda: None); fn(); s()
    return bench.Timer(stmt="fn(); s()", globals={"fn": fn, "s": s}).blocked_autorange(min_run_time=0.4).median * 1e6
def both(name, make):
    r = {d: t(make(d), d) for d in ("cpu", "mps")}
    print(f"{name:52s} cpu {r['cpu']:10.1f} us  mps {r['mps']:10.1f} us  {r['mps']/r['cpu']:7.2f}x", flush=True)
n = 1 << 20; S = 1024
both("bincount minlength=16, 1M",   lambda d: (lambda x=torch.randint(0, 16, (n,)).to(d): torch.bincount(x, minlength=16)))
both("bincount minlength=1024, 1M", lambda d: (lambda x=torch.randint(0, 1024, (n,)).to(d): torch.bincount(x, minlength=1024)))
both("histc 256 bins, 1M",          lambda d: (lambda x=torch.rand(n).to(d): torch.histc(x, 256, 0.0, 1.0)))
both("sum(dim=(-2,-1)) (1,3,S,S)",  lambda d: (lambda x=torch.randn(1, 3, S, S).to(d): x.sum(dim=(-2, -1))))
both("sum(dim=-1) (1,3,S,S)",       lambda d: (lambda x=torch.randn(1, 3, S, S).to(d): x.sum(dim=-1)))
both("mean(dim=(3,5)) 6-D 2x2 view", lambda d: (lambda x=torch.randn(1, 2, S, S).to(d): x.view(1, 2, S // 2, 2, S // 2, 2).mean(dim=(3, 5))))
both("avg_pool2d(2) same result",   lambda d: (lambda x=torch.randn(1, 2, S, S).to(d): F.avg_pool2d(x, 2)))
both("median(dim=-1) rows of 9, 3M rows", lambda d: (lambda x=torch.randn(1, 3, S * S, 9).to(d): x.median(dim=-1)[0]))
both("median(dim=-1) rows of 121, 196k rows", lambda d: (lambda x=torch.randn(1, 3, 256 * 256, 121).to(d): x.median(dim=-1)[0]))
both("max(dim=4) (1,3,256,256,3,3) contiguous", lambda d: (lambda x=torch.randn(1, 3, 256, 256, 3, 3).to(d): x.max(dim=4)[0]))
both("amax(dim=(4,5)) (1,3,256,256,7,7)", lambda d: (lambda x=torch.randn(1, 3, 256, 256, 7, 7).to(d): x.amax(dim=(4, 5))))
B = 65536
both("linalg.inv batched 3x3, B=65536",   lambda d: (lambda a=(torch.randn(B, 3, 3) + 3 * torch.eye(3)).to(d): torch.linalg.inv(a)))
both("linalg.solve batched 3x3, B=65536", lambda d: (lambda a=(torch.randn(B, 3, 3) + 3 * torch.eye(3)).to(d), b=torch.randn(B, 3, 1).to(d): torch.linalg.solve(a, b)))
both("linalg.eigh batched 3x3, B=65536",  lambda d: (lambda a=(lambda r: r @ r.transpose(-1, -2) + torch.eye(3))(torch.randn(B, 3, 3)).to(d): torch.linalg.eigh(a)))
both("conv3d depthwise C=1 k3, 64^3",     lambda d: (lambda x=torch.randn(1, 1, 64, 64, 64).to(d), w=torch.randn(1, 1, 3, 3, 3).to(d): F.conv3d(x, w, padding=1)))
both("mm (65536,64)^T @ (65536,64)",      lambda d: (lambda a=torch.randn(65536, 64).to(d): a.t() @ a))
both("topk k=2 on (4096,4096)",           lambda d: (lambda x=torch.randn(4096, 4096).to(d): x.topk(2, dim=-1, largest=False)))
both("min(dim=-1) on (4096,4096)",        lambda d: (lambda x=torch.randn(4096, 4096).to(d): x.min(dim=-1)))

4. Allocator growth in a long-lived process

After several out-of-memory failures (MPS backend out of memory (MPS allocated: 9.01 GiB … max allowed: 9.07 GiB) for descriptor nets on 16384 patches) the same process ran LoFTR at 512² in 55.6 s; a fresh process runs it in 0.50 s (CPU 2.83 s), with driver_allocated_memory at 2.07 GiB. Everything else in this issue was re-measured in fresh processes because of that. recommended_max_memory() reports 5.33 GiB on this 8 GB machine.

5. Backend contract differences (FYI, not bugs)

  • native_batch_norm_backward in eval mode: the CPU forward returns empty save_mean / save_invstd and its backward accepts them; the MPS backward asserts on an empty placeholder (OperationUtils.mm:501 [srcBuf length] > 0). End to end BatchNorm2d.eval() backward on MPS matches CPU, so this only bites callers that feed CPU-shaped saved tensors to the MPS op.
  • log_sigmoid_forward returns a full-size buffer on CPU and an empty one on MPS (as CUDA does).
  • _assert_tensor_metadata(device=) treats mps and mps:0 as different devices.

6. Checked and fine on nightly

Strided/expanded/diagonal-view copies to MPS, grid_sample 2-D/3-D forward and backward (all padding modes, in-range and out-of-range grids, float16/bfloat16 — where MPS is closer to the float32 reference than CPU half is), complex conj views and fft-based convolution, SDPA, batched eigh/svd/solve numerics, scatter_add/index_put_ up to accumulation order. The torch 2.14 batched-SVD ≥ 8192-element ceiling (#4201) was not hit by SVD replays up to (2048, 8, 9), but it was not bisected on nightly either.

Environment

torch 2.15.0.dev20260913 (nightly cpu wheel) | python 3.11.14 | macOS-26.5.1-arm64 (Apple M1, 8 GB) | MPS=True | PYTORCH_ENABLE_MPS_FALLBACK unset | kornia 633951bd7

Posted on behalf of @ducha-aiki by Claude (Fable 5.1).