Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(metrics): validate device consistency in disparity metrics (#6227)

Ali Tharwat95c7cc4f02bf
diff --git a/changelog.d/6227.fixed.md b/changelog.d/6227.fixed.md
new file mode 100644
index 000000000..3d097f5c9
--- /dev/null
+++ b/changelog.d/6227.fixed.md
@@ -0,0 +1 @@
+`mean_absolute_disparity_error`, `root_mean_squared_disparity_error`, `mean_bad_pixel_error` and `kitti_d1_error` move a `valid_mask` that is on another device than the disparity maps to the maps' device. In 0.9.0, a CPU mask with CUDA or MPS maps raised torch's `RuntimeError` under every reduction; it works again and gives the same result as a mask on the maps' device. Maps on two different devices now raise kornia's `DeviceError` instead of torch's `RuntimeError`. `DeviceError` is a `ValueError`, not a `RuntimeError`, so an `except RuntimeError` around such a call no longer catches it. A 0-d map on the CPU still combines with a 0-d map on another device, because torch treats a 0-d CPU tensor as a scalar.
diff --git a/kornia/metrics/disparity.py b/kornia/metrics/disparity.py
index 979e76842..15edd44a7 100644
--- a/kornia/metrics/disparity.py
+++ b/kornia/metrics/disparity.py
@@ -19,7 +19,12 @@ from typing import Optional
import torch
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE
+from kornia.core.check import (
+ KORNIA_CHECK,
+ KORNIA_CHECK_IS_TENSOR,
+ KORNIA_CHECK_SAME_DEVICE,
+ KORNIA_CHECK_SAME_SHAPE,
+)
def _is_broadcastable_to(shape: torch.Size, target_shape: torch.Size) -> bool:
@@ -36,6 +41,10 @@ def _check_disparity_inputs(
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_IS_TENSOR(target)
KORNIA_CHECK_SAME_SHAPE(input, target)
+ # torch combines a 0-d CPU tensor with a tensor on any device, as a scalar, so a 0-d pair with one map on the CPU
+ # is not checked. Maps with dimensions, and 0-d maps on two other devices, must share a device.
+ if input.ndim > 0 or (input.device.type != "cpu" and target.device.type != "cpu"):
+ KORNIA_CHECK_SAME_DEVICE(input, target)
# The reductions below accumulate in float32 and cast back to the map dtype. For an integer
# map that cast truncates, which would turn a ratio into 0 instead of raising, so reject
# integers here. KITTI ships disparity as a uint16 PNG, so this is a realistic input.
@@ -54,7 +63,8 @@ def _check_disparity_inputs(
f"valid_mask shape must be broadcastable to the input shape. Got: {valid_mask.shape} and {input.shape}",
)
- return valid_mask.to(torch.bool).broadcast_to(input.shape)
+ # A mask on another device, such as a CPU mask with CUDA maps, is moved to the maps.
+ return valid_mask.to(device=input.device, dtype=torch.bool).broadcast_to(input.shape)
def _reduce_disparity_error(error: torch.Tensor, valid_mask: Optional[torch.Tensor], reduction: str) -> torch.Tensor:
diff --git a/tests/metrics/test_disparity.py b/tests/metrics/test_disparity.py
index 7d25cf026..691034659 100644
--- a/tests/metrics/test_disparity.py
+++ b/tests/metrics/test_disparity.py
@@ -19,7 +19,7 @@ import pytest
import torch
import kornia
-from kornia.core.exceptions import BaseError, ShapeError, TypeCheckError
+from kornia.core.exceptions import BaseError, DeviceError, ShapeError, TypeCheckError
from testing.base import BaseTester
@@ -231,6 +231,10 @@ class TestMeanAbsoluteDisparityError(BaseTester):
kornia.metrics.mean_absolute_disparity_error(sample, sample, mask)
assert "broadcastable" in str(errinfo.value)
+ with pytest.raises(DeviceError) as errinfo:
+ kornia.metrics.mean_absolute_disparity_error(sample, sample.to("meta"))
+ assert "Device mismatch" in str(errinfo.value)
+
with pytest.raises(NotImplementedError) as errinfo:
kornia.metrics.mean_absolute_disparity_error(sample, 2.0 * sample, reduction="foo")
assert "Invalid reduction option." in str(errinfo.value)
@@ -304,6 +308,10 @@ class TestRootMeanSquaredDisparityError(BaseTester):
kornia.metrics.root_mean_squared_disparity_error(None, sample)
assert "Type mismatch: expected Tensor" in str(errinfo.value)
+ with pytest.raises(DeviceError) as errinfo:
+ kornia.metrics.root_mean_squared_disparity_error(sample, sample.to("meta"))
+ assert "Device mismatch" in str(errinfo.value)
+
with pytest.raises(NotImplementedError) as errinfo:
kornia.metrics.root_mean_squared_disparity_error(sample, 2.0 * sample, reduction="foo")
assert "Invalid reduction option." in str(errinfo.value)
@@ -456,6 +464,10 @@ class TestMeanBadPixelError(BaseTester):
kornia.metrics.mean_bad_pixel_error(None, sample)
assert "Type mismatch: expected Tensor" in str(errinfo.value)
+ with pytest.raises(DeviceError) as errinfo:
+ kornia.metrics.mean_bad_pixel_error(sample, sample.to("meta"))
+ assert "Device mismatch" in str(errinfo.value)
+
with pytest.raises(NotImplementedError) as errinfo:
kornia.metrics.mean_bad_pixel_error(sample, 2.0 * sample, reduction="foo")
assert "Invalid reduction option." in str(errinfo.value)
@@ -625,6 +637,10 @@ class TestKittiD1Error(BaseTester):
kornia.metrics.kitti_d1_error(sample, sample, valid_mask=mask)
assert "broadcastable" in str(errinfo.value)
+ with pytest.raises(DeviceError) as errinfo:
+ kornia.metrics.kitti_d1_error(sample, sample.to("meta"))
+ assert "Device mismatch" in str(errinfo.value)
+
with pytest.raises(NotImplementedError) as errinfo:
kornia.metrics.kitti_d1_error(sample, 2.0 * sample, reduction="foo")
assert "Invalid reduction option." in str(errinfo.value)
@@ -714,3 +730,49 @@ class TestConventionsDisparity(BaseTester):
# a (B,) mask is aligned with W, not with the batch: rejected here since W = 4 != B = 2 (W == B would broadcast)
with pytest.raises((ValueError, BaseError)):
metric(input, target, valid_mask=torch.tensor([True, False], device=device))
+
+
+_DISPARITY_METRICS = (
+ kornia.metrics.mean_absolute_disparity_error,
+ kornia.metrics.root_mean_squared_disparity_error,
+ kornia.metrics.mean_bad_pixel_error,
+ kornia.metrics.kitti_d1_error,
+)
+
+
+class TestDisparityDevices(BaseTester):
+ @pytest.mark.parametrize("reduction", ["mean", "sum", "none"])
+ def test_valid_mask_on_another_device(self, device, dtype, reduction):
+ # A CPU mask with maps on an accelerator is moved to the maps (0.9.0rc1 indexed the maps with it).
+ sample = torch.tensor([[1.0, 2.0, 30.0], [4.0, 5.0, 60.0]], device=device, dtype=dtype)
+ target = torch.tensor([[1.5, 9.0, 30.0], [4.0, 1.0, 50.0]], device=device, dtype=dtype)
+ mask = torch.tensor([[True, True, False], [True, True, True]])
+ for metric in _DISPARITY_METRICS:
+ expected = metric(sample, target, valid_mask=mask.to(device), reduction=reduction)
+ actual = metric(sample, target, valid_mask=mask, reduction=reduction)
+ self.assert_close(actual, expected, rtol=0, atol=0)
+ # The same path on every CI leg: maps on the meta device with a CPU mask.
+ out = metric(sample.to("meta"), target.to("meta"), valid_mask=mask, reduction=reduction)
+ assert out.device.type == "meta"
+
+ def test_scalar_maps_on_two_devices(self, device, dtype):
+ # A 0-d CPU map is a scalar that torch combines with a map on any device.
+ sample = torch.tensor(7.0, device=device, dtype=dtype)
+ target = torch.tensor(3.0, dtype=dtype)
+ for metric in _DISPARITY_METRICS:
+ self.assert_close(metric(sample, target), metric(sample, target.to(device)), rtol=0, atol=0)
+ self.assert_close(metric(target, sample), metric(target.to(device), sample), rtol=0, atol=0)
+ out = _DISPARITY_METRICS[0](sample.to("meta"), target)
+ assert out.device.type == "meta"
+
+ def test_scalar_maps_on_two_other_devices(self, device, dtype):
+ # Only a 0-d CPU tensor mixes with another device in torch, so 0-d maps on two other devices are rejected.
+ if device.type == "cpu":
+ pytest.skip("needs a device other than the CPU and meta")
+ sample = torch.tensor(7.0, device=device, dtype=dtype)
+ target = torch.tensor(3.0, device="meta", dtype=dtype)
+ for metric in _DISPARITY_METRICS:
+ with pytest.raises(DeviceError, match="Device mismatch"):
+ metric(sample, target)
+ with pytest.raises(DeviceError, match="Device mismatch"):
+ metric(target, sample)