🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Optimize CPU/CUDA flagship hotspots and correct benchmark baselines (#5997)
Dmytro Mishkin5bb235457aac
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex 5aa0cdb77..fddc9771a 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -272,6 +272,10 @@ with figures embedded in the PR description. Local reruns should write JSON outs## Sample results — geometry flagship ops+Historical rotation comparisons below used torchvision’s default nearest interpolation against+Kornia’s bilinear interpolation. Do not use those ratios to compare libraries. The current+harness explicitly uses bilinear and distinguishes shared angles from per-image parameters.+Directional numbers only — reproduce on your own hardware for anything you cite. Measured2026-08-07, commit `5eaa7a10`, Apple Silicon (macOS 26.5, arm64), Python 3.11, torch 2.9.1,kornia 0.9.0rc1, OpenCV 4.11.0, float32, 256×256, 4 threads. Throughput in items/s (higher is@@ -328,9 +332,9 @@ NVIDIA RTX PRO 6000 Blackwell (AMD Turin host):- **Batched GPU is kornia's regime and the margin is large:** compiled `warp_perspective` atbatch 32 beats OpenCV's per-image CPU loop by ~45× (L4) to ~72× (RTX PRO 6000); eager aloneis ~20–30×.-- **`rotate` is a found weak spot:** torchvision v2 beats kornia on every GPU tested- (~1.7–2×, up to ~4× vs eager where compile was unavailable). First data-driven optimization- target for the Stage-3 iteration.+- **Historical `rotate` ratios do not establish a library ranking:** the apparent torchvision+ advantage used nearest interpolation against Kornia's bilinear interpolation. Remeasure with+ the current matched-interpolation harness, distinguishing shared angles from per-image parameters.- **`resize`:** kornia eager matches torchvision almost exactly (same underlying kernel);`torch.compile` is a large win at big batches on newer GPUs (3.6M img/s at batch 128 onBlackwell) but *regressed* resize on L4 at batch ≤ 32 — compile is not a free win, measure@@ -478,6 +482,9 @@ The honest reading:## Sample results — augmentation flagship (class API)+Historical `RandomAffine` comparisons below used nearest interpolation for torchvision and+bilinear for Kornia. The current harness matches bilinear interpolation; rerun before comparing.+Directional numbers only — reproduce on your own hardware for anything you cite. Measured2026-08-08, commit `c97b0f9a`, Apple Silicon (macOS 26.5, arm64), Python 3.11, torch 2.9.1,torchvision 0.24.1, albumentations 2.0.8, OpenCV 4.11.0, Pillow 12.3, float32, 256×256,diff --git a/benchmarks/augmentation/flagship.py b/benchmarks/augmentation/flagship.pyindex fd53fe2d6..916585a32 100644--- a/benchmarks/augmentation/flagship.py+++ b/benchmarks/augmentation/flagship.py@@ -141,7 +141,16 @@ def build_ops(if include("RandomAffine"):row = kornia_row("RandomAffine", KA.RandomAffine(degrees=30.0, translate=(0.1, 0.1), scale=(0.8, 1.2), p=1.0))row["torchvision v2"] = (- tv(T2.RandomAffine(degrees=30.0, translate=(0.1, 0.1), scale=(0.8, 1.2))) if T2 else None+ tv(+ T2.RandomAffine(+ degrees=30.0,+ translate=(0.1, 0.1),+ scale=(0.8, 1.2),+ interpolation=T2.InterpolationMode.BILINEAR,+ )+ )+ if T2+ else None)row["albumentations"] = (alb(A.Affine(rotate=(-30.0, 30.0), translate_percent=(0.0, 0.1), scale=(0.8, 1.2), p=1.0)) if A else Nonediff --git a/benchmarks/geometry/flagship.py b/benchmarks/geometry/flagship.pyindex fcdf7e98c..0ca7d5723 100644--- a/benchmarks/geometry/flagship.py+++ b/benchmarks/geometry/flagship.py@@ -25,6 +25,7 @@ kornia (batched float BCHW) OpenCV (uint8 HWC, per-image Python loop) torch``warp_perspective`` ``cv2.warpPerspective`` —``warp_affine`` ``cv2.warpAffine`` —``rotate`` ``cv2.warpAffine(getRotationMatrix2D)`` ``tvf.rotate``+``rotate_shared`` ``cv2.warpAffine(getRotationMatrix2D)`` ``tvf.rotate````resize`` ``cv2.resize`` ``tvf.resize````get_perspective_transform`` ``cv2.getPerspectiveTransform`` (per pair) —============================= ========================================== ==============@@ -35,6 +36,8 @@ a Python loop — its native regime. Columns are regime comparisons, not apples-Equal footing: bilinear interpolation, no antialiasing anywhere (torchvision gets an explicit``antialias=False``), identical transform parameters across backends, pinned seeds.+``rotate`` passes B angle parameters; ``rotate_shared`` passes a singleton angle so Kornia can+reuse one sampling grid. Both use 30 degrees, matching torchvision's shared-angle API.Usage:python benchmarks/geometry/flagship.py --batches 1,8,32 --size 256 --device cpu@@ -71,7 +74,7 @@ from common import (import kornia.geometry as KG-OPS = ("warp_perspective", "warp_affine", "rotate", "resize", "get_perspective_transform")+OPS = ("warp_perspective", "warp_affine", "rotate", "rotate_shared", "resize", "get_perspective_transform")def build_ops(@@ -132,11 +135,25 @@ def build_ops(if include("rotate"):row = kornia_row("rotate", lambda: KG.rotate(batch_f, angle))if cv2:- m_rot = cv2.getRotationMatrix2D((w / 2, h / 2), angle_deg, 1.0)+ m_rot = cv2.getRotationMatrix2D(((w - 1) / 2, (h - 1) / 2), angle_deg, 1.0)row["opencv"] = lambda: [cv2.warpAffine(im, m_rot, (w, h)) for im in imgs_u8]- row["torchvision v2"] = (lambda: tvf.rotate(batch_f, angle_deg)) if tvf else None+ row["torchvision v2"] = (+ (lambda: tvf.rotate(batch_f, angle_deg, interpolation=tvf.InterpolationMode.BILINEAR)) if tvf else None+ )ops["rotate"] = row+ if include("rotate_shared"):+ # One transform shared by the batch; keep the independent-parameter row above too.+ shared_angle = angle[:1]+ row = kornia_row("rotate_shared", lambda: KG.rotate(batch_f, shared_angle))+ if cv2:+ m_rot_shared = cv2.getRotationMatrix2D(((w - 1) / 2, (h - 1) / 2), angle_deg, 1.0)+ row["opencv"] = lambda: [cv2.warpAffine(im, m_rot_shared, (w, h)) for im in imgs_u8]+ row["torchvision v2"] = (+ (lambda: tvf.rotate(batch_f, angle_deg, interpolation=tvf.InterpolationMode.BILINEAR)) if tvf else None+ )+ ops["rotate_shared"] = row+if include("resize"):dst_size = (h // 2, w // 2)row = kornia_row("resize", lambda: KG.resize(batch_f, dst_size, interpolation="bilinear"))diff --git a/changelog.d/5997.fixed.md b/changelog.d/5997.fixed.mdnew file mode 100644index 000000000..11ef365d8--- /dev/null+++ b/changelog.d/5997.fixed.md@@ -0,0 +1 @@+Reduce scalar gamma adjustment overhead, batch confusion-matrix accumulation, skip settled distance-transform inference iterations, avoid dense one-hot intermediates for unweighted reduced focal loss, and reuse sampling grids for shared non-trainable rotation and affine transforms. Preserve TorchScript gamma adjustment and dynamic image/angle batches in rotation traces. Keep real-mode FX capture static and preserve affine-warp empty-batch validation in traces.diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.pyindex 0e6e57d8a..7da9e8ea4 100644--- a/kornia/contrib/distance_transform.py+++ b/kornia/contrib/distance_transform.py@@ -21,8 +21,11 @@ import mathimport torchfrom torch import nn+from torch._subclasses.fake_tensor import is_fake+from torch.fx.experimental.proxy_tensor import get_proxy_modefrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE+from kornia.core.utils import is_compilingfrom kornia.filters import filter2d, filter3dfrom kornia.geometry.grid import create_meshgrid, create_meshgrid3d@@ -86,6 +89,29 @@ def _off_centre_tap_sum(kernel_size: int, h: float, ndim: int) -> float:return total - 1.0 # drop the centre tap+def _can_stop_cascade(image: torch.Tensor) -> bool:+ # Capture and function transforms cannot branch on a tensor's value. Keep the fixed loop for+ # differentiation as well, including forward AD on an input without requires_grad.+ if torch.jit.is_scripting():+ return False+ if (+ torch.jit.is_tracing()+ or is_compiling()+ or get_proxy_mode() is not None+ or torch._C._are_functorch_transforms_active()+ ):+ return False+ if image.requires_grad and torch.is_grad_enabled():+ return False+ # Only CPU and CUDA hold readable data here; meta, fake and lazy tensors do not, and reading a+ # flag would synchronize MPS. A CUDA graph capture cannot synchronize either.+ if image.device.type not in ("cpu", "cuda") or is_fake(image):+ return False+ if image.is_cuda and torch.cuda.is_current_stream_capturing():+ return False+ return torch.autograd.forward_ad.unpack_dual(image).tangent is None++def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float) -> torch.Tensor:device = image.devicedtype = image.dtype@@ -103,6 +129,7 @@ def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float)out = torch.zeros_like(image, dtype=compute_dtype)boundary = image.to(compute_dtype)signal_ones = torch.ones_like(boundary)+ can_stop = _can_stop_cascade(image)for i in range(n_iters):cdt = filter2d(boundary, kernel, border_type="replicate")@@ -112,9 +139,10 @@ def _distance_transform_2d_impl(image: torch.Tensor, kernel_size: int, h: float)cdt = torch.nan_to_num(cdt, nan=0.0, posinf=0.0, neginf=0.0)mask = cdt > 0- # No data-dependent early-out: the loop bound (n_iters) is fixed, and once no pixels- # remain the remaining iterations are exact no-ops (out += 0*mask, where(False,...)- # leaves boundary unchanged). Running them all keeps the op fullgraph-compilable.+ # Once the mask is empty the boundary cannot change, so every later iteration adds zero.+ # Check only every eight rounds to amortize the device synchronization in eager inference.+ if can_stop and (i + 1) % 8 == 0 and not bool(mask.any()):+ breakoffset: int = i * k_halfout = out + (offset + cdt) * mask.to(dtype=out.dtype)boundary = torch.where(mask, signal_ones, boundary)@@ -137,6 +165,7 @@ def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float)out = torch.zeros_like(image, dtype=compute_dtype)boundary = image.to(compute_dtype)signal_ones = torch.ones_like(boundary)+ can_stop = _can_stop_cascade(image)for i in range(n_iters):cdt = filter3d(boundary, kernel, border_type="replicate")@@ -146,9 +175,9 @@ def _distance_transform_3d_impl(image: torch.Tensor, kernel_size: int, h: float)cdt = torch.nan_to_num(cdt, nan=0.0, posinf=0.0, neginf=0.0)mask = cdt > 0- # No data-dependent early-out: the loop bound (n_iters) is fixed, and once no pixels- # remain the remaining iterations are exact no-ops (out += 0*mask, where(False,...)- # leaves boundary unchanged). Running them all keeps the op fullgraph-compilable.+ # As in 2-D, retain a static loop for capture and differentiation, and amortize eager checks.+ if can_stop and (i + 1) % 8 == 0 and not bool(mask.any()):+ breakoffset: int = i * k_halfout = out + (offset + cdt) * mask.to(dtype=out.dtype)boundary = torch.where(mask, signal_ones, boundary)diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex a5263a123..14553c36c 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -17,6 +17,7 @@from __future__ import annotations+import structfrom math import pifrom typing import ClassVar, Optional, Union@@ -108,6 +109,8 @@ def _make_factor_broadcastable(factor: torch.Tensor, image: torch.Tensor) -> toronly lines the ranks up: shapes that still do not broadcast are reported by the op itself."""if factor.dim() > image.dim():+ if torch.jit.is_scripting():+ raise ValueError("Factor has more dimensions than the image and cannot be broadcast.")raise ValueError(f"Factor has more dimensions than the image and cannot be broadcast: got factor shape "f"{tuple(factor.shape)} for image shape {tuple(image.shape)}."@@ -419,6 +422,29 @@ def adjust_gamma(if not isinstance(gain, (float, torch.Tensor)):raise TypeError(f"The gain should be a positive float or torch.Tensor. Got {type(gain)}")+ # Python scalars need no device-side validation or parameter transfers. Half precision+ # keeps the tensor path: rounding a parameter before the operation matters there.+ # Keep invalid values on that path too, including negatives that round to signed zero.+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript must skip the eager-only body+ if (+ not torch.jit.is_tracing()+ and not is_compiling()+ and isinstance(gamma, float)+ and isinstance(gain, float)+ and input.dtype in (torch.float32, torch.float64)+ and input.ndim > 0+ ):+ limits = torch.finfo(input.dtype)+ if 0.0 <= gamma <= limits.max and 0.0 <= gain <= limits.max:+ # Scalar power inspects its exponent before converting to the tensor dtype.+ # Round on the host first, as tensor construction did: near zero/one this+ # affects both the value at black pixels and its gradient. Captured calls+ # retain the tensor expression, which the compiler can constant-fold.+ if input.dtype == torch.float32:+ gamma = struct.unpack("f", struct.pack("f", gamma))[0]+ gain = struct.unpack("f", struct.pack("f", gain))[0]+ return (input.pow(gamma) * gain).clamp(0.0, 1.0)+if isinstance(gamma, float):gamma = torch.tensor([gamma], device=input.device, dtype=input.dtype)diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex 8722ff559..6c241a160 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -191,7 +191,10 @@ def affine(if tensor.shape[0] == 1 and matrix.shape[0] != 1:tensor = tensor.expand(matrix.shape[0], tensor.shape[1], tensor.shape[2], tensor.shape[3])- matrix = matrix.expand(tensor.shape[0], -1, -1)+ # Keep a shared matrix singleton so warp_affine builds only one sampling grid.+ # Keep parameter-gradient reductions in their original order, and retain batch validation.+ if matrix.shape[0] != 1 or tensor.shape[0] == 0 or matrix.requires_grad:+ matrix = matrix.expand(tensor.shape[0], -1, -1)# warp the input tensorheight: int = tensor.shape[-2]@@ -326,8 +329,22 @@ def rotate(# compute the rotation matrix# TODO: add broadcasting to get_rotation_matrix2d for center- angle = angle.expand(tensor.shape[0])- center = center.expand(tensor.shape[0], -1)+ # A singleton angle and center describe one transform shared by all images. Keep+ # it singleton through affine so warp_affine can reuse its sampling grid. Trainable+ # parameters keep the original reduction order, which matters for half-precision gradients.+ batch = tensor.shape[0]+ if (+ tensor.dim() == 4+ and batch > 0+ and angle.shape == (1,)+ and not angle.requires_grad+ and not center.requires_grad+ and (center.shape == (2,) or center.shape == (1, 2)) # noqa: PLR1714 - TorchScript shape checks+ and not torch.jit.is_tracing()+ ):+ batch = 1+ angle = angle.expand(batch)+ center = center.expand(batch, -1)rotation_matrix: torch.Tensor = _compute_rotation_matrix(angle, center)# warp using the affine transformdiff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 364a84052..78e19ccce 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -504,7 +504,12 @@ def warp_affine(gx = m[:, 0, 0, None, None] * base_x + m[:, 0, 1, None, None] * base_y + m[:, 0, 2, None, None]gy = m[:, 1, 0, None, None] * base_x + m[:, 1, 1, None, None] * base_y + m[:, 1, 2, None, None]grid = torch.stack([gx, gy], dim=-1) # (B_M, H, W, 2)- if B_M == 1 and B > 1:+ if torch.jit.is_tracing():+ # Keep both batch sizes dynamic. Using their maximum expands a shared grid for non-empty images,+ # but leaves a singleton grid intact for an empty source so grid_sample still rejects that pairing.+ batch = torch.maximum(torch._shape_as_tensor(src)[0], torch._shape_as_tensor(M)[0])+ grid = grid.expand(batch, -1, -1, -1)+ elif B_M == 1 and B > 1:grid = grid.expand(B, -1, -1, -1)if padding_mode == "fill":diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 7c1d5a31a..d53b6025f 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -111,18 +111,31 @@ def focal_loss(target, target_mask = mask_ignore_pixels(target, ignore_index)- # create the labels one hot torch.Tensor- target_one_hot: torch.Tensor = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)+ # Reduced, unweighted losses only need the target-class terms. Keep the dense path for parameters whose+ # non-target zero slices can become NaN (e.g. an infinite class weight or a negative focusing exponent).+ reduced = (+ reduction in ("mean", "sum")+ and weight is None+ and 0 <= gamma < float("inf")+ and (alpha is None or 0 <= alpha <= 1)+ )+ target_one_hot: Optional[torch.Tensor] = None+ if reduced:+ KORNIA_CHECK(target.dtype == torch.int64, f"labels must be of dtype torch.int64. Got: {target.dtype}")+ KORNIA_CHECK(pred.shape[1] >= 1, f"The number of classes must be >= 1. Got: {pred.shape[1]}")+ else:+ target_one_hot = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)- # mask ignore pixelsif target_mask is not None:- target_mask.unsqueeze_(1)- target_one_hot = target_one_hot * target_mask+ target_mask = target_mask.unsqueeze(1)+ if target_one_hot is not None:+ target_one_hot = target_one_hot * target_mask# Exclude ignored logits before log-softmax: an overflowing log probability times zero is NaN.pred = pred.masked_fill(~target_mask, 0.0)- # compute F.softmax over the classes axis- log_pred_soft: torch.Tensor = pred.log_softmax(1)+ log_pred_soft = pred.log_softmax(1)+ if reduced:+ log_pred_soft = log_pred_soft.gather(1, target.unsqueeze(1))# compute the actual focal loss# For 0 < gamma < 1, x ** gamma has an infinite derivative at x = 0, so a probability that rounds to 1 gives a@@ -132,16 +145,26 @@ def focal_loss(saturated = base == 0focal_weight = torch.where(saturated, base.detach().pow(gamma), base.masked_fill(saturated, 1.0).pow(gamma))# Mask before multiplying: a non-target log probability of -inf otherwise gives NaN values and gradients.- log_pred_soft = log_pred_soft.masked_fill(target_one_hot == 0, 0.0)- loss_tmp: torch.Tensor = -focal_weight * log_pred_soft * target_one_hot+ if target_one_hot is not None:+ log_pred_soft = log_pred_soft.masked_fill(target_one_hot == 0, 0.0)+ loss_tmp = -focal_weight * log_pred_soft * target_one_hot+ else:+ if target_mask is not None:+ log_pred_soft = log_pred_soft.masked_fill(~target_mask, 0.0)+ loss_tmp = -focal_weight * log_pred_softnum_of_classes = pred.shape[1]broadcast_dims = [-1] + [1] * len(pred.shape[2:])if alpha is not None:- alpha_fac = torch.tensor(- [1 - alpha] + [alpha] * (num_of_classes - 1), dtype=loss_tmp.dtype, device=loss_tmp.device- )- alpha_fac = alpha_fac.view(broadcast_dims)+ if reduced:+ # Fill the two factors on the device: a per-call class vector would be a blocking host-to-device copy.+ alpha_fac = torch.where(+ target.unsqueeze(1) == 0, loss_tmp.new_full((), 1 - alpha), loss_tmp.new_full((), alpha)+ )+ else:+ alpha_fac = torch.tensor(+ [1 - alpha] + [alpha] * (num_of_classes - 1), dtype=loss_tmp.dtype, device=loss_tmp.device+ ).view(broadcast_dims)loss_tmp = alpha_fac * loss_tmpif weight is not None:@@ -161,7 +184,12 @@ def focal_loss(if reduction == "none":loss = loss_tmpelif reduction == "mean":- loss = torch.mean(loss_tmp)+ if reduced:+ # Accumulate before dividing by C: summing in half precision can overflow even when the mean is finite.+ acc_dtype = torch.float32 if loss_tmp.dtype in (torch.float16, torch.bfloat16) else loss_tmp.dtype+ loss = (loss_tmp.mean(dtype=acc_dtype) / num_of_classes).to(loss_tmp.dtype)+ else:+ loss = torch.mean(loss_tmp)elif reduction == "sum":loss = torch.sum(loss_tmp)else:diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.pyindex 96596aff5..96d7fe4c3 100644--- a/kornia/metrics/confusion_matrix.py+++ b/kornia/metrics/confusion_matrix.py@@ -104,19 +104,21 @@ def confusion_matrix(_check_label_range("pred", pred, num_classes)_check_label_range("target", target, num_classes)- # hack for bitcounting 2 arrays together- # NOTE: torch.bincount does not implement batched version- # The cell index is formed in int64: in the labels' own dtype it wraps, for uint8 from num_classes = 17.- pre_bincount: torch.Tensor = pred.long() + target.long() * num_classes- pre_bincount_vec: torch.Tensor = pre_bincount.reshape(batch_size, -1)-- confusion_list = []- for iter_id in range(batch_size):- pb: torch.Tensor = pre_bincount_vec[iter_id]- bin_count: torch.Tensor = torch.bincount(pb, minlength=num_classes**2)- confusion_list.append(bin_count)-- confusion_vec: torch.Tensor = torch.stack(confusion_list)+ # Form indices in int64: uint8 labels would otherwise wrap from num_classes = 17.+ indices = (pred.long() + target.long() * num_classes).reshape(batch_size, -1)+ # A fixed-size histogram avoids per-sample bincount launches and their dynamic output sizes.+ # Accumulate integers before converting to float32 so large counts do not lose increments.+ num_cells = num_classes * num_classes+ # On CUDA every pixel is a global atomic add, and pixels sharing a cell serialize. Spread consecutive+ # pixels over up to 256 copies of the histogram (at most 16384 cells per sample) and sum the copies.+ # The count depends on the class count only, so captured graphs stay free of shape guards.+ copies = max(1, min(256, 16384 // num_cells)) if indices.is_cuda else 1+ if copies > 1:+ indices = indices + (torch.arange(indices.shape[1], device=indices.device) % copies) * num_cells+ confusion_vec = torch.zeros(batch_size, copies * num_cells, device=pred.device, dtype=torch.int64)+ confusion_vec.scatter_add_(1, indices, torch.ones_like(indices))+ if copies > 1:+ confusion_vec = confusion_vec.view(batch_size, copies, num_cells).sum(1)confusion_mat: torch.Tensor = confusion_vec.view(batch_size, num_classes, num_classes).to(torch.float32) # BxKxKif normalized:diff --git a/tests/contrib/test_conv_distance_transformer.py b/tests/contrib/test_conv_distance_transformer.pyindex f08f60f79..a8494d9aa 100644--- a/tests/contrib/test_conv_distance_transformer.py+++ b/tests/contrib/test_conv_distance_transformer.py@@ -15,10 +15,12 @@# limitations under the License.#+import importlibimport mathimport pytestimport torch+from torch.fx.experimental.proxy_tensor import make_fximport korniafrom kornia.core.exceptions import BaseError, TypeCheckError@@ -28,9 +30,119 @@ from testing.base import BaseTester, supports_conv2d, supports_replicate_paddingclass TestConvDistanceTransform(BaseTester):+ @pytest.mark.parametrize("ndim", [2, 3])+ def test_settled_inference_stops_work(self, ndim, device, dtype, monkeypatch):+ module = importlib.import_module("kornia.contrib.distance_transform")+ name = "filter2d" if ndim == 2 else "filter3d"+ original = getattr(module, name)+ calls = []++ def observed(*args, **kwargs):+ calls.append(None)+ return original(*args, **kwargs)++ monkeypatch.setattr(module, name, observed)+ sample = torch.ones((1, 1) + (32,) * ndim, device=device, dtype=dtype)+ output = kornia.contrib.distance_transform(sample)+ self.assert_close(output, torch.zeros_like(sample))+ expected_calls = 8 if device.type in ("cpu", "cuda") else 32+ assert len(calls) == expected_calls++ @pytest.mark.parametrize("ndim", [2, 3])+ @pytest.mark.parametrize("signal", ["empty", "dense", "sparse", "fractional"])+ def test_inference_matches_differentiable_cascade(self, ndim, signal, device, dtype):+ sample = torch.zeros((2, 1) + (17,) * ndim, device=device, dtype=dtype)+ if signal == "dense":+ sample.fill_(1)+ elif signal != "empty":+ sample[(0, 0) + (0,) * ndim] = 1 if signal == "sparse" else 0.25+ sample[(1, 0) + (8,) * ndim] = 1+ expected = kornia.contrib.distance_transform(sample.clone().requires_grad_())+ actual = kornia.contrib.distance_transform(sample)+ self.assert_close(actual, expected, rtol=0, atol=0)++ @pytest.mark.parametrize("ndim", [2, 3])+ def test_trace_keeps_propagating_on_new_data(self, ndim, device, dtype):+ dense = torch.ones((1, 1) + (17,) * ndim, device=device, dtype=dtype)+ traced = torch.jit.trace(kornia.contrib.DistanceTransform(), dense)+ sparse = torch.zeros_like(dense)+ sparse[(0, 0) + (0,) * ndim] = 1+ self.assert_close(traced(sparse), kornia.contrib.distance_transform(sparse))++ @pytest.mark.parametrize("ndim", [2, 3])+ def test_make_fx_real_trace_keeps_propagating_on_new_data(self, ndim, device, dtype):+ def distance_transform(image):+ return kornia.contrib.distance_transform(image)++ empty = torch.zeros((1, 1) + (9,) * ndim, device=device, dtype=dtype)+ traced = make_fx(distance_transform, tracing_mode="real")(empty)+ sparse = torch.zeros_like(empty)+ sparse[(0, 0) + (0,) * ndim] = 1+ self.assert_close(traced(sparse), kornia.contrib.distance_transform(sparse))++ def test_function_transforms(self, device, dtype):+ sample = torch.rand(2, 1, 9, 9, device=device, dtype=dtype)+ op = kornia.contrib.distance_transform+ actual = torch.vmap(lambda x: op(x.unsqueeze(0)).squeeze(0))(sample)+ self.assert_close(actual, op(sample))+ tangent = torch.ones_like(sample)+ _, expected_jvp = torch.func.jvp(op, (sample,), (tangent,))+ with torch.autograd.forward_ad.dual_level():+ dual = torch.autograd.forward_ad.make_dual(sample, tangent)+ _, actual_jvp = torch.autograd.forward_ad.unpack_dual(op(dual))+ self.assert_close(actual_jvp, expected_jvp)++ @pytest.mark.parametrize("ndim", [2, 3])+ def test_no_grad_inference_stops_work(self, ndim, device, dtype, monkeypatch):+ # Inside no_grad nothing is recorded, so a requires_grad input may stop early as well.+ module = importlib.import_module("kornia.contrib.distance_transform")+ name = "filter2d" if ndim == 2 else "filter3d"+ original = getattr(module, name)+ calls = []++ def observed(*args, **kwargs):+ calls.append(None)+ return original(*args, **kwargs)++ monkeypatch.setattr(module, name, observed)+ sample = torch.ones((1, 1) + (32,) * ndim, device=device, dtype=dtype, requires_grad=True)+ with torch.no_grad():+ output = kornia.contrib.distance_transform(sample)+ self.assert_close(output, torch.zeros_like(sample))+ expected_calls = 8 if device.type in ("cpu", "cuda") else 32+ assert len(calls) == expected_calls++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("ndim", [2, 3])+ def test_shape_only_tensors(self, ndim):+ # Meta and fake tensors carry no data, so the eager early exit must not read a flag from them.+ shape = (1, 1) + (17,) * ndim+ assert kornia.contrib.distance_transform(torch.zeros(shape, device="meta")).shape == shape+ with torch._subclasses.fake_tensor.FakeTensorMode():+ assert kornia.contrib.distance_transform(torch.zeros(shape)).shape == shape++ @pytest.mark.parametrize("spatial_shape", [(33, 33), (17, 17, 17)])+ def test_cuda_graph_capture(self, spatial_shape, device, dtype):+ if device.type != "cuda":+ pytest.skip("CUDA graphs need a CUDA device")+ sample = torch.zeros(2, 1, *spatial_shape, device=device, dtype=dtype)+ sample[(0, 0) + (4,) * len(spatial_shape)] = 1+ sample[(1, 0) + (12,) * len(spatial_shape)] = 1+ expected = kornia.contrib.distance_transform(sample)+ stream = torch.cuda.Stream()+ stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ kornia.contrib.distance_transform(sample)+ torch.cuda.current_stream().wait_stream(stream)+ graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(graph):+ captured = kornia.contrib.distance_transform(sample)+ graph.replay()+ self.assert_close(captured, expected, rtol=0, atol=0)+@pytest.mark.parametrize("kernel_size", [3, 5, 7])@pytest.mark.parametrize("shape", [(1, 3, 100, 100), (2, 2, 10, 10, 10)])- def test_smoke(self, kernel_size, shape, device, dtype):+ def test_smoke(self, kernel_size, shape, device, dtype, cudnn_tf32_follows_option):sample = torch.rand(*shape, device=device, dtype=dtype)distance_transformer = kornia.contrib.DistanceTransform(kernel_size)diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex b2ae4107c..3e1c7e77c 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -26,7 +26,7 @@ from kornia import enhancefrom kornia.constants import pifrom kornia.core._compat import torch_version_ge-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availabledef _sync(device) -> None:@@ -315,6 +315,63 @@ class TestAdjustGamma(BaseTester):out = kornia.enhance.adjust_gamma(img, 1.0)assert out.shape == shape+ @pytest.mark.parametrize("gamma,gain", [(0.1, 0.1234567), (0.5, 0.9), (2.0, 1.0), (1e-50, 1e-50)])+ def test_scalar_and_tensor_parameters(self, device, dtype, gamma, gain):+ image = torch.linspace(0, 1, 33, device=device, dtype=dtype).reshape(1, 3, 11)+ expected = kornia.enhance.adjust_gamma(image, image.new_tensor([gamma]), image.new_tensor([gain]))+ self.assert_close(kornia.enhance.adjust_gamma(image, gamma, gain), expected)++ @pytest.mark.parametrize("parameter", ["gamma", "gain"])+ def test_negative_scalar_rounds_to_zero(self, device, dtype, parameter):+ if dtype == torch.float64:+ pytest.skip("The negative value is representable in float64")+ image = torch.full((1, 2, 2), 0.5, device=device, dtype=dtype)+ kwargs = {"gamma": 1.0, "gain": 1.0, parameter: -1e-50}+ expected = kornia.enhance.adjust_gamma(image, **{**kwargs, parameter: 0.0})+ self.assert_close(kornia.enhance.adjust_gamma(image, **kwargs), expected, rtol=0, atol=0)++ @pytest.mark.parametrize("gamma", [1e-50, 0.99999999, 1.00000001, 1.99999999])+ def test_rounded_scalar_exponent_at_zero(self, device, gamma):+ image = torch.tensor([0.0, 0.5, 1.0], device=device, dtype=torch.float32, requires_grad=True)+ expected = kornia.enhance.adjust_gamma(image, image.new_tensor([gamma]))+ actual = kornia.enhance.adjust_gamma(image, gamma)+ # MPS scalar/tensor power kernels can round nonzero pixels differently.+ self.assert_close(actual, expected)+ self.assert_close(actual[0], expected[0], rtol=0, atol=0)+ actual_grad = torch.autograd.grad(actual.sum(), image)[0]+ expected_grad = torch.autograd.grad(expected.sum(), image)[0]+ self.assert_close(actual_grad, expected_grad)+ self.assert_close(actual_grad[0], expected_grad[0], rtol=0, atol=0)++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("value", [-0.1, float("nan")])+ @pytest.mark.parametrize("parameter", ["gamma", "gain"])+ def test_invalid_scalar_parameters(self, parameter, value):+ image = torch.ones(1, 1, 2, 2)+ with pytest.raises(RuntimeError, match="must be non-negative"):+ kornia.enhance.adjust_gamma(image, **{"gamma": 1.0, "gain": 1.0, parameter: value})++ def test_tensor_parameter_gradients(self, device):+ if device.type == "mps":+ pytest.skip("MPS does not support float64 gradcheck")+ image = torch.full((2, 1, 2, 2), 0.4, device=device, dtype=torch.float64, requires_grad=True)+ gamma = torch.tensor([0.8, 1.2], device=device, dtype=torch.float64, requires_grad=True)+ gain = torch.tensor([0.7, 0.9], device=device, dtype=torch.float64, requires_grad=True)+ self.gradcheck(kornia.enhance.adjust_gamma, (image, gamma, gain))++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_scalar_export(self, device, dtype):+ image = torch.full((1, 2, 2), 0.4, device=device, dtype=dtype)+ module = kornia.enhance.AdjustGamma(0.7, 0.9)+ exported = torch.export.export(module, (image,), strict=True).module()+ self.assert_close(exported(image), module(image))++ def test_scalar_jit(self, device, dtype):+ image = torch.full((1, 2, 2), 0.4, device=device, dtype=dtype)+ module = kornia.enhance.AdjustGamma(0.7, 0.9)+ scripted = torch.jit.script(module)+ self.assert_close(scripted(image), module(image))+def test_gamma_zero(self, device, dtype):data = torch.tensor([[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.pyindex bc4d3c5fe..23f9c6816 100644--- a/tests/geometry/transform/test_affine.py+++ b/tests/geometry/transform/test_affine.py@@ -24,7 +24,7 @@ import torchimport korniafrom kornia.core.exceptions import DeviceError, TypeCheckError-from testing.base import BaseTester, supports_reflect_padding+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available, supports_reflect_paddingclass TestResize(BaseTester):@@ -500,6 +500,95 @@ class TestRescale(BaseTester):class TestRotate(BaseTester):+ @pytest.mark.parametrize("align_corners", [False, True])+ @pytest.mark.parametrize("center_shape", [None, (2,), (1, 2), (3, 2)])+ @pytest.mark.parametrize("train_transform", [False, True])+ def test_shared_angle_values_and_gradients(self, device, dtype, align_corners, center_shape, train_transform):+ image = torch.rand(3, 2, 5, 7, device=device, dtype=dtype, requires_grad=True)+ angle = torch.tensor([23.0], device=device, dtype=dtype, requires_grad=train_transform)+ center = None+ if center_shape is not None:+ center = torch.full(center_shape, 1.3, device=device, dtype=dtype, requires_grad=train_transform)+ actual = kornia.geometry.transform.rotate(image, angle, center, align_corners=align_corners)+ expanded_center = None if center is None else center.expand(3, -1)+ expected = kornia.geometry.transform.rotate(+ image, angle.expand(3), expanded_center, align_corners=align_corners+ )+ self.assert_close(actual, expected)+ inputs = tuple(t for t in (image, angle, center) if t is not None and t.requires_grad)+ weights = torch.rand_like(actual)+ actual_grads = torch.autograd.grad(actual, inputs, weights)+ expected_grads = torch.autograd.grad(expected, inputs, weights)+ for actual_grad, expected_grad in zip(actual_grads, expected_grads):+ self.assert_close(actual_grad, expected_grad)++ def test_independent_equal_angles_gradients(self, device, dtype):+ image = torch.rand(3, 1, 5, 7, device=device, dtype=dtype)+ angle = torch.full((3,), 23.0, device=device, dtype=dtype, requires_grad=True)+ actual = kornia.geometry.transform.rotate(image, angle)+ expected = torch.cat([kornia.geometry.transform.rotate(image[i : i + 1], angle[i : i + 1]) for i in range(3)])+ self.assert_close(actual, expected)+ self.assert_close(torch.autograd.grad(actual.sum(), angle)[0], torch.autograd.grad(expected.sum(), angle)[0])++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_shared_angle_export(self, device, dtype):+ image = torch.rand(3, 2, 5, 7, device=device, dtype=dtype)+ angle = torch.tensor([23.0], device=device, dtype=dtype)+ module = kornia.geometry.transform.Rotate(angle)+ exported = torch.export.export(module, (image,)).module()+ self.assert_close(exported(image), module(image))++ def test_shared_angle_trace(self, device, dtype):+ image = torch.rand(3, 2, 5, 7, device=device, dtype=dtype)+ angle = torch.tensor([23.0], device=device, dtype=dtype)+ traced = torch.jit.trace(kornia.geometry.transform.rotate, (image, angle), check_trace=False)+ if dtype in (torch.float16, torch.bfloat16):+ # Tracing uses affine_grid rather than the eager grid expression. Their rounding already+ # differs on CUDA half on the baseline, so compare with the same traced per-image path.+ def expanded_rotation(image, angle):+ return kornia.geometry.transform.rotate(image, angle.expand(image.shape[0]))++ reference = torch.jit.trace(expanded_rotation, (image, angle), check_trace=False)+ expected = reference(image, angle)+ else:+ expected = kornia.geometry.transform.rotate(image, angle)+ self.assert_close(traced(image, angle), expected)++ def test_trace_generalizes_over_image_and_angle_batches(self, device, dtype):+ image = torch.rand(1, 1, 5, 7, device=device, dtype=dtype)+ angle = torch.tensor([23.0], device=device, dtype=dtype)+ traced = torch.jit.trace(kornia.geometry.transform.rotate, (image, angle), check_trace=False)+ image = torch.rand(4, 1, 5, 7, device=device, dtype=dtype)+ angle = torch.tensor([0.0, 10.0, 20.0, 30.0], device=device, dtype=dtype)+ if dtype in (torch.float16, torch.bfloat16):+ # See test_shared_angle_trace: compare two traced affine_grid paths at reduced precision.+ def expanded_rotation(image, angle):+ return kornia.geometry.transform.rotate(image, angle.expand(image.shape[0]))++ expected = torch.jit.trace(expanded_rotation, (image[:1], angle[:1]), check_trace=False)(image, angle)+ else:+ expected = kornia.geometry.transform.rotate(image, angle)+ self.assert_close(traced(image, angle), expected)++ @pytest.mark.parametrize("op", ["rotate", "Rotate", "affine"])+ def test_shared_trace_generalizes_over_batch(self, device, dtype, op):+ # A trace (and the TorchScript ONNX export built on it) recorded at batch 1 must not bake in the batch.+ angle = torch.tensor([23.0], device=device, dtype=dtype)+ matrix = torch.tensor([[[0.9, 0.2, 1.0], [-0.1, 1.1, -0.5]]], device=device, dtype=dtype)+ fns = {+ "rotate": lambda x: kornia.geometry.transform.rotate(x, angle),+ "Rotate": kornia.geometry.transform.Rotate(angle),+ "affine": lambda x: kornia.geometry.transform.affine(x, matrix),+ }+ fn = fns[op]+ traced = torch.jit.trace(fn, torch.rand(1, 2, 5, 7, device=device, dtype=dtype), check_trace=False)+ image = torch.rand(4, 2, 5, 7, device=device, dtype=dtype)+ if dtype in (torch.float16, torch.bfloat16):+ # Tracing builds the grid with affine_grid; compare shapes only, see test_shared_angle_trace.+ assert traced(image).shape == image.shape+ else:+ self.assert_close(traced(image), fn(image))+def test_angle90(self, device, dtype):# prepare input datainp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], device=device, dtype=dtype)@@ -831,6 +920,23 @@ class TestShear(BaseTester):class TestAffine2d(BaseTester):+ @pytest.mark.parametrize("image_batch,matrix_batch", [(3, 1), (1, 3), (0, 1)])+ def test_function_batch_broadcast(self, device, dtype, image_batch, matrix_batch):+ image = torch.rand(image_batch, 2, 5, 7, device=device, dtype=dtype)+ matrix = torch.tensor([[1.0, 0.1, 0.3], [0.2, 1.0, -0.4]], device=device, dtype=dtype)+ matrix = matrix.expand(matrix_batch, -1, -1)+ batch = 0 if image_batch == 0 else max(image_batch, matrix_batch)+ expected = kornia.geometry.transform.warp_affine(+ image.expand(batch, -1, -1, -1), matrix.expand(batch, -1, -1), (5, 7)+ )+ self.assert_close(kornia.geometry.transform.affine(image, matrix), expected)++ def test_function_invalid_batch(self, device, dtype):+ image = torch.rand(3, 2, 5, 7, device=device, dtype=dtype)+ matrix = torch.eye(2, 3, device=device, dtype=dtype).expand(2, -1, -1)+ with pytest.raises(RuntimeError):+ kornia.geometry.transform.affine(image, matrix)+def test_affine_no_args(self):with pytest.raises(RuntimeError):kornia.geometry.transform.Affine()diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.pyindex 725562451..42c004691 100644--- a/tests/geometry/transform/test_imgwarp.py+++ b/tests/geometry/transform/test_imgwarp.py@@ -78,7 +78,7 @@ def test_empty_destination_matches_nonempty_batch_semantics(op_name, src_batch,"""An empty destination broadcasts and rejects batch pairings exactly as the non-empty path.The three operations disagree on purpose -- ``warp_perspective`` requires equal batches,- ``warp_affine`` expands a singleton matrix only to a source batch above one, and ``remap``+ ``warp_affine`` expands a singleton matrix only to a non-empty source batch, and ``remap``expands a singleton map batch to the image batch unconditionally -- so the empty path ispinned against whatever the non-empty call does rather than against a hardcoded expectation."""@@ -495,6 +495,57 @@ class TestRotationMatrix2d(BaseTester):class TestWarpAffine(BaseTester):+ def test_onnx_dynamic_batches(self, tmp_path):+ pytest.importorskip("onnx")+ ort = pytest.importorskip("onnxruntime")++ class Wrapper(torch.nn.Module):+ def forward(self, image, matrix):+ return kornia.geometry.warp_affine(image, matrix, (5, 7))++ model = Wrapper().eval()+ image = torch.rand(1, 2, 5, 7)+ matrix = torch.eye(2, 3)[None]+ path = tmp_path / "warp_affine.onnx"+ torch.onnx.export(+ model,+ (image, matrix),+ path,+ input_names=["image", "matrix"],+ output_names=["warped"],+ dynamic_axes={"image": {0: "batch"}, "matrix": {0: "transforms"}, "warped": {0: "batch"}},+ opset_version=20,+ dynamo=False,+ )+ session = ort.InferenceSession(str(path), providers=["CPUExecutionProvider"])+ for src_batch, transform_batch in [(1, 1), (4, 1), (4, 4)]:+ batch_image = image.expand(src_batch, -1, -1, -1)+ batch_matrix = matrix.expand(transform_batch, -1, -1)+ actual = session.run(None, {"image": batch_image.numpy(), "matrix": batch_matrix.numpy()})[0]+ self.assert_close(torch.from_numpy(actual), model(batch_image, batch_matrix))++ @pytest.mark.parametrize("src_batch,transform_batch", [(0, 1), (1, 0), (0, 0), (1, 1), (4, 1), (4, 4), (1, 4)])+ def test_trace_preserves_batch_semantics(self, src_batch, transform_batch, device, dtype):+ if device.type == "mps" and 0 in (src_batch, transform_batch) and torch_version_lt(2, 14, 0):+ pytest.skip("MPS grid_sample asserts on a zero-element batch before torch 2.14")++ def warp(image, matrix):+ return kornia.geometry.warp_affine(image, matrix, (5, 7))++ image = torch.rand(1, 2, 5, 7, device=device, dtype=dtype)+ matrix = torch.eye(2, 3, device=device, dtype=dtype)[None]+ traced = torch.jit.trace(warp, (image, matrix), check_trace=False)+ image = image.expand(src_batch, -1, -1, -1)+ matrix = matrix.expand(transform_batch, -1, -1)+ if src_batch == transform_batch or (src_batch > 0 and transform_batch == 1):+ expected = warp(image, matrix)+ self.assert_close(traced(image, matrix), expected)+ else:+ with pytest.raises(RuntimeError):+ warp(image, matrix)+ with pytest.raises(RuntimeError):+ traced(image, matrix)+def test_smoke(self, device, dtype):batch_size, channels, height, width = 1, 2, 3, 4aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None] # 1x2x3diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.pyindex ea49df07f..49bf4981d 100644--- a/tests/losses/test_focal_loss.py+++ b/tests/losses/test_focal_loss.py@@ -170,6 +170,77 @@ class TestBinaryFocalLossWithLogits(BaseTester):class TestFocalLoss(BaseTester):+ @pytest.mark.parametrize("reduction", ["mean", "sum"])+ @pytest.mark.parametrize("shape", [(2, 4), (2, 4, 3, 5), (0, 4, 3)])+ @pytest.mark.parametrize("ignore_index", [None, -100, 0])+ def test_reduced_matches_dense_value_and_gradient(self, device, dtype, reduction, shape, ignore_index):+ generator = torch.Generator().manual_seed(17)+ logits = torch.randn(shape, generator=generator).to(device=device, dtype=dtype).requires_grad_()+ labels = torch.randint(shape[1], (shape[0], *shape[2:]), generator=generator).to(device)+ if labels.numel() and ignore_index is not None:+ labels.reshape(-1)[0] = ignore_index+ if logits.ndim > 3:+ logits = logits.transpose(-1, -2)+ labels = labels.transpose(-1, -2) if labels.ndim > 2 else labels+ # Compare the public dense contract, including empty means and the class-count denominator.+ dense = kornia.losses.focal_loss(logits, labels, 0.25, 0.5, "none", ignore_index=ignore_index)+ expected = dense.mean() if reduction == "mean" else dense.sum()+ actual = kornia.losses.focal_loss(logits, labels, 0.25, 0.5, reduction, ignore_index=ignore_index)+ if logits.numel() == 0 and reduction == "mean":+ assert actual.isnan()+ assert expected.isnan()+ else:+ self.assert_close(actual, expected)+ self.assert_close(torch.autograd.grad(actual, logits)[0], torch.autograd.grad(expected, logits)[0])++ @pytest.mark.parametrize("reduction", ["mean", "sum"])+ @pytest.mark.parametrize("alpha,gamma", [(0.25, -1.0), (float("inf"), 2.0), (0.25, float("nan"))])+ def test_reduced_unusual_parameters_match_dense(self, device, dtype, reduction, alpha, gamma):+ logits = torch.tensor([[1000.0, 0.0, 0.0]], device=device, dtype=dtype, requires_grad=True)+ labels = torch.tensor([1], device=device)+ dense = kornia.losses.focal_loss(logits, labels, alpha, gamma, "none")+ expected = dense.mean() if reduction == "mean" else dense.sum()+ actual = kornia.losses.focal_loss(logits, labels, alpha, gamma, reduction)+ assert actual.isnan()+ assert expected.isnan()++ @pytest.mark.parametrize("reduction", ["mean", "sum"])+ def test_reduced_weight_gradient_and_promotion(self, device, dtype, reduction):+ logits = torch.tensor([[1.0, 2.0, 3.0], [2.0, 0.0, 1.0]], device=device, dtype=dtype, requires_grad=True)+ labels = torch.tensor([0, 2], device=device)+ weight = torch.tensor([0.5, 1.5, 2.0], device=device, dtype=torch.float32, requires_grad=True)+ dense = kornia.losses.focal_loss(logits, labels, 0.25, 0.5, "none", weight)+ expected = dense.mean() if reduction == "mean" else dense.sum()+ actual = kornia.losses.focal_loss(logits, labels, 0.25, 0.5, reduction, weight)+ self.assert_close(actual, expected)+ actual_grads = torch.autograd.grad(actual, (logits, weight))+ expected_grads = torch.autograd.grad(expected, (logits, weight))+ for actual_grad, expected_grad in zip(actual_grads, expected_grads):+ self.assert_close(actual_grad, expected_grad)++ def test_reduced_alpha_does_not_synchronize(self, device, dtype):+ if device.type != "cuda":+ pytest.skip("CUDA synchronization check")+ logits = torch.randn(2, 4, 3, 5, device=device, dtype=dtype, requires_grad=True)+ labels = torch.randint(4, (2, 3, 5), device=device)+ expected = kornia.losses.focal_loss(logits, labels, 0.25, 2.0, "none").mean()+ previous_sync_debug_mode = torch.cuda.get_sync_debug_mode()+ torch.cuda.set_sync_debug_mode("error")+ try:+ actual = kornia.losses.focal_loss(logits, labels, 0.25, 2.0, "mean")+ finally:+ torch.cuda.set_sync_debug_mode(previous_sync_debug_mode)+ self.assert_close(actual, expected)++ def test_reduced_saved_tensor_memory(self, device, dtype):+ # A reduced objective should not retain dense per-class one-hot and focal-factor intermediates.+ logits = torch.zeros(2, 21, 4, 5, device=device, dtype=dtype, requires_grad=True)+ labels = torch.zeros(2, 4, 5, device=device, dtype=torch.int64)+ saved = []+ with torch.autograd.graph.saved_tensors_hooks(lambda value: saved.append(value) or value, lambda value: value):+ kornia.losses.focal_loss(logits, labels, 0.25, reduction="mean")+ assert sum(value.numel() * value.element_size() for value in saved) < 4 * logits.numel() * logits.element_size()+@pytest.mark.parametrize("reduction", ["none", "mean", "sum"])@pytest.mark.parametrize("gamma", [0.0, 0.5, 2.0])@pytest.mark.parametrize("alpha", [None, 0.25])@@ -224,7 +295,11 @@ class TestFocalLoss(BaseTester):elif reduction == "sum":expected = expected.sum()actual = kornia.losses.focal_loss(logits, labels, alpha, gamma, reduction, weight)- self.assert_close(actual, expected, rtol=0, atol=0)+ if not weighted and reduction != "none":+ # Gathering target terms changes the reduction order relative to the dense reference.+ self.assert_close(actual, expected)+ else:+ self.assert_close(actual, expected, rtol=0, atol=0)self.assert_close(torch.autograd.grad(actual.sum(), logits)[0], torch.autograd.grad(expected.sum(), reference)[0])@@ -401,7 +476,8 @@ class TestFocalLoss(BaseTester):self.assert_close(values[off_class], torch.zeros_like(values[off_class]), rtol=0, atol=0)assert (values[~off_class] > 0).all()- def test_dynamo(self, device, dtype, torch_optimizer):+ @pytest.mark.parametrize("reduction", ["none", "mean", "sum"])+ def test_dynamo(self, device, dtype, torch_optimizer, reduction):num_classes = 3logits = torch.rand(2, num_classes, device=device, dtype=dtype)labels = torch.randint(num_classes, (2,), device=device)@@ -409,7 +485,7 @@ class TestFocalLoss(BaseTester):op = kornia.losses.focal_lossop_optimized = torch_optimizer(op)- args = (0.25, 2.0)+ args = (0.25, 2.0, reduction)actual = op_optimized(logits, labels, *args)expected = op(logits, labels, *args)self.assert_close(actual, expected)diff --git a/tests/metrics/test_confusion.py b/tests/metrics/test_confusion.pyindex 566d87f3f..2cf37da69 100644--- a/tests/metrics/test_confusion.py+++ b/tests/metrics/test_confusion.py@@ -20,10 +20,15 @@ import torchfrom torch._dynamo.testing import CompileCounterimport kornia-from kornia.core._compat import torch_version_ltfrom kornia.core.exceptions import BaseError-from testing.base import BaseTester+from testing.base import (+ DYNAMIC_EXPORT_UNAVAILABLE_REASON,+ DYNAMO_UNAVAILABLE_REASON,+ BaseTester,+ dynamic_export_is_available,+ dynamo_is_available,+)class TestConfusionMatrix(BaseTester):@@ -255,7 +260,20 @@ class TestConfusionMatrix(BaseTester):expected = torch.zeros(2, 3, 3, device=device, dtype=torch.float32)self.assert_close(kornia.metrics.confusion_matrix(labels, labels, num_classes=3), expected, rtol=0, atol=0)- @pytest.mark.skipif(torch_version_lt(2, 14, 0), reason="torch.export cannot capture the bincount before torch 2.14")+ @pytest.mark.parametrize("num_classes", [2, 21, 200])+ def test_counts_match_per_sample_bincount(self, device, num_classes):+ # 1000 pixels do not split evenly over the CUDA histogram copies, and sample 0 sends every pixel to one cell.+ generator = torch.Generator().manual_seed(0)+ pred = torch.randint(num_classes, (3, 1000), generator=generator)+ target = torch.randint(num_classes, (3, 1000), generator=generator)+ pred[0], target[0] = 0, num_classes - 1+ cells = num_classes * num_classes+ expected = torch.stack([torch.bincount(p + t * num_classes, minlength=cells) for p, t in zip(pred, target)])+ expected = expected.view(3, num_classes, num_classes).to(device=device, dtype=torch.float32)+ actual = kornia.metrics.confusion_matrix(pred.to(device), target.to(device), num_classes)+ self.assert_close(actual, expected, rtol=0, atol=0)++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)def test_export_counts_like_eager(self, device, dtype):# The range check reads the data, which torch.export cannot capture, so it is skipped under export.class _ConfusionMatrix(torch.nn.Module):@@ -268,9 +286,22 @@ class TestConfusionMatrix(BaseTester):for p, t in ((pred, target), (target, pred.flip(-1))):self.assert_close(exported(p, t), kornia.metrics.confusion_matrix(p, t, num_classes=3), rtol=0, atol=0)- @pytest.mark.skipif(- torch_version_lt(2, 14, 0), reason="fullgraph tracing cannot capture the bincount before torch 2.14"- )+ @pytest.mark.skipif(not dynamic_export_is_available(), reason=DYNAMIC_EXPORT_UNAVAILABLE_REASON)+ def test_export_dynamic_batch(self, device):+ class _ConfusionMatrix(torch.nn.Module):+ def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ return kornia.metrics.confusion_matrix(pred, target, num_classes=3, normalized=True)++ pred = torch.tensor([[0, 1, 2], [2, 1, 0]], device=device)+ target = torch.tensor([[1, 1, 2], [0, 0, 0]], device=device)+ batch = torch.export.Dim("batch", min=1, max=8)+ exported = torch.export.export(+ _ConfusionMatrix(), (pred, target), dynamic_shapes=({0: batch}, {0: batch}), strict=True+ ).module()+ pred, target = pred.repeat(2, 1), target.repeat(2, 1)+ self.assert_close(exported(pred, target), kornia.metrics.confusion_matrix(pred, target, 3, True))++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)def test_trace_counts_like_eager(self, device, dtype):# The range check reads the data, so any capture has to skip it, not only export (#5037).pred = torch.tensor([[0, 1, 2, 2], [1, 1, 0, 2]], device=device)