π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature,augmentation): use math.pi instead of the float32 tensor pi in forward arithmetic (#5131)
εΊζ’η30bb4cde4620
diff --git a/changelog.d/5131.fixed.md b/changelog.d/5131.fixed.mdnew file mode 100644index 000000000..5ac7f917f--- /dev/null+++ b/changelog.d/5131.fixed.md@@ -0,0 +1,11 @@+`PatchDominantGradientOrientation`, `LAFOrienter`, `SIFTDescriptor`, `DenseSIFTDescriptor`, `SIFTDescriptorFromPyramid`,+`SIFTFeature`, `SIFTFeatureScaleSpace`, `LightGlueMatcher`, `RandomHue`, `ColorJiggle` and `ColorJitter` now use+`math.pi` instead of the float32 tensor `kornia.constants.pi` in their forward arithmetic (#5127). Their float64 results+used the float32 value of pi, 8.7e-8 above pi: orientation angles move by up to about 3e-6 rad and descriptor entries by+up to about 1e-6, the orientations `LightGlueMatcher` wraps into [0, 2 pi) are no longer 1.7e-7 rad too large, and a+hue shift of `f` turns is no longer `f * 1.7e-7` rad too large (with float64 hue factors in `ColorJiggle` and+`ColorJitter`). float32 results are unchanged. On CPU, `PatchDominantGradientOrientation` used to round 2 pi to the half+dtype before its bin-to-angle product: a third of its float16 angles move by up to 3.9e-3 rad and 2% of its bfloat16+angles by up to 3.1e-2 rad, and the frames oriented by `LAFOrienter` and by the default patch backend of `SIFTFeature`+and `SIFTFeatureScaleSpace` move with them. Every other float16 and bfloat16 result, and every half result on MPS, is+unchanged.diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.pyindex 2ea6edad8..cb9329238 100644--- a/kornia/augmentation/_2d/intensity/color_jiggle.py+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py@@ -15,6 +15,7 @@# limitations under the License.#+import mathfrom collections.abc import Sequencefrom typing import Any, Callable, Dict, List, Optional, Tuple, Union@@ -23,7 +24,6 @@ from torch.distributions import Distributionfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D-from kornia.constants import pifrom kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturation@@ -51,7 +51,7 @@ def _adjust_saturation(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensodef _adjust_hue(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:- return _contiguous_output(adjust_hue(input, factor * 2 * pi))+ return _contiguous_output(adjust_hue(input, factor * 2 * math.pi))_StepFn = Callable[[torch.Tensor, torch.Tensor], torch.Tensor]@@ -115,7 +115,7 @@ def _brightness_step(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:def _hue_step(input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:- return adjust_hue(input, factor * 2 * pi)+ return adjust_hue(input, factor * 2 * math.pi)_NEUTRAL = (1.0, 1.0, 1.0, 0.0)diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex 5d1bcad7e..7ec8059cc 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -15,6 +15,7 @@# limitations under the License.#+import mathfrom collections.abc import Sequencefrom typing import Any, Dict, List, Optional, Tuple, Union@@ -29,7 +30,6 @@ from kornia.augmentation._2d.intensity.color_jiggle import (_dispatch_color_steps,_Steps,)-from kornia.constants import pifrom kornia.enhance import (adjust_brightness_accumulative,adjust_contrast_with_mean_subtraction,@@ -189,7 +189,7 @@ class ColorJitter(_PicklableCompileMixin, IntensityAugmentationBase2D):return _dispatch_color_steps(input, params, self._fixed_order, self._cond_fn, _NEUTRAL, steps)def _adjust_hue_turns(self, input: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:- return self._hue_fn(input, factor * 2 * pi)+ return self._hue_fn(input, factor * 2 * math.pi)def compile(self,diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.pyindex cf2534307..aa8427947 100644--- a/kornia/augmentation/_2d/intensity/hue.py+++ b/kornia/augmentation/_2d/intensity/hue.py@@ -15,6 +15,7 @@# limitations under the License.#+import mathfrom typing import Any, Dict, Optional, Tupleimport torch@@ -22,7 +23,6 @@ import torchfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.augmentation.utils import _range_bound-from kornia.constants import pifrom kornia.enhance.adjust import adjust_hue@@ -102,4 +102,4 @@ class RandomHue(IntensityAugmentationBase2D):transform: Optional[torch.Tensor] = None,) -> torch.Tensor:hue_factor = params["hue_factor"].to(input)- return adjust_hue(input, hue_factor * 2 * pi)+ return adjust_hue(input, hue_factor * 2 * math.pi)diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex 85e8602c9..c045fec68 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -15,6 +15,7 @@# limitations under the License.#+import mathimport warningsfrom typing import ClassVar, Dict, List, Literal, Optional, Tuple, Union@@ -22,7 +23,6 @@ import torchfrom torch import nnfrom kornia.color import rgb_to_grayscale-from kornia.constants import pifrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_LAFfrom kornia.core.utils import is_exportingfrom kornia.geometry.subpix import ConvQuadInterp3d@@ -733,9 +733,9 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):else:hw2_ = torch.tensor(hw2, device=dev)ori0 = torch.deg2rad(get_laf_orientation(lafs1).reshape(1, -1))- ori0[ori0 < 0] += 2.0 * pi+ ori0[ori0 < 0] += 2.0 * math.piori1 = torch.deg2rad(get_laf_orientation(lafs2).reshape(1, -1))- ori1[ori1 < 0] += 2.0 * pi+ ori1[ori1 < 0] += 2.0 * math.piinput_dict = {"image0": {"keypoints": keypoints1,diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex 64328fd11..ab6c40523 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -15,12 +15,12 @@# limitations under the License.#+import mathfrom typing import Any, Dict, List, Tuple, Unionimport torchfrom torch import nn-from kornia.constants import pifrom kornia.core.download import load_state_dict_from_urlfrom kornia.core.utils import _l2_normalizefrom kornia.filters import GaussianBlur2d, SpatialGradient@@ -257,7 +257,7 @@ class EmbedGradients(nn.Module):def spatial_kernel_embedding(kernel_type: str, grids: Dict[str, torch.Tensor]) -> torch.Tensor:r"""Compute embeddings for cartesian and polar parametrizations."""- factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}+ factors = {"phi": 1.0, "rho": math.pi / sqrt2, "x": math.pi / 2, "y": math.pi / 2}if kernel_type == "cart":coeffs_ = "xy"params_ = ["x", "y"]diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex c9176df43..566f0c467 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -15,13 +15,13 @@# limitations under the License.#+import mathfrom typing import Dict, Optionalimport torchimport torch.nn.functional as Ffrom torch import nn-from kornia.constants import pifrom kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.filters import SpatialGradient, get_gaussian_discrete_kernel1d, get_gaussian_kernel2d@@ -129,7 +129,7 @@ class PatchDominantGradientOrientation(nn.Module):mag, ori = _gradient_magnitude_orientation(gx, gy, self.eps)mag = mag * weighting- o_big = float(self.num_ang_bins) * (ori + 1.0 * pi) / (2.0 * pi)+ o_big = float(self.num_ang_bins) * (ori + math.pi) / (2.0 * math.pi)bo0_big = torch.floor(o_big)wo1_big = o_big - bo0_bigbo0_big = bo0_big % self.num_ang_bins@@ -178,7 +178,7 @@ class PatchDominantGradientOrientation(nn.Module):# uniform one has no peak: the parabolic refinement is `0 / 0` there, so it is skipped.denom = left + right - 2.0 * centerc_subpix = torch.where(denom != 0, 0.5 * (left - right) / denom, torch.zeros_like(denom))- return -((2.0 * pi * (indices.to(patch.dtype) + c_subpix) / float(self.num_ang_bins)) - pi)+ return -((2.0 * math.pi * (indices.to(patch.dtype) + c_subpix) / float(self.num_ang_bins)) - math.pi)class OriNet(nn.Module):diff --git a/kornia/feature/sift/pyramid.py b/kornia/feature/sift/pyramid.pyindex 502d0b635..e7684fcae 100644--- a/kornia/feature/sift/pyramid.py+++ b/kornia/feature/sift/pyramid.py@@ -19,13 +19,13 @@from __future__ import annotations+import mathfrom typing import Tupleimport torchimport torch.nn.functional as Ffrom torch import nn-from kornia.constants import pifrom kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom kornia.core.utils import _l2_normalizefrom kornia.feature.laf import (@@ -151,12 +151,12 @@ class SIFTDescriptorFromPyramid(nn.Module):histograms = histograms.to(working_dtype)affine = affine.to(working_dtype)angles = torch.arange(source_bins, dtype=histograms.dtype, device=histograms.device)- angles = 2.0 * pi * angles / float(source_bins)+ angles = 2.0 * math.pi * angles / float(source_bins)directions = torch.stack([torch.cos(angles), torch.sin(angles)], dim=-1)transformed = torch.einsum("bnji,kj->bnki", affine, directions)magnitude = torch.linalg.vector_norm(transformed, dim=-1)local_angle = torch.atan2(transformed[..., 1], transformed[..., 0])- position = (local_angle % (2.0 * pi)) * float(output_bins) / (2.0 * pi)+ position = (local_angle % (2.0 * math.pi)) * float(output_bins) / (2.0 * math.pi)lower = torch.floor(position).long() % output_binsupper = (lower + 1) % output_binsupper_weight = position - torch.floor(position)@@ -246,7 +246,8 @@ class SIFTDescriptorFromPyramid(nn.Module):denominator = left + right - 2.0 * centersafe_denominator = torch.where(denominator != 0, denominator, torch.ones_like(denominator))offset = torch.where(denominator != 0, 0.5 * (left - right) / safe_denominator, torch.zeros_like(denominator))- return 2.0 * pi * (index.to(lafs.dtype).reshape(b, n) + offset.reshape(b, n)) / float(self.orientation_bins)+ angle = index.to(lafs.dtype).reshape(b, n) + offset.reshape(b, n)+ return 2.0 * math.pi * angle / float(self.orientation_bins)def _descriptors(self,diff --git a/kornia/feature/sift/scale_space.py b/kornia/feature/sift/scale_space.pyindex f521d8307..ebe33369a 100644--- a/kornia/feature/sift/scale_space.py+++ b/kornia/feature/sift/scale_space.py@@ -37,7 +37,6 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.constants import pifrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.utils import _l2_normalizefrom kornia.feature.laf import _grid_sample_patches, laf_from_center_scale_ori, laf_is_valid, rotate_laf@@ -610,7 +609,7 @@ class _SIFTScaleSpaceDescriptor(nn.Module):@staticmethoddef _angular_histogram(mag: torch.Tensor, angle: torch.Tensor, bins: int) -> torch.Tensor:- position = (angle % (2.0 * pi)) * bins / (2.0 * pi)+ position = (angle % (2.0 * math.pi)) * bins / (2.0 * math.pi)lower = position.floor().long() % binsweight1 = position - position.floor()output = mag.new_zeros(*mag.shape[:-1], bins)@@ -638,7 +637,7 @@ class _SIFTScaleSpaceDescriptor(nn.Module):denominator = left + right - 2 * centersafe = torch.where(denominator != 0, denominator, torch.ones_like(denominator))offset = torch.where(denominator != 0, 0.5 * (left - right) / safe, torch.zeros_like(denominator))- return (-2.0 * pi * (index.to(lafs.dtype) + offset) / 36.0).reshape(lafs.shape[:2])+ return (-2.0 * math.pi * (index.to(lafs.dtype) + offset) / 36.0).reshape(lafs.shape[:2])def _describe(self, gradients: torch.Tensor, lafs: torch.Tensor, layer_indices: torch.Tensor, level_height: int@@ -664,7 +663,7 @@ class _SIFTScaleSpaceDescriptor(nn.Module):"""Accumulate the two angular votes per sample into the 4 x 4 spatial cells."""b, n, _ = mag.shapeweight = torch.exp(-0.78125 * (xx.square() + yy.square())).to(mag.dtype)- angular = (angle % (2 * pi)) * 8 / (2 * pi)+ angular = (angle % (2 * math.pi)) * 8 / (2 * math.pi)lower = angular.floor()fraction = angular - lowerlower = lower.long().bitwise_and(7)diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex e20599aa8..f426b08be 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -22,7 +22,6 @@ import torchimport torch.nn.functional as Ffrom torch import nn-from kornia.constants import pifrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.utils import _l2_normalizefrom kornia.filters import get_gaussian_kernel2d, spatial_gradient@@ -67,7 +66,7 @@ def _gradient_magnitude_orientation(sq = gx * gx + gy * gynonzero = sq > 0mag = torch.where(nonzero, torch.sqrt(sq + eps), torch.zeros_like(sq))- ori = torch.where(nonzero, torch.atan2(gy, gx + eps) + 2.0 * pi, torch.full_like(sq, 2.0 * pi))+ ori = torch.where(nonzero, torch.atan2(gy, gx + eps) + 2.0 * math.pi, torch.full_like(sq, 2.0 * math.pi))return mag.to(dtype), ori.to(dtype)@@ -82,7 +81,7 @@ def _dense_sift_histograms_from_gradients(descriptor tensor."""mag, ori = _gradient_magnitude_orientation(gx, gy, eps)- o_big = float(num_ang_bins) * ori / (2.0 * pi)+ o_big = float(num_ang_bins) * ori / (2.0 * math.pi)bo0 = torch.floor(o_big)w1 = o_big - bo0bo0 = bo0 % num_ang_bins@@ -246,7 +245,7 @@ class SIFTDescriptor(nn.Module):mag, ori = _gradient_magnitude_orientation(gx, gy, self.eps)mag = mag * self.gk.expand_as(mag).type_as(mag).to(mag.device)- o_big = float(self.num_ang_bins) * ori / (2.0 * pi)+ o_big = float(self.num_ang_bins) * ori / (2.0 * math.pi)bo0_big_ = torch.floor(o_big)wo1_big_ = o_big - bo0_big_diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 42674082c..f76e65eb6 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -1751,6 +1751,20 @@ class TestColorJiggle(BaseTester):self.assert_close(f(input), expected, low_tolerance=True)+ @pytest.mark.parametrize("order", [None, (3,)])+ def test_float64_half_turn_uses_full_precision_pi_5127(self, device, order):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ torch.manual_seed(0)+ image = torch.rand(2, 3, 5, 5, device=device, dtype=torch.float64)+ hue = kornia.color.rgb_to_hsv(image)[:, 0]+ # A float64 range gives float64 factors. The random order and a fixed `order` apply the hue step+ # through separate functions (the per-step loop and the `torch.cond` branch table).+ aug = ColorJiggle(hue=torch.tensor((0.5, 0.5), dtype=torch.float64), p=1.0, order=order)+ shifted = kornia.color.rgb_to_hsv(aug(image))[:, 0]+ error = torch.remainder(shifted - hue, 2 * torch.pi) - torch.pi+ self.assert_close(error, torch.zeros_like(error), rtol=0.0, atol=1e-12)+def test_sequential(self, device, dtype):if dtype == torch.float16:pytest.skip("not work for half-precision")@@ -2272,6 +2286,19 @@ class TestColorJitter(BaseTester):self.assert_close(f(input), expected, low_tolerance=True)+ def test_float64_half_turn_uses_full_precision_pi_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ torch.manual_seed(0)+ image = torch.rand(2, 3, 5, 5, device=device, dtype=torch.float64)+ hue = kornia.color.rgb_to_hsv(image)[:, 0]+ aug = ColorJitter(hue=(0.5, 0.5), p=1.0)+ # ColorJitter draws its factors in the generator dtype, float32 unless set otherwise.+ aug.set_rng_device_and_dtype(device, torch.float64)+ shifted = kornia.color.rgb_to_hsv(aug(image))[:, 0]+ error = torch.remainder(shifted - hue, 2 * torch.pi) - torch.pi+ self.assert_close(error, torch.zeros_like(error), rtol=0.0, atol=1e-12)+def test_sequential(self, device, dtype):if dtype == torch.float16:pytest.skip("not work for half-precision")@@ -2592,6 +2619,17 @@ class TestRandomHue(BaseTester):self.assert_close(f(input), expected, low_tolerance=True)self.assert_close(f.transform_matrix, expected_transform, low_tolerance=True)+ def test_float64_half_turn_uses_full_precision_pi_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ torch.manual_seed(0)+ image = torch.rand(2, 3, 5, 5, device=device, dtype=torch.float64)+ hue = kornia.color.rgb_to_hsv(image)[:, 0]+ shifted = kornia.color.rgb_to_hsv(RandomHue(hue=(0.5, 0.5), p=1.0)(image))[:, 0]+ # Circular distance of the shift from pi; the float32 pi overshot it by 8.7e-8.+ error = torch.remainder(shifted - hue, 2 * torch.pi) - torch.pi+ self.assert_close(error, torch.zeros_like(error), rtol=0.0, atol=1e-12)+def test_same_on_batch(self, device, dtype):f = RandomHue(hue=(-0.5, 0.5), same_on_batch=True)input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.pyindex 769bf478b..b9bc0ff1c 100644--- a/tests/feature/test_local_features_orientation.py+++ b/tests/feature/test_local_features_orientation.py@@ -123,6 +123,29 @@ class TestPatchDominantGradientOrientation(BaseTester):model_jit = torch.jit.script(PatchDominantGradientOrientation(13).to(patches.device, patches.dtype).eval())self.assert_close(model(patches), model_jit(patches))+ def test_float64_rotation_by_pi_shifts_angle_by_pi_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ # Rotating a patch by 180 degrees negates every gradient, so the angular histogram is the same+ # histogram shifted by half its bins and the two angles differ by exactly pi. The float32 pi+ # in the angle-to-bin and bin-to-angle scales put that difference about 1e-7 off in float64.+ patches = torch.rand(6, 1, 32, 32, device=device, dtype=torch.float64)+ model = PatchDominantGradientOrientation(32, eps=1e-14).to(device, torch.float64)+ difference = torch.remainder(model(patches) - model(patches.flip(-1, -2)), 2 * torch.pi)+ self.assert_close(difference, torch.full_like(difference, torch.pi), rtol=0.0, atol=1e-9)++ def test_float64_axis_ramps_give_exact_angles_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ # A ramp along +x puts every gradient at angle 0 and one along +y at pi / 2: both land on bin+ # centres, so the angles are exact. A common offset in the angle-to-bin or bin-to-angle mapping+ # cancels in the rotation test above but moves these.+ axis = torch.arange(32, device=device, dtype=torch.float64)+ patches = torch.stack([axis.expand(32, 32), axis[:, None].expand(32, 32)]).unsqueeze(1)+ angles = PatchDominantGradientOrientation(32, eps=1e-14).to(device, torch.float64)(patches)+ expected = torch.tensor([0.0, -torch.pi / 2], device=device, dtype=torch.float64)+ self.assert_close(angles, expected, rtol=0.0, atol=1e-12)+class TestOrientationHalfPrecisionIsFinite(BaseTester):"""A flat patch has a zero gradient; `sqrt(gx*gx + gy*gy + eps)` must not give NaN in float16.diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.pyindex fd9831187..2fc8554fb 100644--- a/tests/feature/test_matching.py+++ b/tests/feature/test_matching.py@@ -583,6 +583,36 @@ class TestLightGlueHardNet(BaseTester):assert isinstance(lg, LightGlueMatcher)+class TestLightGlueMatcherOrientations(BaseTester):+ def test_float64_orientations_wrap_by_full_precision_two_pi_5127(self, device, monkeypatch):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ seen = {}++ class _RecordingLightGlue(torch.nn.Module):+ # Stands in for the network, whose construction downloads weights; the matcher only+ # prepares its inputs.+ def __init__(self, *args, **kwargs):+ super().__init__()++ def forward(self, data):+ seen.update(data)+ matches = torch.full((1, data["image0"]["keypoints"].shape[1]), -1, device=device)+ return {"matches0": matches, "matching_scores0": torch.zeros_like(matches, dtype=torch.float64)}++ monkeypatch.setattr("kornia.feature.integrated.LightGlue", _RecordingLightGlue)+ degrees = torch.tensor([[-90.0, -45.0, 30.0], [-135.0, 60.0, -30.0]], device=device, dtype=torch.float64)+ xy = torch.rand(2, 3, 2, device=device, dtype=torch.float64) * 50+ scale = torch.full((2, 3, 1, 1), 4.0, device=device, dtype=torch.float64)+ lafs = laf_from_center_scale_ori(xy, scale, degrees.unsqueeze(-1))+ descriptors = torch.rand(3, 128, device=device, dtype=torch.float64)+ LightGlueMatcher("disk")(descriptors, descriptors, lafs[:1], lafs[1:])+ # Negative angles move into [0, 2 pi); the float32 pi added 1.7e-7 rad too much.+ expected = torch.remainder(torch.deg2rad(degrees), 2 * torch.pi)+ self.assert_close(seen["image0"]["oris"], expected[:1], rtol=0.0, atol=1e-12)+ self.assert_close(seen["image1"]["oris"], expected[1:], rtol=0.0, atol=1e-12)++class TestMatchSteererGlobal(BaseTester):@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32), (32, 32, 8)])@pytest.mark.parametrize("matching_mode", ["nn", "mnn", "snn", "smnn"])diff --git a/tests/feature/test_sift_pyramid.py b/tests/feature/test_sift_pyramid.pyindex a510915dc..b2178f51d 100644--- a/tests/feature/test_sift_pyramid.py+++ b/tests/feature/test_sift_pyramid.py@@ -40,6 +40,15 @@ class TestSIFTDescriptorFromPyramid(BaseTester):assert empty_lafs.shape == (2, 0, 2, 3)assert empty_descriptors.shape == (2, 0, 128)+ def test_float64_identity_remap_keeps_histogram_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ histograms = torch.rand(1, 3, 8, 5, device=device, dtype=torch.float64)+ affine = torch.eye(2, device=device, dtype=torch.float64).expand(1, 3, 2, 2)+ remapped = SIFTDescriptorFromPyramid._remap_angles(histograms, affine, 8)+ # The float32 pi moved 2.2e-7 of every bin past pi into its lower neighbour.+ self.assert_close(remapped, histograms, rtol=0.0, atol=1e-12)+def test_horizontal_gradient_keeps_orientation(self, device, dtype):image = torch.arange(64, device=device, dtype=dtype).reshape(1, 1, 1, 64).expand(1, 1, 64, 64)xy = torch.tensor([[[32.0, 32.0]]], device=device, dtype=dtype)@@ -49,6 +58,21 @@ class TestSIFTDescriptorFromPyramid(BaseTester):get_laf_orientation(oriented), torch.zeros(1, 1, 1, device=device, dtype=dtype), rtol=0.0, atol=1e-2)+ def test_float64_vertical_gradient_orientation_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ # The peak lands on orientation bin 9 of 36, so the bin-to-angle scale decides the angle; the+ # horizontal case above sits on bin 0 and cannot see it.+ image = torch.arange(64, device=device, dtype=torch.float64).reshape(1, 1, 64, 1).expand(1, 1, 64, 64)+ xy = torch.tensor([[[32.0, 32.0]]], device=device, dtype=torch.float64)+ lafs = laf_from_center_scale_ori(xy, torch.full((1, 1, 1, 1), 8.0, device=device, dtype=torch.float64))+ oriented, _ = (+ SIFTDescriptorFromPyramid(rootsift=False).to(device, torch.float64).orient_and_describe(image, lafs)+ )+ angle = torch.deg2rad(get_laf_orientation(oriented)).flatten()+ # The float32 pi put this angle 1.6e-8 rad off; the residual here is about 6e-11.+ self.assert_close(angle, torch.full_like(angle, -torch.pi / 2), rtol=0.0, atol=1e-9)+def test_flat_input_has_finite_backward(self, device, dtype):image = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype, requires_grad=True)xy = torch.tensor([[[32.0, 32.0]]], device=device, dtype=dtype)diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.pyindex 2dc10cdd0..b85393666 100644--- a/tests/feature/test_sift_scale_space.py+++ b/tests/feature/test_sift_scale_space.py@@ -55,6 +55,28 @@ class TestSharedSIFTScaleSpace(BaseTester):expected[2, 1:3, 2:4] = 0.5self.assert_close(actual, expected, atol=2e-6, rtol=2e-6)+ def test_float64_bin_centre_angles_fill_one_bin_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ angle = torch.arange(36, device=device, dtype=torch.float64).view(1, 36, 1) * (2 * torch.pi / 36)+ # The gradient angles arrive in [2 pi, 4 pi), where the `%` takes part as well.+ for offset in (0.0, 2 * torch.pi):+ histogram = _SIFTScaleSpaceDescriptor._angular_histogram(torch.ones_like(angle), angle + offset, 36)+ # The float32 pi in the bin scale leaked up to 9.7e-7 of the upper bins into their lower neighbour.+ eye = torch.eye(36, device=device, dtype=torch.float64)+ self.assert_close(histogram[0], eye, rtol=0.0, atol=1e-12)++ def test_float64_bin_centre_angles_fill_one_descriptor_bin_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ # One sample per frame at the patch centre, whose angle sits on one of the 8 bin centres.+ angle = 2 * torch.pi + torch.arange(8, device=device, dtype=torch.float64).view(1, 8, 1) * (torch.pi / 4)+ centre = torch.zeros(1, device=device, dtype=torch.float64)+ votes = _SIFTScaleSpaceDescriptor._descriptor_histograms(torch.ones_like(angle), angle, centre, centre)+ # Summing the 16 spatial cells leaves each frame's angular histogram.+ histogram = votes.reshape(8, 16, 8).sum(1)+ self.assert_close(histogram, torch.eye(8, device=device, dtype=torch.float64), rtol=0.0, atol=1e-12)+def test_histogram_gradcheck(self, device):if device.type == "mps":pytest.skip("MPS does not support float64 gradcheck")@@ -199,6 +221,20 @@ class TestSharedSIFTScaleSpace(BaseTester):self.assert_close(desc[0, 0], desc[0, 1], atol=0.002, rtol=0.002)self.assert_close(desc.norm(dim=-1), torch.ones(1, 2, device=device, dtype=dtype))+ def test_float64_vertical_gradient_orientation_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ axis = torch.arange(64, device=device, dtype=torch.float64)+ pyramid = [torch.stack([axis[None, :].expand(64, 64), axis[:, None].expand(64, 64)])[None, None]]+ lafs = torch.tensor([[[[6.0, 0, 16], [0, 6.0, 16]]] * 2], device=device, dtype=torch.float64)+ octaves = torch.zeros(1, 2, device=device, dtype=torch.long)+ levels = torch.tensor([[0, 1]], device=device)+ oriented, _ = _SIFTScaleSpaceDescriptor()(pyramid, lafs, octaves, levels)+ angles = torch.deg2rad(get_laf_orientation(oriented)).flatten()+ # The vertical layer peaks on orientation bin 9 of 36; the float32 pi put its angle 1.6e-8 rad off.+ expected = torch.tensor([0.0, -torch.pi / 2], device=device, dtype=torch.float64)+ self.assert_close(angles, expected, rtol=0.0, atol=1e-9)+def test_mask_padding_and_empty(self, device, dtype):feature = SIFTFeatureScaleSpace(4, descriptor_backend="pyramid").to(device, dtype)image = torch.rand(2, 1, 40, 40, device=device, dtype=dtype)diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.pyindex b7b1c6d1b..587dc306f 100644--- a/tests/feature/test_siftdesc.py+++ b/tests/feature/test_siftdesc.py@@ -21,6 +21,7 @@ import torchfrom kornia.feature.siftdesc import (DenseSIFTDescriptor,SIFTDescriptor,+ _dense_sift_histograms_from_gradients,get_sift_bin_ksize_stride_pad,get_sift_pooling_kernel,)@@ -74,6 +75,19 @@ class TestSIFTDescriptor(BaseTester):sift = SIFTDescriptor(15).to(device, dtype)self.gradcheck(sift, (patches,), nondet_tol=1e-4)+ def test_float64_axis_ramps_vote_in_one_bin_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ # Every gradient of a ramp along +x (-x) points at angle 0 (pi), the centre of angular bin 0 (4).+ axis = torch.arange(32, device=device, dtype=torch.float64)+ patches = torch.stack([axis.expand(32, 32), -axis.expand(32, 32)]).unsqueeze(1)+ descriptors = SIFTDescriptor(32, rootsift=False).to(device, torch.float64)(patches).view(2, 8, 16)+ expected = torch.zeros_like(descriptors)+ expected[0, 0], expected[1, 4] = descriptors[0, 0], descriptors[1, 4]+ # The float32 pi in the bin scale leaked every vote into the bin below (4.3e-8 after normalisation).+ self.assert_close(descriptors, expected, rtol=0.0, atol=1e-12)+ assert (descriptors[0, 0] > 0.1).all() and (descriptors[1, 4] > 0.1).all()+@pytest.mark.skip("Compiled functions can't take variable number")def test_jit(self, device, dtype):B, C, H, W = 1, 1, 32, 32@@ -385,3 +399,17 @@ class TestDenseSIFTDescriptor(BaseTester):batch_size, channels, height, width = 1, 1, 16, 16patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)self.gradcheck(DenseSIFTDescriptor(4, 2, 2), (patches), nondet_tol=1e-4)++ def test_float64_bin_centre_gradient_votes_in_one_bin_5127(self, device):+ if device.type == "mps":+ pytest.skip("float64 is unavailable on MPS")+ bins = 8+ angle = torch.arange(bins, device=device, dtype=torch.float64) * (2 * torch.pi / bins)+ # Unit gradients at the bin centres, plus one zero gradient that votes nowhere.+ gx = torch.cat([torch.cos(angle), angle.new_zeros(1)]).view(1, 1, 1, bins + 1)+ gy = torch.cat([torch.sin(angle), angle.new_zeros(1)]).view(1, 1, 1, bins + 1)+ histograms = _dense_sift_histograms_from_gradients(gx, gy, bins, eps=0.0)+ expected = torch.zeros(bins, bins + 1, device=device, dtype=torch.float64)+ expected[:, :bins] = torch.eye(bins, device=device, dtype=torch.float64)+ # The float32 pi in the orientation offset and the bin scale leaked up to 1e-7 into the lower bin.+ self.assert_close(histograms[0, :, 0], expected, rtol=0.0, atol=1e-12)