π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(metrics): add KITTI D1 disparity error (#3931)
Leonardo Vannibd5577992fa7
diff --git a/changelog.d/3931.added.md b/changelog.d/3931.added.mdnew file mode 100644index 000000000..d87d8bb32--- /dev/null+++ b/changelog.d/3931.added.md@@ -0,0 +1,7 @@+`kornia.metrics.kitti_d1_error`, the outlier ratio reported by the KITTI 2015 stereo benchmark.+A pixel counts as an outlier only when its absolute disparity error exceeds `abs_threshold`+**and** its relative error exceeds `rel_threshold`, both strictly, with the ground truth as the+relative denominator. That conjunction is what separates it from `mean_bad_pixel_error`, which+applies the absolute criterion alone and so penalises large disparities for errors that are small+next to their magnitude. A batch is pooled over every valid pixel, as the devkit accumulates it,+rather than averaged per image. Closes #3758.diff --git a/changelog.d/3931.breaking.md b/changelog.d/3931.breaking.mdnew file mode 100644index 000000000..a168bcee3--- /dev/null+++ b/changelog.d/3931.breaking.md@@ -0,0 +1,9 @@+`mean_absolute_disparity_error`, `root_mean_squared_disparity_error` and `mean_bad_pixel_error`+now raise a kornia error naming the dtypes when either disparity map is not floating point, as+does the new `kitti_d1_error`. Previously `reduction='mean'` already failed on integer maps with a+torch `RuntimeError` from `mean()`, but `reduction='sum'` and `reduction='none'` returned results:+an `int64` sum and an integer per-pixel map for the absolute and bad-pixel metrics, and `float32`+for the root-mean-square one. Those calls now raise. The guard exists because the reductions+accumulate in `float32` and cast back to the map's dtype, which for an integer map would truncate+a ratio such as 0.5 to 0, and KITTI ships disparity as a `uint16` PNG, so a plausible-looking+wrong score was the alternative. Convert integer maps with `.float()` before calling.diff --git a/changelog.d/3931.fixed.md b/changelog.d/3931.fixed.mdnew file mode 100644index 000000000..37f946ca6--- /dev/null+++ b/changelog.d/3931.fixed.md@@ -0,0 +1,8 @@+The `kornia.metrics` disparity reductions accumulate in `float32` for `float16` and `bfloat16`+inputs, so `mean_absolute_disparity_error`, `root_mean_squared_disparity_error` and+`mean_bad_pixel_error` no longer return `inf` on an image-sized map. A `float16` sum saturates at+65504, and a `bfloat16` sum lost roughly 0.5% over 100k terms. `root_mean_squared_disparity_error`+additionally squared in the input dtype, so a 300 px error saturated before any reduction ran;+it now squares in the accumulator dtype. A mixed-dtype pair now returns the promoted dtype from+every metric in the module rather than the dtype of `input`, matching what+`mean_absolute_disparity_error` already did.diff --git a/docs/source/metrics.stereo.rst b/docs/source/metrics.stereo.rstindex 1c3446ac0..e96ad31e8 100644--- a/docs/source/metrics.stereo.rst+++ b/docs/source/metrics.stereo.rst@@ -6,3 +6,4 @@ Stereo.. autofunction:: mean_absolute_disparity_error.. autofunction:: root_mean_squared_disparity_error.. autofunction:: mean_bad_pixel_error+.. autofunction:: kitti_d1_errordiff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.pyindex ba285127f..4cbf2ea2a 100644--- a/kornia/metrics/__init__.py+++ b/kornia/metrics/__init__.py@@ -24,7 +24,12 @@ PSNR, SSIM, endpoint error, and stereo disparity error.from .accuracy import accuracyfrom .average_meter import AverageMeterfrom .confusion_matrix import confusion_matrix-from .disparity import mean_absolute_disparity_error, mean_bad_pixel_error, root_mean_squared_disparity_error+from .disparity import (+ kitti_d1_error,+ mean_absolute_disparity_error,+ mean_bad_pixel_error,+ root_mean_squared_disparity_error,+)from .endpoint_error import AEPE, aepe, average_endpoint_errorfrom .mean_average_precision import mean_average_precisionfrom .mean_iou import mean_iou, mean_iou_bbox@@ -45,6 +50,7 @@ __all__ = ["auc_from_errors","average_endpoint_error","confusion_matrix",+ "kitti_d1_error","mean_absolute_disparity_error","mean_average_precision","mean_bad_pixel_error",diff --git a/kornia/metrics/disparity.py b/kornia/metrics/disparity.pyindex d3e20ed1b..5490eae51 100644--- a/kornia/metrics/disparity.py+++ b/kornia/metrics/disparity.py@@ -36,6 +36,14 @@ def _check_disparity_inputs(KORNIA_CHECK_IS_TENSOR(input)KORNIA_CHECK_IS_TENSOR(target)KORNIA_CHECK_SAME_SHAPE(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.+ KORNIA_CHECK(+ input.is_floating_point() and target.is_floating_point(),+ "Disparity maps must have a floating point dtype. "+ f"Got: {input.dtype} and {target.dtype}. Convert them first, for example with `.float()`.",+ )if valid_mask is None:return None@@ -50,14 +58,28 @@ def _check_disparity_inputs(def _reduce_disparity_error(error: torch.Tensor, valid_mask: Optional[torch.Tensor], reduction: str) -> torch.Tensor:- """Reduce a per-pixel error map over the valid pixels according to ``reduction``."""+ """Reduce a per-pixel error map over the valid pixels according to ``reduction``.++ The sums are accumulated in ``float32`` for half-precision inputs. A ``float16`` sum saturates+ at 65504, so an image-sized map would otherwise reduce to ``inf``, and a ``bfloat16`` sum loses+ several significant digits over the same number of terms. The result is cast back to the dtype+ of ``error`` so that the metrics keep returning the dtype of their input.+ """+ out_dtype = error.dtype+ acc_dtype = torch.promote_types(out_dtype, torch.float32)++ if valid_mask is not None:+ # Zeroing the invalid pixels keeps the shape static. Indexing with the mask would make the+ # output shape depend on the mask values, which torch.compile cannot trace in a full graph.+ error = torch.where(valid_mask, error, 0)+if reduction == "mean":- error = error.mean() if valid_mask is None else error[valid_mask].mean()+ count = error.numel() if valid_mask is None else valid_mask.sum()+ error = (error.sum(dtype=acc_dtype) / count).to(out_dtype)elif reduction == "sum":- error = error.sum() if valid_mask is None else error[valid_mask].sum()+ error = error.sum(dtype=acc_dtype).to(out_dtype)elif reduction == "none":- if valid_mask is not None:- error = torch.where(valid_mask, error, torch.zeros_like(error))+ passelse:raise NotImplementedError("Invalid reduction option.")@@ -97,6 +119,12 @@ def mean_absolute_disparity_error(Note:If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.+ Note:+ Sums are accumulated in ``float32`` for ``float16`` and ``bfloat16`` inputs and the result+ is cast back, so ``'mean'`` stays accurate on image-sized maps. ``'sum'`` returns the input+ dtype as well, so a ``float16`` total above 65504 still saturates to ``inf`` β reduce with+ ``'none'`` and sum in a wider dtype if you need totals that large.+Examples:>>> input = torch.tensor([[0.0, 1.0], [2.0, 3.0]])>>> target = torch.tensor([[0.0, 1.0], [2.0, 4.0]])@@ -150,6 +178,11 @@ def root_mean_squared_disparity_error(Note:If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.+ Note:+ For ``float16`` and ``bfloat16`` inputs the squared error and its reduction are computed in+ ``float32`` and only the final value is cast back. Without that, a disparity error above+ 256 px would already saturate the ``float16`` squared error to ``inf``.+Examples:>>> input = torch.zeros(2, 2)>>> target = torch.tensor([[0.0, 0.0], [0.0, 1.0]])@@ -162,8 +195,13 @@ def root_mean_squared_disparity_error("""mask = _check_disparity_inputs(input, target, valid_mask)- error = (input - target) ** 2- return _reduce_disparity_error(error, mask, reduction).sqrt()+ # Square in float32 for half-precision inputs: a 300 px disparity error already squares to+ # 90000, past the 65504 float16 ceiling, so the per-pixel map would saturate to inf before any+ # reduction happens. The square root brings the value back into range before the cast back.+ out_dtype = torch.promote_types(input.dtype, target.dtype)+ acc_dtype = torch.promote_types(out_dtype, torch.float32)+ error = (input.to(acc_dtype) - target.to(acc_dtype)) ** 2+ return _reduce_disparity_error(error, mask, reduction).sqrt().to(out_dtype)def mean_bad_pixel_error(@@ -184,8 +222,10 @@ def mean_bad_pixel_error(\text{Bad}_{\tau}(D, D^{gt}) =\frac{1}{|\mathcal{V}|}\sum_{p \in \mathcal{V}} [|D_{p} - D^{gt}_{p}| > \tau]- This corresponds to the bad-pixel percentage reported by the Middlebury and KITTI stereo- benchmarks, expressed as a fraction in :math:`[0, 1]` instead of a percentage.+ This corresponds to the bad-pixel percentage reported by the Middlebury stereo benchmark,+ expressed as a fraction in :math:`[0, 1]` instead of a percentage. It is **not** the number+ KITTI reports: that benchmark uses D1, which adds a relative criterion on top of this one.+ See :func:`kitti_d1_error`.Args:input: the predicted disparity map with arbitrary shape :math:`(*)`.@@ -202,10 +242,22 @@ def mean_bad_pixel_error(Return:the computed metric as a scalar, or the per-pixel bad-pixel map if ``reduction='none'``.+ The scalar is a **fraction** in :math:`[0, 1]`, not a percentage, and a batch is **pooled**+ over every valid pixel of every image rather than averaged per image.Note:If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.+ Note:+ This is an indicator metric built from comparisons, so it has no useful gradient. The+ output does not require grad and cannot be used as a loss.++ Note:+ Sums are accumulated in ``float32`` for ``float16`` and ``bfloat16`` inputs and the result+ is cast back, so ``'mean'`` stays accurate on image-sized maps. ``'sum'`` returns the input+ dtype as well, so a ``float16`` count above 65504 still saturates to ``inf`` β reduce with+ ``'none'`` and sum in a wider dtype if you need counts that large.+Examples:>>> input = torch.zeros(2, 2)>>> target = torch.tensor([[0.0, 1.0], [2.0, 4.0]])@@ -218,5 +270,95 @@ def mean_bad_pixel_error("""mask = _check_disparity_inputs(input, target, valid_mask)- bad = ((input - target).abs() > threshold).to(input.dtype)+ bad = ((input - target).abs() > threshold).to(torch.promote_types(input.dtype, target.dtype))return _reduce_disparity_error(bad, mask, reduction)+++def kitti_d1_error(+ input: torch.Tensor,+ target: torch.Tensor,+ abs_threshold: float = 3.0,+ rel_threshold: float = 0.05,+ valid_mask: Optional[torch.Tensor] = None,+ reduction: str = "mean",+) -> torch.Tensor:+ r"""Compute the KITTI D1 error between two disparity maps.++ A pixel is considered an outlier when its absolute disparity error exceeds ``abs_threshold``+ **and** its relative disparity error exceeds ``rel_threshold``. Given predicted and ground truth+ disparity maps :math:`D` and :math:`D^{gt}` with valid pixels :math:`\mathcal{V}`, the metric is:++ .. math::++ \text{D1}(D, D^{gt}) = \frac{1}{|\mathcal{V}|}\sum_{p \in \mathcal{V}}+ \left[|D_{p} - D^{gt}_{p}| > \tau_{abs} \;\wedge\;+ \frac{|D_{p} - D^{gt}_{p}|}{|D^{gt}_{p}|} > \tau_{rel}\right]++ This is the outlier ratio reported by the KITTI 2015 stereo benchmark, expressed as a fraction+ in :math:`[0, 1]` instead of a percentage. Unlike :func:`mean_bad_pixel_error`, the additional+ relative criterion keeps large disparities from being penalised for errors that are small+ compared to their magnitude.++ Args:+ input: the predicted disparity map with arbitrary shape :math:`(*)`.+ target: the ground truth disparity map with the same shape as ``input``.+ abs_threshold: the absolute disparity error above which a pixel may be an outlier.+ rel_threshold: the relative disparity error above which a pixel may be an outlier.+ valid_mask: optional mask broadcastable to the shape of ``input``, where nonzero+ (``True``) values mark the pixels to evaluate. Non-boolean masks are converted+ to boolean. If ``None``, all pixels are evaluated.+ reduction: specifies the reduction to apply to the output:+ ``'none'`` | ``'mean'`` | ``'sum'``. ``'mean'``: the fraction of outliers among+ the valid pixels, ``'sum'``: the number of outliers among the valid pixels,+ ``'none'``: no reduction will be applied and the per-pixel outlier map is+ returned, with masked-out positions set to zero.++ Return:+ the computed metric as a scalar, or the per-pixel outlier map if ``reduction='none'``.+ The scalar is a **fraction** in :math:`[0, 1]`, not a percentage. A batch is **pooled**:+ every valid pixel of every image contributes equally to one ratio, which is what the KITTI+ devkit accumulates and what the leaderboard reports. That is not the same as averaging the+ per-image D1 values, and the two differ whenever the images hold different numbers of valid+ pixels.++ Note:+ If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.++ Note:+ This is an indicator metric built from comparisons, so it has no useful gradient. The+ output does not require grad and cannot be used as a loss.++ Note:+ Pixels with a zero ground truth disparity yield a non-finite relative error. Because both+ criteria must hold, such pixels are classified by ``abs_threshold`` alone and the output+ stays finite. KITTI marks these pixels as invalid, so prefer passing ``valid_mask``.++ Note:+ A ``nan`` in either map is counted as an **inlier**, because every comparison against+ ``nan`` is false and both criteria must hold. The metric therefore stays finite where+ :func:`mean_absolute_disparity_error` would propagate the ``nan``. Mask non-finite pixels+ out with ``valid_mask`` rather than relying on either behaviour.++ Note:+ Sums are accumulated in ``float32`` for ``float16`` and ``bfloat16`` inputs and the result+ is cast back, so ``'mean'`` stays accurate on image-sized maps. ``'sum'`` returns the input+ dtype as well, so a ``float16`` count above 65504 still saturates to ``inf`` β reduce with+ ``'none'`` and sum in a wider dtype if you need counts that large.++ Examples:+ >>> input = torch.tensor([1.0, 5.0, 104.0, 20.0])+ >>> target = torch.tensor([1.0, 1.0, 100.0, 10.0])+ >>> kitti_d1_error(input, target)+ tensor(0.5000)++ Reference:+ M. Menze and A. Geiger. Object Scene Flow for Autonomous Vehicles. CVPR 2015.+ https://www.cvlibs.net/datasets/kitti/eval_scene_flow.php?benchmark=stereo++ """+ mask = _check_disparity_inputs(input, target, valid_mask)+ error = (input - target).abs()+ outlier = ((error > abs_threshold) & (error / target.abs() > rel_threshold)).to(+ torch.promote_types(input.dtype, target.dtype)+ )+ return _reduce_disparity_error(outlier, mask, reduction)diff --git a/tests/metrics/test_disparity.py b/tests/metrics/test_disparity.pyindex 2a74baae6..54ef345fe 100644--- a/tests/metrics/test_disparity.py+++ b/tests/metrics/test_disparity.py@@ -24,6 +24,126 @@ from kornia.core.exceptions import BaseError, ShapeError, TypeCheckErrorfrom testing.base import BaseTester+def _dynamo_inputs(device, dtype):+ """Build inputs that exercise the masked reduction, the path that must stay compile-friendly."""+ input = torch.rand(2, 4, 5, device=device, dtype=dtype) * 10.0+ target = torch.rand(2, 4, 5, device=device, dtype=dtype) * 10.0 + 1.0+ mask = torch.rand(2, 4, 5, device=device) > 0.3+ return input, target, mask+++_LARGE_VALID = 100_000+_LARGE_INVALID = 20_000+++def _large_masked_inputs(device, dtype):+ """Build a masked disparity pair large enough to overflow a half-precision accumulator.++ ``float16`` saturates at 65504, so summing a map this size in the input dtype yields ``inf``.+ Exactly 3/4 of the 100k valid pixels are off by 100 px on a ground truth disparity of 100, and+ the masked-out tail is wildly wrong so that it changes the result if it ever leaks into a+ reduction.+ """+ n_outliers = 3 * _LARGE_VALID // 4+ target = torch.full((_LARGE_VALID + _LARGE_INVALID,), 100.0, device=device, dtype=dtype)+ input = target.clone()+ input[:n_outliers] = 200.0+ input[_LARGE_VALID:] = 10000.0++ mask = torch.zeros_like(target, dtype=torch.bool)+ mask[:_LARGE_VALID] = True+ return input, target, mask+++_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,+]++[email protected]("metric", _DISPARITY_METRICS, ids=lambda m: m.__name__)[email protected]("int_dtype", [torch.uint8, torch.int32, torch.int64])+def test_convention_integer_disparity_maps_are_rejected(metric, int_dtype, device):+ """An integer disparity map must raise rather than return a truncated number.++ The reductions accumulate in float32 and cast back to the map's dtype, which for an integer map+ truncates the ratio: every metric here returned 0 for a true value of 0.5 before the guard.+ That is not a hypothetical input, since KITTI ships disparity as a uint16 PNG and+ ``torch.from_numpy(imread(...))`` hands back an integer tensor, so the failure would show up as+ a plausible-looking score rather than an error.+ """+ target = torch.tensor([10, 10], device=device, dtype=int_dtype)+ input = torch.tensor([10, 20], device=device, dtype=int_dtype)++ with pytest.raises(BaseError) as errinfo:+ metric(input, target)+ assert "floating point" in str(errinfo.value)++ # the same maps as floats still work; the integer path truncated each of these toward zero+ expected = {+ kornia.metrics.mean_absolute_disparity_error: 5.0, # mean(|0|, |10|), truncated to 5+ kornia.metrics.root_mean_squared_disparity_error: 50.0**0.5, # sqrt(mean(0, 100)), truncated to 7+ kornia.metrics.mean_bad_pixel_error: 0.5, # 1 of 2 pixels over 3 px, truncated to 0+ kornia.metrics.kitti_d1_error: 0.5, # 1 of 2 pixels over both thresholds, truncated to 0+ }[metric]+ assert metric(input.float(), target.float()).item() == pytest.approx(expected, rel=1e-5)+++def _can_hold(device: torch.device, dtype: torch.dtype) -> bool:+ """Probe whether a backend can allocate a dtype at all, rather than hardcoding per backend.++ MPS has no float64, so the float32-by-float64 pair below cannot even be built there. Probing+ at runtime means the wider pair starts being exercised on its own once a backend gains the+ dtype, instead of staying permanently skipped behind a device name.+ """+ try:+ torch.zeros(1, device=device, dtype=dtype)+ except (TypeError, RuntimeError, NotImplementedError):+ return False+ return True++[email protected]("metric", _DISPARITY_METRICS, ids=lambda m: m.__name__)+def test_convention_result_dtype_is_the_promoted_one(metric, device):+ """A mixed-dtype pair returns the promoted dtype, the same for every metric in the module.++ float32 by float64 is the pair that regressed: it returned float64 before the half-precision+ reduction fix and float32 after, while mean_absolute_disparity_error kept returning float64.+ float16 by float32 makes the same point on a backend that cannot hold float64, so the rule is+ checked everywhere rather than only where the regression was first measured.+ """+ pairs = [(torch.float16, torch.float32, torch.float32)]+ if _can_hold(device, torch.float64):+ pairs.append((torch.float32, torch.float64, torch.float64))++ for input_dtype, target_dtype, expected in pairs:+ target = torch.rand(8, device=device, dtype=target_dtype) * 100.0+ input = (target + 4.0).to(input_dtype)++ assert metric(input, target).dtype == expected+ assert metric(input.to(target_dtype), target).dtype == target_dtype+ assert metric(input, target.to(input_dtype)).dtype == input_dtype+++ "metric", [kornia.metrics.mean_bad_pixel_error, kornia.metrics.kitti_d1_error], ids=lambda m: m.__name__+)+def test_convention_indicator_metrics_have_no_gradient(metric, device):+ """Both indicator metrics are built from comparisons, so they carry no gradient.++ Documented rather than fixed: a counting metric has no useful derivative. The contrast with+ ``mean_absolute_disparity_error``, which does propagate gradients, is what makes it worth+ pinning, since the two live in the same module and look interchangeable.+ """+ target = torch.rand(8, device=device, dtype=torch.float32) * 100.0+ input = (target.clone() + 4.0).requires_grad_()++ assert not metric(input, target).requires_grad+ assert kornia.metrics.mean_absolute_disparity_error(input, target).requires_grad++class TestMeanAbsoluteDisparityError(BaseTester):def test_smoke(self, device, dtype):input = torch.rand(2, 1, 4, 5, device=device, dtype=dtype)@@ -115,6 +235,19 @@ class TestMeanAbsoluteDisparityError(BaseTester):kornia.metrics.mean_absolute_disparity_error(sample, 2.0 * sample, reduction="foo")assert "Invalid reduction option." in str(errinfo.value)+ def test_large_masked_reduction(self, device, dtype):+ # 3/4 of the valid pixels are off by 100 px, the rest are exact.+ input, target, mask = _large_masked_inputs(device, dtype)+ actual = kornia.metrics.mean_absolute_disparity_error(input, target, mask)+ self.assert_close(actual, torch.tensor(75.0, device=device, dtype=dtype))+ assert actual.dtype == dtype++ def test_dynamo(self, device, dtype, torch_optimizer):+ input, target, mask = _dynamo_inputs(device, dtype)+ op = kornia.metrics.mean_absolute_disparity_error+ op_optimized = torch_optimizer(op)+ self.assert_close(op(input, target, mask), op_optimized(input, target, mask))+class TestRootMeanSquaredDisparityError(BaseTester):def test_smoke(self, device, dtype):@@ -175,6 +308,30 @@ class TestRootMeanSquaredDisparityError(BaseTester):kornia.metrics.root_mean_squared_disparity_error(sample, 2.0 * sample, reduction="foo")assert "Invalid reduction option." in str(errinfo.value)+ def test_large_masked_reduction(self, device, dtype):+ # sqrt(0.75 * 100^2)+ input, target, mask = _large_masked_inputs(device, dtype)+ actual = kornia.metrics.root_mean_squared_disparity_error(input, target, mask)+ self.assert_close(actual, torch.tensor(86.6025403784, device=device, dtype=dtype))+ assert actual.dtype == dtype++ def test_large_error_does_not_saturate_the_square(self, device, dtype):+ # 300^2 = 90000 is past the float16 ceiling, so the squared error map must not be+ # accumulated in the input dtype.+ target = torch.full((64,), 100.0, device=device, dtype=dtype)+ input = target + 300.0+ actual = kornia.metrics.root_mean_squared_disparity_error(input, target)+ self.assert_close(actual, torch.tensor(300.0, device=device, dtype=dtype))++ actual_none = kornia.metrics.root_mean_squared_disparity_error(input, target, reduction="none")+ self.assert_close(actual_none, torch.full((64,), 300.0, device=device, dtype=dtype))++ def test_dynamo(self, device, dtype, torch_optimizer):+ input, target, mask = _dynamo_inputs(device, dtype)+ op = kornia.metrics.root_mean_squared_disparity_error+ op_optimized = torch_optimizer(op)+ self.assert_close(op(input, target, mask), op_optimized(input, target, mask))+class TestMeanBadPixelError(BaseTester):def test_smoke(self, device, dtype):@@ -246,3 +403,186 @@ class TestMeanBadPixelError(BaseTester):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)++ def test_large_masked_reduction(self, device, dtype):+ # 3/4 of the valid pixels are off by 100 px, well past the 3 px threshold.+ input, target, mask = _large_masked_inputs(device, dtype)+ actual = kornia.metrics.mean_bad_pixel_error(input, target, valid_mask=mask)+ self.assert_close(actual, torch.tensor(0.75, device=device, dtype=dtype))+ assert actual.dtype == dtype++ def test_dynamo(self, device, dtype, torch_optimizer):+ input, target, mask = _dynamo_inputs(device, dtype)+ op = kornia.metrics.mean_bad_pixel_error+ op_optimized = torch_optimizer(op)+ self.assert_close(op(input, target, 0.5, mask), op_optimized(input, target, 0.5, mask))+++class TestKittiD1Error(BaseTester):+ # D1 marks a pixel as an outlier only when BOTH criteria hold:+ # |d - d_gt| > abs_threshold AND |d - d_gt| / |d_gt| > rel_threshold+ # errors = [0.0, 4.0, 4.0, 10.0]+ # relative = [0.0, 4.0, 0.04, 1.0]+ # abs > 3 = [F, T, T, T]+ # rel > .05 = [F, T, F, T]+ # outlier = [0, 1, 0, 1] -> mean 0.5, sum 2.0+ INPUT = [1.0, 5.0, 104.0, 20.0]+ TARGET = [1.0, 1.0, 100.0, 10.0]++ def _sample(self, device, dtype):+ return (+ torch.tensor(self.INPUT, device=device, dtype=dtype),+ torch.tensor(self.TARGET, device=device, dtype=dtype),+ )++ def test_smoke(self, device, dtype):+ # Scaled to a realistic disparity range on purpose: on maps drawn from [0, 1) the error can+ # never exceed the 3 px absolute threshold, so the outlier branch would never be taken and+ # the metric would be a constant 0 whatever the implementation did.+ input = 100.0 * torch.rand(2, 1, 4, 5, device=device, dtype=dtype)+ target = 100.0 * torch.rand(2, 1, 4, 5, device=device, dtype=dtype)+ actual = kornia.metrics.kitti_d1_error(input, target)+ assert actual.shape == torch.Size([])+ assert 0.0 <= actual.item() <= 1.0+ per_pixel = kornia.metrics.kitti_d1_error(input, target, reduction="none")+ assert per_pixel.shape == input.shape+ assert bool((per_pixel > 0).any()), "the outlier branch was never exercised"++ def test_metric_mean_reduction(self, device, dtype):+ input, target = self._sample(device, dtype)+ expected = torch.tensor(0.5, device=device, dtype=dtype)+ actual = kornia.metrics.kitti_d1_error(input, target, reduction="mean")+ self.assert_close(actual, expected)++ def test_metric_sum_reduction(self, device, dtype):+ input, target = self._sample(device, dtype)+ expected = torch.tensor(2.0, device=device, dtype=dtype)+ actual = kornia.metrics.kitti_d1_error(input, target, reduction="sum")+ self.assert_close(actual, expected)++ def test_metric_no_reduction(self, device, dtype):+ input, target = self._sample(device, dtype)+ expected = torch.tensor([0.0, 1.0, 0.0, 1.0], device=device, dtype=dtype)+ actual = kornia.metrics.kitti_d1_error(input, target, reduction="none")+ self.assert_close(actual, expected)++ def test_perfect_prediction(self, device, dtype):+ sample = torch.rand(4, 4, device=device, dtype=dtype) + 1.0+ expected = torch.tensor(0.0, device=device, dtype=dtype)+ actual = kornia.metrics.kitti_d1_error(sample, sample)+ self.assert_close(actual, expected)++ def test_absolute_criterion_alone_is_not_an_outlier(self, device, dtype):+ # 4 px of error on a disparity of 100 exceeds the 3 px threshold but is only 4% relative+ # error, so D1 does not count it, while the plain bad-pixel metric does.+ input = torch.tensor([104.0], device=device, dtype=dtype)+ target = torch.tensor([100.0], device=device, dtype=dtype)+ self.assert_close(kornia.metrics.kitti_d1_error(input, target), torch.tensor(0.0, device=device, dtype=dtype))+ self.assert_close(+ kornia.metrics.mean_bad_pixel_error(input, target), torch.tensor(1.0, device=device, dtype=dtype)+ )++ def test_relative_criterion_alone_is_not_an_outlier(self, device, dtype):+ # 2 px of error on a disparity of 10 is 20% relative error but stays within the 3 px+ # absolute threshold, so D1 does not count it either.+ input = torch.tensor([12.0], device=device, dtype=dtype)+ target = torch.tensor([10.0], device=device, dtype=dtype)+ expected = torch.tensor(0.0, device=device, dtype=dtype)+ self.assert_close(kornia.metrics.kitti_d1_error(input, target), expected)++ # Snippet used to generate expected (the devkit predicate, evaluate_scene_flow.cpp:13-14,51):+ # d_err = fabs(d_gt - d_est) > 3.0 && fabs(d_gt - d_est) / fabs(d_gt) > 0.05+ # (10, 13): err 3.0, rel 0.300 -> 3.0 > 3.0 is False -> 0.0+ # (100, 105): err 5.0, rel 0.050 -> 0.05 > 0.05 is False -> 0.0+ # (78, 82): err 4.0, rel 4/78 = 0.05128 > 0.05, 4/82 = 0.04878 -> 1.0+ # (-100, -90): err 10.0, rel 10/|-100| = 0.100 -> 1.0+ @pytest.mark.parametrize(+ ("target_value", "input_value", "expected_value"),+ [(10.0, 13.0, 0.0), (100.0, 105.0, 0.0), (78.0, 82.0, 1.0), (-100.0, -90.0, 1.0)],+ ids=["abs-exactly-at-threshold", "rel-exactly-at-threshold", "gt-is-the-denominator", "negative-gt"],+ )+ def test_convention_boundary_cases(self, target_value, input_value, expected_value, device, dtype):+ """Pin the two details that distinguish D1 from a near-miss implementation.++ Both comparisons are strict, so a pixel sitting exactly on either threshold is an inlier.+ Making either one non-strict flips the first two cases. The relative error divides by the+ **ground truth**, not the prediction: at (78, 82) the two give 0.05128 and 0.04878, which+ straddle the 0.05 threshold, so swapping the denominator flips that case. The negative pair+ pins the ``fabs(d_gt)`` in the devkit, since a signed denominator makes the ratio negative+ and never greater than the threshold.+ """+ input = torch.tensor([input_value], device=device, dtype=dtype)+ target = torch.tensor([target_value], device=device, dtype=dtype)+ expected = torch.tensor(expected_value, device=device, dtype=dtype)+ self.assert_close(kornia.metrics.kitti_d1_error(input, target), expected)++ def test_thresholds(self, device, dtype):+ input = torch.tensor([104.0], device=device, dtype=dtype)+ target = torch.tensor([100.0], device=device, dtype=dtype)++ # lowering the relative threshold below the 4% relative error makes the pixel an outlier+ actual = kornia.metrics.kitti_d1_error(input, target, rel_threshold=0.01)+ self.assert_close(actual, torch.tensor(1.0, device=device, dtype=dtype))++ # raising the absolute threshold above the 4 px error rules it out again+ actual = kornia.metrics.kitti_d1_error(input, target, abs_threshold=5.0, rel_threshold=0.01)+ self.assert_close(actual, torch.tensor(0.0, device=device, dtype=dtype))++ def test_valid_mask(self, device, dtype):+ input, target = self._sample(device, dtype)+ mask = torch.tensor([True, True, True, False], device=device)++ actual_mean = kornia.metrics.kitti_d1_error(input, target, valid_mask=mask, reduction="mean")+ self.assert_close(actual_mean, torch.tensor(1.0 / 3.0, device=device, dtype=dtype))++ actual_sum = kornia.metrics.kitti_d1_error(input, target, valid_mask=mask, reduction="sum")+ self.assert_close(actual_sum, torch.tensor(1.0, device=device, dtype=dtype))++ actual_none = kornia.metrics.kitti_d1_error(input, target, valid_mask=mask, reduction="none")+ expected_none = torch.tensor([0.0, 1.0, 0.0, 0.0], device=device, dtype=dtype)+ self.assert_close(actual_none, expected_none)++ def test_zero_target_disparity(self, device, dtype):+ # A zero ground truth disparity makes the relative error non-finite. Because both criteria+ # must hold, such pixels fall back to the absolute threshold and the output stays finite.+ input = torch.tensor([0.0, 5.0], device=device, dtype=dtype)+ target = torch.tensor([0.0, 0.0], device=device, dtype=dtype)++ actual = kornia.metrics.kitti_d1_error(input, target, reduction="none")+ expected = torch.tensor([0.0, 1.0], device=device, dtype=dtype)+ self.assert_close(actual, expected)+ assert torch.isfinite(actual).all()++ def test_exception(self, device, dtype):+ sample = torch.ones(4, 4, device=device, dtype=dtype)++ with pytest.raises(TypeCheckError) as errinfo:+ kornia.metrics.kitti_d1_error(None, sample)+ assert "Type mismatch: expected Tensor" in str(errinfo.value)++ with pytest.raises(ShapeError) as errinfo:+ kornia.metrics.kitti_d1_error(sample, sample[..., :2])+ assert "Shape mismatch" in str(errinfo.value)++ with pytest.raises(BaseError) as errinfo:+ mask = torch.ones(3, device=device, dtype=torch.bool)+ kornia.metrics.kitti_d1_error(sample, sample, valid_mask=mask)+ assert "broadcastable" 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)++ def test_large_masked_reduction(self, device, dtype):+ # 3/4 of the valid pixels are off by 100 px on a disparity of 100: 100 % relative error,+ # so both criteria hold and the outlier ratio is exactly 0.75.+ input, target, mask = _large_masked_inputs(device, dtype)+ actual = kornia.metrics.kitti_d1_error(input, target, valid_mask=mask)+ self.assert_close(actual, torch.tensor(0.75, device=device, dtype=dtype))+ assert actual.dtype == dtype++ def test_dynamo(self, device, dtype, torch_optimizer):+ input, target, mask = _dynamo_inputs(device, dtype)+ op = kornia.metrics.kitti_d1_error+ op_optimized = torch_optimizer(op)+ self.assert_close(op(input, target, 3.0, 0.05, mask), op_optimized(input, target, 3.0, 0.05, mask))