Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): route MPS SVD and svdvals through CPU at 8192 elements or more (#4455)

Vimal Kumar Yadavd6a03e270307
diff --git a/TESTING.md b/TESTING.md
index 63e14b7f6..cba867346 100644
--- a/TESTING.md
+++ b/TESTING.md
@@ -298,7 +298,7 @@ profile manifest.
| `complex128` (cdouble) | `TypeError: Cannot convert a MPS Tensor to float64 dtype` (`NotImplementedError: … not implemented for 'ComplexDouble'` before 2.14) | all |
| `torch.autocast("mps")` | Converts output to float16 instead of preserving original dtype | all |
| `torch.linalg.eigvals` (non-symmetric) | `NotImplementedError: The operator 'aten::_linalg_eigvals' is not currently implemented for the MPS device` | all, 2.14.0 included |
-| **batched** `torch.linalg.svd` / `svdvals` / `lstsq` whose input holds 8192 elements or more | `RuntimeError: Failed to created pipeline state object … XPC_ERROR_CONNECTION_INTERRUPTED` | 2.14.0 |
+| `torch.linalg.svd` / `svdvals` / `lstsq` whose input holds 8192 elements or more | `RuntimeError: Failed to created pipeline state object … XPC_ERROR_CONNECTION_INTERRUPTED` | 2.14.0 |
| `F.grid_sample` with `padding_mode="border"` on 2D | `RuntimeError: MPS: Unsupported Border padding mode` | <= 2.9.1 |
| `F.grid_sample` with `mode="nearest"` on 5-D (3D volumes) | `RuntimeError: grid_sampler_3d: Unsupported Nearest interpolation` | <= 2.9.1 |
| `grid_sample` backward (2D and 3D) | `NotImplementedError: The operator 'aten::grid_sampler_2d_backward' …` | <= 2.9.1 |
@@ -310,16 +310,23 @@ backward passes, and for the two `grid_sample` forward modes above. That took th
baseline from 200 entries to 14. The intermediate 2.10-2.13 releases were not checked, and
kornia still supports torch 2.5.1, so the workarounds for those rows stay.
-The new native SVD path carries its own ceiling: a **batched** `svd`, `svdvals` or `lstsq` fails
-to build a Metal pipeline once its input holds 8192 elements or more (batch x rows x cols). The
-threshold is inclusive and it is the first failing size, not the last working one -- measured
-`(511, 4, 4)` = 8176 passes, `(512, 4, 4)` = 8192 raises. A single unbatched matrix is unaffected
-at any size: `(1, 128, 128)` holds 16384 elements and succeeds, because torch stages a lone large
-matrix on the CPU (`matrix too large to stage in MPS threadgroup memory ... falling back to CPU`).
-That ceiling is why `RANSAC`'s batched minimal solvers still raise on MPS
-([#4201](https://github.com/kornia/kornia/issues/4201)). It is *not* why they are absent from the
-baseline below -- see the next section: they are skipped, because they abort the process before
-they can raise.
+The new native SVD path carries its own ceiling: `svd`, `svdvals` or `lstsq` fails to build a
+Metal pipeline once its input holds 8192 elements or more (batch x rows x cols). The threshold
+is inclusive and it is the first failing size, not the last working one -- measured
+`(511, 4, 4)` = 8176 passes, `(512, 4, 4)` = 8192 raises. The boundary is a byte count, not
+an element count: 8192 float32 elements are exactly 32768 bytes, the MPS threadgroup limit,
+and torch's own "matrix too large to stage in MPS threadgroup memory ... falling back to CPU"
+check triggers on *greater than* that limit, so an input sitting exactly on it neither falls
+back nor compiles. Shape is irrelevant -- `(128, 64)`, `(64, 128)`, `(8192, 1)` and `(1, 8192)`
+all raise, and 8191 and 8193 elements both pass -- which is why the guard counts elements and
+does not inspect batch rank. That ceiling is why `RANSAC`'s
+batched minimal solvers used to raise on MPS
+([#4201](https://github.com/kornia/kornia/issues/4201)). `_torch_svd_cast` and
+`_torch_linalg_svdvals` now route such inputs through the CPU, so the fundamental and
+homography solvers no longer hit it; `find_essential` still raises, for an unrelated
+reason -- `run_5point` calls `torch.linalg.eigvals`, which has no MPS kernel. The ceiling
+is *not* why those solvers are absent from the baseline below -- see the next section:
+they are skipped, because they abort the process before they can raise.
**How Kornia handles these automatically.** The test infrastructure in `conftest.py` and `testing/base.py` skips known-unsupported test classes at collection time so you don't need per-test guards for the common cases:
diff --git a/changelog.d/+migration-024.added.md b/changelog.d/+migration-024.added.md
index 1d1bcb928..c7694b3b2 100644
--- a/changelog.d/+migration-024.added.md
+++ b/changelog.d/+migration-024.added.md
@@ -9,11 +9,13 @@ solver off the device, and the `yuv420`/`yuv422` empty-input reshape defect. Sep
`tests/geometry/test_ransac.py` is *skipped* rather than pinned β€” it aborts the process on the
runners' paravirtualized GPU, and a `SIGABRT` has no exception type to record
([#4204](https://github.com/kornia/kornia/issues/4204)); the skip costs 9 tests that pass on real
-Apple hardware, and `--run-mps-process-abort` runs them locally. The underlying limit is that a
-**batched** `torch.linalg.svd`/`svdvals`/`lstsq` fails to build a Metal pipeline once its input
-holds 8192 elements or more, which keeps `RANSAC`'s batched minimal solvers off the device
-([#4201](https://github.com/kornia/kornia/issues/4201)); a single unbatched matrix is unaffected
-at any size. The image stays on `macos-15`: on `macos-latest` (macOS 26) the runner's *virtual*
+Apple hardware, and `--run-mps-process-abort` runs them locally. The underlying limit is that
+`torch.linalg.svd`/`svdvals`/`lstsq` fails to build a Metal pipeline once its input
+holds 8192 elements or more, which used to keep `RANSAC`'s batched minimal solvers off the
+device ([#4201](https://github.com/kornia/kornia/issues/4201)); `_torch_svd_cast` and
+`_torch_linalg_svdvals` now route such inputs through the CPU, so the fundamental and
+homography solvers reach it, while `find_essential` still raises on `torch.linalg.eigvals`,
+which has no MPS kernel. The image stays on `macos-15`: on `macos-latest` (macOS 26) the runner's *virtual*
GPU cannot compile the Metal 4 cooperative-tensor shaders torch 2.14 emits, which fails 664
tests β€” a physical M1 on macOS 26 compiles them fine. kornia still supports torch 2.5.1, so the
in-tree MPS workarounds stay. (#4202)
diff --git a/changelog.d/4455.fixed.md b/changelog.d/4455.fixed.md
new file mode 100644
index 000000000..3cf11461f
--- /dev/null
+++ b/changelog.d/4455.fixed.md
@@ -0,0 +1,7 @@
+SVD no longer fails on MPS at 8192 elements or more. torch 2.14's MPS `linalg.svd` and
+`linalg.svdvals` fail to build their Metal pipeline state object once an input holds 8192 elements
+or more, whatever the per-matrix shape. At realistic batch sizes `find_fundamental` and `solve_pnp_dlt`
+raised that "Failed to created pipeline state object" exception; `find_homography_dlt(..., solver="svd")`
+instead caught it, emitted a "SVD did not converge" warning, and returned an uninitialized (invalid)
+tensor. Such inputs are now decomposed on the CPU and moved back. `find_essential` still raises on
+MPS at any batch size, because `run_5point` calls `torch.linalg.eigvals`, which has no MPS kernel.
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index c668b4e41..583e49da8 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -278,6 +278,9 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
For numerical stability, fp32 inputs are promoted to fp64 (except on MPS where fp64 is unsupported).
+
+ An MPS input past the shader-compilation ceiling is decomposed on the CPU and moved back, which
+ is what keeps the batched minimal solvers behind ``RANSAC`` working on Apple silicon.
"""
if is_mps_tensor_safe(input):
dtype = torch.float32
@@ -286,7 +289,20 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
else:
dtype = _normalize_to_float32_or_float64(input.dtype)
- out1, out2, out3H = torch.linalg.svd(input.to(dtype))
+ x = input.to(dtype)
+ # torch 2.14's MPS ``linalg.svd`` raises "Failed to created pipeline state object" -- a Metal
+ # shader compilation failure, not memory pressure -- once an input holds 8192 elements
+ # or more, whatever the per-matrix shape. The bound is inclusive: 8192 is the first failing
+ # size rather than the last working one, measured as ``(511, 4, 4)`` = 8176 passing and
+ # ``(512, 4, 4)`` = 8192 raising. It is inlined rather than named because this function is
+ # scripted (via ``zca_mean``) and TorchScript cannot close over a module global.
+ if is_mps_tensor_safe(x) and x.numel() >= 8192:
+ # SVD is per-matrix, so decomposing the whole batch on the CPU gives the same result; the
+ # casts back to the MPS device keep the autograd graph intact.
+ U, S, Vh = torch.linalg.svd(x.cpu())
+ out1, out2, out3H = U.to(x.device), S.to(x.device), Vh.to(x.device)
+ else:
+ out1, out2, out3H = torch.linalg.svd(x)
# Since kornia requires torch>=2.5.1, we can always use .mH
out3 = out3H.mH
return (out1.to(input.dtype), out2.to(input.dtype), out3.to(input.dtype))
@@ -304,8 +320,17 @@ def _torch_linalg_svdvals(input: torch.Tensor) -> torch.Tensor:
KORNIA_CHECK_IS_TENSOR(input, "Input must be torch.Tensor")
dtype = _normalize_to_float32_or_float64(input.dtype)
- # Since kornia requires torch>=2.5.1, we can always use torch.linalg.svdvals
- out = torch.linalg.svdvals(input.to(dtype))
+ x = input.to(dtype)
+ # ``svdvals`` shares the shader-compilation ceiling documented in
+ # ``_torch_svd_cast``: on torch 2.14's MPS backend an input holding
+ # 8192 elements or more fails to build its Metal pipeline state. This path
+ # reaches ``solve_pnp_dlt``, which raised for any batch large enough to
+ # cross it.
+ if is_mps_tensor_safe(x) and x.numel() >= 8192:
+ out = torch.linalg.svdvals(x.cpu()).to(x.device)
+ else:
+ # Since kornia requires torch>=2.5.1, we can always use torch.linalg.svdvals
+ out = torch.linalg.svdvals(x)
return out.to(input.dtype)
diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.py
index 21ccba425..92ab27d31 100644
--- a/tests/core/test_helpers.py
+++ b/tests/core/test_helpers.py
@@ -24,9 +24,11 @@ from kornia.core.utils import (
_extract_device_dtype,
_torch_histc_cast,
_torch_inverse_cast,
+ _torch_linalg_svdvals,
_torch_solve_cast,
_torch_svd_cast,
is_exporting,
+ is_mps_tensor_safe,
register_module_state,
safe_inverse_with_mask,
safe_solve_with_mask,
@@ -206,6 +208,81 @@ class TestSvdCast:
tol_val: float = 1e-1 if dtype == torch.float16 else 1e-3
assert_close(a, u @ torch.diag_embed(s) @ v.transpose(-2, -1), atol=tol_val, rtol=tol_val)
+ def test_batch_above_mps_ceiling(self, device, dtype):
+ # torch 2.14's MPS SVD raises at 8192 input elements or more (#4201), far below the hypothesis
+ # count RANSAC's batched minimal solvers use; 1000 * 3 * 3 = 9000 elements clears it.
+ torch.manual_seed(0)
+ a = torch.randn(1000, 3, 3, device=device, dtype=dtype)
+ u, s, v = _torch_svd_cast(a)
+
+ assert u.device == a.device
+ assert s.device == a.device
+ assert v.device == a.device
+ # Both half dtypes round three factors back before the reconstruction contracts them.
+ tol_val: float = 1e-1 if dtype in (torch.float16, torch.bfloat16) else 1e-3
+ assert_close(a, u @ torch.diag_embed(s) @ v.transpose(-2, -1), atol=tol_val, rtol=tol_val)
+
+ def test_svdvals_at_mps_ceiling(self, device, dtype, monkeypatch):
+ # svdvals shares the 8192-element ceiling with svd (#4201), and feeds
+ # solve_pnp_dlt. 512 4x4 matrices is exactly the boundary.
+ torch.manual_seed(0)
+ a = torch.randn(512, 4, 4, device=device, dtype=dtype)
+ assert a.numel() == 8192
+
+ seen = []
+ real = torch.linalg.svdvals
+
+ def spy(x, *args, **kwargs):
+ seen.append(x.device.type)
+ return real(x, *args, **kwargs)
+
+ monkeypatch.setattr(torch.linalg, "svdvals", spy)
+ s = _torch_linalg_svdvals(a)
+
+ assert s.device == a.device
+ assert s.shape == (512, 4)
+ if a.device.type == "mps":
+ assert seen == ["cpu"], "an 8192-element MPS batch must take the CPU fallback"
+ assert torch.isfinite(s).all()
+
+ def test_batch_at_mps_ceiling(self, device, dtype, monkeypatch):
+ # 8192 is the first failing size rather than the last working one (#4201), so a batch that
+ # holds exactly 8192 elements has to take the CPU fallback too. 512 * 4 * 4 is the measured
+ # boundary case. Spying on the decomposition itself keeps the check meaningful off MPS,
+ # where it asserts the fallback stays out of the way.
+ torch.manual_seed(0)
+ a = torch.randn(512, 4, 4, device=device, dtype=dtype)
+ assert a.numel() == 8192
+
+ seen = []
+ real_svd = torch.linalg.svd
+
+ def spy_svd(x, *args, **kwargs):
+ seen.append(x.device.type)
+ return real_svd(x, *args, **kwargs)
+
+ monkeypatch.setattr(torch.linalg, "svd", spy_svd)
+ u, s, v = _torch_svd_cast(a)
+
+ expected = "cpu" if is_mps_tensor_safe(a) else a.device.type
+ assert seen == [expected]
+ assert u.device == a.device
+ assert s.device == a.device
+ assert v.device == a.device
+ tol_val: float = 1e-1 if dtype in (torch.float16, torch.bfloat16) else 1e-3
+ assert_close(a, u @ torch.diag_embed(s) @ v.transpose(-2, -1), atol=tol_val, rtol=tol_val)
+
+ def test_gradient_above_mps_ceiling(self, device, dtype):
+ # Decomposing the batch elsewhere must not detach it from the graph.
+ torch.manual_seed(0)
+ a = torch.randn(1000, 3, 3, device=device, dtype=dtype, requires_grad=True)
+ _, s, _ = _torch_svd_cast(a)
+
+ s.sum().backward()
+ assert a.grad is not None
+ assert a.grad.device == a.device
+ assert not a.grad.isnan().any()
+
class TestSolveCast:
def test_smoke(self, device, dtype):