π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): refine pyramid SIFT orientation without image patches (#5762)
Dmytro Mishkin192170e01243
diff --git a/changelog.d/5762.fixed.md b/changelog.d/5762.fixed.mdnew file mode 100644index 000000000..6b6e89a33--- /dev/null+++ b/changelog.d/5762.fixed.md@@ -0,0 +1 @@+`SIFTFeature(descriptor_backend="pyramid")` and `SIFTDescriptorFromPyramid` now estimate orientation from smoothed, densely sampled gradient maps without extracting image patches. Descriptor histograms are independent of orientation resolution, and separable spatial pooling reduces CPU extraction cost.diff --git a/docs/source/feature.local_features.rst b/docs/source/feature.local_features.rstindex f52b19495..c17e06825 100644--- a/docs/source/feature.local_features.rst+++ b/docs/source/feature.local_features.rst@@ -38,6 +38,15 @@ Local features (detector and descriptor together).. autoclass:: SIFTFeature:members: forward+``SIFTFeature(descriptor_backend="pyramid")`` uses shared image-pyramid maps+without extracting image patches. Orientation integrates a smoothed gradient+field before angular binning, separately from the descriptor histogram maps.+The default orientation histogram and global descriptor maps each have 36 bins,+with independent resolutions. Descriptor maps are pooled with separable tent+filters and remapped into 8 angular bins per local spatial cell. Both stages share+the image pyramid, which is built independently of the detector. The default+``patch`` backend is unchanged.+The scale-space SIFT preset supports ``descriptor_backend="pyramid"`` forspecialized sparse extraction from the detector's Gaussian pyramid::diff --git a/kornia/feature/sift/pyramid.py b/kornia/feature/sift/pyramid.pyindex ce6aa054e..bf71c8540 100644--- a/kornia/feature/sift/pyramid.py+++ b/kornia/feature/sift/pyramid.py@@ -34,8 +34,13 @@ from kornia.feature.laf import (laf_is_valid,rotate_laf,)-from kornia.feature.siftdesc import _dense_sift_histograms_from_gradients, _rootsift, get_sift_pooling_kernel-from kornia.filters import get_gaussian_kernel2d, spatial_gradient+from kornia.feature.siftdesc import (+ _dense_sift_histograms_from_gradients,+ _gradient_magnitude_orientation,+ _rootsift,+ get_sift_pooling_kernel,+)+from kornia.filters import gaussian_blur2d, get_gaussian_discrete_kernel1d, get_gaussian_kernel2d, spatial_gradientfrom kornia.geometry.transform import pyrdown@@ -52,9 +57,12 @@ class SIFTDescriptorFromPyramid(nn.Module):<https://www.vlfeat.org/api/dsift.html>`_ with orientation-relative spatial andangular binning as in OpenCV's `SIFT implementation<https://github.com/opencv/opencv/blob/4.x/modules/features2d/src/sift.simd.hpp>`_:- gradients are binned once at each pyramid octave, then local orientation and- descriptor histograms are sampled from those maps. Unlike patch-wise SIFT,- no image patch is resampled before either stage.+ descriptor gradients are binned once at each pyramid octave. Orientation uses+ a separate gradient field, smoothed with a one-pixel Gaussian at each octave,+ and integrates 19x19 gradient samples with a Gaussian of sigma one third of+ the LAF scale. Gradients are transformed into the frame before orientation+ histogramming, avoiding interpolation of already quantized angular bins.+ Unlike patch-wise SIFT, no image patch is resampled before either stage.For a general affine LAF the global angular bins are remapped through theLAF's ``A.T`` gradient pullback, including its direction-dependent magnitude.@@ -72,6 +80,8 @@ class SIFTDescriptorFromPyramid(nn.Module):rootsift: If ``True``, apply RootSIFT after clipping and normalization.clipval: Descriptor clipping threshold.orientation_bins: Number of bins for dominant-orientation assignment.+ Independent of the descriptor's global histogram resolution (at least 36+ bins), which is remapped to ``num_ang_bins`` in each local frame.Shape:- image: :math:`(B, 1, H, W)`@@ -102,13 +112,17 @@ class SIFTDescriptorFromPyramid(nn.Module):self.rootsift = rootsiftself.clipval = clipvalself.orientation_bins = orientation_bins+ self._descriptor_bins = max(36, num_ang_bins)self.eps = 1e-10pooling = get_sift_pooling_kernel(spatial_bin_size).reshape(1, 1, spatial_bin_size, spatial_bin_size)self.register_buffer("descriptor_pooling_kernel", pooling)- # A 9x9 grid approximates integration over the roughly 19-pixel octave- # support while keeping sparse orientation assignment inexpensive.- weighting = get_gaussian_kernel2d((9, 9), (9.0 / 6.0, 9.0 / 6.0), True)- self.register_buffer("orientation_weighting", weighting.reshape(1, 1, 9, 9), persistent=False)+ # Match the patch orienter's Gaussian support while integrating gradients+ # before angular binning, without extracting image patches.+ weighting = get_gaussian_kernel2d((19, 19), (19.0 / 6.0, 19.0 / 6.0), True)+ self.register_buffer("orientation_weighting", weighting.reshape(1, 1, 19, 19), persistent=False)+ self.register_buffer(+ "orientation_smoothing", get_gaussian_discrete_kernel1d(5, 1.6).reshape(1, 1, 5), persistent=False+ )@staticmethoddef _num_pyramid_levels(image: torch.Tensor) -> int:@@ -208,38 +222,42 @@ class SIFTDescriptorFromPyramid(nn.Module):def _orientation(self,pyramid: list[torch.Tensor],- histograms: list[torch.Tensor | None],+ gradients: list[torch.Tensor | None],lafs: torch.Tensor,levels: torch.Tensor,) -> torch.Tensor:b, n = lafs.shape[:2]result = lafs.new_zeros(b, n, self.orientation_bins)- for level_index, (image, hist) in enumerate(zip(pyramid, histograms)):- if hist is None:- # No valid LAF selected this octave, so it carries no histogram map.+ for level_index, (image, grad) in enumerate(zip(pyramid, gradients)):+ if grad is None:+ # No valid LAF selected this octave, so it carries no gradient map.continue- weighting = self.orientation_weighting.to(dtype=hist.dtype, device=hist.device).reshape(1, 1, 1, -1)+ weighting = self.orientation_weighting.to(lafs).reshape(1, 1, -1)for batch_index in range(b):selected = (levels[batch_index] == level_index).nonzero().flatten()if selected.numel() == 0:continuecurrent_lafs = lafs[batch_index : batch_index + 1, selected]level_lafs = self._laf_at_level(current_lafs, pyramid, level_index)- # Histogram remapping is linear, so weight the sampled support before- # the per-LAF angular pullback and avoid a 9x9 remapped temporary.- sampled = (- self._sample(- hist[batch_index : batch_index + 1], image[batch_index : batch_index + 1], level_lafs, 9- )- * weighting- ).sum(-1)- mapped = self._remap_angles(- sampled.unsqueeze(-1), level_lafs[..., :2, :2], self.orientation_bins- ).squeeze(-1)- result[batch_index, selected] = mapped[0].to(result.dtype)+ sampled = self._sample(+ grad[batch_index : batch_index + 1], image[batch_index : batch_index + 1], level_lafs, 19+ )+ # Pull gradients back through the actual affine frame before+ # binning. Quantized global directions lose cancellation under+ # interpolation and need not represent the local gradient.+ local = torch.einsum("bnji,bnjs->bnis", level_lafs[..., :2, :2], sampled.to(level_lafs.dtype))+ magnitude, angle = _gradient_magnitude_orientation(local[:, :, 0], local[:, :, 1], self.eps)+ position = (angle % (2.0 * math.pi)) * self.orientation_bins / (2.0 * math.pi)+ lower = position.floor().long() % self.orientation_bins+ upper_weight = position - position.floor()+ magnitude = magnitude * weighting+ histogram = magnitude.new_zeros(1, selected.numel(), self.orientation_bins)+ histogram.scatter_add_(-1, lower, magnitude * (1.0 - upper_weight))+ histogram.scatter_add_(-1, (lower + 1) % self.orientation_bins, magnitude * upper_weight)+ result[batch_index, selected] = histogram[0].to(result.dtype)smoothed = F.conv1d(F.pad(result.reshape(b * n, 1, -1), (2, 2), mode="circular"),- result.new_tensor([1, 4, 6, 4, 1]).view(1, 1, -1) / 16.0,+ self.orientation_smoothing.to(result),)smoothed = smoothed.squeeze(1)index = smoothed.argmax(dim=1)@@ -252,6 +270,79 @@ class SIFTDescriptorFromPyramid(nn.Module):angle = index.to(lafs.dtype).reshape(b, n) + offset.reshape(b, n)return 2.0 * math.pi * angle / float(self.orientation_bins)+ def _pool_histograms(self, hist: torch.Tensor) -> torch.Tensor:+ """Pool spatial cells without allocating a two-dimensional convolution workspace."""+ if (+ hist.device.type == "cpu"+ and not torch.is_grad_enabled()+ and not torch.compiler.is_compiling()+ and self.spatial_bin_size % 2 == 0+ ):+ return self._pool_histograms_cpu_inference(hist)+ kernel = self.descriptor_pooling_kernel.to(dtype=hist.dtype, device=hist.device)+ # The tent kernel is separable. Two one-dimensional convolutions+ # avoid a full-resolution ksize**2 im2col workspace on CPU.+ center = self.spatial_bin_size // 2+ horizontal = kernel[:, :, center : center + 1, :]+ vertical = kernel[:, :, :, center : center + 1] / kernel[:, :, center : center + 1, center : center + 1]+ pooled = F.conv2d(hist.reshape(-1, 1, hist.shape[-2], hist.shape[-1]), horizontal, padding=(0, center))+ pooled = F.conv2d(pooled, vertical, padding=(center, 0)).reshape(+ hist.shape[0],+ hist.shape[1],+ hist.shape[-2] + (self.spatial_bin_size % 2 == 0),+ hist.shape[-1] + (self.spatial_bin_size % 2 == 0),+ )+ if self.spatial_bin_size % 2 == 0:+ # An even pooling kernel is centred between pixel centres. Average+ # its four neighbours so map index (y, x) stays registered to image+ # pixel (y, x), which is the LAF/grid-sampling convention.+ hist = 0.25 * (+ pooled[:, :, :-1, :-1] + pooled[:, :, 1:, :-1] + pooled[:, :, :-1, 1:] + pooled[:, :, 1:, 1:]+ )+ else:+ hist = pooled+ return hist++ def _pool_histograms_cpu_inference(self, hist: torch.Tensor) -> torch.Tensor:+ """CPU inference tent pooling with reusable accumulation maps.++ The differentiable convolution path above remains the fallback. ``add_``+ with a scalar coefficient avoids allocating a product and sum map for+ every separable-kernel tap.+ """+ size = self.spatial_bin_size+ center = size // 2+ weight = self.descriptor_pooling_kernel.to(hist)[0, 0, center]+ height, width = hist.shape[-2:]+ padded = F.pad(hist, (center, center, 0, 0))+ horizontal = hist.new_empty(*hist.shape[:-1], width + 1)+ # Row tiles keep the 36-bin source and output working sets within the+ # CPU cache instead of streaming the complete map once per tent tap.+ weights = weight.tolist()+ tile_rows = 32+ for row_start in range(0, height, tile_rows):+ row_end = min(row_start + tile_rows, height)+ output = horizontal[..., row_start:row_end, :]+ torch.mul(padded[..., row_start:row_end, : width + 1], weights[0], out=output)+ for index, value in enumerate(weights[1:], 1):+ output.add_(padded[..., row_start:row_end, index : index + width + 1], alpha=value)+ padded = F.pad(horizontal, (0, 0, center, center))+ normalizer = weight[center]+ weights = (weight / normalizer).tolist()+ output = hist.new_empty(*hist.shape)+ for row_start in range(0, height, tile_rows):+ row_end = min(row_start + tile_rows, height)+ # One extra vertical row supplies the lower neighbours for the+ # registered 2x2 average, so no full (B, C, H+1, W+1) map exists.+ vertical = hist.new_empty(*hist.shape[:-2], row_end - row_start + 1, width + 1)+ torch.mul(padded[..., row_start : row_end + 1, :], weights[0], out=vertical)+ for index, value in enumerate(weights[1:], 1):+ vertical.add_(padded[..., row_start + index : row_end + index + 1, :], alpha=value)+ registered = output[..., row_start:row_end, :]+ torch.add(vertical[..., :-1, :-1], vertical[..., 1:, :-1], out=registered)+ registered.add_(vertical[..., :-1, 1:]).add_(vertical[..., 1:, 1:]).mul_(0.25)+ return output+def _descriptors(self,pyramid: list[torch.Tensor],@@ -266,24 +357,7 @@ class SIFTDescriptorFromPyramid(nn.Module):# Skip before pooling: an unused octave's (B, bins, H, W) map is# both the largest allocation here and the most expensive conv2d.continue- kernel = self.descriptor_pooling_kernel.to(dtype=hist.dtype, device=hist.device)- pooled = F.conv2d(- hist.reshape(-1, 1, hist.shape[-2], hist.shape[-1]), kernel, padding=self.spatial_bin_size // 2- ).reshape(- hist.shape[0],- hist.shape[1],- hist.shape[-2] + (self.spatial_bin_size % 2 == 0),- hist.shape[-1] + (self.spatial_bin_size % 2 == 0),- )- if self.spatial_bin_size % 2 == 0:- # An even pooling kernel is centred between pixel centres. Average- # its four neighbours so map index (y, x) stays registered to image- # pixel (y, x), which is the LAF/grid-sampling convention.- hist = 0.25 * (- pooled[:, :, :-1, :-1] + pooled[:, :, 1:, :-1] + pooled[:, :, :-1, 1:] + pooled[:, :, 1:, 1:]- )- else:- hist = pooled+ hist = self._pool_histograms(hist)for batch_index in range(b):selected = (levels[batch_index] == level_index).nonzero().flatten()if selected.numel() == 0:@@ -375,24 +449,31 @@ class SIFTDescriptorFromPyramid(nn.Module):return lafs.to(laf_dtype), descriptors.to(image_dtype)pyramid = self._pyramid(image, max_level + 1)histograms: list[torch.Tensor | None] = []+ orientation_gradients: list[torch.Tensor | None] = []for level_index, level_image in enumerate(pyramid):# An intermediate octave still has to be resampled to reach the ones# above it, but binning its gradients is pure waste when no LAF- # samples it: the map is (B, orientation_bins, H, W) at full octave+ # samples it: the map is (B, descriptor_bins, H, W) at full octave# resolution and is pooled again per descriptor level.if not level_used[level_index]:histograms.append(None)+ orientation_gradients.append(None)continuegradients = spatial_gradient(level_image, "diff")histograms.append(_dense_sift_histograms_from_gradients(- gradients[:, :, 0], gradients[:, :, 1], self.orientation_bins, self.eps+ gradients[:, :, 0], gradients[:, :, 1], self._descriptor_bins, self.eps))+ if not upright:+ # Suppress pixel noise before sampling the shared gradient field.+ # No image patches or per-LAF image gradients are constructed.+ smoothed = gaussian_blur2d(level_image, (7, 7), (1.0, 1.0), border_type="replicate")+ orientation_gradients.append(spatial_gradient(smoothed, "diff")[:, 0])if upright:oriented_lafs = safe_lafselse:- angles = self._orientation(pyramid, histograms, safe_lafs, levels)+ angles = self._orientation(pyramid, orientation_gradients, safe_lafs, levels)# Kornia's LAF rotation is clockwise in image coordinates. Rotate the# frame against its dominant local gradient so it becomes horizontal.oriented_lafs = rotate_laf(safe_lafs, -torch.rad2deg(angles).unsqueeze(-1))diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex df288716e..6fea17154 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -88,7 +88,12 @@ def _dense_sift_histograms_from_gradients(bo1 = (bo0 + 1) % num_ang_binsw0 = (1.0 - w1) * magw1 = w1 * mag- return torch.cat([(bo0 == i).to(gx.dtype) * w0 + (bo1 == i).to(gx.dtype) * w1 for i in range(num_ang_bins)], 1)+ # Each gradient votes into only two bins. Scatter those votes directly,+ # avoiding a full-image equality mask and temporary for every angular bin.+ histograms = gx.new_zeros(gx.shape[0], num_ang_bins, gx.shape[-2], gx.shape[-1])+ histograms.scatter_add_(1, bo0.long() % num_ang_bins, w0)+ histograms.scatter_add_(1, bo1.long() % num_ang_bins, w1)+ return histogramsdef _dense_sift_histograms(input: torch.Tensor, num_ang_bins: int, eps: float) -> torch.Tensor:diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex 410e60b62..a28a52c86 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -856,6 +856,28 @@ class TestLocalFeatureMatcher(BaseTester):class TestSIFTPyramidBackend(BaseTester):+ def test_sift_pyramid_does_not_extract_image_patches(self, device, dtype, monkeypatch):+ def unexpected_patch(*args, **kwargs):+ raise AssertionError("The pyramid backend must operate on shared maps without image patches")++ monkeypatch.setattr(kornia.feature.LAFOrienter, "forward", unexpected_patch)+ monkeypatch.setattr(kornia.feature.LAFDescriptor, "forward", unexpected_patch)+ original_sample = kornia.feature.SIFTDescriptorFromPyramid._sample+ sampled_channels = []++ def sample_maps(maps, *args):+ assert maps.shape[1] != 1, "Sparse sampling must not extract patches from the grayscale image"+ sampled_channels.append(maps.shape[1])+ return original_sample(maps, *args)++ monkeypatch.setattr(kornia.feature.SIFTDescriptorFromPyramid, "_sample", staticmethod(sample_maps))+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ feature = SIFTFeature(3, descriptor_backend="pyramid").to(device, dtype).eval()+ lafs, _, descriptors = feature(image)+ assert lafs.shape == (1, 3, 2, 3)+ assert torch.isfinite(descriptors).all()+ assert set(sampled_channels) == {2, feature.descriptor._descriptor_bins}+@pytest.mark.parametrize("preset", [kornia.feature.SIFTFeature, kornia.feature.SIFTFeatureScaleSpace])@pytest.mark.parametrize("upright", [False, True])def test_sparse_output_and_real_descriptor(self, device, dtype, preset, upright):diff --git a/tests/feature/test_sift_pyramid.py b/tests/feature/test_sift_pyramid.pyindex b2178f51d..0f595fd55 100644--- a/tests/feature/test_sift_pyramid.py+++ b/tests/feature/test_sift_pyramid.py@@ -26,6 +26,44 @@ from testing.base import BaseTester, supports_reflect_paddingclass TestSIFTDescriptorFromPyramid(BaseTester):+ def test_orientation_rejects_pixel_oscillation_5748(self, device, dtype):+ # A horizontal ramp with a four-pixel vertical oscillation. Integrating+ # smoothed gradients preserves the ramp; the former sparse histogram+ # sampling aliases the oscillation into an orientation about -51 degrees.+ axis = torch.arange(65, device=device, dtype=torch.float32)+ image = (0.2 * axis[None, :] + 0.25 * torch.sin(torch.pi / 2 * (axis[:, None] - 32)))[None, None]+ image = image.to(dtype)+ lafs = torch.tensor([[[[8.0, 0.0, 32.0], [0.0, 8.0, 32.0]]]], device=device, dtype=dtype)+ oriented, _ = SIFTDescriptorFromPyramid().to(device, dtype).orient_and_describe(image, lafs)+ self.assert_close(+ get_laf_orientation(oriented), torch.zeros(1, 1, 1, device=device, dtype=dtype), rtol=0.0, atol=5.0+ )++ @pytest.mark.parametrize("size", [1, 3, 4, 8, 9])+ @pytest.mark.parametrize("inference", [False, True])+ def test_separable_pooling_matches_full_kernel(self, device, dtype, size, inference):+ feature = SIFTDescriptorFromPyramid(spatial_bin_size=size).to(device, dtype)+ # Cross the CPU pooling tile boundary and leave a partial final tile.+ hist = torch.rand(2, 36, 37, 19, device=device, dtype=dtype)+ # The public descriptor promotes reduced-precision images before pooling.+ if dtype in (torch.float16, torch.bfloat16):+ hist = hist.float()+ pooled = torch.nn.functional.conv2d(+ hist.reshape(-1, 1, 37, 19), feature.descriptor_pooling_kernel.to(hist), padding=size // 2+ )+ if size % 2 == 0:+ pooled = torch.nn.functional.avg_pool2d(pooled, 2, stride=1)+ with torch.set_grad_enabled(not inference):+ actual = feature._pool_histograms(hist)+ self.assert_close(actual.to(dtype), pooled.reshape_as(hist).to(dtype))++ def test_orientation_bins_do_not_change_supplied_frame_descriptors(self, device, dtype):+ image = torch.rand(1, 1, 48, 48, device=device, dtype=dtype)+ lafs = torch.tensor([[[[8.0, 2.0, 24.0], [-2.0, 8.0, 24.0]]]], device=device, dtype=dtype)+ coarse = SIFTDescriptorFromPyramid(orientation_bins=18).to(device, dtype)+ fine = SIFTDescriptorFromPyramid(orientation_bins=72).to(device, dtype)+ self.assert_close(coarse(image, lafs), fine(image, lafs))+def test_shape_norm_and_empty(self, device, dtype):image = torch.rand(2, 1, 64, 80, device=device, dtype=dtype)xy = torch.tensor([[[24.0, 24.0], [48.0, 40.0]], [[20.0, 30.0], [52.0, 36.0]]], device=device, dtype=dtype)@@ -162,7 +200,8 @@ class TestSIFTDescriptorFromPyramid(BaseTester):monkeypatch.setattr(implementation, "spatial_gradient", gradient)oriented, descriptors = feature.orient_and_describe(image, lafs)- assert shapes == [(40, 40)]+ # Description and orientation use distinct gradient maps at the used octave.+ assert shapes == [(40, 40), (40, 40)]# Skipping the unused octaves must not change a single output value.# Only CPU can be held to bitwise equality: the histogram scatter uses@@ -241,11 +280,23 @@ class TestSIFTDescriptorFromPyramid(BaseTester):assert torch.isfinite(image.grad).all()assert torch.isfinite(lafs.grad).all()- def test_gradcheck(self, device):+ @pytest.mark.parametrize("upright", [False, True])+ def test_gradcheck(self, device, upright):image = torch.rand(1, 1, 8, 8, device=device, dtype=torch.float64)lafs = torch.tensor([[[[2.0, 0.0, 3.0], [0.0, 2.0, 3.0]]]], device=device, dtype=torch.float64)feature = SIFTDescriptorFromPyramid(spatial_bin_size=3).to(device, torch.float64)- self.gradcheck(lambda image: feature(image, lafs), (image,))+ self.gradcheck(lambda image: feature.orient_and_describe(image, lafs, upright=upright)[1], (image,))++ @pytest.mark.parametrize("inference", [False, True])+ def test_dynamo(self, device, dtype, torch_optimizer, inference):+ image = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)+ lafs = torch.tensor([[[[6.0, 0.0, 16.0], [0.0, 6.0, 16.0]]]], device=device, dtype=dtype)+ feature = SIFTDescriptorFromPyramid().to(device, dtype)+ with torch.set_grad_enabled(not inference):+ expected_lafs, expected_descriptors = feature.orient_and_describe(image, lafs)+ actual_lafs, actual_descriptors = torch_optimizer(feature.orient_and_describe)(image, lafs)+ self.assert_close(actual_lafs, expected_lafs)+ self.assert_close(actual_descriptors, expected_descriptors)def test_empty_batch(self, device, dtype):image = torch.empty(0, 1, 40, 40, device=device, dtype=dtype)diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.pyindex 738adf8b7..ce4efff61 100644--- a/tests/feature/test_siftdesc.py+++ b/tests/feature/test_siftdesc.py@@ -601,10 +601,10 @@ class TestDenseSIFTDescriptor(BaseTester):patches = 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):+ @pytest.mark.parametrize("bins", [8, 36])+ def test_float64_bin_centre_gradient_votes_in_one_bin_5127(self, device, bins):if device.type == "mps":pytest.skip("float64 is unavailable on MPS")- bins = 8angle = 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)