Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters)!: give otsu_threshold's slow path a differentiable threshold (#5426)

Dmytro Mishkin920910064b9e
diff --git a/changelog.d/5426.breaking.md b/changelog.d/5426.breaking.md
new file mode 100644
index 000000000..2b97df773
--- /dev/null
+++ b/changelog.d/5426.breaking.md
@@ -0,0 +1,27 @@
+`otsu_threshold` and `OtsuThreshold` with `slow_and_differentiable=True` now return a threshold with a gradient with
+respect to the input, and return different threshold values:
+
+- The threshold now has a gradient. Its value is the hard Otsu split of the path's histogram, and its gradient is a
+ straight-through surrogate: the gradient of a soft-argmax over the between-class variance curve of a wider kernel
+ density estimate, with a standard deviation of 0.5 bin, at a temperature relative to the curve, so it does not depend
+ on the intensity scale of the input. The threshold used to have no gradient. The thresholded image is still
+ `x * (x > threshold)`, whose gradient is that mask.
+- The histogram is now the mass that a Gaussian kernel density estimate with a standard deviation of 0.1 bin puts in
+ each of the `nbins` bins, so every pixel contributes its full mass. The estimate used to be sampled at `nbins` points
+ with a fixed bandwidth of `1e-3` in input units, which missed every pixel more than a few `1e-3` away from a sample
+ point, most pixels at small `nbins`. The thresholds change accordingly, and are usually within one bin of the
+ default path's.
+- The threshold is now read with the default path's bin-edge convention: the upper edge of the selected bin among
+ `nbins` equal bins over the plane's range, or for an integer input the largest integer below that edge. It used to
+ be read from the `nbins` sample points `linspace(min, max, nbins)`, up to one bin above the split. As on the default path,
+ a floating-point threshold is kept at or above the largest background pixel and below the smallest foreground
+ pixel, so `x > threshold` reproduces the split.
+- Of splits that give the same partition, the lowest is now taken on every device: a bin counts as non-empty only
+ above 1 % of one pixel's mass. The kernel tails used to give empty bins a tiny positive mass, the rounding of the
+ cumulative sums chose between equivalent splits, and CPU and MPS could return different thresholds for the same
+ input.
+- The path no longer calls `.item()`, so it supports `torch.export` and compiles with `fullgraph=True`.
+- The slow path now computes its surrogate on the plane shifted by its minimum and divided by its range, or by its
+ largest magnitude when the range overflows, and cancels this normalization from its first-order gradient. Higher-order derivatives through this normalization do not represent the original-unit soft threshold.
+ Finite inputs near the dtype limits or with tiny ranges keep finite thresholds and gradients; hard edges whose range
+ would overflow or whose bin width would underflow are reconstructed in bounded units as well.
diff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.py
index 85bd2c480..a254adf2d 100644
--- a/kornia/filters/otsu_thresholding.py
+++ b/kornia/filters/otsu_thresholding.py
@@ -22,75 +22,168 @@ from typing import Optional, Tuple
import torch
from kornia.core.check import KORNIA_CHECK
-from kornia.enhance.histogram import histogram as diff_histogram
class OtsuThreshold(torch.nn.Module):
"""Otsu thresholding module for PyTorch tensors."""
+ # Standard deviation, in bin widths, of the Gaussian kernel density estimate whose histogram selects the
+ # threshold of ``slow_and_differentiable=True``.
+ _KDE_BANDWIDTH: float = 0.1
+ # Standard deviation, in bin widths, of the wider estimate behind that threshold's gradient. At 0.1 bin a pixel more
+ # than about 0.3 bin from every bin edge would get under 1e-3 of the largest pixel gradient; at 0.5 bin a pixel's
+ # gradient varies smoothly with its value instead of concentrating on pixels near a bin edge.
+ _SURROGATE_BANDWIDTH: float = 0.5
+ # Temperature of the soft-argmax behind that gradient, relative to the largest between-class variance of the plane.
+ _SOFT_ARGMAX_TEMPERATURE: float = 0.01
+ # A bin of the kernel density estimate counts as non-empty above this fraction of one pixel's mass: the kernel
+ # tails give every bin a positive mass, down to about 1e-23 of a pixel.
+ _NONEMPTY_BIN_MASS: float = 0.01
+
def __init__(self) -> None:
"""Initialize the OtsuThreshold module."""
super().__init__()
@staticmethod
- def __histogram(
- xs: torch.Tensor, bins: int, diff: bool = False
- ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
+ def __histogram(xs: torch.Tensor, bins: int) -> Tuple[torch.Tensor, torch.Tensor, 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: Whether to use a differentiable histogram. Default: False.
Returns:
- Normalized histograms, bin edges, and each pixel's bin index (None for the KDE path).
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: Normalized histograms, bin edges, and each pixel's bin
+ index.
"""
+ # 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.
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_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, bins, device=xs.device, dtype=edge_dtype)
- if min_val == max_val:
- # 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
- else:
- 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)
+ 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 with the arithmetic of `_upper_edge`'s
+ # ordinary ranges. The membership guard in `forward` keeps the mask independent of the edges' last bit.
+ 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
+
+ @staticmethod
+ def _kde_histogram(coords: torch.Tensor, bins: int, bandwidth: float) -> torch.Tensor:
+ """Compute the bin masses of a Gaussian kernel density estimate for each row of coords.
+
+ Args:
+ coords (torch.Tensor): 2D tensor (n, N) of values in bin coordinates: bin k is [k, k + 1).
+ bins (int): Number of bins.
+ bandwidth (float): Standard deviation of the Gaussian kernel, in bin widths.
+
+ Returns:
+ torch.Tensor: Histograms (n, bins), each summing to 1. A pixel's mass below 0 or above ``bins`` stays in
+ the first or the last bin, so every pixel carries its full mass.
+ """
+ inner_edges = torch.arange(1, bins, device=coords.device, dtype=coords.dtype)
+ histograms = []
+ for i in range(coords.shape[0]):
+ # fraction of the row's mass above each inner edge
+ above = torch.special.ndtr((coords[i, :, None] - inner_edges) / bandwidth).mean(dim=0)
+ above = torch.cat([above.new_ones(1), above, above.new_zeros(1)])
+ histograms.append(above[:-1] - above[1:])
+ return torch.stack(histograms)
+
+ @staticmethod
+ def _between_class_variance(histograms: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Compute Otsu's between-class variance of each split of each histogram, in squared bin widths.
+
+ Args:
+ histograms (torch.Tensor): Normalized histograms (n, bins).
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: The between-class variance (n, bins - 1) of the split after each bin
+ but the last, -1 where a class is empty, and the mask of the splits whose two classes are non-empty.
+ """
+ bin_values = torch.arange(histograms.shape[1], device=histograms.device, dtype=histograms.dtype)
+ total_weight = torch.sum(histograms, dim=1) # Shape: (nchannel,)
+ total_sum = torch.sum(histograms * bin_values, dim=1) # Shape: (nchannel,)
+ cumsum_weight = torch.cumsum(histograms, dim=1) # Shape: (nchannel, nbins)
+ cumsum_sum = torch.cumsum(histograms * bin_values, dim=1) # Shape: (nchannel, nbins)
+
+ # Compute weights and sums for background and foreground
+ weight_bg = cumsum_weight[:, :-1] # Shape: (nchannel, nbins-1)
+ sum_bg = cumsum_sum[:, :-1] # Shape: (nchannel, nbins-1)
+ weight_fg = total_weight[:, None] - weight_bg # Shape: (nchannel, nbins-1)
+ sum_fg = total_sum[:, None] - sum_bg # Shape: (nchannel, nbins-1)
+
+ # Compute means; an empty class divides by 1, so that no inf or nan reaches a gradient
+ valid_bg = weight_bg > 0
+ valid_fg = weight_fg > 0
+ mean_bg = sum_bg / torch.where(valid_bg, weight_bg, torch.ones_like(weight_bg))
+ mean_fg = sum_fg / torch.where(valid_fg, weight_fg, torch.ones_like(weight_fg))
+
+ # Compute inter-class variance, setting invalid cases to -1
+ valid = valid_bg & valid_fg
+ inter_class_var = torch.where(
+ valid, weight_bg * weight_fg * (mean_bg - mean_fg) ** 2, torch.full_like(weight_bg, -1.0)
+ )
+ return inter_class_var, valid
+
+ @staticmethod
+ def _upper_edge(min_val: torch.Tensor, max_val: torch.Tensor, index: torch.Tensor, bins: int) -> torch.Tensor:
+ """Compute edge ``index`` of ``bins`` equal bins from ``min_val`` to ``max_val``, without leaving the graph.
+
+ On ordinary ranges this matches ``torch.linspace(min_val, max_val, bins + 1)[index]``'s symmetric
+ interpolation and exact end points: from the minimum for the lower half of the edges, from the maximum for
+ the upper half. Extreme ranges are reconstructed in bounded units.
+ """
+ span = max_val - min_val
+ step = span / bins
+ k = index.to(step.dtype)
+ # The default path's edges use the same arithmetic. 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.
+ lower_half = index < (bins + 1) // 2
+ edge = torch.where(lower_half, torch.addcmul(min_val, k, step), torch.addcmul(max_val, k - bins, step))
+ # Opposite-sign finite extrema can overflow their difference, while subnormal ranges lose their step on
+ # division by bins; reconstruct those edges in bounded units instead. This helper receives detached
+ # extrema, so its unused arm has no backward path.
+ scale = torch.maximum(min_val.abs(), max_val.abs()).clamp_min(torch.finfo(min_val.dtype).tiny)
+ lo, hi = min_val / scale, max_val / scale
+ bounded_step = (hi - lo) / bins
+ bounded_edge = torch.where(
+ lower_half, torch.addcmul(lo, k, bounded_step), torch.addcmul(hi, k - bins, bounded_step)
+ )
+ ordinary = span.isfinite() & (span >= torch.finfo(span.dtype).tiny * bins)
+ return torch.where(ordinary, edge, bounded_edge * scale)
+
+ @staticmethod
+ def _soft_threshold(coords: torch.Tensor, min_val: torch.Tensor, span: torch.Tensor, bins: int) -> torch.Tensor:
+ """Compute the bounded-unit soft-argmax behind the first-order gradient of ``slow_and_differentiable=True``.
- return torch.stack(histograms_list), torch.stack(bin_edges_list), None
+ The between-class variance curve of a kernel density estimate of ``_SURROGATE_BANDWIDTH`` bins weights the
+ upper edge of split ``k`` by ``softmax(var_k / (T * max(var)))`` with ``T = _SOFT_ARGMAX_TEMPERATURE``. The
+ curve is in bin units and the temperature is relative to it, so the weights do not depend on the intensity
+ scale of the plane.
+ """
+ histograms = OtsuThreshold._kde_histogram(coords, bins, OtsuThreshold._SURROGATE_BANDWIDTH)
+ inter_class_var, valid = OtsuThreshold._between_class_variance(histograms)
+ largest = inter_class_var.amax(dim=1, keepdim=True)
+ largest = torch.where(largest > 0, largest, torch.ones_like(largest))
+ logits = inter_class_var / (OtsuThreshold._SOFT_ARGMAX_TEMPERATURE * largest)
+ # A finite floor, not -inf, for invalid splits: a constant plane has no valid split, and its weights stay finite
+ logits = torch.where(valid, logits, torch.full_like(logits, torch.finfo(logits.dtype).min))
+ weights = torch.softmax(logits, dim=1)
+ # the split after bin k has its upper edge at k + 1 bins from the minimum
+ upper_edges = torch.arange(1, bins, device=weights.device, dtype=weights.dtype)
+ return min_val + ((weights * upper_edges).sum(dim=1) / bins) * span
def transform_input(
self, x: torch.Tensor, original_shape: Optional[torch.Size] = None
@@ -130,8 +223,9 @@ class OtsuThreshold(torch.nn.Module):
Args:
x (torch.Tensor): Image or batch of images to threshold.
nbins (int, optional): Number of bins for histogram computation. Default is 256.
- slow_and_differentiable (bool, optional): If True, use a differentiable histogram computation.
- Default is False.
+ slow_and_differentiable (bool, optional): If True, build the histogram from a Gaussian kernel density
+ estimate and give the threshold a gradient with respect to ``x``; see
+ :func:`~kornia.filters.otsu_threshold`. Default is False.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Thresholded tensor, threshold values.
@@ -156,60 +250,69 @@ class OtsuThreshold(torch.nn.Module):
"Tensor dtype not supported for Otsu thresholding.",
)
- # Compute histogram and bin edges
- 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)
- total_weight = torch.sum(histograms, dim=1) # Shape: (nchannel,)
- total_sum = torch.sum(histograms * bin_values, dim=1) # Shape: (nchannel,)
- cumsum_weight = torch.cumsum(histograms, dim=1) # Shape: (nchannel, nbins)
- cumsum_sum = torch.cumsum(histograms * bin_values, dim=1) # Shape: (nchannel, nbins)
-
- # Compute weights and sums for background and foreground
- weight_bg = cumsum_weight[:, :-1] # Shape: (nchannel, nbins-1)
- sum_bg = cumsum_sum[:, :-1] # Shape: (nchannel, nbins-1)
- weight_fg = total_weight[:, None] - weight_bg # Shape: (nchannel, nbins-1)
- sum_fg = total_sum[:, None] - sum_bg # Shape: (nchannel, nbins-1)
-
- # Compute means, avoiding division by zero
- mean_bg = torch.where(weight_bg > 0, sum_bg / weight_bg, torch.tensor(0.0, device=histograms.device))
- mean_fg = torch.where(weight_fg > 0, sum_fg / weight_fg, torch.tensor(0.0, device=histograms.device))
-
- # Compute inter-class variance, setting invalid cases to -1
- valid = (weight_bg > 0) & (weight_fg > 0)
- if not slow_and_differentiable:
+ if slow_and_differentiable:
+ # Histogram arithmetic in float32, or float64 for a float64 input, as on the default path. No .item():
+ # the minimum, maximum and bin coordinates of each plane stay tensors.
+ xs = x_flattened.to(torch.float64 if x.dtype == torch.float64 else torch.float32)
+ min_val = xs.amin(dim=1).detach()
+ max_val = xs.amax(dim=1).detach()
+ # Evaluate the surrogate in bounded units, with an identity gradient to xs. For a detached offset o and
+ # positive scale s, the original-unit surrogate is o + s * f((xs - o) / s), whose derivative is exactly
+ # f'((xs - o) / s). Cancelling s here avoids both overflowing ranges and underflowing intermediate backward
+ # signals. Subtracting the minimum before scaling keeps the relative differences of a narrow range far
+ # from zero; a range that overflows is scaled by the largest magnitude instead.
+ span = (max_val - min_val)[:, None]
+ finite_span = span.isfinite()
+ offset = torch.where(finite_span, min_val[:, None], torch.zeros_like(span))
+ largest = xs.detach().abs().amax(dim=1, keepdim=True).clamp_min(torch.finfo(xs.dtype).tiny)
+ scale = torch.where(finite_span, torch.where(span > 0, span, torch.ones_like(span)), largest)
+ bounded = (xs.detach() - offset) / scale + (xs - xs.detach())
+ bounded_min = bounded.amin(dim=1)
+ bounded_span = bounded.amax(dim=1) - bounded_min
+ # The minimum maps to 0, the maximum to nbins, bin k is [k, k + 1). A constant plane maps to 0.
+ safe_span = torch.where(bounded_span > 0, bounded_span, torch.ones_like(bounded_span))
+ coords = ((bounded - bounded_min[:, None]) / safe_span[:, None]) * nbins
+ histograms = self._kde_histogram(coords.detach(), nbins, self._KDE_BANDWIDTH)
+ inter_class_var, _ = self._between_class_variance(histograms)
+ # The kernel tails give every bin some mass, so a split after an empty bin, which repeats the partition of
+ # the split before it, would compete on rounding noise: only splits after a non-empty bin compete, and
+ # the lowest of equivalent splits wins on every device.
+ nonempty = histograms[:, :-1] > self._NONEMPTY_BIN_MASS / xs.shape[1]
+ inter_class_var = torch.where(nonempty, inter_class_var, torch.full_like(inter_class_var, -1.0))
+ lower_edges = min_val
+ # Each pixel's bin in the coordinates the estimate is built on; the guard below reads the split from it.
+ indices = coords.detach().to(torch.int64).clamp(0, nbins - 1)
+ else:
+ # Compute histogram and bin edges
+ histograms, bin_edges, indices = self.__histogram(x_flattened, bins=nbins)
+ inter_class_var, _ = self._between_class_variance(histograms)
# 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)
- )
+ nonempty = histograms[:, :-1] > 0
+ inter_class_var = torch.where(nonempty, inter_class_var, torch.full_like(inter_class_var, -1.0))
+ lower_edges = bin_edges[:, 0]
# Find the maximum inter-class variance and corresponding threshold
t_max = torch.argmax(inter_class_var, dim=1) # Shape: (nchannel,)
max_var = inter_class_var.gather(1, t_max[:, None]).squeeze(1) # Shape: (nchannel,)
- upper_edges = bin_edges.gather(1, (t_max + 1)[:, None]).squeeze(1)
+ if slow_and_differentiable:
+ upper_edges = self._upper_edge(min_val, max_val, t_max + 1, nbins)
+ else:
+ upper_edges = bin_edges.gather(1, (t_max + 1)[:, None]).squeeze(1)
if not x.is_floating_point():
# An integer pixel on or above the upper edge is counted in the foreground, so the integer threshold is
# the largest integer below that edge. Truncating toward zero would round a negative edge up, and keep
# 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)
+ best_thresholds = torch.where(max_var > 0, upper_edges, lower_edges).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
- )
+ # 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.
@@ -228,23 +331,24 @@ class OtsuThreshold(torch.nn.Module):
# 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)
+ # 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(upper_edges.dtype), previous.to(upper_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()
plane_max = x_flattened.amax(dim=1).detach()
best_thresholds = torch.where(plane_min == plane_max, plane_min, best_thresholds)
+ if slow_and_differentiable and x.is_floating_point() and torch.is_grad_enabled() and x.requires_grad:
+ # Straight-through: the value stays the hard split above, the gradient is that of the soft-argmax
+ # threshold of the wider estimate. On a constant plane that threshold is the plane's minimum.
+ soft_thresholds = self._soft_threshold(coords, bounded_min, bounded_span, nbins)
+ best_thresholds = best_thresholds + (soft_thresholds - soft_thresholds.detach()).to(x.dtype)
+
# Apply thresholding: keep values strictly greater than the threshold
thresholded = (x_flattened > best_thresholds[:, None]).to(x.dtype) * x_flattened
thresholded = thresholded.reshape(orig_shape)
@@ -260,19 +364,20 @@ def otsu_threshold(
) -> Tuple[torch.Tensor, torch.Tensor]:
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. 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``.
+ Each image/channel plane uses its own histogram range. 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. 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. Both paths support ``torch.export`` and full-graph
+ ``torch.compile``.
Args:
x (Tensor): Input tensor (image or batch of images).
nbins (int): Number of bins for histogram computation, default is 256.
- slow_and_differentiable (bool): If True, use a differentiable histogram computation. Default is False.
+ slow_and_differentiable (bool): If True, build the histogram from a Gaussian kernel density estimate and give
+ the threshold a gradient with respect to ``x``; see the note below. Default is False.
return_mask (bool): If True, return the boolean mask ``x > threshold`` in place of the thresholded image,
with each pixel compared against the threshold of its own image and channel. If False, return the
thresholded image.
@@ -294,6 +399,31 @@ def otsu_threshold(
.. note::
You may found more information about the Otsu algorithm here: https://en.wikipedia.org/wiki/Otsu's_method
+ .. note::
+ With ``slow_and_differentiable=True``, each pixel is spread into a Gaussian with a standard deviation of 0.1
+ bin, and the histogram holds the mass of these Gaussians in each bin, a pixel's mass beyond the plane's range
+ staying in the first or the last bin, so every pixel contributes its full mass. The threshold is the upper edge
+ of the bin selected by the best split of that histogram, as on the default path, and is usually within one bin
+ of the default threshold. A bin counts as non-empty only above 1 % of one pixel's mass, so of the splits that
+ give the same partition the lowest is taken on every device. Each pixel's class is the side of the selected
+ edge its bin lies on, and a floating threshold is corrected to separate the two classes as on the default
+ path.
+
+ The threshold uses a hard split, and its first-order gradient is a straight-through surrogate: the
+ gradient of a soft-argmax over the between-class variance curve :math:`\sigma_B^2(k)` of a wider estimate,
+ with a standard deviation of 0.5 bin, so that a pixel's gradient varies smoothly with its value instead of
+ concentrating on pixels near a bin edge. Split :math:`k` is weighted by
+ :math:`\operatorname{softmax}_k\left(\sigma_B^2(k) / (0.01 \max_j \sigma_B^2(j))\right)`. The curve's means
+ are measured in bins and the temperature is relative to the curve, so the weights do not depend on the
+ intensity scale or offset of ``x``. The surrogate is evaluated on the plane shifted by its minimum and
+ divided by its range, or by its largest magnitude when the range overflows, with these factors cancelled
+ from its first-order gradient, so narrow and finite extreme ranges stay safe. Higher-order derivatives through
+ this straight-through normalization do not represent derivatives of the original-unit soft threshold.
+ Finite differences of the hard threshold do not match the surrogate gradient. The wider estimate is computed
+ only when ``x`` requires a gradient. With the default ``slow_and_differentiable=False``
+ the threshold has no gradient. On both paths the thresholded image is ``x * (x > threshold)``, whose gradient
+ with respect to ``x`` is that mask.
+
Example:
>>> import torch
>>> from kornia.filters.otsu_thresholding import otsu_threshold
diff --git a/tests/filters/test_otsu_thresholding.py b/tests/filters/test_otsu_thresholding.py
index 2751e393f..26cb569ef 100644
--- a/tests/filters/test_otsu_thresholding.py
+++ b/tests/filters/test_otsu_thresholding.py
@@ -18,6 +18,7 @@
import pytest
import torch
+from kornia.core._compat import torch_version
from kornia.filters.otsu_thresholding import OtsuThreshold, otsu_threshold
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, assert_close, dynamo_is_available
@@ -63,9 +64,9 @@ class TestOtsuThreshold(BaseTester):
@staticmethod
def _separated_image(device, dtype):
- """A fixed 5x5 image whose ``nbins=3`` Otsu threshold is 0.5 and keeps 14 of 25 pixels.
+ """A fixed 5x5 image whose ``nbins=3`` slow-path Otsu threshold is 2/3 and keeps 10 of 25 pixels.
- Every pixel is at least 1.9e-3 from the threshold in each tested dtype (the smallest margin is 1.95e-3, in
+ Every pixel is at least 6.3e-3 from the threshold in each tested dtype (the smallest margin is 6.35e-3, in
float16), so a finite-difference step cannot move a pixel across it. The values are fixed rather than drawn: a
random draw often puts the threshold at the data maximum (empty output) or at a near-tie between two splits,
and gradcheck then fails.
@@ -89,9 +90,11 @@ class TestOtsuThreshold(BaseTester):
assert (out > 0).any()
assert not (img64 > threshold).all()
assert (img64 - threshold).abs().min() > 1e-3
- # The analytical gradient of the output is just the mask (no gradient flows through the threshold), so
- # this only checks that no pixel crosses the threshold under the finite-difference perturbation.
- self.gradcheck(otsu_threshold, (img, 3, True, False))
+ # The analytical gradient of the thresholded image is just the mask (no gradient flows from the image output
+ # through the threshold), so this only checks that no pixel crosses the threshold under the finite-difference
+ # perturbation. The threshold output is left out: its value is piecewise constant and its gradient a
+ # straight-through surrogate, which finite differences cannot check (see TestOtsuThresholdDifferentiable).
+ self.gradcheck(lambda img: otsu_threshold(img, 3, True, False)[0], (img,))
def test_differentiable_tensor_otsu(self, device, dtype):
img = self._separated_image(device, dtype).requires_grad_(True)
@@ -289,9 +292,10 @@ class TestOtsuThreshold(BaseTester):
@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)
+ # Three bins over [0, 1.5] put the first upper edge at 0.5, the split the KDE selects. A pixel on that edge
+ # belongs to the foreground and must not be removed by the strict comparison. Without a collision, keep the
+ # edge exactly.
+ image = torch.tensor([[0.0, 0.0, 0.0, middle, 1.5, 1.5]], 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:
@@ -299,10 +303,10 @@ class TestOtsuThreshold(BaseTester):
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)
+ def test_slow_path_downward_rounded_edge_keeps_background_pixel_excluded_5422(self, device):
+ # The float32 edge 0.50065 over [2**-10, 1.5] rounds down to the pixel 0.5 in bfloat16. That pixel lies below
+ # the edge, so lowering the threshold to keep it, as for an upward-rounded edge, would promote it.
+ image = torch.tensor([[2**-10] * 3 + [0.5, 1.5, 1.5]], 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]]
@@ -476,3 +480,324 @@ def test_otsu_threshold_basic(shape, device, dtype):
img = torch.rand(shape, device=device, dtype=dtype)
thresh_result, _thresh_value = otsu_threshold(img)
assert thresh_result.shape == img.shape
+
+
+def _bimodal_uint8_image(device):
+ # the image of #5172: every value 0..255 once, plus 300 pixels at 60 and 300 at 190
+ values = torch.cat([torch.arange(256), torch.full((300,), 60), torch.full((300,), 190)])
+ return values.to(device=device, dtype=torch.uint8).view(1, 1, 8, 107)
+
+
+def _quantile_mixture(device, dtype, dark=(0.3, 0.06, 700), bright=(0.7, 0.1, 300), bright_shift=0.0, levels=None):
+ """A (1, 1, 20, 50) image of two modes, each ``(mean, std, count)``, at the quantiles of a normal distribution.
+
+ Quantiles rather than a random draw: the image is the same on every device and in every run. The default modes
+ overlap, so the threshold sits between them and follows them. With ``levels``, the values are rounded to multiples
+ of ``1 / levels``, as in an 8-bit image scaled to [0, 1].
+ """
+
+ def quantiles(n):
+ p = (torch.arange(n, dtype=torch.float64) + 0.5) / n
+ return 2**0.5 * torch.erfinv(2 * p - 1)
+
+ (dark_mean, dark_std, dark_count), (bright_mean, bright_std, bright_count) = dark, bright
+ x = torch.cat(
+ [
+ dark_mean + dark_std * quantiles(dark_count),
+ bright_mean + bright_shift + bright_std * quantiles(bright_count),
+ ]
+ )
+ if levels is not None:
+ x = (x * levels).round().clamp(0, levels) / levels
+ return x.view(1, 1, 20, 50).to(device=device, dtype=dtype)
+
+
+def _documented_soft_threshold(x, nbins, bandwidth=0.5, temperature=0.01):
+ # The formula of otsu_threshold's note, written independently: Gaussian bin masses with the tails kept in the end
+ # bins, the between-class variance in bins, and a softmax at `temperature` times its maximum over the upper edges
+ # k + 1 of the splits.
+ v = x.flatten()
+ lo, hi = v.min(), v.max()
+ c = (v - lo) * nbins / (hi - lo)
+ edges = torch.arange(1, nbins, dtype=v.dtype, device=v.device)
+ above = 0.5 * (1 + torch.erf((c[:, None] - edges) / (bandwidth * 2**0.5))).mean(0)
+ p = -torch.diff(torch.cat([above.new_ones(1), above, above.new_zeros(1)]))
+ k = torch.arange(nbins, dtype=v.dtype, device=v.device)
+ w0, s0 = p.cumsum(0)[:-1], (p * k).cumsum(0)[:-1]
+ w1, s1 = 1 - w0, (p * k).sum() - s0
+ var = w0 * w1 * (s0 / w0 - s1 / w1) ** 2
+ return lo + (torch.softmax(var / (temperature * var.max()), 0) * edges).sum() * (hi - lo) / nbins
+
+
+class TestOtsuThresholdDifferentiable(BaseTester):
+ # No gradcheck on the threshold: its value comes from a hard split, while its gradient is that of
+ # a soft-argmax over a smoother between-class variance curve (straight-through), so finite differences of the
+ # threshold do not match it by design. These tests check that the gradient exists, is finite, is consistent with
+ # translating a plane, reaches every pixel and points the right way.
+ def test_threshold_has_a_gradient_5174(self, device, dtype):
+ x = _quantile_mixture(device, dtype).requires_grad_(True)
+ out, threshold = otsu_threshold(x, slow_and_differentiable=True)
+ assert threshold.requires_grad
+ (grad,) = torch.autograd.grad(threshold.sum(), x, retain_graph=True)
+ assert grad.isfinite().all()
+ assert grad.count_nonzero() > 0
+
+ # the gradient leaves the value alone: the same input without a gradient gets the same threshold
+ _, detached = otsu_threshold(x.detach(), slow_and_differentiable=True)
+ assert not detached.requires_grad
+ self.assert_close(threshold.detach(), detached, rtol=0.0, atol=0.0)
+
+ # the thresholded image is x * (x > threshold): its gradient is the mask
+ (grad,) = torch.autograd.grad(out.sum(), x)
+ self.assert_close(grad, (x.detach() > threshold.detach()).to(dtype))
+
+ # the default path's threshold has no gradient
+ _, threshold = otsu_threshold(x)
+ assert not threshold.requires_grad
+
+ @pytest.mark.parametrize("scale_kind", ["large", "small", "subnormal"])
+ @pytest.mark.parametrize("signed", [False, True])
+ def test_finite_extreme_ranges_5426(self, scale_kind, signed, device, dtype):
+ if scale_kind == "subnormal" and device.type == "mps" and dtype != torch.float16:
+ pytest.skip("MPS flushes float32 and bfloat16 subnormals to zero")
+ limits = torch.finfo(dtype)
+ scale = {"large": limits.max, "small": limits.tiny * 64, "subnormal": limits.tiny / 64}[scale_kind]
+ levels = torch.tensor([[0.0, 0.1, 0.2, 0.6, 0.8, 1.0]], device=device, dtype=dtype)
+ if signed:
+ levels = 2 * levels - 1
+ x = (levels * scale).requires_grad_(True)
+ out, threshold = otsu_threshold(x, slow_and_differentiable=True)
+ (grad,) = torch.autograd.grad(threshold.sum(), x, retain_graph=True)
+ assert threshold.isfinite().all()
+ assert grad.isfinite().all()
+ self.assert_close(grad.float().sum(), grad.new_tensor(1.0).float(), rtol=0, atol=1e-2)
+ assert torch.equal(threshold.detach(), otsu_threshold(x.detach(), slow_and_differentiable=True)[1])
+ (image_grad,) = torch.autograd.grad(out.sum(), x)
+ self.assert_close(image_grad, (x.detach() > threshold.detach()).to(dtype))
+
+ # Compare against the independent documented formula on the same quantized pixels in ordinary units.
+ # The derivative of s * f(x / s) is f'(x / s), so a finite scale must leave this gradient unchanged.
+ work_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ normalized = (x.detach().to(work_dtype) / scale).requires_grad_(True)
+ (expected_grad,) = torch.autograd.grad(_documented_soft_threshold(normalized, 256), normalized)
+ self.assert_close(grad, expected_grad.to(dtype))
+ expected = otsu_threshold(normalized.detach(), slow_and_differentiable=True)[1]
+ self.assert_close(
+ threshold.detach().to(work_dtype) / scale,
+ expected,
+ rtol=max(8 * limits.eps, 1e-11),
+ # Subnormal thresholds round in units of the smallest subnormal, rather than relative to their value.
+ atol=limits.tiny * limits.eps / scale,
+ )
+
+ @pytest.mark.parametrize("scale_kind", ["large", "subnormal"])
+ def test_extreme_constant_plane_gradient_5426(self, scale_kind, device, dtype):
+ if scale_kind == "subnormal" and device.type == "mps" and dtype != torch.float16:
+ pytest.skip("MPS flushes float32 and bfloat16 subnormals to zero")
+ limits = torch.finfo(dtype)
+ value = limits.max if scale_kind == "large" else limits.tiny / 64
+ x = torch.full((2, 3), value, device=device, dtype=dtype, requires_grad=True)
+ mask, threshold = otsu_threshold(x, slow_and_differentiable=True, return_mask=True)
+ (grad,) = torch.autograd.grad(threshold.sum(), x)
+ assert torch.equal(threshold.detach(), x.detach().flatten()[:1])
+ assert not mask.any()
+ self.assert_close(grad, torch.full_like(x, 1 / x.numel()))
+
+ def test_low_contrast_offset_plane_keeps_its_gradient_and_split_5426(self, device, dtype):
+ # Levels one ulp apart around 1.5: scaling by the largest magnitude before subtracting the minimum rounds their
+ # differences, which changed the gradient and promoted level 2 at 256 bins. Translating the plane must not.
+ levels = torch.tensor([[0, 1, 2, 6, 8, 10]], device=device, dtype=dtype)
+ x = (1.5 + levels * torch.finfo(dtype).eps).requires_grad_(True)
+ (grad,) = torch.autograd.grad(otsu_threshold(x, 8, slow_and_differentiable=True)[1].sum(), x)
+ reference = x.detach().cpu().double().requires_grad_(True)
+ (expected,) = torch.autograd.grad(_documented_soft_threshold(reference, 8), reference)
+ self.assert_close(grad, expected.to(device=device, dtype=dtype), rtol=1e-3, atol=1e-3)
+ mask, _ = otsu_threshold(x.detach(), 256, slow_and_differentiable=True, return_mask=True)
+ expected_mask, _ = otsu_threshold(levels, 256, slow_and_differentiable=True, return_mask=True)
+ assert mask.tolist() == expected_mask.tolist() == [[False, False, False, True, True, True]]
+
+ def test_narrow_two_level_plane_keeps_background_when_edge_rounds_down_5426(self, device, dtype):
+ # The first upper edge lies less than half an ulp above the minimum and rounds down onto it. That threshold
+ # already separates the levels, so it must not be lowered below the background pixel.
+ x = 1.5 + torch.tensor([[0, 10, 10]], device=device, dtype=dtype) * torch.finfo(dtype).eps
+ mask, threshold = otsu_threshold(x, 256, slow_and_differentiable=True, return_mask=True)
+ assert mask.tolist() == [[False, True, True]]
+ self.assert_close(threshold, x[:, 0], rtol=0, atol=0)
+
+ def test_subnormal_range_keeps_background_when_edge_rounds_down_5426(self, device, dtype):
+ if device.type == "mps" and dtype != torch.float16:
+ pytest.skip("MPS flushes float32 and bfloat16 subnormals to zero")
+ # The selected edge is 86 / 256 * 3u = 1.0078125u, which rounds down onto the background pixel u.
+ u = torch.nextafter(torch.zeros((), dtype=dtype), torch.ones((), dtype=dtype)).item()
+ x = torch.tensor([[0, 1, 3]], device=device, dtype=dtype) * u
+ mask, _ = otsu_threshold(x, 256, slow_and_differentiable=True, return_mask=True)
+ assert mask.tolist() == [[False, False, True]]
+
+ def test_threshold_gradient_sums_to_one_per_plane_5174(self, device, dtype):
+ # Moving every pixel of a plane by c moves its threshold by c and no other plane's, so the gradient of each
+ # plane's threshold sums to 1 over that plane and is 0 on the others. A constant plane's threshold is its value,
+ # whose gradient its pixels share.
+ planes = [
+ _quantile_mixture(device, dtype),
+ _quantile_mixture(device, dtype, dark=(0.3, 0.08, 600), bright=(0.7, 0.08, 400), levels=255),
+ torch.linspace(0, 1, 1000, dtype=torch.float64).square().view(1, 1, 20, 50).to(device=device, dtype=dtype),
+ torch.full((1, 1, 20, 50), 0.4, device=device, dtype=dtype),
+ ]
+ x = torch.cat(planes).view(2, 2, 20, 50).requires_grad_(True)
+ _, thresholds = otsu_threshold(x, slow_and_differentiable=True)
+ (grad,) = torch.autograd.grad(thresholds.sum(), x, retain_graph=True)
+ # bfloat16 rounds each pixel's gradient to 8 bits, and the rounding errors add up over the plane
+ atol = 3e-3 if dtype == torch.bfloat16 else 1e-3
+ self.assert_close(grad.float().sum(dim=(-2, -1)), torch.ones(2, 2, device=device), rtol=0.0, atol=atol)
+ self.assert_close(grad[1, 1], torch.full_like(grad[1, 1], 1 / 1000))
+
+ (grad,) = torch.autograd.grad(thresholds[0], x)
+ assert grad.flatten(0, 1)[1:].count_nonzero() == 0
+
+ def test_threshold_gradient_reaches_every_pixel_5174(self, device, dtype):
+ # An 8-bit image scaled to [0, 1]: at 256 bins its levels sit at fixed positions inside their bins. The gradient
+ # comes from a kernel density estimate 0.5 bin wide, so it does not concentrate on the pixels near a bin edge.
+ # The 0.1-bin estimate that selects the threshold's value would leave about half of this image's pixels, those
+ # more than about 0.3 bin from every bin edge, below 1e-3 of the largest gradient. A pixel where the gradient
+ # changes sign, near the threshold, can get an arbitrarily small gradient under any estimate; in this image the
+ # smallest is 1.5e-2 of the largest.
+ x = _quantile_mixture(device, dtype, dark=(0.3, 0.08, 600), bright=(0.7, 0.08, 400), levels=255)
+ x.requires_grad_(True)
+ _, threshold = otsu_threshold(x, slow_and_differentiable=True)
+ (grad,) = torch.autograd.grad(threshold.sum(), x)
+ magnitude = grad.abs().float()
+ assert (magnitude > 1e-3 * magnitude.max()).all()
+
+ def test_threshold_gradient_is_the_documented_surrogate_5174(self, device, dtype):
+ # The gradient is that of the note's soft-argmax: 0.5-bin kernel density estimate, temperature 0.01 of the
+ # curve's maximum. The other tests check its properties, which other bandwidths and temperatures share too.
+ if dtype != torch.float64:
+ pytest.skip("checks the formula, not dtype rounding")
+ x = _quantile_mixture(device, dtype).requires_grad_(True)
+ (grad,) = torch.autograd.grad(otsu_threshold(x, nbins=64, slow_and_differentiable=True)[1].sum(), x)
+ (expected,) = torch.autograd.grad(_documented_soft_threshold(x, 64), x)
+ self.assert_close(grad, expected, rtol=1e-9, atol=1e-12)
+
+ def test_threshold_gradient_follows_the_bright_mode_5174(self, device, dtype):
+ x = _quantile_mixture(device, dtype).requires_grad_(True)
+ _, threshold = otsu_threshold(x, slow_and_differentiable=True)
+ (grad,) = torch.autograd.grad(threshold.sum(), x)
+ up_image = _quantile_mixture(device, dtype, bright_shift=0.05)
+ down_image = _quantile_mixture(device, dtype, bright_shift=-0.05)
+ _, up = otsu_threshold(up_image, slow_and_differentiable=True)
+ _, down = otsu_threshold(down_image, slow_and_differentiable=True)
+ # shifting the bright mode moves the threshold the same way ...
+ assert up.item() > threshold.item() > down.item()
+
+ # ... and the gradient along that shift, the sum over the bright pixels, agrees in sign and is close to the
+ # threshold's actual response, (up - down) / 0.1 = 0.45, against a gradient of 0.39. The response is measured
+ # on float32 copies of half-precision images: rounding the two thresholds themselves to bfloat16 (2**-8 near
+ # 0.5) would move it by up to 2 * 2**-8 / 0.1 = 0.08.
+ reference_dtype = torch.promote_types(dtype, torch.float32)
+ _, up = otsu_threshold(up_image.to(reference_dtype), slow_and_differentiable=True)
+ _, down = otsu_threshold(down_image.to(reference_dtype), slow_and_differentiable=True)
+ response = (up.item() - down.item()) / 0.1
+ along_shift = grad.flatten()[700:].float().sum().item()
+ assert along_shift > 0
+ assert abs(along_shift - response) < 0.1
+ assert grad.flatten()[:700].float().sum().item() > 0
+
+ def test_slow_and_fast_thresholds_agree_within_one_bin_5174(self, device, dtype):
+ # The slow histogram is the mass a Gaussian kernel density estimate of bandwidth 0.1 bin puts in each bin. It
+ # differs from histc's only by the part of a pixel's mass, within a fraction of a bin of an edge, that falls in
+ # the neighbouring bin. On the images of #5174 and #5172 below, that moves the best split up by at most one
+ # bin: 0 <= slow - fast <= one bin, plus the rounding of both thresholds to the dtype (the two paths also
+ # compute the same edge with different float arithmetic, which differs in the last bits). Not a property of
+ # every image: two near-tied splits far apart can swap under any change of histogram estimator. The default
+ # path runs on the CPU, where it takes the lowest of splits that give the same partition; on MPS its
+ # cumulative sums can make a later one win (0.4766 instead of 0.4000 on the bimodal image, #5421).
+ generator = torch.Generator().manual_seed(0)
+ noise = torch.rand(1000, generator=generator, dtype=torch.float64)
+ ramp_a = torch.linspace(0, 1, 60, dtype=torch.float64).square().view(1, 1, 6, 10)
+ ramp_b = torch.linspace(0.6, 4.3, 60, dtype=torch.float64).view(1, 1, 6, 10)
+ cases = [
+ ("bimodal", torch.cat([0.3 + 0.1 * noise[:500], 0.6 + 0.1 * noise[500:]]).view(1, 1, 20, 50), 256),
+ ("mass at 0.3", torch.tensor([0.0] * 10 + [0.3] * 80 + [1.0] * 10).view(1, 1, 1, -1), 16),
+ ("mass at 0.7", torch.tensor([0.0] * 10 + [0.7] * 80 + [1.0] * 10).view(1, 1, 1, -1), 16),
+ ("uint8 values", _bimodal_uint8_image("cpu").double(), 256),
+ ("nbins=2", torch.tensor([[0.0, 0.1, 0.2, 0.55, 0.9, 1.0]]), 2),
+ ("ramp a", ramp_a, 256),
+ ("ramp b", ramp_b, 256),
+ ]
+ thresholds = {}
+ for name, x, nbins in cases:
+ if name == "ramp a" and dtype == torch.bfloat16:
+ # bfloat16 rounds one pixel of this ramp onto the bin edge 106 / 256: histc counts it in bin 106, the
+ # kernel splits it between bins 105 and 106, and the splits on its two sides are within 0.003 % of each
+ # other in between-class variance, so the slow path takes the other one, 6 bins up
+ continue
+ x = x.to(device=device, dtype=dtype)
+ _, fast = otsu_threshold(x.cpu(), nbins=nbins)
+ _, slow = otsu_threshold(x, nbins=nbins, slow_and_differentiable=True)
+ bin_width = (x.max().item() - x.min().item()) / nbins
+ rounding = torch.finfo(dtype).eps * max(abs(fast.item()), abs(slow.item()))
+ assert -rounding <= slow.item() - fast.item() <= bin_width + rounding, name
+ thresholds[name] = slow.item()
+ # every pixel contributes to the slow histogram: the 80 pixels at 0.3 or 0.7 decide between the two images
+ assert thresholds["mass at 0.3"] != thresholds["mass at 0.7"]
+
+ # an integer image gets the largest integer below the edge on both paths
+ image = _bimodal_uint8_image(device)
+ assert otsu_threshold(image, slow_and_differentiable=True)[1].item() == 125
+ assert otsu_threshold(image.cpu())[1].item() == 125
+
+ def test_equivalent_splits_take_the_lowest_5174(self, device, dtype):
+ # 1 / x on 60 evenly spaced x leaves runs of empty bins between its upper levels, so several splits give the
+ # same partition. The kernel tails put about 1e-23 of a pixel in each empty bin; counted as mass, they would
+ # leave the choice between those splits to the rounding of the cumulative sums, and in float16 on the CPU, or
+ # in float32 on MPS, the highest of them, 6 bins up, would win. Only a bin above 1 % of a pixel counts as
+ # non-empty, so the lowest wins on every device, as on the default path on the CPU.
+ x = (1 / torch.linspace(1, 10, 60, dtype=torch.float64)).view(1, 1, 6, 10).to(dtype)
+ _, expected = otsu_threshold(x)
+ _, slow = otsu_threshold(x.to(device), slow_and_differentiable=True)
+ self.assert_close(slow.cpu(), expected, rtol=4 * torch.finfo(dtype).eps, atol=0.0)
+
+ @pytest.mark.parametrize("slow_and_differentiable", [False, True])
+ def test_dynamo(self, slow_and_differentiable, device, dtype, torch_optimizer, optimizer_backend):
+ x = _quantile_mixture(device, dtype)
+ # neither path calls .item(), so each compiles as one graph
+ op = torch_optimizer(
+ lambda x: otsu_threshold(x, nbins=64, slow_and_differentiable=slow_and_differentiable), fullgraph=True
+ )
+ expected = otsu_threshold(x, nbins=64, slow_and_differentiable=slow_and_differentiable)
+ actual = op(x)
+ self.assert_close(actual[0], expected[0])
+ self.assert_close(actual[1], expected[1])
+
+ if slow_and_differentiable:
+ if (
+ optimizer_backend == "inductor"
+ and dtype == torch.float64
+ and device.type == "cpu"
+ and torch_version().startswith("2.5.")
+ ):
+ pytest.skip(
+ "PyTorch 2.5.1 CPU Inductor has no `fmadd` overload for `VectorizedN<double, 2>` in the softmax "
+ "backward"
+ )
+ x = x.clone().requires_grad_(True)
+ (expected_grad,) = torch.autograd.grad(otsu_threshold(x, 64, True)[1].sum(), x)
+ (actual_grad,) = torch.autograd.grad(op(x)[1].sum(), x)
+ # The plane's minimum pixel collects the backward of the minimum, which cancels terms of order 1 down to
+ # about 1e-3. In float32, eager and compiled each land within about 6e-6 of the float64 surrogate there,
+ # rounding in opposite directions on MPS, so allow both errors.
+ tolerance = {"rtol": 1e-4, "atol": 2e-5} if dtype == torch.float32 else {}
+ self.assert_close(actual_grad, expected_grad, **tolerance)
+
+ # Compiler rewrites must preserve the scale cancellation at both ends of the finite dtype range.
+ limits = torch.finfo(dtype)
+ levels = torch.tensor([[-1.0, -0.8, -0.6, 0.2, 0.6, 1.0]], device=device, dtype=dtype)
+ x = torch.stack([levels * limits.max, levels * (limits.tiny * 64)]).requires_grad_(True)
+ expected = otsu_threshold(x, 64, True)[1]
+ actual = op(x)[1]
+ assert actual.isfinite().all()
+ self.assert_close(actual, expected)
+ (expected_grad,) = torch.autograd.grad(expected.sum(), x)
+ (actual_grad,) = torch.autograd.grad(actual.sum(), x)
+ assert actual_grad.isfinite().all()
+ self.assert_close(actual_grad, expected_grad)