π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): empty batch through ScaleSpaceDetector and the patch descriptors; linked outputs for a no-candidate image (#6052)
Dmytro Mishkinda6093ab2636
diff --git a/changelog.d/6052.fixed.md b/changelog.d/6052.fixed.mdnew file mode 100644index 000000000..2924eb0b4--- /dev/null+++ b/changelog.d/6052.fixed.md@@ -0,0 +1 @@+`ScaleSpaceDetector` (`forward` and `detect`) and the patch descriptors `SIFTDescriptor`, `HardNet`, `HardNet8`, `HyNet`, `TFeat` and `SOSNet` accept an empty batch and return empty outputs of the documented shapes: responses `(0, N)` and LAFs `(0, N, 2, 3)` from the detector, descriptors `(0, D)` from the descriptors. So do `LocalFeature`, `SIFTFeatureScaleSpace` and `get_laf_descriptors` on zero images. They raised an unrelated reshape `RuntimeError`; an invalid input still raises what the same invalid non-empty input raises. A `ScaleSpaceDetector` call on one image with no detected candidates returns responses linked to autograd; a backward through them raised.diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex 276f1f2c0..76e22ca28 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -146,7 +146,7 @@ class HardNet(nn.Module):if input.device.type == "cpu" and input.dtype == torch.float32:x_norm = x_norm.to(memory_format=torch.channels_last)x_features: torch.Tensor = self.features(x_norm)- x_out = x_features.view(x_features.size(0), -1)+ x_out = x_features.flatten(1)# A constant patch drives the features to zero; the default `eps` is not representable in# float16, where the normalisation would then return NaN.return _l2_normalize(x_out, dim=1)@@ -261,7 +261,7 @@ class HardNet8(nn.Module):x_features: torch.Tensor = self.features(x_norm)mean: torch.Tensor = torch.jit.annotate(torch.Tensor, self.mean)components: torch.Tensor = torch.jit.annotate(torch.Tensor, self.components)- x_flat = x_features.view(x_features.size(0), -1)+ x_flat = x_features.flatten(1)x_prePCA = _l2_normalize(x_flat, dim=1)pca = torch.mm(x_prePCA - mean, components)return _l2_normalize(pca, dim=1)diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.pyindex 46e0247ec..4ef6258d2 100644--- a/kornia/feature/hynet.py+++ b/kornia/feature/hynet.py@@ -349,4 +349,4 @@ class HyNet(nn.Module):x = self.desc_norm(x.float() + self.eps_l2_norm).to(x.dtype)else:x = self.desc_norm(x + self.eps_l2_norm)- return x.view(x.size(0), -1)+ return x.flatten(1)diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex 8b5d1932d..66f728f3d 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -189,7 +189,9 @@ def get_laf_descriptors(# So we need to reshape a bit :)B, N, CH, H, W = patches.size()# `reshape`, not `view`: a descriptor may return a non-contiguous output, e.g. a channels-last convolution.- return _run_descriptor(patch_descriptor, patches.view(B * N, CH, H, W)).reshape(B, N, -1)+ # The width is spelled out: a `-1` is ambiguous when the batch is empty.+ descriptors = _run_descriptor(patch_descriptor, patches.view(B * N, CH, H, W))+ return descriptors.reshape(B, N, descriptors.shape[1:].numel())class LAFDescriptor(nn.Module):diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex 6531442e5..798495136 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -786,6 +786,16 @@ def _extract_patches_from_pyramid_levelwise(return out+def _empty_patches(img: torch.Tensor, laf: torch.Tensor, B: int, N: int, PS: int) -> torch.Tensor:+ r"""Zero patches ``(B, N, CH, PS, PS)`` of an empty batch or an empty LAF set, linked to ``img`` and ``laf``.++ The sum of a zero-width slice is a zero that autograd traces back to both inputs, so a loss on the+ patches backpropagates (a zero gradient) instead of raising on a tensor with no graph.+ """+ link = img.flatten()[:0].sum() + laf.flatten()[:0].sum().to(img.dtype)+ return torch.zeros(B, N, img.shape[1], PS, PS, device=img.device, dtype=img.dtype) + link++def extract_patches_simple(img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True) -> torch.Tensor:@@ -818,7 +828,7 @@ def extract_patches_simple(_, ch, h, w = img.size()B, N, _, _ = laf.size()if B == 0 or N == 0:- return torch.zeros(B, N, ch, PS, PS, device=img.device, dtype=img.dtype)+ return _empty_patches(img, laf, B, N, PS)# See `extract_patches_from_pyramid`: a non-finite value anywhere in a training-time LAF# frame, including only its center, would reach `grid_sample` as an invalid grid, and the CPU# border-padding backward kernel can segfault on it. Mark the whole frame invalid and@@ -884,7 +894,7 @@ def extract_patches_from_pyramid(B, N, _, _ = laf.size()_, ch, h, w = img.size()if B == 0 or N == 0:- return torch.zeros(B, N, ch, PS, PS, device=img.device, dtype=img.dtype)+ return _empty_patches(img, laf, B, N, PS)# max_level is a compile-time constant for static image shapes.max_level = min(h, w) // PS# Build exactly the pyramid that can provide a PS-sized patch. ``pyrdown`` defines its outputdiff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 82346c3b0..a73420604 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -179,7 +179,7 @@ def _zero_unfilled(lafs: torch.Tensor, filled: torch.Tensor) -> torch.Tensor:The response cannot serve: :class:`ScaleSpaceDetector`'s response function is pluggable andmay be signed, so an exact zero there is a legitimate maximum."""- return torch.where(filled.view(filled.shape[0], -1, 1, 1), lafs, torch.zeros_like(lafs))+ return torch.where(filled[..., None, None], lafs, torch.zeros_like(lafs))_BUILTIN_SUBPIX = (ConvQuadInterp3d, AdaptiveQuadInterp3d, IterativeQuadInterp3d)@@ -235,6 +235,8 @@ class ScaleSpaceDetector(nn.Module):- The LAFs are float32 for a float16 or bfloat16 image and float64 for a float64 one; the responses keep theresponse function's dtype. Non-maximum suppression and sub-pixel refinement run on the response promoted toat least float32.+ - A batch of zero images returns empty outputs of the documented shapes, after the checks a non-empty batch+ runs.- Known defects: an octave passes only its ``num_features`` strongest candidates to the border test and to themask check of their refined centres, so the slot of a candidate rejected there stays empty even when aweaker valid candidate exists (`#5741 <https://github.com/kornia/kornia/issues/5741>`_).@@ -513,9 +515,9 @@ class ScaleSpaceDetector(nn.Module):# every tensor describes the same (channel, scale, y, x) candidate. Responses# are single-channel by the contract checked above, but custom sub-pixel modules# still have to preserve this axis order.- mask_flat = cand_mask.reshape(B, -1) # (B, C*L*H*W)- resp_flat = response_max.reshape(B, -1) # (B, C*L*H*W)- coord_flat = coord_max.movedim(2, -1).reshape(B, -1, 3) # (B, C*L*H*W, 3)+ mask_flat = cand_mask.flatten(1) # (B, C*L*H*W)+ resp_flat = response_max.flatten(1) # (B, C*L*H*W)+ coord_flat = coord_max.movedim(2, -1).flatten(1, -2) # (B, C*L*H*W, 3)if B == 1:nms_idx = mask_flat[0].nonzero(as_tuple=True)[0] # (M,)@@ -528,7 +530,8 @@ class ScaleSpaceDetector(nn.Module):idxs = nms_idx[local_idx].unsqueeze(0)resp_flat_best = resp_flat_best.unsqueeze(0) # (1, k_eff)else:- resp_flat_best = resp_flat.new_zeros(1, 0)+ # A zero-width slice, not a fresh tensor: the empty result stays linked to the response.+ resp_flat_best = resp_flat[:, :0]idxs = nms_idx.new_empty(1, 0)else:# Batched fallback: mask non-candidates to -inf so they lose top-K to every finite@@ -547,9 +550,9 @@ class ScaleSpaceDetector(nn.Module):if self.minima_are_also_good:# Merge coordinates only for the selected features, not for every voxel# in the octave (three full image volumes per scale level).- coord_min_flat = coord_min.movedim(2, -1).reshape(B, -1, 3)+ coord_min_flat = coord_min.movedim(2, -1).flatten(1, -2)min_coords_best = torch.gather(coord_min_flat, 1, coord_idxs)- take_min_best = torch.gather(take_min_mask.reshape(B, -1), 1, idxs)+ take_min_best = torch.gather(take_min_mask.flatten(1), 1, idxs)max_coords_best = torch.where(take_min_best.unsqueeze(-1), min_coords_best, max_coords_best)B, N = resp_flat_best.size()@@ -581,7 +584,7 @@ class ScaleSpaceDetector(nn.Module):# region. Re-check the refined centre against the resampled mask, conservatively: every# octave pixel the centre touches (its floor and ceil in x and y) has to be allowed, as a# zero region already suppresses every candidate within one octave pixel of it.- keep_flat = oct_keep.reshape(oct_keep.shape[0], -1) # (1 or B, H*W)+ keep_flat = oct_keep.flatten(1) # (1 or B, H*W)if keep_flat.shape[0] != B:keep_flat = keep_flat.expand(B, -1)x0 = cx.floor().long().clamp_(0, w - 1)@@ -706,7 +709,7 @@ class ScaleSpaceDetector(nn.Module):2, 3)`. A slot that no detection filled -- there were fewer candidates than requested, or the border ormask test rejected a candidate -- carries a zero response and a zero LAF, and sorts after every realdetection. The converse does not hold: a signed response function can peak at exactly zero, and that- slot keeps its frame.+ slot keeps its frame. A batch of zero images returns empty outputs of these shapes."""responses, lafs, _ = self._detect(img, num_feats, mask)return responses, lafsdiff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 4d6754a96..15404736d 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -299,7 +299,6 @@ class SIFTDescriptor(nn.Module)::math:`(B, \text{num\_ang\_bins} \times \text{num\_spatial\_bins}^2)`."""KORNIA_CHECK_SHAPE(input, ["B", "1", f"{self.patch_size}", f"{self.patch_size}"])- B: int = input.shape[0]pk_weight = self.pk.weight.to(input.dtype).to(input.device)pk_bias = self.pk.biasif pk_bias is not None:@@ -336,7 +335,7 @@ class SIFTDescriptor(nn.Module):],1,)- ang_bins = ang_bins.view(B, -1)+ ang_bins = ang_bins.flatten(1)# A constant patch has an all-zero gradient and therefore a zero-norm descriptor; the# default `eps` is not representable in float16, where it would come back NaN.ang_bins = _l2_normalize(ang_bins, dim=1)diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex 0a1ad6fbd..f2ab44778 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -124,4 +124,4 @@ class SOSNet(nn.Module):descr = self.desc_norm(descr.float() + eps).to(descr.dtype)else:descr = self.desc_norm(descr + eps)- return descr.view(descr.size(0), -1)+ return descr.flatten(1)diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.pyindex 623f83361..c6ca72954 100644--- a/kornia/feature/tfeat.py+++ b/kornia/feature/tfeat.py@@ -98,5 +98,5 @@ class TFeat(nn.Module):"""KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])x = self.features(input)- x = x.view(x.size(0), -1)+ x = x.flatten(1)return self.descr(x)diff --git a/tests/feature/test_hardnet.py b/tests/feature/test_hardnet.pyindex d5a5e5ca3..b92450223 100644--- a/tests/feature/test_hardnet.py+++ b/tests/feature/test_hardnet.py@@ -33,6 +33,15 @@ class TestHardNet(BaseTester):out = hardnet(inp)assert out.shape == (1, 128)+ def test_empty_batch(self, device, dtype):+ # A batch of zero patches returns an empty descriptor batch, in the dtype a non-empty call returns.+ model = HardNet(pretrained=False).to(device, dtype).eval()+ one = model(torch.ones(1, 1, 32, 32, device=device, dtype=dtype))+ out = model(torch.zeros(0, 1, 32, 32, device=device, dtype=dtype))+ assert out.shape == (0, one.shape[1])+ assert out.dtype == one.dtype+ assert out.device == one.device+@pytest.mark.slowdef test_shape_batch(self, device):inp = torch.ones(4, 1, 32, 32, device=device)@@ -61,6 +70,15 @@ class TestHardNet8(BaseTester):out = hardnet(inp)assert out.shape == (1, 128)+ def test_empty_batch(self, device, dtype):+ # A batch of zero patches returns an empty descriptor batch, in the dtype a non-empty call returns.+ model = HardNet8(pretrained=False).to(device, dtype).eval()+ one = model(torch.ones(1, 1, 32, 32, device=device, dtype=dtype))+ out = model(torch.zeros(0, 1, 32, 32, device=device, dtype=dtype))+ assert out.shape == (0, one.shape[1])+ assert out.dtype == one.dtype+ assert out.device == one.device+def test_shape_batch(self, device):inp = torch.ones(4, 1, 32, 32, device=device)hardnet = HardNet8(pretrained=False).to(device).eval()diff --git a/tests/feature/test_hynet.py b/tests/feature/test_hynet.pyindex 665080856..0b6ad3662 100644--- a/tests/feature/test_hynet.py+++ b/tests/feature/test_hynet.py@@ -64,6 +64,15 @@ class TestHyNet(BaseTester):assert len(downloads) == 1HyNet(pretrained=False, is_bias_FRN=False)+ def test_empty_batch(self, device, dtype):+ # A batch of zero patches returns an empty descriptor batch, in the dtype a non-empty call returns.+ model = HyNet(pretrained=False).to(device, dtype).eval()+ one = model(torch.ones(1, 1, 32, 32, device=device, dtype=dtype))+ out = model(torch.zeros(0, 1, 32, 32, device=device, dtype=dtype))+ assert out.shape == (0, one.shape[1])+ assert out.dtype == one.dtype+ assert out.device == one.device+def test_shape_batch(self, device):inp = torch.ones(4, 1, 32, 32, device=device)hynet = HyNet(pretrained=False).to(device).eval()diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex 85ea25b0d..52f89983e 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -79,6 +79,52 @@ class TestGetLAFDescriptors(BaseTester):self.assert_close(descs_test_from_rgb, descs_reference)self.assert_close(descs_test_from_gray, descs_reference)+ def test_empty_batch(self, device, dtype):+ # Zero images with a (0, N) LAF set: N > 0 slots per image, none of which exists.+ PS = 16+ sift = SIFTDescriptor(PS).to(device, dtype)+ img = torch.zeros(0, 1, 48, 64, device=device, dtype=dtype)+ lafs = torch.zeros(0, 5, 2, 3, device=device, dtype=dtype)+ descs = get_laf_descriptors(img, lafs, sift, PS)+ assert descs.shape == (0, 5, 128)+ assert descs.dtype == dtype++ def test_empty_batch_gradients_reach_both_inputs(self, device, dtype):+ # The patches of an empty batch are linked to the image and the LAFs, so a loss on the descriptors alone+ # backpropagates (a zero gradient), also through a descriptor with no parameters.+ PS = 16+ sift = SIFTDescriptor(PS).to(device, dtype)+ img = torch.zeros(0, 1, 48, 64, device=device, dtype=dtype, requires_grad=True)+ lafs = torch.zeros(0, 5, 2, 3, device=device, dtype=dtype, requires_grad=True)+ get_laf_descriptors(img, lafs, sift, PS).sum().backward()+ assert img.grad is not None+ assert lafs.grad is not None+ assert img.grad.shape == img.shape+ assert lafs.grad.shape == lafs.shape++ @pytest.mark.parametrize("n_lafs", [0, 4])+ @pytest.mark.parametrize("n_images", [0, 2])+ @pytest.mark.parametrize("shape", [(64, 1), (), (3, 5)])+ def test_the_width_is_everything_a_patch_descriptor_returns(self, device, dtype, shape, n_images, n_lafs):+ # The descriptor width is the numel of what one patch yields, whatever the rank of the output, also when+ # the batch of patches is empty and `-1` could not infer it.+ class Stub(torch.nn.Module):+ def forward(self, patches):+ return patches.new_ones(patches.shape[0], *shape)++ PS = 8+ img = torch.rand(n_images, 1, 48, 64, device=device, dtype=dtype)+ lafs = torch.zeros(n_images, n_lafs, 2, 3, device=device, dtype=dtype)+ lafs[..., 0, 0] = 8.0+ lafs[..., 1, 1] = 8.0+ lafs[..., 0, 2] = 24.0+ lafs[..., 1, 2] = 24.0+ width = torch.Size(shape).numel()+ with warnings.catch_warnings():+ warnings.simplefilter("ignore") # the empty-LAF warning+ descs = get_laf_descriptors(img, lafs, Stub(), PS)+ assert descs.shape == (n_images, n_lafs, width)+def test_gradcheck(self, device):dtype = torch.float64B, C, H, W = 1, 1, 32, 32@@ -501,6 +547,26 @@ class TestLocalFeature(BaseTester):with pytest.raises(ValueError, match="should be > 0"):LocalFeature(ScaleSpaceDetector(10), SIFTDescriptor(32), coef)+ def test_empty_batch(self, device, dtype):+ # H != W; the detector and the descriptor both accept a batch of zero images.+ PS, n = 16, 7+ local_feature = LocalFeature(ScaleSpaceDetector(n), LAFDescriptor(SIFTDescriptor(PS), PS)).to(device, dtype)+ one = local_feature(torch.rand(1, 1, 48, 64, device=device, dtype=dtype))+ lafs, responses, descs = local_feature(torch.zeros(0, 1, 48, 64, device=device, dtype=dtype))+ assert lafs.shape == (0, n, 2, 3)+ assert responses.shape == (0, n)+ assert descs.shape == (0, n, 128)+ for actual, expected in zip((lafs, responses, descs), one):+ assert actual.dtype == expected.dtype+ assert actual.device == expected.device++ def test_empty_batch_sift_feature_scale_space(self, device, dtype):+ feature = kornia.feature.SIFTFeatureScaleSpace(7).to(device, dtype)+ lafs, responses, descs = feature(torch.zeros(0, 1, 48, 64, device=device, dtype=dtype))+ assert lafs.shape == (0, 7, 2, 3)+ assert responses.shape == (0, 7)+ assert descs.shape == (0, 7, 128)+def test_smoke(self, device, dtype):det = ScaleSpaceDetector(10)desc = SIFTDescriptor(32)diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.pyindex 047df8eab..f02ca18fb 100644--- a/tests/feature/test_laf.py+++ b/tests/feature/test_laf.py@@ -1086,6 +1086,23 @@ class TestExtractPatchesSimple(BaseTester):self.assert_close(torch.compile(kornia.feature.extract_patches_simple, fullgraph=True)(img, laf, 10), expected)+class TestEmptyPatchesAreLinked(BaseTester):+ @pytest.mark.parametrize(+ "extract", [kornia.feature.extract_patches_simple, kornia.feature.extract_patches_from_pyramid]+ )+ @pytest.mark.parametrize("batch, n_lafs", [(0, 5), (2, 0), (0, 0)])+ def test_zero_patches_keep_the_links_to_the_inputs(self, device, dtype, extract, batch, n_lafs):+ img = torch.rand(batch, 2, 48, 64, device=device, dtype=dtype, requires_grad=True)+ laf = torch.rand(batch, n_lafs, 2, 3, device=device, dtype=dtype, requires_grad=True)+ patches = extract(img, laf, 16)+ assert patches.shape == (batch, n_lafs, 2, 16, 16)+ assert patches.dtype == dtype+ assert patches.requires_grad+ patches.sum().backward()+ self.assert_close(img.grad, torch.zeros_like(img))+ self.assert_close(laf.grad, torch.zeros_like(laf))++class TestExtractPatchesPyr(BaseTester):def test_shape(self, device):laf = torch.rand(5, 4, 2, 3, device=device)diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 80f8a2d3a..07a764c76 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -21,7 +21,8 @@ from torch.utils._python_dispatch import TorchDispatchModeimport korniafrom kornia.core.check import ShapeError-from kornia.feature import KeyNetDetector+from kornia.core.exceptions import BaseError+from kornia.feature import BlobDoG, KeyNetDetectorfrom kornia.feature.scale_space_detector import (MultiResolutionDetector,ScaleSpaceDetector,@@ -203,6 +204,79 @@ class TestScaleSpaceDetector(BaseTester):assert lafs.shape == torch.Size([7, n_feats, 2, 3])assert resps.shape == torch.Size([7, n_feats])+ @pytest.mark.parametrize("with_mask", [False, True])+ @pytest.mark.parametrize("config", ["default", "minima", "scale_space_response", "conv_subpix"])+ def test_empty_batch(self, device, dtype, with_mask, config):+ # A batch of zero images returns empty outputs of the documented shapes, with the dtypes a one-image+ # call returns in the same input dtype (LAFs float32 for a half image, responses in the image dtype),+ # still linked to the input for autograd.+ kwargs = {+ "default": {},+ "minima": {"minima_are_also_good": True},+ "scale_space_response": {"scale_space_response": True, "resp_module": BlobDoG()},+ "conv_subpix": {"subpix_module": ConvQuadInterp3d()},+ }[config]+ det = ScaleSpaceDetector(50, **kwargs).to(device, dtype)+ ones = torch.ones(1, 1, 64, 80, device=device, dtype=dtype)+ one_img = torch.rand(1, 1, 64, 80, device=device, dtype=dtype).requires_grad_(True)+ one_lafs, one_resps = det(one_img, ones if with_mask else None)+ empty = torch.zeros(0, 1, 64, 80, device=device, dtype=dtype).requires_grad_(True)+ mask = torch.ones(0, 1, 64, 80, device=device, dtype=dtype) if with_mask else None+ lafs, resps = det(empty, mask)+ assert lafs.shape == torch.Size([0, 50, 2, 3])+ assert resps.shape == torch.Size([0, 50])+ assert lafs.dtype == one_lafs.dtype+ assert lafs.device == one_lafs.device+ assert resps.dtype == one_resps.dtype+ assert resps.device == one_resps.device+ # Both outputs stay linked to the input, and backward runs.+ assert lafs.requires_grad+ assert resps.requires_grad+ (lafs.sum() + resps.sum()).backward()+ assert empty.grad is not None+ assert empty.grad.shape == empty.shape+ # `detect` with an explicit `num_feats` returns the requested count; a mask of one broadcasts.+ one_resps, one_lafs = det.detect(torch.zeros(1, 1, 64, 80, device=device, dtype=dtype), 7)+ resps, lafs = det.detect(empty.detach(), 7, ones if with_mask else None)+ assert resps.shape == torch.Size([0, 7])+ assert lafs.shape == torch.Size([0, 7, 2, 3])+ assert lafs.dtype == one_lafs.dtype+ assert resps.dtype == one_resps.dtype++ def test_an_image_without_candidates_stays_linked_to_the_input(self, device, dtype):+ # A DoG response is exactly zero everywhere on an all-zero image, so no octave has a candidate and every slot is+ # unfilled; the empty selection must still be a function of the response, so a loss on it can backward.+ det = ScaleSpaceDetector(10, scale_space_response=True, resp_module=BlobDoG()).to(device, dtype)+ img = torch.zeros(1, 1, 64, 80, device=device, dtype=dtype, requires_grad=True)+ lafs, resps = det(img)+ assert torch.count_nonzero(resps) == 0+ assert lafs.requires_grad+ assert resps.requires_grad+ (lafs.sum() + resps.sum()).backward()+ assert img.grad is not None+ # An image without candidates has no gradient to give.+ assert torch.count_nonzero(img.grad) == 0++ @pytest.mark.parametrize(+ "img_tail, mask_shape, error",+ [+ ((3, 64, 80), None, BaseError),+ ((64, 80), None, ValueError),+ ((1, 64, 80), (1, 64, 80), BaseError),+ ((1, 64, 80), (1, 3, 64, 80), BaseError),+ ((1, 64, 80), (1, 1, 32, 80), BaseError),+ ((1, 64, 80), (2, 1, 64, 80), BaseError),+ ],+ ids=["3-channels", "3-d-image", "mask-rank-3", "mask-3-channels", "mask-size", "mask-batch"],+ )+ def test_empty_batch_is_validated_like_a_non_empty_one(self, device, dtype, img_tail, mask_shape, error):+ det = ScaleSpaceDetector(5).to(device, dtype)+ mask = None if mask_shape is None else torch.ones(mask_shape, device=device, dtype=dtype)+ for batch in (0, 1):+ img = torch.zeros(batch, *img_tail, device=device, dtype=dtype)+ with pytest.raises(error):+ det(img, mask)+def test_toy(self, device, dtype):inp = torch.zeros(1, 1, 33, 33, device=device, dtype=dtype)inp[:, :, 13:-13, 13:-13] = 1.0diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.pyindex 09cf75e23..9d83349ae 100644--- a/tests/feature/test_siftdesc.py+++ b/tests/feature/test_siftdesc.py@@ -103,6 +103,16 @@ class TestSIFTDescriptor(BaseTester):out = sift(inp)assert out.shape == (1, 128)+ @pytest.mark.parametrize("patch_size", [32, 15])+ def test_empty_batch(self, device, dtype, patch_size):+ # A batch of zero patches returns an empty descriptor batch, in the dtype a non-empty call returns.+ sift = SIFTDescriptor(patch_size).to(device, dtype)+ one = sift(torch.ones(1, 1, patch_size, patch_size, device=device, dtype=dtype))+ out = sift(torch.zeros(0, 1, patch_size, patch_size, device=device, dtype=dtype))+ assert out.shape == (0, 128)+ assert out.dtype == one.dtype+ assert out.device == one.device+def test_batch_shape(self, device, dtype):inp = torch.ones(2, 1, 15, 15, device=device, dtype=dtype)sift = SIFTDescriptor(15).to(device, dtype)diff --git a/tests/feature/test_sosnet.py b/tests/feature/test_sosnet.pyindex 187623b7a..063c07876 100644--- a/tests/feature/test_sosnet.py+++ b/tests/feature/test_sosnet.py@@ -31,6 +31,15 @@ class TestSOSNet(BaseTester):out = sosnet(inp)assert out.shape == (1, 128)+ def test_empty_batch(self, device, dtype):+ # A batch of zero patches returns an empty descriptor batch, in the dtype a non-empty call returns.+ model = SOSNet(pretrained=False).to(device, dtype).eval()+ one = model(torch.ones(1, 1, 32, 32, device=device, dtype=dtype))+ out = model(torch.zeros(0, 1, 32, 32, device=device, dtype=dtype))+ assert out.shape == (0, one.shape[1])+ assert out.dtype == one.dtype+ assert out.device == one.device+def test_shape_batch(self, device):inp = torch.ones(16, 1, 32, 32, device=device)sosnet = SOSNet(pretrained=False).to(device).eval()diff --git a/tests/feature/test_tfeat.py b/tests/feature/test_tfeat.pyindex ad8ecdd0e..69a3218ca 100644--- a/tests/feature/test_tfeat.py+++ b/tests/feature/test_tfeat.py@@ -31,6 +31,15 @@ class TestTFeat(BaseTester):out = tfeat(inp)assert out.shape == (1, 128)+ def test_empty_batch(self, device, dtype):+ # A batch of zero patches returns an empty descriptor batch, in the dtype a non-empty call returns.+ model = TFeat(pretrained=False).to(device, dtype).eval()+ one = model(torch.ones(1, 1, 32, 32, device=device, dtype=dtype))+ out = model(torch.zeros(0, 1, 32, 32, device=device, dtype=dtype))+ assert out.shape == (0, one.shape[1])+ assert out.dtype == one.dtype+ assert out.device == one.device+@pytest.mark.slowdef test_pretrained(self, device):inp = torch.ones(1, 1, 32, 32, device=device)