π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
refactor(geometry): cusolver-free get_perspective_transform via closed form (#3840)
Edgar Ribae1c678359d39
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.pyindex b24b337b4..27807c183 100644--- a/kornia/augmentation/_2d/geometric/resized_crop.py+++ b/kornia/augmentation/_2d/geometric/resized_crop.py@@ -101,6 +101,11 @@ class RandomResizedCrop(GeometricAugmentationBase2D):"cropping_mode": cropping_mode,"padding_mode": "zeros",}+ # In "slice" mode the image is cropped by index (``crop_by_indices``) and apply_transform+ # never reads the transform matrix β only box/keypoint propagation does. Defer building it+ # (a full get_perspective_transform) until ``.transform_matrix`` is actually accessed.+ # "resample" mode warps through the matrix, so it must be built eagerly.+ self._compute_matrix_lazily = cropping_mode == "slice"def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]diff --git a/kornia/core/utils.py b/kornia/core/utils.pyindex 3d2ca2878..427c12774 100644--- a/kornia/core/utils.py+++ b/kornia/core/utils.py@@ -151,6 +151,22 @@ def _inverse_3x3_closed_form(input: torch.Tensor) -> torch.Tensor:well-conditioned matrices; behavior on singular matrices is undefined(no explicit check, same as ``torch.linalg.inv`` itself)."""+ if not torch.jit.is_tracing():+ # inv(M) = adj(M) / det, and for a 3x3 the adjugate rows are cross products of the+ # columns: with columns (a, b, c), the inverse rows are (b x c, c x a, a x b) / det,+ # det = a . (b x c). Three fused ``cross`` ops instead of nine scalar cofactor+ # expressions and four stacks β far fewer kernel launches (dominant on small matrices).+ col_a = input[..., :, 0]+ col_b = input[..., :, 1]+ col_c = input[..., :, 2]+ row0 = torch.linalg.cross(col_b, col_c, dim=-1)+ row1 = torch.linalg.cross(col_c, col_a, dim=-1)+ row2 = torch.linalg.cross(col_a, col_b, dim=-1)+ det = (col_a * row0).sum(-1)+ return torch.stack([row0, row1, row2], dim=-2) / det[..., None, None]++ # Under tracing (legacy ONNX / jit.trace) stick to the plain scalar adjugate: it lowers to+ # basic arithmetic that every opset supports, whereas ``cross`` may not.a = input[..., 0, 0]b = input[..., 0, 1]c = input[..., 0, 2]diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.pyindex 78cb5838f..383d89687 100644--- a/kornia/geometry/transform/crop2d.py+++ b/kornia/geometry/transform/crop2d.py@@ -355,14 +355,13 @@ def crop_by_indices(y1 = src[:, 0, 1]y2 = src[:, 3, 1] + 1- if (- len(x1.unique(sorted=False))- == len(x2.unique(sorted=False))- == len(y1.unique(sorted=False))- == len(y2.unique(sorted=False))- == 1- ):- out = input_tensor[..., int(y1[0]) : int(y2[0]), int(x1[0]) : int(x2[0])]+ # Move the four coordinate columns to Python in a single device sync (one ``tolist`` over a+ # stacked tensor) instead of a ``unique`` per column plus a device-to-host ``int(...)`` inside+ # every loop iteration β the coordinates index Python-level slicing, so they must be host ints.+ x1l, x2l, y1l, y2l = torch.stack([x1, x2, y1, y2], dim=0).tolist()++ if x1l.count(x1l[0]) == B and x2l.count(x2l[0]) == B and y1l.count(y1l[0]) == B and y2l.count(y2l[0]) == B:+ out = input_tensor[..., y1l[0] : y2l[0], x1l[0] : x2l[0]]if size is not None and out.shape[-2:] != size:return resize(out, size, interpolation=interpolation, align_corners=align_corners, side="short", antialias=antialias@@ -373,8 +372,8 @@ def crop_by_indices(size = h.unique(sorted=False), w.unique(sorted=False)out = torch.empty(B, C, *size, device=input_tensor.device, dtype=input_tensor.dtype)# Find out the cropped shapes that need to be resized.- for i, _ in enumerate(out):- _out = input_tensor[i : i + 1, :, int(y1[i]) : int(y2[i]), int(x1[i]) : int(x2[i])]+ for i in range(B):+ _out = input_tensor[i : i + 1, :, y1l[i] : y2l[i], x1l[i] : x2l[i]]if _out.shape[-2:] != size:if shape_compensation == "resize":out[i] = resize(diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 78b1877bb..7cd4ba7dd 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -24,7 +24,12 @@ import torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPEfrom kornia.core.ops import eye_like-from kornia.core.utils import _inverse_3x3_closed_form, _torch_inverse_cast, _torch_solve_cast+from kornia.core.utils import (+ _inverse_3x3_closed_form,+ _normalize_to_float32_or_float64,+ _torch_inverse_cast,+ _torch_solve_cast,+)from kornia.geometry.conversions import (angle_to_rotation_matrix,axis_angle_to_rotation_matrix,@@ -139,13 +144,22 @@ def warp_perspective(# otherwise crash every warp on GPU).src_norm_trans_dst_norm = _inverse_3x3_closed_form(dst_norm_trans_src_norm) # Bx3x3- # this piece of code substitutes F.affine_grid since it does not support 3x3- grid = (- create_meshgrid(h_out, w_out, normalized_coordinates=True, device=src.device)- .to(src.dtype)- .expand(B, h_out, w_out, 2)- )- grid = transform_points(src_norm_trans_dst_norm[:, None, None], grid)+ # Substitutes F.affine_grid (which only handles the affine 2x3 case) by applying the full 3x3+ # projective transform to every grid point directly.+ grid = create_meshgrid(h_out, w_out, normalized_coordinates=True, device=src.device).to(src.dtype)+ if torch.jit.is_tracing():+ # Under tracing/ONNX use the reference transform_points path (its op set exports cleanly).+ grid = transform_points(src_norm_trans_dst_norm[:, None, None], grid.expand(B, h_out, w_out, 2))+ else:+ # Eager fast path: inline the per-point projective map (three broadcasts and a divide),+ # avoiding transform_points' repeat_interleave of the matrix to B*H copies + homogeneous+ # round-trip.+ gx0, gy0 = grid[..., 0], grid[..., 1] # (1, H, W)+ m = src_norm_trans_dst_norm # (B, 3, 3)+ denom = m[:, 2, 0, None, None] * gx0 + m[:, 2, 1, None, None] * gy0 + m[:, 2, 2, None, None]+ gx = (m[:, 0, 0, None, None] * gx0 + m[:, 0, 1, None, None] * gy0 + m[:, 0, 2, None, None]) / denom+ gy = (m[:, 1, 0, None, None] * gx0 + m[:, 1, 1, None, None] * gy0 + m[:, 1, 2, None, None]) / denom+ grid = torch.stack([gx, gy], dim=-1) # (B, H, W, 2)if padding_mode == "fill":return _fill_and_warp(src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)@@ -226,7 +240,28 @@ def warp_affine(# batch of images (``M`` is ``1x2x3`` with ``src`` ``BxCxHxW``), build one grid and expand it# (a stride-0 view, no copy) instead of materializing B identical grids β this is what makes a# batch-shared warp as cheap as torchvision's. When ``B_M == B`` (per-sample) nothing changes.- grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :], [B_M, C, dsize[0], dsize[1]], align_corners=align_corners)+ if torch.jit.is_tracing():+ # Under tracing/ONNX use F.affine_grid (a single op the exporter lowers cleanly).+ grid = F.affine_grid(+ src_norm_trans_dst_norm[:, :2, :], [B_M, C, dsize[0], dsize[1]], align_corners=align_corners+ )+ else:+ # Eager fast path: apply the affine matrix to a base grid directly instead of F.affine_grid+ # β three broadcast multiply-adds per axis, markedly cheaper on launch-bound hardware. The+ # base grid reproduces F.affine_grid's convention for the requested ``align_corners`` (pixel+ # corners at +/-1 vs pixel centers). A shared (1x2x3) matrix broadcasts across the batch.+ h_out, w_out = dsize+ if align_corners:+ xs = torch.linspace(-1.0, 1.0, w_out, device=src.device, dtype=src.dtype)+ ys = torch.linspace(-1.0, 1.0, h_out, device=src.device, dtype=src.dtype)+ else:+ xs = torch.linspace(-1.0 + 1.0 / w_out, 1.0 - 1.0 / w_out, w_out, device=src.device, dtype=src.dtype)+ ys = torch.linspace(-1.0 + 1.0 / h_out, 1.0 - 1.0 / h_out, h_out, device=src.device, dtype=src.dtype)+ base_y, base_x = torch.meshgrid(ys, xs, indexing="ij") # (H, W)+ m = src_norm_trans_dst_norm # (B_M, 3, 3); affine, so the bottom row is [0, 0, 1]+ 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:grid = grid.expand(B, -1, -1, -1)@@ -373,17 +408,24 @@ def _unit_square_to_quad(points: torch.Tensor) -> torch.Tensor:def _get_perspective_transform_closed_form(points_src: torch.Tensor, points_dst: torch.Tensor) -> torch.Tensor:- """ONNX-traceable perspective transform via two unit-square decompositions.+ """Perspective transform via two unit-square (Heckbert) decompositions.Computes ``H = H_d @ inv(H_s)`` where ``H_s`` maps the unit square to- ``points_src`` and ``H_d`` maps it to ``points_dst``. Replaces the 8x8- ``torch.linalg.solve`` in :func:`get_perspective_transform` with two 3x3- Heckbert constructions and one 3x3 inverse β all closed-form ops that the- legacy ONNX exporter supports.+ ``points_src`` and ``H_d`` maps it to ``points_dst``, so ``H`` maps+ ``points_src`` onto ``points_dst`` directly. Uses only arithmetic and a+ closed-form 3x3 inverse β no ``torch.linalg.solve`` β so it needs no+ LAPACK/cusolver backend (runs on the Jetson wheel) and traces cleanly for+ ONNX. The result is normalized to ``H[2, 2] == 1`` to match the DLT+ convention. Computed in float32/float64 for numerical stability, then cast+ back to the input dtype."""- h_s = _unit_square_to_quad(points_src)- h_d = _unit_square_to_quad(points_dst)- return h_d @ _inverse_3x3_closed_form(h_s)+ dtype = points_src.dtype+ work_dtype = _normalize_to_float32_or_float64(dtype)+ h_s = _unit_square_to_quad(points_src.to(work_dtype))+ h_d = _unit_square_to_quad(points_dst.to(work_dtype))+ transform = h_d @ _inverse_3x3_closed_form(h_s)+ transform = transform / transform[..., 2:3, 2:3]+ return transform.to(dtype)def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> torch.Tensor:@@ -437,47 +479,11 @@ def get_perspective_transform(points_src: torch.Tensor, points_dst: torch.TensorKORNIA_CHECK(points_src.shape == points_dst.shape, "Source data shape must match Destination data shape.")KORNIA_CHECK(points_src.dtype == points_dst.dtype, "Source data type must match Destination data type.")- # Under tracing (legacy torch.onnx.export, torch.jit.trace), use the closed-form- # Heckbert decomposition: the legacy ONNX tracer does not lower- # ``aten::linalg_solve``, but the closed-form path only uses arithmetic ops- # + a closed-form 3x3 inverse, both fully supported. ``torch.jit.is_tracing()``- # is JIT-script-safe (unlike ``torch.onnx.is_in_onnx_export``, which contains- # an ``import`` statement that JIT script cannot compile).- if torch.jit.is_tracing():- return _get_perspective_transform_closed_form(points_src, points_dst)-- # we build matrix A by using only 4 point correspondence. The linear- # system is solved with the least square method, so here- # we could even pass more correspondence-- # create the lhs torch.Tensor with shape # Bx8x8- B: int = points_src.shape[0] # batch_size-- A = torch.empty(B, 8, 8, device=points_src.device, dtype=points_src.dtype)-- # we need to perform in batch- _zeros = torch.zeros(B, device=points_src.device, dtype=points_src.dtype)- _ones = torch.ones(B, device=points_src.device, dtype=points_src.dtype)-- for i in range(4):- x1, y1 = points_src[..., i, 0], points_src[..., i, 1] # Bx4- x2, y2 = points_dst[..., i, 0], points_dst[..., i, 1] # Bx4-- A[:, 2 * i] = torch.stack([x1, y1, _ones, _zeros, _zeros, _zeros, -x1 * x2, -y1 * x2], -1)- A[:, 2 * i + 1] = torch.stack([_zeros, _zeros, _zeros, x1, y1, _ones, -x1 * y2, -y1 * y2], -1)-- # the rhs torch.Tensor- b = points_dst.view(-1, 8, 1)-- # solve the system Ax = b- X: torch.Tensor = _torch_solve_cast(A, b)-- # create variable to return the Bx3x3 transform- M = torch.empty(B, 9, device=points_src.device, dtype=points_src.dtype)- M[..., :8] = X[..., 0] # Bx8- M[..., -1].fill_(1)-- return M.view(-1, 3, 3) # Bx3x3+ # Solve via two closed-form unit-square (Heckbert) decompositions rather than an 8x8+ # ``torch.linalg.solve``. Both yield the perspective transform mapping ``points_src`` onto+ # ``points_dst``; the closed form additionally needs no LAPACK/cusolver backend (so it runs on+ # the Jetson wheel, where ``linalg.solve`` dlopen-fails) and traces cleanly for ONNX.+ return _get_perspective_transform_closed_form(points_src, points_dst)# TODO: move to kornia.geometry.affine