Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): stabilize low-precision histogram counts and gradients (#5988)

Karnajeet Gosavi7e48560b248c
diff --git a/changelog.d/5988.fixed.md b/changelog.d/5988.fixed.md
new file mode 100644
index 000000000..ac7f90c9e
--- /dev/null
+++ b/changelog.d/5988.fixed.md
@@ -0,0 +1 @@
+`image_histogram2d` now returns float32 counts and pdf for float16 and bfloat16 images, with automatic centers or centers of the image dtype, instead of the image dtype; cast the result if you need the image dtype. In float16 a bin count above 65504, such as the black half of a 512x512 image, used to become `inf` and its pdf `NaN`, and bfloat16 counts were rounded (66048 instead of 65998). The 1-D `histogram` now evaluates float16 and bfloat16 kernels in float32 and still returns the input dtype: at 65536 samples, 64 bins and bandwidth 0.01 its float16 gradient had a 34 % relative error against float64 and now follows it.
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 52e502f26..4afcad7e1 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -118,6 +118,8 @@ def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsi
histogram2d uses the same batch convention for a joint density. bandwidth must be
finite and positive; the check runs on CPU and CUDA via ``torch._assert_async`` and
raises ``RuntimeError``. kornia skips it on MPS by design, so invalid values do not raise there.
+ For float16 and bfloat16 samples and bins, the kernels are evaluated in float32 and the result
+ is cast back to that dtype.
The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
@@ -138,6 +140,13 @@ def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsi
torch.Size([1, 128])
"""
+ # In half precision the gradient reaches the samples through per-bin terms below the normal range: evaluate the
+ # kernels in float32. The 0-d bandwidth does not promote the kernels, so it does not pick the dtype either.
+ kernel_dtype = torch.promote_types(x.dtype, bins.dtype)
+ if kernel_dtype in (torch.float16, torch.bfloat16):
+ pdf, _ = marginal_pdf(x.float().unsqueeze(2), bins.float(), bandwidth.float(), epsilon)
+ return pdf.to(kernel_dtype)
+
pdf, _ = marginal_pdf(x.unsqueeze(2), bins, bandwidth, epsilon)
return pdf
@@ -193,12 +202,12 @@ def _check_image_rank(image: torch.Tensor) -> None:
def _restore_float_dtype(hist: torch.Tensor, image: torch.Tensor, auto_centers: bool) -> torch.Tensor:
- """Hand back the image's own dtype after wider bin centers promoted the result.
+ """Hand back the image's dtype when it can represent the histogram counts.
Only for auto-built centers on a floating-point image: an integer image or explicit ``centers`` keep the promoted
- dtype they always had, and casting a KDE result into an integer dtype would truncate it (uint8 wraps modulo 256).
+ dtype (at least float32), and half-precision counts stay float32 because ordinary image counts exceed their range.
"""
- if auto_centers and image.is_floating_point():
+ if auto_centers and image.is_floating_point() and image.dtype not in (torch.float16, torch.bfloat16):
return hist.to(image.dtype)
return hist
@@ -246,7 +255,9 @@ def image_histogram2d(
Spatial axes are the final two axes; input (H, W), (C, H, W), and
(B, C, H, W) return matching leading axes followed by bins; other ranks raise. Automatic
centers lie at min + (i + 0.5) * bandwidth; values outside the supplied range contribute
- according to the selected kernel rather than being clipped into an endpoint bin.
+ according to the selected kernel rather than being clipped into an endpoint bin. Float16 and
+ bfloat16 images are accumulated and returned in float32, or in the dtype of wider explicit
+ ``centers``: the bin counts of ordinary images exceed float16's range (65504) and bfloat16's precision.
The calculation uses triangular kernel density estimation.
@@ -308,14 +319,14 @@ def image_histogram2d(
auto_centers = centers is None
bandwidth = _validate_histogram_bandwidth(min, max, n_bins, bandwidth, auto_centers)
+ # Preserve the supplied center precision while promoting half inputs enough to represent image-sized counts.
+ center_dtype = centers.dtype if centers is not None else torch.float32
+ compute_dtype = torch.promote_types(torch.float32, torch.promote_types(image.dtype, center_dtype))
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.
- compute_dtype = torch.promote_types(image.dtype, torch.float32)
centers = min + bandwidth * (torch.arange(n_bins, device=image.device, dtype=compute_dtype) + 0.5)
- centers = centers.reshape(-1, 1, 1, 1, 1)
+ centers = centers.to(compute_dtype).reshape(-1, 1, 1, 1, 1)
- u = torch.abs(image.unsqueeze(0) - centers) / bandwidth
+ u = torch.abs(image.to(compute_dtype).unsqueeze(0) - centers) / bandwidth
if kernel == "gaussian":
kernel_values = torch.exp(-0.5 * u**2)
diff --git a/tests/enhance/test_conventions_enhance.py b/tests/enhance/test_conventions_enhance.py
index 34964a25c..fcad5fb66 100644
--- a/tests/enhance/test_conventions_enhance.py
+++ b/tests/enhance/test_conventions_enhance.py
@@ -82,13 +82,16 @@ class TestEnhanceConventions(BaseTester):
def test_convention_image_histogram_triangular_range(self, device, dtype):
# Centers are 0.25 and 0.75; 1.1 lies outside [0, 1] and keeps its triangular weight
- # 1 - 0.35 / 0.5 = 0.3 for the 0.75 bin instead of being clipped to 1.0 (weight 0.5) or dropped.
+ # for the 0.75 bin instead of being clipped to 1.0 (weight 0.5) or dropped.
image = torch.tensor([[0.25, 1.1]], device=device, dtype=dtype)
hist, pdf = kornia.enhance.image_histogram2d(
image, min=0.0, max=1.0, n_bins=2, bandwidth=0.5, kernel="triangular", return_pdf=True
)
- self.assert_close(hist, torch.tensor([1.0, 0.3], device=device, dtype=dtype))
- self.assert_close(pdf, torch.tensor([1.0, 0.3], device=device, dtype=dtype) / 1.3)
+ output_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ weight = 1.0 - (image[0, 1].to(output_dtype) - 0.75).abs() / 0.5
+ expected_hist = torch.stack((torch.ones((), device=device, dtype=output_dtype), weight))
+ self.assert_close(hist, expected_hist)
+ self.assert_close(pdf, expected_hist / expected_hist.sum())
def test_convention_image_histogram_automatic_centers_follow_bandwidth(self, device, dtype):
image = torch.tensor([[0.125]], device=device, dtype=dtype)
@@ -96,7 +99,8 @@ class TestEnhanceConventions(BaseTester):
image, min=0.0, max=1.0, n_bins=2, bandwidth=0.25, kernel="triangular"
)
# Centers are 0.125 and 0.375, generated as min + (i + 0.5) * bandwidth.
- self.assert_close(hist, torch.tensor([1.0, 0.0], device=device, dtype=dtype))
+ output_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ self.assert_close(hist, torch.tensor([1.0, 0.0], device=device, dtype=output_dtype))
@pytest.mark.parametrize("explicit_center", [False, True])
@pytest.mark.parametrize("return_pdf", [False, True])
diff --git a/tests/enhance/test_histogram.py b/tests/enhance/test_histogram.py
index 88b11ccfc..78b9ad0ed 100644
--- a/tests/enhance/test_histogram.py
+++ b/tests/enhance/test_histogram.py
@@ -142,12 +142,8 @@ class TestImageHistogram2d(BaseTester):
@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
@pytest.mark.parametrize("return_pdf", [False, True])
- def test_auto_centers_preserve_input_dtype(self, device, dtype, return_pdf):
- """The float32-centers fix above (test_large_n_bins_float16_centers_not_collapsed)
- must not itself change the function's public return dtype: before that fix, a
- float16/bfloat16 image with centers=None returned float16/bfloat16 hist/pdf. Building
- centers at float32 promotes u/kernel_values through ordinary PyTorch type promotion,
- so hist/pdf must be explicitly cast back to image.dtype at the return boundary."""
+ def test_auto_centers_use_float32_for_low_precision_counts(self, device, dtype, return_pdf):
+ """Half-precision counts can exceed the dtype's finite range, so keep those counts in float32."""
if device.type == "mps" and dtype == torch.bfloat16 and torch_version_lt(2, 14, 0):
pytest.skip("bfloat16 on MPS is only exercised on torch >= 2.14 (the version of the blocking MPS job)")
torch.manual_seed(0)
@@ -155,8 +151,23 @@ class TestImageHistogram2d(BaseTester):
hist, pdf = TestImageHistogram2d.fcn(image, 0.0, 1.0, 64, kernel="gaussian", return_pdf=return_pdf)
- assert hist.dtype == dtype
- assert pdf.dtype == dtype
+ assert hist.dtype == torch.float32
+ assert pdf.dtype == torch.float32
+
+ @pytest.mark.parametrize("explicit_centers", [False, True])
+ def test_float16_large_image_counts_and_pdf_are_finite(self, device, explicit_centers):
+ torch.manual_seed(0)
+ image = torch.rand(1, 1, 512, 512, device=device, dtype=torch.float16) * 255.0
+ image[..., :256, :] = 0.0
+ centers = torch.arange(256, device=device, dtype=torch.float16) if explicit_centers else None
+
+ hist, pdf = TestImageHistogram2d.fcn(image, 0.0, 255.0, 256, centers=centers, return_pdf=True)
+
+ assert hist.dtype == torch.float32
+ assert pdf.dtype == torch.float32
+ assert torch.isfinite(hist).all()
+ assert torch.isfinite(pdf).all()
+ assert hist[..., 0].max() > 65504
@pytest.mark.parametrize("dtype", [torch.uint8, torch.int32])
def test_integer_image_is_not_cast_into_an_integer_histogram(self, device, dtype):
@@ -379,6 +390,29 @@ class TestHistogram2d(BaseTester):
class TestHistogram(BaseTester):
fcn = kornia.enhance.histogram
+ @pytest.mark.parametrize("bandwidth_dtype", ["input", "float32"])
+ def test_gradient_of_65536_samples_matches_float64(self, device, dtype, bandwidth_dtype):
+ # The gradient reaches the samples through per-bin kernel terms that scale like 1 / N and fall below the
+ # float16 normal range. A float32 bandwidth tensor, as in the docstring example, must not skip the fix.
+ index = torch.arange(65536, dtype=torch.float64)
+ x = ((index * 0.6180339887498949) % 1)[None].to(device=device, dtype=dtype)
+ bins = torch.linspace(0, 1, 64, device=device, dtype=dtype)
+ bandwidth = torch.tensor(0.01, device=device, dtype=dtype if bandwidth_dtype == "input" else torch.float32)
+ weights = torch.linspace(-1, 1, 64, dtype=torch.float64).to(dtype)
+
+ def grad(x, bins, bandwidth):
+ x = x.detach().requires_grad_()
+ hist = TestHistogram.fcn(x, bins, bandwidth)
+ assert hist.dtype == x.dtype
+ (hist * weights.to(hist)).sum().backward()
+ return x.grad.cpu().double()
+
+ # float64 reference on the CPU, from the same dtype-rounded inputs.
+ expected = grad(x.cpu().double(), bins.cpu().double(), bandwidth.cpu().double())
+ actual = grad(x, bins, bandwidth)
+ tolerance = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-4
+ assert ((actual - expected).norm() / expected.norm()).item() < tolerance
+
def test_shape(self, device, dtype):
inp = torch.ones(1, 16, device=device, dtype=dtype)
bins = torch.linspace(0, 255, 32, device=device, dtype=dtype)