π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): validate histogram bandwidths (#5347)
Arc0000074e3ce6dfc226
diff --git a/changelog.d/5347.breaking.md b/changelog.d/5347.breaking.mdnew file mode 100644index 000000000..458fe94cd--- /dev/null+++ b/changelog.d/5347.breaking.md@@ -0,0 +1 @@+`histogram`, `histogram2d` and `image_histogram2d` now reject a bandwidth that is zero, negative or not finite, and `image_histogram2d` also rejects `n_bins < 1` and an empty or non-finite `[min, max]` range when it builds the centers or the bandwidth from them. These inputs used to return NaNs or meaningless values, or a low-level error (`n_bins=0` raised `ZeroDivisionError`); `histogram` and `histogram2d` returned the same result for a negative bandwidth as for its absolute value. `histogram` and `histogram2d` now raise `RuntimeError` from an asynchronous check, like the other tensor-parameter checks in `kornia.enhance` (skipped on MPS); `image_histogram2d` raises `ValueError`. `image_histogram2d` now treats its documented `bandwidth=-1` as the automatic bandwidth, where it used to apply -1 as a literal negative bandwidth, and an empty `centers` tensor as automatic centers, where it used to return zero bins.diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.pyindex 07d812ca7..edc3f1b6f 100644--- a/kornia/enhance/histogram.py+++ b/kornia/enhance/histogram.py@@ -15,12 +15,15 @@# limitations under the License.#+import mathfrom typing import Optional, Tupleimport torchfrom kornia.core.exceptions import ShapeError+from .adjust import _assert_async_value_check+def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor, epsilon: float = 1e-10@@ -57,6 +60,10 @@ def marginal_pdf(if not sigma.dim() == 0:raise ValueError(f"Input sigma must be a of the shape 1. Got {sigma.shape}")+ # Asynchronous like the other tensor-parameter checks in kornia.enhance: no host sync, and a compiled graph+ # keeps the check instead of skipping it.+ _assert_async_value_check(torch.isfinite(sigma) & (sigma > 0), "Bandwidth must be finite and greater than zero.")+residuals = values - bins.unsqueeze(0).unsqueeze(0)kernel_values = torch.exp(-0.5 * (residuals / sigma).pow(2))@@ -178,6 +185,32 @@ def _restore_float_dtype(hist: torch.Tensor, image: torch.Tensor, auto_centers:return hist+def _is_finite(value: float) -> bool:+ """Same as ``math.isfinite``, but traceable when Dynamo turns a changed float argument into a symbolic float."""+ return -math.inf < value < math.inf+++def _validate_histogram_bandwidth(+ min: float, max: float, n_bins: int, bandwidth: Optional[float], auto_centers: bool+) -> float:+ """Validate the range needed for automatic values and resolve the bandwidth sentinel."""+ auto_bandwidth = bandwidth is None or bandwidth == -1.0+ if auto_centers or auto_bandwidth:+ if n_bins <= 0:+ raise ValueError(f"n_bins must be greater than zero for automatically generated values. Got {n_bins}.")+ if not _is_finite(min) or not _is_finite(max) or max <= min:+ raise ValueError(+ f"The automatically generated histogram range must be finite and non-empty. Got [{min}, {max}]."+ )++ if bandwidth is None or bandwidth == -1.0:+ bandwidth = (max - min) / n_bins++ if not _is_finite(bandwidth) or bandwidth <= 0.0:+ raise ValueError(f"Bandwidth must be finite and greater than zero. Got {bandwidth}.")+ return bandwidth++def image_histogram2d(image: torch.Tensor,min: float = 0.0,@@ -201,11 +234,11 @@ def image_histogram2d(:attr:`centers` is specified.n_bins: The number of histogram bins. Ignored when:attr:`centers` is specified.- bandwidth: Smoothing factor. If not specified or equal to -1,- :math:`(bandwidth = (max - min) / n_bins)`.+ bandwidth: Positive finite smoothing factor. If not specified or equal to -1,+ it is calculated as :math:`(max - min) / n_bins`.centers: Centers of the bins with shape :math:`(n_bins,)`.- If not specified or empty, it is calculated as centers of- equal width bins of [min, max] range.+ If not specified or empty, it is calculated as centers of equal-width bins+ over the non-empty finite [min, max] range.return_pdf: If True, also return probability densities foreach bin.kernel: kernel to perform kernel density estimation@@ -246,10 +279,11 @@ def image_histogram2d(if not isinstance(return_pdf, bool):raise TypeError(f"Return_pdf type is not a bool. Got {type(return_pdf)}.")- if bandwidth is None:- bandwidth = (max - min) / n_bins-+ if centers is not None and centers.numel() == 0:+ centers = Noneauto_centers = centers is None+ bandwidth = _validate_histogram_bandwidth(min, max, n_bins, bandwidth, auto_centers)+if centers is None:# Build the bin-center grid at a dtype that represents the bin indices exactly: image.dtype alone collapses# distinct centers for float16/bfloat16, and a fixed float32 would downgrade a float64 image.diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.pyindex f1b60e6ea..217eae158 100644--- a/kornia/enhance/zca.py+++ b/kornia/enhance/zca.py@@ -118,7 +118,7 @@ class ZCAWhitening(nn.Module):unexpected_keys: list[str],error_msgs: list[str],) -> None:- version = local_metadata.get("version", None)+ version = local_metadata.get("version")for name in ("mean_vector", "transform_matrix", "transform_inv"):key = prefix + namecurrent = self._buffers[name]diff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.pyindex 61a3f902f..252b9ffc2 100644--- a/tests/enhance/test_histogram.py+++ b/tests/enhance/test_histogram.py@@ -195,6 +195,71 @@ class TestImageHistogram2d(BaseTester):assert hist.dtype == torch.float64assert pdf.dtype == torch.float64+ @pytest.mark.parametrize("bandwidth", [0.0, -2.0, float("nan"), float("inf"), float("-inf")])+ def test_rejects_invalid_bandwidth(self, bandwidth):+ image = torch.ones(4, 4)+ with pytest.raises(ValueError, match="Bandwidth must be finite and greater than zero"):+ TestImageHistogram2d.fcn(image, bandwidth=bandwidth)++ @pytest.mark.parametrize(+ "bounds", [(0.0, 0.0), (1.0, 0.0), (float("nan"), 1.0), (float("-inf"), 0.0), (0.0, float("inf"))]+ )+ @pytest.mark.parametrize("empty_centers", [False, True])+ def test_rejects_invalid_automatically_generated_range(self, bounds, empty_centers):+ centers = torch.empty(0) if empty_centers else None+ with pytest.raises(ValueError, match="automatically generated histogram range"):+ TestImageHistogram2d.fcn(torch.ones(4, 4), min=bounds[0], max=bounds[1], centers=centers)++ def test_automatic_centers_need_a_range_with_explicit_bandwidth(self):+ # Automatic centers are spread over [min, max], so an explicit bandwidth does not waive the range check.+ with pytest.raises(ValueError, match="automatically generated histogram range"):+ TestImageHistogram2d.fcn(torch.ones(4, 4), min=0.0, max=0.0, bandwidth=0.5)++ def test_negative_one_bandwidth_with_explicit_centers_needs_a_range(self):+ # The automatic bandwidth is (max - min) / n_bins, so the sentinel needs the range even with explicit centers.+ centers = torch.tensor([0.25, 0.75])+ with pytest.raises(ValueError, match="automatically generated histogram range"):+ TestImageHistogram2d.fcn(torch.ones(4, 4), min=0.0, max=0.0, bandwidth=-1.0, centers=centers)++ def test_rejects_zero_bins_for_automatic_values(self):+ with pytest.raises(ValueError, match="n_bins must be greater than zero"):+ TestImageHistogram2d.fcn(torch.ones(4, 4), 0.0, 1.0, 0)++ @pytest.mark.parametrize("kernel", ["triangular", "gaussian", "uniform", "epanechnikov"])+ def test_negative_one_bandwidth_selects_automatic_value(self, kernel):+ image = torch.rand(8, 8)+ hist_auto, pdf_auto = TestImageHistogram2d.fcn(image, 0.0, 1.0, 4, kernel=kernel, return_pdf=True)+ hist_sentinel, pdf_sentinel = TestImageHistogram2d.fcn(+ image, 0.0, 1.0, 4, bandwidth=-1.0, kernel=kernel, return_pdf=True+ )+ torch.testing.assert_close(hist_sentinel, hist_auto)+ torch.testing.assert_close(pdf_sentinel, pdf_auto)++ def test_explicit_centers_and_bandwidth_do_not_require_an_automatic_range(self):+ centers = torch.tensor([0.25, 0.75])+ hist, pdf = TestImageHistogram2d.fcn(+ torch.ones(4, 4), min=0.0, max=0.0, bandwidth=0.5, centers=centers, return_pdf=True+ )+ assert torch.isfinite(hist).all()+ assert torch.isfinite(pdf).all()++ def test_empty_centers_select_automatic_centers(self):+ image = torch.rand(4, 4)+ hist_none, pdf_none = TestImageHistogram2d.fcn(image, 0.0, 1.0, 4, return_pdf=True)+ hist_empty, pdf_empty = TestImageHistogram2d.fcn(image, 0.0, 1.0, 4, centers=torch.empty(0), return_pdf=True)+ torch.testing.assert_close(hist_empty, hist_none)+ torch.testing.assert_close(pdf_empty, pdf_none)++ def test_dynamo_fullgraph_traces_changing_range_and_bandwidth(self):+ # A changed float argument recompiles with a symbolic float, and the range and bandwidth checks must stay+ # traceable for it (math.isfinite on a symbolic float breaks the graph on torch 2.14).+ torch._dynamo.reset()+ compiled = torch.compile(TestImageHistogram2d.fcn, fullgraph=True, backend="eager")+ image = torch.linspace(0.0, 1.0, 6).reshape(2, 3)+ for max_value, bandwidth in [(1.0, None), (2.0, None), (1.0, 0.5), (1.0, 0.25)]:+ expected = TestImageHistogram2d.fcn(image, 0.0, max_value, 2, bandwidth)[0]+ self.assert_close(compiled(image, 0.0, max_value, 2, bandwidth)[0], expected)+class TestHistogram2d(BaseTester):fcn = kornia.enhance.histogram2d@@ -287,3 +352,25 @@ class TestHistogram(BaseTester):pdf = TestHistogram.fcn(input1, input2, bandwidth)ans = 0.1 * torch.ones(1, 10, device=device, dtype=dtype)self.assert_close(ans, pdf)++ @pytest.mark.parametrize("bandwidth", [0.0, -1.0, float("nan"), float("inf"), float("-inf")])+ def test_rejects_invalid_bandwidth(self, bandwidth):+ value = torch.tensor(bandwidth)+ bins = torch.tensor([0.0, 1.0])+ samples = torch.tensor([[0.0, 1.0]])+ # CPU tensors: the asynchronous value assert raises synchronously there.+ with pytest.raises(RuntimeError, match="Bandwidth must be finite and greater than zero"):+ kornia.enhance.histogram(samples, bins, value)+ with pytest.raises(RuntimeError, match="Bandwidth must be finite and greater than zero"):+ kornia.enhance.histogram2d(samples, samples, bins, value)++ def test_dynamo_fullgraph_rejects_invalid_bandwidth(self):+ # The compiled graph carries the same bandwidth check as eager instead of skipping it.+ torch._dynamo.reset()+ compiled = torch.compile(kornia.enhance.histogram, fullgraph=True, backend="eager")+ bins = torch.tensor([0.0, 1.0])+ samples = torch.tensor([[0.0, 1.0]])+ bandwidth = torch.tensor(0.5)+ self.assert_close(compiled(samples, bins, bandwidth), kornia.enhance.histogram(samples, bins, bandwidth))+ with pytest.raises(RuntimeError, match="Bandwidth must be finite and greater than zero"):+ compiled(samples, bins, torch.tensor(0.0))