π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(tracking): HomographyTracker tracks with float16 and bfloat16 matchers; one homography dtype on every path (#6058)
Dmytro Mishkinea6a2349b201
diff --git a/changelog.d/5978.added.md b/changelog.d/5978.added.mdindex b882a88c9..e99ec191e 100644--- a/changelog.d/5978.added.md+++ b/changelog.d/5978.added.md@@ -1 +1 @@-`kornia.tracking` and the numeric and tooling exports of `kornia.contrib` document their conventions in Convention blocks, the contrib page lists `histogram_matching` and `interp` and maps the connected-component connectivity onto SciPy, OpenCV and scikit-image, and the known defects link their issues (#5956, #5967, #5968).+`kornia.tracking` and the numeric and tooling exports of `kornia.contrib` document their conventions in Convention blocks, the contrib page lists `histogram_matching` and `interp` and maps the connected-component connectivity onto SciPy, OpenCV and scikit-image, and the known defects link their issues (#5956, #5967).diff --git a/changelog.d/6058.breaking.md b/changelog.d/6058.breaking.mdnew file mode 100644index 000000000..abd3fa89c--- /dev/null+++ b/changelog.d/6058.breaking.md@@ -0,0 +1 @@+`HomographyTracker` returns and stores every homography, `no_match()`'s included, in float32 for a `float16` or `bfloat16` target and in the target's dtype otherwise, whatever the dtype of the frame, of the matcher's keypoints or of a `previous_homography` assigned from outside. A homography found by matching used to have the keypoints' dtype: a `float64` tracker whose matcher returns float32 keypoints returned float32 homographies, and a float32 tracker given float64 frames, by a matcher that returns keypoints in the frame's dtype, returned float64 ones. `no_match()` returned the half dtype. The tracker now also tracks with `float16` and `bfloat16` matchers. The second frame raised: in `warp_perspective`, which got the half frame with the float32 inverse of the first frame's float32 homography, or in `linalg.inv` for a half `previous_homography`. The prior is now inverted and the frame warped in float32, and the fast matcher gets the warped frame in the frame's dtype. Half keypoints are widened to float32 before RANSAC; a bfloat16 fit was rounded to bfloat16 and moved the tracked points by pixels. The caller's autocast no longer runs the tracker's own warp, keypoint mapping and `ransac` fit in half precision; under `bfloat16` autocast the keypoint mapping was up to 7.6 px off on a 600 px frame, and a `RANSAC(local_optimization="dlt")` fit was several pixels off. A float32 tracker whose matcher returns float64 keypoints, or with a float64 `previous_homography` assigned from outside, raised in `track_next_frame`.diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.pyindex d509f8cf1..2700bca6d 100644--- a/kornia/tracking/planar_tracker.py+++ b/kornia/tracking/planar_tracker.py@@ -41,8 +41,11 @@ class HomographyTracker(nn.Module):the target or to that matcher's weights afterwards are not noticed; call :meth:`set_target` again.- A failed match returns ``(H, False)`` with ``H`` uninitialised (:meth:`no_match`). A failure while trackingalso drops the previous homography, so the next frame is matched from scratch by ``initial_matcher``.- - Known defect: with ``float16`` or ``bfloat16`` images, tracking raises on the frame after the first match- (`#5968 <https://github.com/kornia/kornia/issues/5968>`_).+ - Every homography the tracker returns or stores as ``previous_homography``, :meth:`no_match`'s included, is+ float32 for a ``float16`` or ``bfloat16`` target and has the target's dtype otherwise, whatever the dtype of+ the frame, of the matcher's keypoints or of a ``previous_homography`` assigned from outside.+ - Keypoints narrower than that dtype are widened to it before ``ransac`` fits them. The caller's autocast+ reaches the matchers, but not the tracker's own warp, keypoint mapping and ``ransac`` fit.Args:initial_matcher: image matching module for a frame without a previous homography, e.g.@@ -110,6 +113,12 @@ class HomographyTracker(nn.Module):"""return self.target.dtype+ @property+ def _homography_dtype(self) -> torch.dtype:+ # The dtype of every homography returned or kept as the prior: float32 for a half target, as the float32+ # keypoints of a half matcher give it, so that it can be inverted and its sampling grid stays sub-pixel.+ return torch.promote_types(self.dtype, torch.float32)+@torch.no_grad()def set_target(self, target: torch.Tensor) -> None:"""Register a new target image and refresh cached matcher features.@@ -198,13 +207,14 @@ class HomographyTracker(nn.Module):"""Return a failed-match response and clear current match statistics.Returns:- A tuple ``(H, is_valid)`` where ``H`` is an uninitialised ``3 x 3`` tensor- on the tracker device and dtype, and ``is_valid`` is ``False``.+ A tuple ``(H, is_valid)`` where ``H`` is an uninitialised ``3 x 3`` tensor on the tracker device, in+ float32 for a ``float16`` or ``bfloat16`` target and in the target's dtype otherwise, and ``is_valid`` is+ ``False``."""self.inliers_num = 0self.keypoints0_num = 0self.keypoints1_num = 0- return torch.empty(3, 3, device=self.device, dtype=self.dtype), False+ return torch.empty(3, 3, device=self.device, dtype=self._homography_dtype), Falsedef match_initial(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:"""Estimate a homography from the initial target frame to frame ``x``.@@ -231,11 +241,16 @@ class HomographyTracker(nn.Module):if self.keypoints0_num < max(self.minimum_inliers_num, 4):return self.no_match()- H, inliers = self.ransac(keypoints0, keypoints1)+ # RANSAC returns its model in the dtype of the keypoints: widen half keypoints first, or the fit is rounded to+ # half before it is widened to the homography dtype.+ keypoints_dtype = torch.promote_types(keypoints0.dtype, self._homography_dtype)+ with torch.autocast(x.device.type, enabled=False):+ H, inliers = self.ransac(keypoints0.to(keypoints_dtype), keypoints1.to(keypoints_dtype))self.inliers_num = inliers.sum().item()if self.inliers_num < self.minimum_inliers_num:return self.no_match()+ H = H.to(self._homography_dtype)self.previous_homography = H.clone()self._prior_source = (self.previous_homography, self.target)@@ -252,26 +267,39 @@ class HomographyTracker(nn.Module):``is_valid`` indicates whether tracking remained reliable.The frame is first prewarped by the inverse of the previous homography, widened by a margin,- then matched with ``fast_matcher`` and verified using RANSAC.+ then matched with ``fast_matcher`` and verified using RANSAC. The inverse is computed in the homography dtype+ (float32 for a ``float16`` or ``bfloat16`` target), the frame is warped in that dtype or in its own if that is+ wider, and ``fast_matcher`` gets the warped frame in the dtype of ``x``. Its keypoints are mapped back and+ fitted in the homography dtype or in their own if that is wider. Autocast is off for the warp, the mapping and+ the fit."""self._drop_prior_of_another_target()KORNIA_CHECK(self.previous_homography is not None,"track_next_frame needs a previous homography; call forward() or match_initial() first.",)- Hwarp = cast(torch.Tensor, self.previous_homography).clone()[None]+ homography_dtype = self._homography_dtype+ Hwarp = cast(torch.Tensor, self.previous_homography).to(homography_dtype, copy=True)[None]# make a bit of border for safetyHwarp[:, 0:2, 0:2] = Hwarp[:, 0:2, 0:2] / 0.8Hwarp[:, 0:2, 2] -= 10.0- Hinv = torch.inverse(Hwarp)h, w = self.target.shape[2:]- frame_warped = warp_perspective(x, Hinv, (h, w))+ # grid_sample takes the image and the sampling grid in one dtype, and a half grid is coarser than a pixel on a+ # large frame (bfloat16 keeps 8 mantissa bits): a half frame is warped in float32 and cast back for the matcher.+ # The caller's autocast would run the warp's matrix products in half again, so it is off for the geometry only.+ warp_dtype = torch.promote_types(x.dtype, homography_dtype)+ with torch.autocast(x.device.type, enabled=False):+ Hinv = torch.inverse(Hwarp)+ frame_warped = warp_perspective(x.to(warp_dtype), Hinv, (h, w)).to(x.dtype)match_dict = self.fast_matcher(self._matcher_input(self.fast_matcher, self._target_representation(False), frame_warped))keypoints0 = match_dict["keypoints0"][match_dict["batch_indexes"] == 0]keypoints1 = match_dict["keypoints1"][match_dict["batch_indexes"] == 0]- keypoints1 = transform_points(Hwarp, keypoints1)+ # Half keypoints are widened before they are mapped back and fitted, as in match_initial.+ keypoints_dtype = torch.promote_types(keypoints0.dtype, homography_dtype)+ with torch.autocast(x.device.type, enabled=False):+ keypoints1 = transform_points(Hwarp, keypoints1.to(keypoints_dtype))self.keypoints0_num = len(keypoints0)self.keypoints1_num = len(keypoints1)@@ -280,13 +308,15 @@ class HomographyTracker(nn.Module):self.reset_tracking()return self.no_match()- H, inliers = self.ransac(keypoints0, keypoints1)+ with torch.autocast(x.device.type, enabled=False):+ H, inliers = self.ransac(keypoints0.to(keypoints_dtype), keypoints1)self.inliers_num = inliers.sum().item()if self.inliers_num < self.minimum_inliers_num:self.reset_tracking()return self.no_match()+ H = H.to(homography_dtype)self.previous_homography = H.clone()self._prior_source = (self.previous_homography, self.target)return H, Truediff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.pyindex 5833a4a35..c4effacfd 100644--- a/tests/tracking/test_planar_tracking.py+++ b/tests/tracking/test_planar_tracking.py@@ -16,7 +16,7 @@#import copy-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchimport pytestimport torch@@ -26,7 +26,8 @@ from kornia.core._compat import torch_version_lefrom kornia.core.exceptions import BaseErrorfrom kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, LoFTR, SIFTFeaturefrom kornia.feature.loftr.loftr import default_cfg-from kornia.geometry import rescale, transform_points+from kornia.geometry import rescale, transform_points, warp_perspective+from kornia.geometry.ransac import RANSACfrom kornia.tracking import HomographyTrackerfrom testing.base import BaseTester@@ -495,13 +496,26 @@ _H_TRUE = torch.tensor([[1.1, 0.05, 7.0], [-0.03, 0.95, 4.0], [1e-4, -2e-4, 1.0]class _ExactMatcher(torch.nn.Module):- """Exact correspondences ``keypoints1 = _H_TRUE(keypoints0)``, in float32 whatever the image dtype."""+ """Exact correspondences ``keypoints1 = _H_TRUE(keypoints0)``, in float32 whatever the image dtype.++ The keypoints are on the frame's device; ``image1_dtypes`` records the dtype of every frame it is given.+ """++ def __init__(self) -> None:+ super().__init__()+ self.image1_dtypes: list = []def forward(self, data: dict) -> dict:+ self.image1_dtypes.append(data["image1"].dtype)+ device = data["image1"].deviceys, xs = torch.meshgrid(torch.arange(3.0, 40, 4), torch.arange(3.0, 50, 4), indexing="ij")kp0 = torch.stack([xs.flatten(), ys.flatten()], -1)kp1 = transform_points(_H_TRUE[None], kp0[None])[0]- return {"keypoints0": kp0, "keypoints1": kp1, "batch_indexes": torch.zeros(len(kp0), dtype=torch.long)}+ return {+ "keypoints0": kp0.to(device),+ "keypoints1": kp1.to(device),+ "batch_indexes": torch.zeros(len(kp0), dtype=torch.long, device=device),+ }class TestHomographyTrackerConventions:@@ -540,12 +554,199 @@ class TestHomographyTrackerConventions:assert torch.equal(tracker.target_initial_representation["descriptors"], cached)@pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])- def test_wart_half_precision_tracking_fails_on_the_second_frame_5968(self, half):- # The first frame returns a float32 homography (float32 keypoints); the second warps the half frame with its- # float32 inverse and raises.+ def test_half_precision_tracks_three_frames(self, half, device):+ # The first frame returns a float32 homography (float32 keypoints). The next ones warp the half frame with the+ # float32 inverse of the prior, in float32: a half sampling grid is coarser than a pixel on a large frame (in+ # bfloat16, 8 mantissa bits). The fast matcher gets the warped frame back in the half dtype.+ initial, fast = _ExactMatcher(), _ExactMatcher()+ tracker = HomographyTracker(initial, fast, minimum_inliers_num=10)+ tracker.set_target(torch.rand(1, 1, 44, 54, device=device, dtype=half))+ with patch("kornia.tracking.planar_tracker.warp_perspective", wraps=warp_perspective) as warp:+ for _ in range(3):+ H, ok = tracker(torch.rand(1, 1, 60, 70, device=device, dtype=half))+ assert ok+ assert H.dtype == torch.float32+ assert [(c.args[0].dtype, c.args[1].dtype) for c in warp.call_args_list] == [(torch.float32,) * 2] * 2+ assert initial.image1_dtypes == [half]+ assert fast.image1_dtypes == [half, half]++ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])+ def test_half_precision_prior_assigned_from_outside(self, half, device):+ # A prior assigned in the half dtype is inverted in float32: linalg.inv has no half kernel.tracker = HomographyTracker(_ExactMatcher(), _ExactMatcher(), minimum_inliers_num=10)- tracker.set_target(torch.rand(1, 1, 44, 54, dtype=half))- _, ok = tracker(torch.rand(1, 1, 60, 70, dtype=half))+ tracker.set_target(torch.rand(1, 1, 44, 54, device=device, dtype=half))+ tracker.previous_homography = _H_TRUE.to(device, half)+ H, ok = tracker.track_next_frame(torch.rand(1, 1, 60, 70, device=device, dtype=half))assert ok- with pytest.raises(RuntimeError):- tracker(torch.rand(1, 1, 60, 70, dtype=half))+ assert H.dtype == torch.float32++ def test_frame_wider_than_the_target_is_warped_in_its_own_dtype(self):+ # A float64 frame for a float32 target is warped in float64, with the float32 inverse of the prior, and not+ # narrowed to float32; the fast matcher gets it in float64. The margin is added to a copy of a prior assigned in+ # the tracker's own dtype, not to the assigned tensor.+ fast = _ExactMatcher()+ tracker = HomographyTracker(_ExactMatcher(), fast, minimum_inliers_num=10)+ tracker.set_target(torch.rand(1, 1, 44, 54))+ prior = _H_TRUE.clone()+ tracker.previous_homography = prior+ with patch("kornia.tracking.planar_tracker.warp_perspective", wraps=warp_perspective) as warp:+ H, ok = tracker.track_next_frame(torch.rand(1, 1, 60, 70, dtype=torch.float64))+ assert ok+ assert H.dtype == torch.float32+ assert (warp.call_args.args[0].dtype, warp.call_args.args[1].dtype) == (torch.float64, torch.float32)+ assert fast.image1_dtypes == [torch.float64]+ assert torch.equal(prior, _H_TRUE)++ @pytest.mark.parametrize("target_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])+ def test_homography_dtype_is_the_same_on_every_path(self, target_dtype, device):+ # _ExactMatcher returns float32 keypoints for every image dtype, so RANSAC estimates in float32; the tracker+ # returns and stores the homography in the target dtype, float32 for a half target.+ if device.type == "mps" and target_dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ expected = torch.promote_types(target_dtype, torch.float32)+ tracker = HomographyTracker(_ExactMatcher(), _ExactMatcher(), minimum_inliers_num=10)+ tracker.set_target(torch.rand(1, 1, 44, 54, device=device, dtype=target_dtype))+ frame = torch.rand(1, 1, 60, 70, device=device, dtype=target_dtype)+ dtypes = {}+ H, ok = tracker.match_initial(frame)+ assert ok+ dtypes["match_initial"], dtypes["prior after match_initial"] = H.dtype, tracker.previous_homography.dtype+ H, ok = tracker.track_next_frame(frame)+ assert ok+ dtypes["track_next_frame"], dtypes["prior after track_next_frame"] = H.dtype, tracker.previous_homography.dtype+ tracker.minimum_inliers_num = 10**6 # more than the 120 matches of _ExactMatcher: every match fails+ H, ok = tracker(frame) # track_next_frame, which fails and drops the prior+ assert not ok+ assert tracker.previous_homography is None+ dtypes["failed track_next_frame"] = H.dtype+ H, ok = tracker(frame) # match_initial, which fails+ assert not ok+ dtypes["failed match_initial"] = H.dtype+ dtypes["no_match"] = tracker.no_match()[0].dtype+ assert dtypes == dict.fromkeys(dtypes, expected)++ def test_bfloat16_sift_tracker_follows_the_float32_tracker(self, device):+ # A bfloat16 LocalFeatureMatcher(SIFTFeature) tracker raised on its second frame, in warp_perspective. The+ # texture is stretched 4x: on the plain one, bfloat16 SIFT finds 41 first-frame matches where float32 finds 116+ # (81 on the stretched one, measured with torch 2.14 on CPU).+ target = ((_texture(120, 160) - 0.5) * 4.0 + 0.5).clamp(0.0, 1.0)+ h_true = [+ torch.tensor([[1.0 + 0.02 * i, 0.03, 9.0 + 3 * i], [-0.02, 1.0 - 0.01 * i, 7.0 + 2 * i], [1e-4, 0.0, 1.0]])+ for i in range(3)+ ]+ frames = [warp_perspective(target, h[None], (136, 182)) for h in h_true]+ corners = torch.tensor([[[0.0, 0.0], [159.0, 0.0], [159.0, 119.0], [0.0, 119.0]]], device=device)+ projected = {}+ for dt in (torch.float32, torch.bfloat16):+ matcher = LocalFeatureMatcher(SIFTFeature(300), DescriptorMatcher("snn", 0.9)).to(device, dt)+ # bfloat16 keeps 44 inliers on frame 2 (CPU; 46 on MPS) and at least 34 over texture seeds 0-7+ tracker = HomographyTracker(matcher, matcher, minimum_inliers_num=20)+ with torch.no_grad():+ tracker.set_target(target.to(device, dt))+ for i, frame in enumerate(frames):+ torch.manual_seed(i) # RANSAC samples with the global generator+ H, ok = tracker(frame.to(device, dt))+ assert ok+ assert H.dtype == torch.float32+ if i == 1:+ projected[dt] = transform_points(H[None], corners)+ # The target corners under the second frame's homographies. Measured (torch 2.14): 0.29 px apart on CPU and+ # 0.42 px on MPS; at most 1.37 px over texture seeds 0-7 on either. The bound is about twice that, below the+ # 5 px inlier threshold of the tracker's default RANSAC.+ assert (projected[torch.bfloat16] - projected[torch.float32]).abs().max().item() < 3.0+++class _FixedMatcher(torch.nn.Module):+ """Fixed correspondences ``keypoints1 = _H_TRUE(keypoints0)`` over a 600 x 450 frame, built once in float32.++ Nothing it returns depends on the frame or on autocast. ``image1`` records every frame it is given.+ """++ def __init__(self, dtype: torch.dtype = torch.float32) -> None:+ super().__init__()+ ys, xs = torch.meshgrid(torch.arange(7.0, 440, 23), torch.arange(5.0, 590, 29), indexing="ij")+ kp0 = torch.stack([xs.flatten(), ys.flatten()], -1)+ self.kp0, self.kp1 = kp0.to(dtype), transform_points(_H_TRUE[None], kp0[None])[0].to(dtype)+ self.image1: list = []++ def forward(self, data: dict) -> dict:+ self.image1.append(data["image1"])+ device = data["image1"].device+ return {+ "keypoints0": self.kp0.to(device),+ "keypoints1": self.kp1.to(device),+ "batch_indexes": torch.zeros(len(self.kp0), dtype=torch.long, device=device),+ }+++class _DtypeSpy(torch.nn.Module):+ def __init__(self, inner: torch.nn.Module) -> None:+ super().__init__()+ self.inner, self.dtypes = inner, []++ def forward(self, kp0, kp1):+ self.dtypes.append((kp0.dtype, kp1.dtype))+ return self.inner(kp0, kp1)+++class TestHomographyTrackerHalfKeypointsAndAutocast:+ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])+ def test_half_keypoints_are_fitted_in_float32(self, half, device):+ # RANSAC returns its model in the keypoints' dtype; a bfloat16 homography moves the frame corners by pixels.+ # The tracker with half keypoints follows the same tracker with float32 keypoints.+ corners = torch.tensor([[[0.0, 0.0], [599.0, 0.0], [599.0, 449.0], [0.0, 449.0]]], dtype=torch.float64)+ projected, ransac_dtypes = {}, {}+ for kp_dtype in (torch.float32, half):+ tracker = HomographyTracker(_FixedMatcher(kp_dtype), _FixedMatcher(kp_dtype), minimum_inliers_num=10)+ tracker.ransac = _DtypeSpy(tracker.ransac)+ tracker.set_target(torch.rand(1, 1, 450, 600, device=device, dtype=half))+ frame = torch.rand(1, 1, 450, 600, device=device, dtype=half)+ projected[kp_dtype] = []+ for _ in range(2): # match_initial, then track_next_frame+ torch.manual_seed(0)+ H, ok = tracker(frame)+ assert ok+ projected[kp_dtype].append(transform_points(H.cpu().double()[None], corners))+ ransac_dtypes[kp_dtype] = tracker.ransac.dtypes+ gaps = [(a - b).abs().max().item() for a, b in zip(projected[torch.float32], projected[half])]+ assert max(gaps) < 1.0, gaps+ assert ransac_dtypes[half] == [(torch.float32, torch.float32)] * 2++ def test_autocast_does_not_reach_the_tracker_geometry(self, device):+ # Under the caller's autocast, the warp's and transform_points' matrix products would run in bfloat16: the+ # keypoints mapped back to the frame moved by up to 7.6 px at 600 px (CPU; 5.9 px on CUDA).+ if device.type == "mps":+ pytest.skip("MPS autocast is not exercised here")+ fast = _FixedMatcher()+ tracker = HomographyTracker(_FixedMatcher(), fast, minimum_inliers_num=10)+ tracker.set_target(torch.rand(1, 1, 450, 600, device=device))+ frame = torch.rand(1, 1, 450, 600, device=device)+ results = []+ for autocast in (False, True):+ tracker.previous_homography = _H_TRUE.to(device)+ torch.manual_seed(0)+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=autocast):+ H, ok = tracker.track_next_frame(frame)+ assert ok+ results.append(H)+ assert torch.equal(fast.image1[0], fast.image1[1])+ 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.+ if device.type == "mps":+ pytest.skip("MPS autocast is not exercised here")+ results = []+ for autocast in (False, True):+ ransac = RANSAC("homography", inl_th=5.0, batch_size=4096, max_iter=10, local_optimization="dlt")+ tracker = HomographyTracker(_FixedMatcher(), _FixedMatcher(), ransac, minimum_inliers_num=10)+ tracker.set_target(torch.rand(1, 1, 450, 600, device=device))+ frame = torch.rand(1, 1, 450, 600, device=device)+ torch.manual_seed(0)+ with torch.autocast(device.type, dtype=torch.bfloat16, enabled=autocast):+ results.append([tracker(frame) for _ in range(2)]) # match_initial, then track_next_frame+ for (H0, ok0), (H1, ok1) in zip(*results):+ assert ok0+ assert ok1+ assert torch.equal(H0, H1)