Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters)!: restore Otsu export and preserve histogram splits (#5441)

Arc000007dc22e6f8005e
diff --git a/changelog.d/5441.breaking.md b/changelog.d/5441.breaking.md
new file mode 100644
index 000000000..595937eee
--- /dev/null
+++ b/changelog.d/5441.breaking.md
@@ -0,0 +1,16 @@
+The default (`slow_and_differentiable=False`) path of `otsu_threshold` and `OtsuThreshold` returns different
+thresholds, and for floating-point input sometimes different masks:
+
+- Of the splits across a run of empty histogram bins, which all give the same classes, the lowest is now taken on
+ every device. On MPS with torch 2.14, cumulative-sum rounding used to pick a later split, so the threshold differed
+ from the CPU's (for example 0.4766 instead of 0.4000) while the mask was the same.
+- A floating-point threshold is now kept at or above the largest pixel of the background bins and below the smallest
+ pixel of the foreground bins, so `x > threshold` reproduces the histogram split. The threshold used to be the bin
+ edge itself, in the input dtype: a pixel exactly on the edge, or on a half-precision edge that rounded up onto it,
+ was dropped from the foreground although the histogram counted it there, and a pixel the histogram counted in the
+ background could lie above the interpolated edge and be kept. Thresholds that already separated the classes stay at
+ the bin edge, although the batched edge computation can differ from the previous per-plane `torch.linspace` in the
+ last bit (seen on MPS in float32). On MPS, a zero foreground boundary in float32 or bfloat16 gives the threshold
+ `-torch.finfo(dtype).tiny`, because MPS comparisons flush subnormal values to zero.
+- A plane containing NaN or an infinite value used to raise `RuntimeError` from `torch.histc`. It now returns a NaN
+ threshold and an all-background mask for that plane; the other planes are unaffected.
diff --git a/changelog.d/5441.fixed.md b/changelog.d/5441.fixed.md
new file mode 100644
index 000000000..d9404e0d1
--- /dev/null
+++ b/changelog.d/5441.fixed.md
@@ -0,0 +1,3 @@
+`otsu_threshold` and `OtsuThreshold` support `torch.export` on the default path again, and compile with
+`fullgraph=True` without graph breaks: the per-plane histograms are computed in one batched operation, without
+`.item()` or a data-dependent branch for constant planes.
diff --git a/docs/source/_data/export_support.json b/docs/source/_data/export_support.json
index 2f25ed510..84c40178a 100644
--- a/docs/source/_data/export_support.json
+++ b/docs/source/_data/export_support.json
@@ -17392,15 +17392,15 @@
"where": ""
},
{
- "compile": "ok-breaks",
- "compile_detail": "4 graph breaks: Unsupported Tensor.item() call with capture_scalar_outputs=False\n Explanation: Dynamo does not support tracing `Tensor.item()` with config.capture_scalar_outpu",
+ "compile": "ok",
+ "compile_detail": "",
"export": "ok",
"export_detail": "",
- "graph_breaks": 4,
+ "graph_breaks": 0,
"name": "filters.otsu_threshold",
"note": "returns (thresholded, threshold)",
"onnx": "fail",
- "onnx_detail": "no ONNX lowering for torch.histc",
+ "onnx_detail": "ConversionError <- DispatchError: No ONNX function found for <OpOverload(op='prims.nextafter', overload='default')>. Failure message: No decompositions register",
"operator": "otsu_threshold",
"package": "kornia.filters",
"ref": "kornia.filters.otsu_threshold",
@@ -17426,15 +17426,15 @@
"where": ""
},
{
- "compile": "ok-breaks",
- "compile_detail": "5 graph breaks: Unsupported Tensor.item() call with capture_scalar_outputs=False\n Explanation: Dynamo does not support tracing `Tensor.item()` with config.capture_scalar_outpu",
+ "compile": "ok",
+ "compile_detail": "",
"export": "ok",
"export_detail": "",
- "graph_breaks": 5,
+ "graph_breaks": 0,
"name": "filters.otsu_threshold[return_mask]",
"note": "",
"onnx": "fail",
- "onnx_detail": "no ONNX lowering for torch.histc",
+ "onnx_detail": "ConversionError <- DispatchError: No ONNX function found for <OpOverload(op='prims.nextafter', overload='default')>. Failure message: No decompositions register",
"operator": "otsu_threshold",
"package": "kornia.filters",
"ref": "kornia.filters.otsu_threshold",
@@ -17443,15 +17443,15 @@
"where": ""
},
{
- "compile": "ok-breaks",
- "compile_detail": "3 graph breaks: Unsupported Tensor.item() call with capture_scalar_outputs=False\n Explanation: Dynamo does not support tracing `Tensor.item()` with config.capture_scalar_outpu",
+ "compile": "ok",
+ "compile_detail": "",
"export": "ok",
"export_detail": "",
- "graph_breaks": 3,
+ "graph_breaks": 0,
"name": "filters.OtsuThreshold",
"note": "",
"onnx": "fail",
- "onnx_detail": "no ONNX lowering for torch.histc",
+ "onnx_detail": "ConversionError <- DispatchError: No ONNX function found for <OpOverload(op='prims.nextafter', overload='default')>. Failure message: No decompositions register",
"operator": "OtsuThreshold",
"package": "kornia.filters",
"ref": "kornia.filters.OtsuThreshold",
diff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.py
index 0894005ab..85bd2c480 100644
--- a/kornia/filters/otsu_thresholding.py
+++ b/kornia/filters/otsu_thresholding.py
@@ -22,7 +22,6 @@ from typing import Optional, Tuple
import torch
from kornia.core.check import KORNIA_CHECK
-from kornia.core.utils import _torch_histc_cast
from kornia.enhance.histogram import histogram as diff_histogram
@@ -34,47 +33,64 @@ class OtsuThreshold(torch.nn.Module):
super().__init__()
@staticmethod
- def __histogram(xs: torch.Tensor, bins: int, diff: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
+ def __histogram(
+ xs: torch.Tensor, bins: int, diff: bool = False
+ ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
"""Compute a histogram for each row of xs, CUDA compatible.
Args:
xs (torch.Tensor): 2D tensor (n, N) with values to histogram.
bins (int): Number of bins.
- diff: denote if the differentiable histagram will be used. Default: False
+ diff: Whether to use a differentiable histogram. Default: False.
Returns:
- Tuple[torch.Tensor, torch.Tensor]: Normalized histograms and bin edges.
+ Normalized histograms, bin edges, and each pixel's bin index (None for the KDE path).
"""
- # Ensure input is float for histogram computation if it's integer type
- # For torch.histc, input should be floating point or quantized.
- if xs.dtype in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]:
+ edge_dtype = torch.float64 if xs.dtype == torch.float64 else torch.float32
+ if not diff:
+ # Keep ranges on the device: scalar extraction and a data-dependent constant-plane branch prevent
+ # torch.export and full-graph compilation. As with histc, histogram construction does not propagate grads.
+ values = xs.detach().to(edge_dtype)
+ min_values = values.amin(dim=1, keepdim=True)
+ max_values = values.amax(dim=1, keepdim=True)
+ widths = max_values - min_values
+ safe_widths = torch.where(widths > 0, widths, torch.ones_like(widths))
+ indices = ((values - min_values) * bins / safe_widths).to(torch.int64).clamp(0, bins - 1)
+ histograms = values.new_zeros((values.shape[0], bins)).scatter_add(1, indices, torch.ones_like(values))
+
+ # Match linspace's symmetric interpolation and exact end points. Whether the multiply-add is fused is up
+ # to the backend: on the arm64 CPU build addcmul and linspace both fuse it, MPS addcmul does not, so edges
+ # can differ in the last bit across devices. The membership guard below keeps the mask independent of it.
+ positions = torch.arange(bins + 1, device=xs.device, dtype=edge_dtype)
+ steps = widths / bins
+ bin_edges = torch.where(
+ positions < (bins + 1) // 2,
+ torch.addcmul(min_values, positions, steps),
+ torch.addcmul(max_values, positions - bins, steps),
+ )
+ return histograms / histograms.sum(dim=1, keepdim=True), bin_edges, indices
+
+ # The KDE path samples `bins` locations rather than histc's `bins + 1` interval edges.
+ if not xs.is_floating_point():
xs = xs.to(torch.float32)
-
min_values = xs.amin(dim=1)
max_values = xs.amax(dim=1)
- histograms = []
- bin_edges = []
- # histc divides [min, max] into `bins` intervals. The KDE path instead samples `bins` locations.
- edge_count = bins if diff else bins + 1
- edge_dtype = torch.float64 if xs.dtype == torch.float64 else torch.float32
-
+ histograms_list = []
+ bin_edges_list = []
for i in range(xs.shape[0]):
min_val = min_values[i].item()
max_val = max_values[i].item()
- edges = torch.linspace(min_val, max_val, edge_count, device=xs.device, dtype=edge_dtype)
+ edges = torch.linspace(min_val, max_val, bins, device=xs.device, dtype=edge_dtype)
if min_val == max_val:
- # No split exists; avoid histc's automatic range expansion for large constant values.
+ # No split exists; avoid the KDE's zero-range case for constant values.
hist = torch.zeros(bins, device=xs.device, dtype=edge_dtype)
hist[0] = 1
- elif diff:
- hist = diff_histogram(xs[i].view(1, -1), edges, torch.tensor(0.001, device=xs.device)).squeeze()
else:
- hist = _torch_histc_cast(xs[i], bins=bins, min=min_val, max=max_val)
-
- histograms.append(hist / hist.sum())
- bin_edges.append(edges)
+ hist = diff_histogram(xs[i].view(1, -1), edges, torch.tensor(0.001, device=xs.device)).squeeze()
+ histograms_list.append(hist / hist.sum())
+ bin_edges_list.append(edges)
- return torch.stack(histograms), torch.stack(bin_edges)
+ return torch.stack(histograms_list), torch.stack(bin_edges_list), None
def transform_input(
self, x: torch.Tensor, original_shape: Optional[torch.Size] = None
@@ -141,7 +157,7 @@ class OtsuThreshold(torch.nn.Module):
)
# Compute histogram and bin edges
- histograms, bin_edges = self.__histogram(x_flattened, bins=nbins, diff=slow_and_differentiable)
+ histograms, bin_edges, indices = self.__histogram(x_flattened, bins=nbins, diff=slow_and_differentiable)
# Vectorized computation of optimal thresholds
bin_values = torch.arange(nbins, device=histograms.device, dtype=torch.float32)
@@ -162,6 +178,10 @@ class OtsuThreshold(torch.nn.Module):
# Compute inter-class variance, setting invalid cases to -1
valid = (weight_bg > 0) & (weight_fg > 0)
+ if not slow_and_differentiable:
+ # Moving through an empty bin cannot change either class. Exclude repeated splits so floating-point
+ # reduction roundoff cannot move the selected edge across an empty gap.
+ valid = valid & (histograms[:, :-1] > 0)
inter_class_var = torch.where(
valid, weight_bg * weight_fg * (mean_bg - mean_fg) ** 2, torch.tensor(-1.0, device=histograms.device)
)
@@ -176,6 +196,49 @@ class OtsuThreshold(torch.nn.Module):
# an integer edge, and drop the level just above the split from the foreground.
upper_edges = upper_edges.ceil() - 1
best_thresholds = torch.where(max_var > 0, upper_edges, bin_edges[:, 0]).to(x.dtype)
+ if x.is_floating_point():
+ if indices is None:
+ # Preserve the KDE edge convention, lowering only a collision with a foreground pixel.
+ boundary = best_thresholds
+ else:
+ # Use actual histogram membership to guard the strict comparison. Interpolated edges can round
+ # onto a pixel, including when a compiler changes fused multiply-add, or when casting to half.
+ # Keep the edge whenever it already separates the classes, otherwise fit it between their pixels.
+ foreground = indices > t_max[:, None]
+ boundary = torch.where(foreground, x_flattened, float("inf")).amin(dim=1).detach()
+ background_max = torch.where(foreground, -float("inf"), x_flattened).amax(dim=1).detach()
+ best_thresholds = torch.where(
+ max_var > 0, torch.maximum(best_thresholds, background_max), best_thresholds
+ )
+ if x.dtype in (torch.float16, torch.bfloat16):
+ # MPS on older supported torch versions has no half/bfloat16 nextafter kernel. Both formats have
+ # monotonically ordered magnitude bits; advance negative values and decrement positive values.
+ # Widen the integer arithmetic explicitly so older Inductor versions preserve the final bitcast.
+ bits = boundary.view(torch.int16).to(torch.int32)
+ direction = torch.where(boundary > 0, 1, -1).to(torch.int32)
+ previous = torch.where(boundary == 0, -32767, bits - direction).to(torch.int16).view(x.dtype)
+ elif x.device.type == "mps":
+ # Metal Inductor does not lower nextafter, so step the float32 representation directly as well.
+ bits = boundary.view(torch.int32)
+ direction = torch.where(boundary > 0, 1, -1).to(torch.int32)
+ previous = torch.where(boundary == 0, -2147483647, bits - direction).view(x.dtype)
+ else:
+ previous = torch.nextafter(boundary, torch.full_like(boundary, -float("inf")))
+ if x.device.type == "mps" and x.dtype in (torch.float32, torch.bfloat16):
+ # MPS flushes these dtypes' subnormals in comparisons. Use the smallest normal negative value so
+ # the strict comparison can still include a foreground pixel whose value is zero.
+ previous = torch.where(boundary == 0, -torch.finfo(x.dtype).tiny, previous)
+ if indices is None:
+ on_threshold = (x_flattened == best_thresholds[:, None]).any(dim=1)
+ lower_threshold = on_threshold & (best_thresholds.to(upper_edges.dtype) >= upper_edges) & (max_var > 0)
+ best_thresholds = torch.where(lower_threshold, previous, best_thresholds)
+ else:
+ # Clamp against the predecessor itself: compilers may defer the half cast until after the
+ # comparison, so comparing with the foreground value can miss an edge that will round up to it.
+ bounded_thresholds = torch.minimum(
+ best_thresholds.to(bin_edges.dtype), previous.to(bin_edges.dtype)
+ ).to(x.dtype)
+ best_thresholds = torch.where(max_var > 0, bounded_thresholds, best_thresholds)
# Preserve a constant plane's exact input value, including integers outside floating-point precision.
plane_min = x_flattened.amin(dim=1).detach()
@@ -198,8 +261,13 @@ def otsu_threshold(
r"""Apply automatic image thresholding using Otsu algorithm to the input tensor.
Each image/channel plane uses its own histogram range. On the default path, the threshold is the upper edge
- of the selected histogram bin. For an integer input it is the largest integer below that value, so
- ``x > threshold`` keeps every pixel on or above it. A constant plane uses its constant value as the threshold.
+ of the selected histogram bin. For an integer input it is the largest integer below that value. For floating
+ input, rounding is corrected when necessary to keep the threshold at or above the largest background pixel
+ and below the smallest foreground pixel, so ``x > threshold`` matches the histogram split. On MPS, a zero
+ foreground boundary in float32 or bfloat16 uses the smallest normal negative value because comparisons flush
+ subnormal values to zero. Empty bins do not introduce candidate splits. A constant plane uses its constant value
+ as the threshold. The default path supports
+ ``torch.export`` and full-graph ``torch.compile``.
Args:
x (Tensor): Input tensor (image or batch of images).
diff --git a/tests/filters/test_otsu_thresholding.py b/tests/filters/test_otsu_thresholding.py
index f13ac21c2..2751e393f 100644
--- a/tests/filters/test_otsu_thresholding.py
+++ b/tests/filters/test_otsu_thresholding.py
@@ -20,7 +20,17 @@ import torch
from kornia.filters.otsu_thresholding import OtsuThreshold, otsu_threshold
-from testing.base import BaseTester, assert_close
+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, assert_close, dynamo_is_available
+
+
+class _FunctionalOtsuThreshold(torch.nn.Module):
+ def __init__(self, return_mask, nbins=2):
+ super().__init__()
+ self.return_mask = return_mask
+ self.nbins = nbins
+
+ def forward(self, image):
+ return otsu_threshold(image, nbins=self.nbins, return_mask=self.return_mask)
class TestOtsuThreshold(BaseTester):
@@ -227,6 +237,190 @@ class TestOtsuThreshold(BaseTester):
assert torch.equal(threshold, image.flatten()[:1])
assert not mask.any()
+ @pytest.mark.parametrize("offset", [-1.0, -126 / 256, 0.0], ids=["negative", "zero", "positive"])
+ def test_float_pixel_on_selected_edge_is_foreground_5422(self, offset, device, dtype):
+ levels = torch.cat([torch.arange(257), torch.full((300,), 60), torch.full((300,), 190)])
+ image = (levels / 256 + offset).to(device=device, dtype=dtype).view(1, -1)
+ mask, threshold = otsu_threshold(image, return_mask=True)
+ edge = torch.tensor([126 / 256 + offset], dtype=dtype)
+ expected = torch.nextafter(edge, torch.full_like(edge, -torch.inf)).to(device)
+ if device.type == "mps" and dtype in (torch.float32, torch.bfloat16) and offset == -126 / 256:
+ # Metal comparisons flush subnormals to zero; the closest usable negative threshold is normal.
+ expected = image.new_tensor([-torch.finfo(dtype).tiny])
+ # histc places the pixel at the upper edge in the next bin. Strict comparison must keep it too,
+ # including when that foreground pixel is zero or negative.
+ self.assert_close(threshold, expected, rtol=0, atol=0)
+ assert mask.sum().item() == 431
+ assert mask[0, 126]
+ assert not mask[0, 125]
+ self.assert_close(mask, image > threshold)
+
+ def test_float_and_integer_edges_keep_same_pixels_5422(self, device):
+ levels = torch.cat([torch.arange(257), torch.full((300,), 60), torch.full((300,), 190)])
+ image = levels.to(device=device, dtype=torch.int16).view(1, -1)
+ integer_mask, integer_threshold = otsu_threshold(image, return_mask=True)
+ float_mask, _ = otsu_threshold(image.float() / 256, return_mask=True)
+ assert integer_threshold.item() == 125
+ assert integer_mask.sum().item() == 431
+ self.assert_close(float_mask, integer_mask)
+
+ def test_rounded_bfloat16_edge_keeps_foreground_pixel_5422(self, device):
+ # The float32 histogram edge is 0.505859375, which rounds up to the existing pixel 0.5078125.
+ image = torch.tensor([[0.01171875, 0.01171875, 0.5078125, 1.0, 1.0]], device=device, dtype=torch.bfloat16)
+ mask, threshold = otsu_threshold(image, nbins=2, return_mask=True)
+ self.assert_close(threshold, image.new_tensor([0.50390625]), rtol=0, atol=0)
+ assert mask.tolist() == [[False, False, True, True, True]]
+
+ def test_downward_rounded_edge_keeps_background_pixel_excluded_5422(self, device):
+ # The float32 edge 0.501953125 rounds down to 0.5. That pixel belongs to the background bin,
+ # so an unconditional nextafter would incorrectly promote it to the foreground.
+ image = torch.tensor([[0.00390625, 0.00390625, 0.5, 1.0, 1.0]], device=device, dtype=torch.bfloat16)
+ mask, threshold = otsu_threshold(image, nbins=2, return_mask=True)
+ self.assert_close(threshold, image.new_tensor([0.5]), rtol=0, atol=0)
+ assert mask.tolist() == [[False, False, False, True, True]]
+
+ def test_background_pixel_above_interpolated_edge_stays_background_5422(self, device):
+ # histc and the bin index put -1.1049999 in the lower of two bins over [-9.03, 6.82], but the interpolated
+ # float32 edge -1.1050000 lies one ulp below it. Comparing against the edge alone made it foreground.
+ image = torch.tensor([[-9.03, -9.03, -1.1049998998641968, 6.82, 6.82]], device=device, dtype=torch.float32)
+ mask, threshold = otsu_threshold(image, nbins=2, return_mask=True)
+ assert mask.tolist() == [[False, False, False, True, True]]
+ self.assert_close(threshold, image[:, 2], rtol=0, atol=0)
+
+ @pytest.mark.parametrize("middle", [0.5, 0.6], ids=["on_edge", "above_edge"])
+ def test_slow_path_edge_correction_keeps_foreground_pixel_5422(self, middle, device, dtype):
+ # Three zeros give the first KDE split a unique maximum when middle=0.5. Its next sample is 0.5,
+ # which must not remove that foreground pixel. Without a collision, preserve the sample exactly.
+ image = torch.tensor([[0.0, 0.0, 0.0, middle, 1.0, 1.0]], device=device, dtype=dtype)
+ mask, threshold = otsu_threshold(image, nbins=3, slow_and_differentiable=True, return_mask=True)
+ expected = torch.tensor([0.5], dtype=dtype)
+ if middle == 0.5:
+ expected = torch.nextafter(expected, torch.full_like(expected, -torch.inf))
+ self.assert_close(threshold, expected.to(device), rtol=0, atol=0)
+ assert mask.tolist() == [[False, False, False, True, True, True]]
+
+ def test_slow_path_downward_rounded_sample_keeps_background_pixel_excluded_5422(self, device):
+ # The middle KDE sample 0.501953125 rounds down to the pixel 0.5 in bfloat16. That pixel lies below the
+ # sample, so lowering the threshold to keep it, as for an upward-rounded sample, would promote it.
+ image = torch.tensor([[0.00390625] * 3 + [0.5, 1.0, 1.0]], device=device, dtype=torch.bfloat16)
+ mask, threshold = otsu_threshold(image, nbins=3, slow_and_differentiable=True, return_mask=True)
+ self.assert_close(threshold, image.new_tensor([0.5]), rtol=0, atol=0)
+ assert mask.tolist() == [[False, False, False, False, True, True]]
+
+ def test_edge_correction_is_independent_for_each_plane_5422(self, device, dtype):
+ image = torch.tensor(
+ [[[0.0, 0.25, 0.5, 1.0]], [[0.0, 0.25, 0.75, 1.0]], [[0.5, 0.5, 0.5, 0.5]]],
+ device=device,
+ dtype=dtype,
+ )
+ mask, threshold = otsu_threshold(image, nbins=2, return_mask=True)
+ edge = torch.tensor(0.5, dtype=dtype)
+ corrected = torch.nextafter(edge, torch.full_like(edge, -torch.inf))
+ expected = torch.stack([corrected, edge, edge]).to(device)
+ # Only the first plane has a pixel equal to its edge. The unmatched edge and constant plane stay exact.
+ self.assert_close(threshold, expected, rtol=0, atol=0)
+ assert mask.tolist() == [[[False, False, True, True]], [[False, False, True, True]], [[False] * 4]]
+
+ @pytest.mark.parametrize("distribution", ["bimodal", "squared"])
+ def test_empty_gap_uses_first_occupied_split_5421(self, distribution, device):
+ # Generate exactly the same float32 pixels on every backend. Empty bins after the winning occupied bin
+ # leave both classes unchanged, but parallel cumsum roundoff used to give one of them a higher score on MPS.
+ if distribution == "bimodal":
+ noise = torch.rand(1000, generator=torch.Generator().manual_seed(0), dtype=torch.float64)
+ image = torch.cat([0.3 + 0.1 * noise[:500], 0.6 + 0.1 * noise[500:]]).float().view(20, 50)
+ expected_threshold, foreground = 0.4000208377838135, 500
+ else:
+ image = torch.linspace(0, 1, 60).square().view(6, 10)
+ expected_threshold, foreground = 101 / 256, 22
+ # Independent torch.histc Otsu references, excluding empty candidate bins, select bins 63 and 100.
+ image = image.to(device)
+ mask, threshold = otsu_threshold(image, return_mask=True)
+ self.assert_close(threshold, image.new_tensor([expected_threshold]), rtol=0, atol=1e-7)
+ assert mask.sum().item() == foreground
+
+ @pytest.mark.parametrize("nbins", [2, 17, 256])
+ def test_tensor_histogram_matches_histc_at_bin_boundaries_5425(self, nbins, device, dtype):
+ stats_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ planes = []
+ for low, high in [(-0.7, 1.1), (32.0, 34.5), (0.0, 1.0 + 2**-30)]:
+ edges = torch.linspace(low, high, nbins + 1, dtype=stats_dtype).to(dtype)
+ interior = edges[1:-1]
+ planes.append(
+ torch.cat(
+ [
+ edges,
+ torch.nextafter(interior, torch.full_like(interior, -torch.inf)),
+ torch.nextafter(interior, torch.full_like(interior, torch.inf)),
+ ]
+ )
+ )
+ planes.append(torch.full_like(planes[0], -0.375))
+ image = torch.stack(planes).to(device)
+ histograms, edges, _ = OtsuThreshold._OtsuThreshold__histogram(image, nbins)
+ for i, plane in enumerate(image.to(stats_dtype)):
+ low, high = plane.min().item(), plane.max().item()
+ if low == high:
+ expected = torch.zeros_like(histograms[i])
+ expected[0] = 1
+ else:
+ # torch.histc independently pins the bin-assignment arithmetic, including adjacent floating values.
+ expected = torch.histc(plane, bins=nbins, min=low, max=high)
+ expected = expected / expected.sum()
+ self.assert_close(histograms[i], expected, rtol=0, atol=0)
+ expected_edges = torch.linspace(low, high, nbins + 1, device=device, dtype=stats_dtype)
+ self.assert_close(edges[i], expected_edges)
+
+ def test_integer_histogram_matches_histc_with_offsets_5425(self, device):
+ image = torch.stack([torch.arange(-128, 129), torch.arange(1000, 1257)]).to(device=device, dtype=torch.int16)
+ histograms, _, _ = OtsuThreshold._OtsuThreshold__histogram(image, 17)
+ for i, plane in enumerate(image.float()):
+ expected = torch.histc(plane, bins=17, min=plane.min().item(), max=plane.max().item())
+ self.assert_close(histograms[i], expected / expected.sum(), rtol=0, atol=0)
+
+ @staticmethod
+ def _capture_images(device, dtype):
+ image = torch.tensor([[[[0.0, 0.25, 0.5, 1.0]], [[0.5, 0.5, 0.5, 0.5]]]], device=device, dtype=dtype)
+ different = torch.tensor([[[[2.0, 2.0, 2.0, 2.0]], [[-1.0, -0.5, 0.0, 1.0]]]], device=device, dtype=dtype)
+ return image, different
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize("api", ["module", "function", "mask"])
+ def test_export_reuses_graph_with_new_ranges_5425(self, api, device, dtype):
+ image, different = self._capture_images(device, dtype)
+ op = OtsuThreshold() if api == "module" else _FunctionalOtsuThreshold(return_mask=api == "mask")
+ extra_args = (2,) if api == "module" else ()
+ exported = torch.export.export(op, (image, *extra_args), strict=True).module()
+ # Swap which plane is constant and change both ranges; capture must not specialize on the observed values.
+ for sample in (image, different):
+ expected = op(sample, *extra_args)
+ actual = exported(sample, *extra_args)
+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)
+ self.assert_close(actual[1], expected[1], rtol=0, atol=0)
+
+ @pytest.mark.parametrize("return_mask", [False, True])
+ def test_dynamo_fullgraph_reuses_new_ranges_5425(self, device, dtype, torch_optimizer, return_mask):
+ image, different = self._capture_images(device, dtype)
+ op = _FunctionalOtsuThreshold(return_mask=return_mask)
+ compiled = torch_optimizer(op, fullgraph=True)
+ for sample in (image, different):
+ expected = op(sample)
+ actual = compiled(sample)
+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)
+ self.assert_close(actual[1], expected[1], rtol=0, atol=0)
+
+ def test_dynamo_bin_edge_pixels_match_eager_5425(self, device, dtype, torch_optimizer):
+ generator = torch.Generator().manual_seed(0)
+ low = torch.rand(20, 1, generator=generator, dtype=dtype) * 8 - 4
+ high = low + torch.rand(20, 1, generator=generator, dtype=dtype) * 5 + 0.01
+ image = (torch.linspace(0, 1, 257, dtype=dtype)[None, :] * (high - low) + low).reshape(20, 1, 257)
+ image = image.to(device)
+ op = _FunctionalOtsuThreshold(return_mask=True, nbins=256)
+ expected = op(image)
+ actual = torch_optimizer(op, fullgraph=True)(image)
+ # Fusing the edge interpolation can move the threshold by one ULP, but must not change bin membership.
+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)
+ self.assert_close(actual[1], expected[1])
+
def test_mask(device, dtype):
input = torch.tensor([[10, 20, 30], [40, 50, 60], [70, 80, 90]], device=device, dtype=dtype)