π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): homography and fundamental solvers and RANSAC fit outside autocast (#6072)
Dmytro Mishkin40c1d46b65e6
diff --git a/changelog.d/6072.fixed.md b/changelog.d/6072.fixed.mdnew file mode 100644index 000000000..566b1e90c--- /dev/null+++ b/changelog.d/6072.fixed.md@@ -0,0 +1,18 @@+`find_homography_dlt`, `find_homography_dlt_iterated`, `find_homography_lines_dlt`,+`find_homography_lines_dlt_iterated`, `find_fundamental`, `run_7point`, `run_8point` and `RANSAC` run with autocast+disabled, so a caller's `torch.autocast` region no longer changes their result. Under bfloat16 autocast a float32 input+used to be fitted with its matrix products in bfloat16 and returned as bfloat16: the iterated DLT homography of 500+points with 1 px noise moved the corners of a 600 x 450 image by 3 to 5 px, a `RANSAC("homography",+local_optimization="dlt")` estimate was about 3 px off instead of 0.5 px, and `find_fundamental` returned a bfloat16+matrix far from the float32 one. On CUDA and MPS, the 8-point `find_fundamental` with more than eight points or with+weights, and `RANSAC("fundamental", local_optimization="dlt")` and `RANSAC("essential", local_optimization="dlt")`,+raised `NotImplementedError` from `torch.linalg.eigh`. The default `local_optimization="lm"` solved and scored its+minimal samples in the autocast dtype, which could change its estimate. They, and `find_affine`, enter that+autocast-free region only inside an autocast region, so the direct solvers keep running on the `meta` device, and+`find_affine`, which raised `RuntimeError: unsupported scalarType` there, now runs too. The 8-point `find_fundamental`,+`RANSAC("fundamental", local_optimization="dlt")` and `RANSAC("essential", local_optimization="dlt")` with float16 or+bfloat16 points solve their eigenproblem in float32: with more than eight points or with weights they raised+`NotImplementedError` from `torch.linalg.eigh` outside CPU autocast and on every other device, and now return the input+dtype. Weights of another dtype than the points take the points' dtype in `find_homography_dlt`,+`find_homography_dlt_iterated`, `find_homography_lines_dlt` and the 8-point `find_fundamental`: autocast used to cast+them together, so half-precision points with float32 weights fitted only inside it, and now fit in and out of it.diff --git a/kornia/core/utils.py b/kornia/core/utils.pyindex ce402aba2..1cba4fbb0 100644--- a/kornia/core/utils.py+++ b/kornia/core/utils.py@@ -20,6 +20,7 @@ import importlib.utilimport platformimport sysfrom collections.abc import Mapping, Sequence+from contextlib import AbstractContextManager, nullcontextfrom dataclasses import asdict, fields, is_dataclassfrom types import FrameType, UnionTypefrom typing import Any, Dict, List, Optional, Tuple, Type, TypeVar, Union, get_args, get_origin, get_type_hints@@ -637,6 +638,28 @@ def is_autocast_enabled(both: bool = True) -> bool:return torch.is_autocast_enabled()+def _autocast_disabled(device_type: str) -> AbstractContextManager[Any]:+ """Return a context that turns off the caller's autocast region for ``device_type``, if one is on.++ Outside autocast it returns a ``nullcontext``: entering ``torch.autocast(enabled=False)`` anyway costs a few+ microseconds per call, a few percent of a small solve, and raises for a device type without autocast, such as+ ``meta``. Every device type torch has an autocast region for is covered, ``xla``, ``hpu`` and a PrivateUse1 backend+ too.+ """+ # ``torch.amp.is_autocast_available`` would ask first, but Dynamo cannot trace it on torch 2.5.1. ``meta`` is+ # answered before asking: under torch.compile, Dynamo turns the RuntimeError below into its own internal error+ # instead of passing it to the ``except``.+ if device_type == "meta":+ return nullcontext()+ try:+ enabled = torch.is_autocast_enabled(device_type)+ except RuntimeError: # a device type without autocast, such as ``meta``+ enabled = False+ if enabled:+ return torch.autocast(device_type=device_type, enabled=False)+ return nullcontext()++# These helpers moved into ``torch.compiler`` over time; resolve them once at import._torch_is_compiling = getattr(torch.compiler, "is_compiling", None) or getattr(torch._dynamo, "is_compiling", None)_torch_is_exporting = getattr(torch.compiler, "is_exporting", None)diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex 840d811aa..048f51fab 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -23,7 +23,7 @@ from typing import Literal, Optional, Tuple, Unionimport torchfrom kornia.core.check import KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECK_SHAPE-from kornia.core.utils import _torch_svd_cast, safe_inverse_with_mask+from kornia.core.utils import _autocast_disabled, _torch_svd_cast, safe_inverse_with_maskfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.solvers.homogeneous import _det3, _null_space_lufrom kornia.geometry.solvers.polynomial_solver import _solve_cubic_real@@ -496,15 +496,17 @@ def run_7point(points1: torch.Tensor, points2: torch.Tensor) -> torch.Tensor:KORNIA_CHECK_SHAPE(points1, ["B", "7", "2"])KORNIA_CHECK_SHAPE(points2, ["B", "7", "2"])- # Reference: Hartley and Zisserman, section 11.1.2; the cubic follows OpenCV's run7Point- # (https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/fundam.cpp).- points1_norm, transform1 = normalize_points(points1)- points2_norm, transform2 = normalize_points(points2)- A = _epipolar_design_rows(points1_norm, points2_norm)- candidates, valid = _seven_point_candidates(A)- # F = T2^T F T1- fmatrix = normalize_transformation(transform2[:, None].mT @ candidates @ transform1[:, None])- return torch.where(valid[..., None, None], fmatrix, torch.zeros_like(fmatrix))+ # Autocast would run the matrix products in half precision and return half-precision candidates.+ with _autocast_disabled(points1.device.type):+ # Reference: Hartley and Zisserman, section 11.1.2; the cubic follows OpenCV's run7Point+ # (https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/fundam.cpp).+ points1_norm, transform1 = normalize_points(points1)+ points2_norm, transform2 = normalize_points(points2)+ A = _epipolar_design_rows(points1_norm, points2_norm)+ candidates, valid = _seven_point_candidates(A)+ # F = T2^T F T1+ fmatrix = normalize_transformation(transform2[:, None].mT @ candidates @ transform1[:, None])+ return torch.where(valid[..., None, None], fmatrix, torch.zeros_like(fmatrix))def run_8point(@@ -533,51 +535,58 @@ def run_8point(KORNIA_CHECK_SHAPE(weights, ["B", "N"])if weights.shape[1] != points1.shape[1]:raise AssertionError(weights.shape)+ # Weights take the points' dtype, as a caller's autocast used to cast them; mixed dtypes now fit outside it too.+ if weights is not None:+ weights = weights.to(points1.dtype)- # Use the same correspondences for Hartley statistics and the weighted DLT system.- pts1n, T1 = normalize_points(points1, weights=weights)- pts2n, T2 = normalize_points(points2, weights=weights)+ # Autocast would run the matrix products in half precision, where CUDA's eigh has no kernel.+ with _autocast_disabled(points1.device.type):+ # Use the same correspondences for Hartley statistics and the weighted DLT system.+ pts1n, T1 = normalize_points(points1, weights=weights)+ pts2n, T2 = normalize_points(points2, weights=weights)- # Design matrix rows A_i = [x2*x1, x2*y1, x2, y2*x1, y2*y1, y2, x1, y1, 1]- # Shape: A β (B, N, 9)- A = _epipolar_design_rows(pts1n, pts2n)+ # Design matrix rows A_i = [x2*x1, x2*y1, x2, y2*x1, y2*y1, y2, x1, y1, 1]+ # Shape: A β (B, N, 9)+ A = _epipolar_design_rows(pts1n, pts2n)- B, N, _ = A.shape+ B, N, _ = A.shape- if weights is None and N == 8:- # A minimal sample has an exact null vector.- h = _eight_point_null_vector(A)- else:- # Build normal matrix M = A^T W A (B,9,9) without forming NxN diagonals.- if weights is None:- if N < use_einsum_at_more_than_points:- # Use GEMM on tall A: (B,9,N) @ (B,N,9)- M = A.transpose(-2, -1).contiguous() @ A- else:- # Accumulate via einsum (saves bandwidth for huge N)- M = torch.einsum("bni,bnj->bij", A, A)+ if weights is None and N == 8:+ # A minimal sample has an exact null vector.+ h = _eight_point_null_vector(A)else:- # Negative weights count as zero. A weight of exactly 0 is the documented way to drop a correspondence,- # and its gradient should be the one-sided derivative from above. ``clamp_min(0)`` passes the gradient- # through at the bound on torch 2.5.1 and 2.9.1 but returns 0 on 2.14 (#4229); ``where`` passes it on- # every version.- w = torch.where(weights < 0, 0.0, weights)- if N < use_einsum_at_more_than_points:- # Scale one factor by w instead of both by sqrt(w). Both build the same A^T W A, but the- # derivative of sqrt is unbounded at 0, so a zero weight got a NaN gradient. This form is linear in- # w, like the einsum branch below.- Aw = A * w.unsqueeze(-1)- M = Aw.transpose(-2, -1).contiguous() @ A+ # Build normal matrix M = A^T W A (B,9,9) without forming NxN diagonals.+ if weights is None:+ if N < use_einsum_at_more_than_points:+ # Use GEMM on tall A: (B,9,N) @ (B,N,9)+ M = A.transpose(-2, -1).contiguous() @ A+ else:+ # Accumulate via einsum (saves bandwidth for huge N)+ M = torch.einsum("bni,bnj->bij", A, A)else:- # Weighted einsum- M = torch.einsum("bni,bnj,bn->bij", A, A, w)-- _evals, evecs = torch.linalg.eigh(M) # ascending order- h = evecs[..., 0] # (B,9), eigenvector for smallest Ξ»- F_rank2 = _enforce_rank2(h.reshape(B, 3, 3))- F = T2.transpose(-2, -1) @ (F_rank2 @ T1)-- return normalize_transformation(F)+ # Negative weights count as zero. A weight of exactly 0 is the documented way to drop a correspondence,+ # and its gradient should be the one-sided derivative from above. ``clamp_min(0)`` passes the gradient+ # through at the bound on torch 2.5.1 and 2.9.1 but returns 0 on 2.14 (#4229); ``where`` passes it on+ # every version.+ w = torch.where(weights < 0, 0.0, weights)+ if N < use_einsum_at_more_than_points:+ # Scale one factor by w instead of both by sqrt(w). Both build the same A^T W A, but the+ # derivative of sqrt is unbounded at 0, so a zero weight got a NaN gradient. This form is linear in+ # w, like the einsum branch below.+ Aw = A * w.unsqueeze(-1)+ M = Aw.transpose(-2, -1).contiguous() @ A+ else:+ # Weighted einsum+ M = torch.einsum("bni,bnj,bn->bij", A, A, w)++ # No device has a half-precision eigh kernel; CPU autocast used to promote this one to float32.+ half = M.dtype in (torch.float16, torch.bfloat16)+ _evals, evecs = torch.linalg.eigh(M.float() if half else M) # ascending order+ h = evecs[..., 0].to(M.dtype) # (B,9), eigenvector for smallest Ξ»+ F_rank2 = _enforce_rank2(h.reshape(B, 3, 3))+ F = T2.transpose(-2, -1) @ (F_rank2 @ T1)++ return normalize_transformation(F)def find_fundamental(@@ -598,6 +607,7 @@ def find_fundamental(- ``weights`` weight each correspondence's equation in the linear system: only their ratios matter, anegative weight counts as zero, and ``method="7POINT"`` ignores them.- When the 7-point cubic has one real root, the two extra ``"7POINT"`` candidates are zero matrices.+ - A caller's autocast region does not change the fit.Args:points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`: :math:`N \ge 8` fordiff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.pyindex fa1076063..537c7ca2b 100644--- a/kornia/geometry/homography.py+++ b/kornia/geometry/homography.py@@ -22,7 +22,13 @@ from typing import Optional, Tuple, Unionimport torchfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE-from kornia.core.utils import _extract_device_dtype, _torch_svd_cast, safe_inverse_with_mask, safe_solve_with_mask+from kornia.core.utils import (+ _autocast_disabled,+ _extract_device_dtype,+ _torch_svd_cast,+ safe_inverse_with_mask,+ safe_solve_with_mask,+)from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.epipolar import normalize_points, normalize_transformationfrom kornia.geometry.epipolar._metrics import _shares_points@@ -509,6 +515,7 @@ def find_homography_dlt(correspondence from the equations, and only relative weights matter.- ``solver="lu"`` and ``"svd"`` give the same homography on exact data, to roundoff scaled by theconditioning of the system; on noisy data they solve different least-squares problems and differ.+ - A caller's autocast region does not change the fit.Args:points1: A set of points in the first image with a tensor shape :math:`(B, N, 2)`.@@ -527,10 +534,15 @@ def find_homography_dlt("""device, dtype = _extract_device_dtype([points1, points2])- A, transform1, transform2 = _homography_dlt_system(points1, points2, weights)- return _homography_from_dlt_system(- A, weights, transform1, _inverse_normalization(transform2), solver, device, dtype- )+ # Weights take the points' dtype, as a caller's autocast used to cast them; mixed dtypes now fit outside it too.+ if weights is not None:+ weights = weights.to(points1.dtype)+ # Autocast would run the DLT's matrix products in half precision and return a half-precision homography.+ with _autocast_disabled(points1.device.type):+ A, transform1, transform2 = _homography_dlt_system(points1, points2, weights)+ return _homography_from_dlt_system(+ A, weights, transform1, _inverse_normalization(transform2), solver, device, dtype+ )def _inverse_normalization(transform: torch.Tensor) -> torch.Tensor:@@ -712,7 +724,7 @@ def find_homography_dlt_iterated(r"""Compute the homography matrix using the iteratively-reweighted least squares (IRWLS).Convention:- - Direction and ``H[2, 2] = 1`` as :func:`find_homography_dlt`. Each solve after the first re-weights+ - Direction, ``H[2, 2] = 1`` and autocast as :func:`find_homography_dlt`. Each solve after the first re-weightswith the Gaussian kernel ``exp(-e**2 / (2 * soft_inl_th**2))`` of the symmetric transfer error ``e``(the root of the summed squared forward and backward transfer errors), so ``soft_inl_th`` is astandard deviation in pixels: a correspondence with ``e = soft_inl_th`` keeps weight ``exp(-1/2)``.@@ -731,16 +743,21 @@ def find_homography_dlt_iterated("""device, dtype = _extract_device_dtype([points1, points2])- # Weighted Hartley normalization changes with each set of IRLS weights.- A, transform1, transform2 = _homography_dlt_system(points1, points2, weights)- transform2_inv = _inverse_normalization(transform2)- H: torch.Tensor = _homography_from_dlt_system(A, weights, transform1, transform2_inv, "lu", device, dtype)- for _ in range(n_iter - 1):- squared_errors: torch.Tensor = symmetric_transfer_error(points1, points2, H, True)- weights_new: torch.Tensor = torch.exp(-squared_errors / (2.0 * (soft_inl_th**2)))- A, transform1, transform2 = _homography_dlt_system(points1, points2, weights_new)+ # Weights take the points' dtype, as a caller's autocast used to cast them; mixed dtypes now fit outside it too.+ if weights is not None:+ weights = weights.to(points1.dtype)+ # Autocast would run the solves and the re-weighting errors in half precision.+ with _autocast_disabled(points1.device.type):+ # Weighted Hartley normalization changes with each set of IRLS weights.+ A, transform1, transform2 = _homography_dlt_system(points1, points2, weights)transform2_inv = _inverse_normalization(transform2)- H = _homography_from_dlt_system(A, weights_new, transform1, transform2_inv, "lu", device, dtype)+ H: torch.Tensor = _homography_from_dlt_system(A, weights, transform1, transform2_inv, "lu", device, dtype)+ for _ in range(n_iter - 1):+ squared_errors: torch.Tensor = symmetric_transfer_error(points1, points2, H, True)+ weights_new: torch.Tensor = torch.exp(-squared_errors / (2.0 * (soft_inl_th**2)))+ A, transform1, transform2 = _homography_dlt_system(points1, points2, weights_new)+ transform2_inv = _inverse_normalization(transform2)+ H = _homography_from_dlt_system(A, weights_new, transform1, transform2_inv, "lu", device, dtype)return H@@ -805,6 +822,7 @@ def find_homography_lines_dlt(through image-2 segment ``i``, so the endpoints need not be point correspondences.- Each segment gives two constraints on the eight degrees of freedom of ``H``, so at least four segmentsare needed, as :func:`find_homography_dlt` needs four points.+ - A caller's autocast region does not change the fit.Args:ls1: A set of line segments in the first image with a tensor shape :math:`(B, N, 2, 2)`, or@@ -843,47 +861,52 @@ def find_homography_lines_dlt(if weights is not None and weights.shape != ls1.shape[:2]:raise AssertionError(weights.shape)- endpoint_weights = weights.repeat_interleave(2, dim=1) if weights is not None else None- points1_norm, transform1 = normalize_points(points1, weights=endpoint_weights)- points2_norm, transform2 = normalize_points(points2, weights=endpoint_weights)- # Pair each segment's own endpoints: the flattened points are [start_0, end_0, start_1, end_1, ...].- segments1_norm = points1_norm.reshape(BS, N, 2, 2)- segments2_norm = points2_norm.reshape(BS, N, 2, 2)- lst1, le1 = segments1_norm[:, :, 0], segments1_norm[:, :, 1]- lst2, le2 = segments2_norm[:, :, 0], segments2_norm[:, :, 1]-- xs1, ys1 = torch.chunk(lst1, dim=-1, chunks=2) # BxNx1- xs2, ys2 = torch.chunk(lst2, dim=-1, chunks=2) # BxNx1- xe1, ye1 = torch.chunk(le1, dim=-1, chunks=2) # BxNx1- xe2, ye2 = torch.chunk(le2, dim=-1, chunks=2) # BxNx1-- A = ys2 - ye2- B = xe2 - xs2- C = xs2 * ye2 - xe2 * ys2-- eps: float = 1e-8-- # http://diis.unizar.es/biblioteca/00/09/000902.pdf- ax = torch.cat([A * xs1, A * ys1, A, B * xs1, B * ys1, B, C * xs1, C * ys1, C], dim=-1)- ay = torch.cat([A * xe1, A * ye1, A, B * xe1, B * ye1, B, C * xe1, C * ye1, C], dim=-1)- # The row count is spelled out: a ``-1`` cannot be inferred for an empty batch.- A = torch.cat((ax, ay), dim=-1).reshape(BS, 2 * N, ax.shape[-1])-- if weights is None:- # All points are equally important- A = A.transpose(-2, -1) @ A- else:- # We should use provided weights- if not ((len(weights.shape) == 2) and (weights.shape == ls1.shape[:2])):- raise AssertionError(weights.shape)- # Scale each segment's two design rows by its weight instead of materializing the- # (B, 2N, 2N) diagonal weight matrix, whose storage grows quadratically with N.- w_full = weights.repeat_interleave(2, dim=1).unsqueeze(1)- A = (A.transpose(-2, -1) * w_full) @ A+ # Weights take the points' dtype, as a caller's autocast used to cast them; mixed dtypes now fit outside it too.+ if weights is not None:+ weights = weights.to(ls1.dtype)+ # Autocast would run the DLT's matrix products in half precision and return a half-precision homography.+ with _autocast_disabled(ls1.device.type):+ endpoint_weights = weights.repeat_interleave(2, dim=1) if weights is not None else None+ points1_norm, transform1 = normalize_points(points1, weights=endpoint_weights)+ points2_norm, transform2 = normalize_points(points2, weights=endpoint_weights)+ # Pair each segment's own endpoints: the flattened points are [start_0, end_0, start_1, end_1, ...].+ segments1_norm = points1_norm.reshape(BS, N, 2, 2)+ segments2_norm = points2_norm.reshape(BS, N, 2, 2)+ lst1, le1 = segments1_norm[:, :, 0], segments1_norm[:, :, 1]+ lst2, le2 = segments2_norm[:, :, 0], segments2_norm[:, :, 1]++ xs1, ys1 = torch.chunk(lst1, dim=-1, chunks=2) # BxNx1+ xs2, ys2 = torch.chunk(lst2, dim=-1, chunks=2) # BxNx1+ xe1, ye1 = torch.chunk(le1, dim=-1, chunks=2) # BxNx1+ xe2, ye2 = torch.chunk(le2, dim=-1, chunks=2) # BxNx1++ A = ys2 - ye2+ B = xe2 - xs2+ C = xs2 * ye2 - xe2 * ys2++ eps: float = 1e-8++ # http://diis.unizar.es/biblioteca/00/09/000902.pdf+ ax = torch.cat([A * xs1, A * ys1, A, B * xs1, B * ys1, B, C * xs1, C * ys1, C], dim=-1)+ ay = torch.cat([A * xe1, A * ye1, A, B * xe1, B * ye1, B, C * xe1, C * ye1, C], dim=-1)+ # The row count is spelled out: a ``-1`` cannot be inferred for an empty batch.+ A = torch.cat((ax, ay), dim=-1).reshape(BS, 2 * N, ax.shape[-1])++ if weights is None:+ # All points are equally important+ A = A.transpose(-2, -1) @ A+ else:+ # We should use provided weights+ if not ((len(weights.shape) == 2) and (weights.shape == ls1.shape[:2])):+ raise AssertionError(weights.shape)+ # Scale each segment's two design rows by its weight instead of materializing the+ # (B, 2N, 2N) diagonal weight matrix, whose storage grows quadratically with N.+ w_full = weights.repeat_interleave(2, dim=1).unsqueeze(1)+ A = (A.transpose(-2, -1) * w_full) @ A- H = _svd_null_vector(A).view(-1, 3, 3)- H = _inverse_normalization(transform2) @ (H @ transform1)- return normalize_transformation(H, eps)+ H = _svd_null_vector(A).view(-1, 3, 3)+ H = _inverse_normalization(transform2) @ (H @ transform1)+ return normalize_transformation(H, eps)def find_homography_lines_dlt_iterated(@@ -922,9 +945,11 @@ def find_homography_lines_dlt_iterated(ls1 = ls1[None]if len(ls2.shape) == 3:ls2 = ls2[None]- H: torch.Tensor = find_homography_lines_dlt(ls1, ls2, weights)- for _ in range(n_iter - 1):- squared_distances: torch.Tensor = _line_segment_squared_distance_one_way(ls1, ls2, H)- weights_new: torch.Tensor = torch.exp(-squared_distances / (2.0 * (soft_inl_th**2)))- H = find_homography_lines_dlt(ls1, ls2, weights_new)+ # Autocast would run the re-weighting distances in half precision.+ with _autocast_disabled(ls1.device.type):+ H: torch.Tensor = find_homography_lines_dlt(ls1, ls2, weights)+ for _ in range(n_iter - 1):+ squared_distances: torch.Tensor = _line_segment_squared_distance_one_way(ls1, ls2, H)+ weights_new: torch.Tensor = torch.exp(-squared_distances / (2.0 * (soft_inl_th**2)))+ H = find_homography_lines_dlt(ls1, ls2, weights_new)return Hdiff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 8cb11326b..628d07d27 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -29,6 +29,7 @@ from torch import nnfrom kornia.core._compat import torch_version_ltfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.utils import _autocast_disabledfrom kornia.geometry._degensac import (_h_degenerate_sample,_h_degenerate_samples,@@ -89,7 +90,7 @@ def _affine_transfer_error(pts1: torch.Tensor, pts2: torch.Tensor, models: torchthat function, it computes in at least float32."""# Scoring needs the same precision as fitting, including inside mixed-precision pipelines.- with torch.autocast(device_type=pts1.device.type, enabled=False):+ with _autocast_disabled(pts1.device.type):num_points = pts1.shape[-2]dtype = torch.promote_types(torch.promote_types(pts1.dtype, pts2.dtype), models.dtype)work = torch.promote_types(dtype, torch.float32)@@ -240,6 +241,7 @@ class RANSAC(nn.Module):runs the same algorithm with its own random stream: a seeded call is reproducible and leaves every globalgenerator unchanged, while an unseeded call consumes one global random seed. Its result is not the eagerone. PROSAC sampling and DEGENSAC are not supported.+ - A caller's autocast region does not change the estimate.Args:model_type: "affine", "homography", "fundamental", "fundamental_7pt", "fundamental_8pt", "essential", or@@ -944,12 +946,19 @@ class RANSAC(nn.Module):"""self.validate_inputs(kp1, kp2, weights)- if self.local_optimization == "lm":- with torch.no_grad():- if self.compiled:- with torch.inference_mode(False), torch.no_grad():- return self._forward_compiled(kp1, kp2)- return self._forward_lm(kp1, kp2)+ # Autocast would solve and score in half precision, which changes the estimate, and CUDA's eigh, which the+ # fundamental refit calls, has no half-precision kernel.+ with _autocast_disabled(kp1.device.type):+ if self.local_optimization == "lm":+ with torch.no_grad():+ if self.compiled:+ with torch.inference_mode(False), torch.no_grad():+ return self._forward_compiled(kp1, kp2)+ return self._forward_lm(kp1, kp2)+ return self._forward_dlt(kp1, kp2)++ def _forward_dlt(self, kp1: torch.Tensor, kp2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """:meth:`forward` with ``local_optimization="dlt"``."""best_score_total = -float("inf")num_tc: int = len(kp1)budget = self.sample_budgetdiff --git a/kornia/geometry/solvers/affine.py b/kornia/geometry/solvers/affine.pyindex df863ef88..63e636092 100644--- a/kornia/geometry/solvers/affine.py+++ b/kornia/geometry/solvers/affine.py@@ -23,6 +23,8 @@ from typing import Optionalimport torch+from kornia.core.utils import _autocast_disabled+__all__ = ["find_affine"]@@ -61,7 +63,7 @@ def _fit_affine_components() -> tuple[torch.Tensor, torch.Tensor]:"""Fit ``points2 = A @ points1 + t`` using a guarded weighted normal equation."""# Explicit casts alone do not prevent autocast from lowering matrix multiplications again.- with torch.autocast(device_type=points1.device.type, enabled=False):+ with _autocast_disabled(points1.device.type):work_dtype = torch.float32 if points1.dtype in (torch.float16, torch.bfloat16) else points1.dtypex, y = points1.to(work_dtype), points2.to(work_dtype)# Weight rescaling leaves the least-squares problem unchanged and avoids@@ -126,7 +128,7 @@ def _find_affine_linear(points1: torch.Tensor, points2: torch.Tensor) -> torch.TNaN under the relative criterion ``det(X^T X) <= eps * trace(X^T X)**2``."""_check_points(points1, points2, 1, batched=False)- with torch.autocast(device_type=points1.device.type, enabled=False):+ with _autocast_disabled(points1.device.type):work_dtype = torch.float32 if points1.dtype in (torch.float16, torch.bfloat16) else points1.dtypex, y = points1.to(work_dtype), points2.to(work_dtype)normal = x.transpose(-1, -2) @ x@@ -150,7 +152,7 @@ def _find_affine_linear_pair(points1: torch.Tensor, points2: torch.Tensor) -> to_check_points(points1, points2, 2, batched=False)if points1.shape[-2] != 2:raise ValueError(f"Exactly 2 correspondences are required. Got {points1.shape[-2]}.")- with torch.autocast(device_type=points1.device.type, enabled=False):+ with _autocast_disabled(points1.device.type):work_dtype = torch.float32 if points1.dtype in (torch.float16, torch.bfloat16) else points1.dtypex, y = points1.to(work_dtype), points2.to(work_dtype)a, b, c, d = x[..., 0, 0], x[..., 0, 1], x[..., 1, 0], x[..., 1, 1]@@ -176,7 +178,7 @@ def _find_affine_triplet(_check_points(points1, points2, 3, batched=True)if points1.shape[-2] != 3:raise ValueError(f"Exactly 3 correspondences are required. Got {points1.shape[-2]}.")- with torch.autocast(device_type=points1.device.type, enabled=False):+ with _autocast_disabled(points1.device.type):work_dtype = torch.float32 if points1.dtype in (torch.float16, torch.bfloat16) else points1.dtypex, y = points1.to(work_dtype), points2.to(work_dtype)origin1, origin2 = x[:, :1], y[:, :1]diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex d1ec3837b..9e7ebf986 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -139,13 +139,8 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::Tescall builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestComputeCorrespondEpilines::test_opencv[cpu-bfloat16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_7point_opencv[cpu-bfloat16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_epipolar_constraint_7point[cpu-bfloat16]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_opencv_svd[cpu-bfloat16]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-bfloat16-1-8]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-bfloat16-2-9]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-bfloat16-3-10]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[cpu-bfloat16-3-10]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_smoke[cpu-bfloat16]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson[cpu-bfloat16]+call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_opencv_svd[cpu-bfloat16]+call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson[cpu-bfloat16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson_7point[cpu-bfloat16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFundamentlFromEssential::test_from_to_essential[cpu-bfloat16]call builtins.AssertionError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_projection_from_krt[cpu-bfloat16]diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txtindex fc1dac7d4..3ff8830e1 100644--- a/testing/half_precision_xfails/cpu_float16.txt+++ b/testing/half_precision_xfails/cpu_float16.txt@@ -127,13 +127,8 @@ call builtins.NotImplementedError tests/geometry/epipolar/test_essential.py::Tescall builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestComputeCorrespondEpilines::test_opencv[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_7point_opencv[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_epipolar_constraint_7point[cpu-float16]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_opencv_svd[cpu-float16]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-float16-1-8]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-float16-2-9]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape[cpu-float16-3-10]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_shape_noweights[cpu-float16-3-10]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_smoke[cpu-float16]-call builtins.NotImplementedError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson[cpu-float16]+call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_opencv_svd[cpu-float16]+call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFindFundamental::test_synthetic_sampson_7point[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_fundamental.py::TestFundamentalFromProjections::test_batch_support_check[cpu-float16]call builtins.AssertionError tests/geometry/epipolar/test_projection.py::TestKRtFromProjection::test_projection_from_krt[cpu-float16]diff --git a/tests/core/test_helpers.py b/tests/core/test_helpers.pyindex c4f63f312..5b81a6c13 100644--- a/tests/core/test_helpers.py+++ b/tests/core/test_helpers.py@@ -15,12 +15,15 @@# limitations under the License.#+from contextlib import nullcontext+import pytestimport torchfrom kornia.core.exceptions import BaseError, DeviceError, TypeCheckErrorfrom kornia.core.utils import (_adjugate_closed_form,+ _autocast_disabled,_closed_form_inverse,_det_perm_closed_form,_extract_device_dtype,@@ -983,3 +986,42 @@ def test_is_autocast_enabled_xpu():assert is_autocast_enabled()assert not is_autocast_enabled()+++def test_autocast_disabled_turns_off_only_an_enabled_region():+ with torch.autocast("cpu", dtype=torch.bfloat16):+ with _autocast_disabled("cpu"):+ assert not torch.is_autocast_enabled("cpu")+ assert (torch.ones(2, 2) @ torch.ones(2, 2)).dtype == torch.float32+ assert torch.is_autocast_enabled("cpu")+ assert not torch.is_autocast_enabled("cpu")++[email protected]("device_type", ["cpu", "cuda", "meta"])+def test_autocast_disabled_outside_autocast_enters_nothing(device_type):+ # Outside autocast there is nothing to turn off: entering torch.autocast(enabled=False) anyway costs a few+ # microseconds per call, and for a device type without autocast, such as "meta", torch.autocast raises.+ context = _autocast_disabled(device_type)+ assert isinstance(context, nullcontext)+ with context:+ assert not is_autocast_enabled()++[email protected]("device_type", ["xla", "hpu"])+def test_autocast_disabled_covers_other_autocast_device_types(device_type):+ # find_affine turned off the autocast region of any device type before it used this helper.+ with torch.autocast(device_type, dtype=torch.bfloat16), _autocast_disabled(device_type):+ assert not torch.is_autocast_enabled(device_type)++[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+def test_eager_backend_traces_autocast_disabled_on_meta():+ # torch.is_autocast_enabled("meta") raises, and under torch.compile Dynamo reports that as its own internal error+ # instead of routing it to an ``except`` in the traced function.+ def fit(x):+ with _autocast_disabled(x.device.type):+ return x @ x.mT++ torch._dynamo.reset()+ x = torch.empty(2, 3, 3, device="meta")+ assert torch.compile(fit, backend="eager", fullgraph=True)(x).shape == (2, 3, 3)diff --git a/tests/geometry/epipolar/test_fundamental.py b/tests/geometry/epipolar/test_fundamental.pyindex 14a8f6568..9e37c5c30 100644--- a/tests/geometry/epipolar/test_fundamental.py+++ b/tests/geometry/epipolar/test_fundamental.py@@ -34,7 +34,7 @@ from kornia.geometry.epipolar.fundamental import ()from kornia.geometry.solvers.homogeneous import _null_space_lu-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availablefrom testing.geometry.create import create_random_fundamental_matrix, generate_two_view_random_scenefrom testing.two_view import two_view_scene@@ -367,6 +367,66 @@ class TestFindFundamental(BaseTester):self.assert_close(grads[0], grads[1], **tol)+class TestFundamentalAutocast(BaseTester):+ @pytest.mark.parametrize(+ "method, num_points, weighted",+ [("7POINT", 7, False), ("8POINT", 8, False), ("8POINT", 100, False), ("8POINT", 100, True)],+ )+ def test_autocast_does_not_reach_the_fit(self, device, method, num_points, weighted):+ # A caller's bfloat16 autocast ran the 7- and 8-point matrix products in bfloat16: float32 points gave a+ # bfloat16 fundamental matrix far from the float32 one, and CUDA's eigh, which has no bfloat16 kernel, raised.+ if device.type not in ("cpu", "cuda"):+ pytest.skip("CPU and CUDA autocast")+ generator = torch.Generator().manual_seed(0)+ points1 = torch.rand(1, num_points, 2, generator=generator) * torch.tensor([640.0, 480.0])+ points2 = points1 + torch.tensor([30.0, -5.0]) + 4.0 * torch.randn(1, num_points, 2, generator=generator)+ weights = torch.rand(1, num_points, generator=generator).to(device) if weighted else None+ points1, points2 = points1.to(device), points2.to(device)+ expected = epi.find_fundamental(points1, points2, weights, method=method)+ with torch.autocast(device.type, dtype=torch.bfloat16):+ actual = epi.find_fundamental(points1, points2, weights, method=method)+ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, atol=0, rtol=0)++ @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])+ @pytest.mark.parametrize("weights_dtype", [None, "points", torch.float32])+ def test_half_precision_points_fit_in_and_out_of_autocast(self, dtype, weights_dtype):+ # CPU autocast ran eigh in float32, so half-precision points fitted under it; no device has a half-precision+ # eigh kernel, so the 8-point fit promotes its normal matrix itself. Autocast also cast float32 weights+ # together with the points, and the fit now casts them itself.+ generator = torch.Generator().manual_seed(0)+ points1 = torch.rand(1, 100, 2, generator=generator) * torch.tensor([640.0, 480.0])+ points2 = points1 + torch.tensor([30.0, -5.0]) + 4.0 * torch.randn(1, 100, 2, generator=generator)+ weights = torch.rand(1, 100, generator=generator)+ points1, points2 = points1.to(dtype), points2.to(dtype)+ if weights_dtype is None:+ weights = expected_weights = None+ else:+ expected_weights = weights.to(dtype)+ weights = expected_weights if weights_dtype == "points" else weights.to(weights_dtype)+ expected = epi.find_fundamental(points1, points2, expected_weights)+ outside = epi.find_fundamental(points1, points2, weights)+ with torch.autocast("cpu", dtype=dtype):+ inside = epi.find_fundamental(points1, points2, weights)+ assert expected.dtype == dtype+ for actual in (outside, inside):+ assert actual.dtype == dtype+ self.assert_close(actual, expected, atol=0, rtol=0)++ def test_meta_device_infers_the_shape(self):+ # torch.autocast raises for the meta device type, so the solvers enter it only inside an autocast region.+ points = torch.empty(2, 9, 2, device="meta")+ assert epi.find_fundamental(points, points).shape == (2, 3, 3)+ assert epi.find_fundamental(points[:, :7], points[:, :7], method="7POINT").shape == (2, 3, 3, 3)++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_eager_backend_traces_the_meta_device(self):+ # Compiled shape inference worked on main; the autocast guard must not break it.+ torch._dynamo.reset()+ points = torch.empty(2, 9, 2, device="meta")+ assert torch.compile(epi.find_fundamental, backend="eager", fullgraph=True)(points, points).shape == (2, 3, 3)++class TestComputeCorrespondEpilines(BaseTester):def test_smoke(self, device, dtype):point = torch.rand(1, 1, 2, device=device, dtype=dtype)diff --git a/tests/geometry/test_affine.py b/tests/geometry/test_affine.pyindex 038efb159..1966a168f 100644--- a/tests/geometry/test_affine.py+++ b/tests/geometry/test_affine.py@@ -125,6 +125,11 @@ class TestFindAffine(BaseTester):tol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 2e-4self.assert_close(actual, expected, rtol=tol, atol=tol)+ def test_meta_device_infers_the_shape(self):+ # torch.autocast raises for the meta device type, so the solver enters it only inside an autocast region.+ points = torch.empty(2, 5, 2, device="meta")+ assert find_affine(points, points).shape == (2, 3, 3)+def test_autocast_preserves_float32_solver_precision(self, device):"""Float32 inputs must not let ambient AMP narrow the affine matrix products."""if device.type not in ("cpu", "cuda", "mps"):diff --git a/tests/geometry/test_homography.py b/tests/geometry/test_homography.pyindex e8b57809d..ddf6b2354 100644--- a/tests/geometry/test_homography.py+++ b/tests/geometry/test_homography.py@@ -1426,6 +1426,85 @@ def _unit_normal(seg: torch.Tensor) -> torch.Tensor:return torch.stack([-d[..., 1], d[..., 0]], -1) / d.norm(dim=-1, keepdim=True)+def _segments(points: torch.Tensor) -> torch.Tensor:+ return points.reshape(points.shape[0], -1, 2, 2)+++class TestHomographyDLTAutocast(BaseTester):+ @pytest.mark.parametrize(+ "solve",+ [+ pytest.param(lambda p1, p2, w: find_homography_dlt(p1[:, :4], p2[:, :4]), id="dlt-4-points"),+ pytest.param(find_homography_dlt, id="dlt-lu"),+ pytest.param(lambda p1, p2, w: find_homography_dlt(p1, p2, w, solver="svd"), id="dlt-svd"),+ pytest.param(lambda p1, p2, w: find_homography_dlt_iterated(p1, p2, w, 5.0), id="dlt-iterated"),+ pytest.param(lambda p1, p2, w: find_homography_lines_dlt(_segments(p1), _segments(p2)), id="lines-dlt"),+ pytest.param(+ lambda p1, p2, w: find_homography_lines_dlt_iterated(_segments(p1), _segments(p2), w[:, ::2], 5.0),+ id="lines-dlt-iterated",+ ),+ ],+ )+ def test_autocast_does_not_reach_the_fit(self, device, solve):+ # A caller's bfloat16 autocast ran the DLT's matrix products in bfloat16: the fit moved by up to 70 % of its+ # largest entry, and float32 points gave a bfloat16 homography.+ if device.type not in ("cpu", "cuda"):+ pytest.skip("CPU and CUDA autocast")+ generator = torch.Generator().manual_seed(0)+ H = torch.tensor([[1.05, 0.03, 4.0], [-0.02, 0.98, 6.0], [1e-4, 2e-5, 1.0]])+ points1 = torch.rand(1, 100, 2, generator=generator) * torch.tensor([600.0, 450.0])+ points2 = transform_points(H[None], points1) + torch.randn(1, 100, 2, generator=generator)+ weights = torch.rand(1, 100, generator=generator)+ points1, points2, weights = points1.to(device), points2.to(device), weights.to(device)+ expected = solve(points1, points2, weights)+ with torch.autocast(device.type, dtype=torch.bfloat16):+ actual = solve(points1, points2, weights)+ assert actual.dtype == torch.float32+ self.assert_close(actual, expected, atol=0, rtol=0)++ @pytest.mark.parametrize(+ "solve",+ [+ pytest.param(find_homography_dlt, id="dlt-lu"),+ pytest.param(lambda p1, p2, w: find_homography_dlt(p1, p2, w, solver="svd"), id="dlt-svd"),+ pytest.param(lambda p1, p2, w: find_homography_dlt_iterated(p1, p2, w, 5.0), id="dlt-iterated"),+ pytest.param(+ lambda p1, p2, w: find_homography_lines_dlt(_segments(p1), _segments(p2), w[:, ::2]), id="lines-dlt"+ ),+ pytest.param(+ lambda p1, p2, w: find_homography_lines_dlt_iterated(_segments(p1), _segments(p2), w[:, ::2], 5.0),+ id="lines-dlt-iterated",+ ),+ ],+ )+ def test_weights_of_another_dtype_take_the_points_dtype(self, solve):+ # bfloat16 points with float32 weights fitted under a caller's autocast, which cast them together. The fit+ # now runs outside autocast and casts the weights itself, with the same result in and out of autocast.+ generator = torch.Generator().manual_seed(0)+ H = torch.tensor([[1.05, 0.03, 4.0], [-0.02, 0.98, 6.0], [1e-4, 2e-5, 1.0]])+ points1 = torch.rand(1, 100, 2, generator=generator) * torch.tensor([600.0, 450.0])+ points2 = transform_points(H[None], points1) + torch.randn(1, 100, 2, generator=generator)+ weights = torch.rand(1, 100, generator=generator)+ points1, points2 = points1.bfloat16(), points2.bfloat16()+ expected = solve(points1, points2, weights.bfloat16())+ outside = solve(points1, points2, weights)+ with torch.autocast("cpu", dtype=torch.bfloat16):+ inside = solve(points1, points2, weights)+ for actual in (outside, inside):+ assert actual.dtype == torch.bfloat16+ self.assert_close(actual, expected, atol=0, rtol=0)++ def test_meta_device_infers_the_shape(self):+ # torch.autocast raises for the meta device type, so the solvers enter it only inside an autocast region.+ points = torch.empty(2, 8, 2, device="meta")+ weights = torch.empty(2, 8, device="meta")+ segments = points.reshape(2, 4, 2, 2)+ assert find_homography_dlt(points, points).shape == (2, 3, 3)+ assert find_homography_dlt_iterated(points, points, weights).shape == (2, 3, 3)+ assert find_homography_lines_dlt(segments, segments).shape == (2, 3, 3)+ assert find_homography_lines_dlt_iterated(segments, segments, weights[:, :4]).shape == (2, 3, 3)++class TestConventionHomography(BaseTester):def test_convention_find_homography_dlt_maps_p1_to_p2(self, device, dtype):if dtype == torch.float16:diff --git a/tests/geometry/test_ransac.py b/tests/geometry/test_ransac.pyindex 32892d233..d8e8e8a87 100644--- a/tests/geometry/test_ransac.py+++ b/tests/geometry/test_ransac.py@@ -1531,6 +1531,28 @@ class TestRANSACBoundedLO(BaseTester):assert not torch.equal(subsets[0][0], subsets[0][1])+class TestRANSACAutocast(BaseTester):+ @pytest.mark.parametrize("model_type", ["homography", "fundamental"])+ @pytest.mark.parametrize("local_optimization", ["lm", "dlt"])+ def test_autocast_does_not_reach_the_estimate(self, device, model_type, local_optimization):+ # Under a caller's bfloat16 autocast, local_optimization="dlt" fitted in bfloat16 and returned a bfloat16+ # model (CUDA "fundamental" raised in eigh), and "lm" solved and scored its minimal samples in bfloat16, which+ # changed its estimate. Noise at half the threshold puts many inliers where bfloat16 scores flip them.+ if device.type not in ("cpu", "cuda"):+ pytest.skip("CPU and CUDA autocast")+ kp1, kp2, _, _, _ = create_dominant_plane_scene(500, 0.9, 0.5, 0, noise=1.0, device=device)+ results = []+ for enabled in (False, True):+ ransac = RANSAC(model_type, inl_th=2.0, seed=0, local_optimization=local_optimization)+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=enabled):+ results.append(ransac(kp1, kp2))+ (expected, expected_inliers), (actual, actual_inliers) = results+ assert actual.dtype == torch.float32+ assert expected_inliers.any()+ self.assert_close(actual, expected, atol=0, rtol=0)+ self.assert_close(actual_inliers, expected_inliers, atol=0, rtol=0)++class TestRANSACValidation(BaseTester):@pytest.mark.parametrize("kwargs",diff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.pyindex c4effacfd..ba0fb7d01 100644--- a/tests/tracking/test_planar_tracking.py+++ b/tests/tracking/test_planar_tracking.py@@ -733,8 +733,8 @@ class TestHomographyTrackerHalfKeypointsAndAutocast:assert torch.equal(results[0], results[1])def test_autocast_does_not_reach_ransac(self, device):- # find_homography_dlt runs its matrix products in the caller's autocast dtype: with local_optimization="dlt",- # a bfloat16 fit moved the frame corners by up to 3.1 px here. The tracker fits with autocast off.+ # With local_optimization="dlt", a bfloat16 fit moved the frame corners by up to 3.1 px here. RANSAC keeps+ # autocast out of its fit; the tracker also fits with autocast off, for a ``ransac`` module that does not.if device.type == "mps":pytest.skip("MPS autocast is not exercised here")results = []