π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): return empty tensors from ALIKED.forward_laf for an empty batch (#6266) (#6377)
Viranshul-P86179730b204
diff --git a/changelog.d/6377.fixed.md b/changelog.d/6377.fixed.mdnew file mode 100644index 000000000..846ea3374--- /dev/null+++ b/changelog.d/6377.fixed.md@@ -0,0 +1,2 @@+`ALIKED.forward_laf` returns `(0, 0, 2, 3)` LAFs, `(0, 0, 1)` responses and `(0, 0, D)` descriptors for an empty batch,+in the dtypes of a non-empty batch, instead of raising (#6266).diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex 91b1467bc..fc6520867 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -1071,6 +1071,17 @@ class ALIKED(nn.Module):B, _, H, W = img.shapewh = torch.tensor([W - 1, H - 1], device=img.device, dtype=torch.promote_types(img.dtype, torch.float32))+ if B == 0:+ # torch.stack rejects an empty list. Derive the empty outputs from the dense maps instead of allocating+ # them, so they stay in the autograd graph, and sample the responses as DKD does, so they keep the+ # dtype a non-empty batch gets (float32 under autocast).+ responses = F.grid_sample(score_map, score_map.new_zeros(0, 1, 0, 2), mode="bilinear", align_corners=True)+ return (+ score_map.flatten()[:0].to(wh.dtype).view(0, 0, 2, 3),+ responses.view(0, 0, 1),+ feature_map.flatten()[:0].view(0, 0, feature_map.shape[1]),+ )+lafs_list: list[torch.Tensor] = []for i in range(B):kps_px = wh * (keypoints[i] + 1) / 2.0 # (N, 2)@@ -1084,7 +1095,7 @@ class ALIKED(nn.Module):lafs_list.append(laf_i)# Pad to the maximum number of keypoints in the batch.- n_max = max(laf.shape[0] for laf in lafs_list) if lafs_list else 0+ n_max = max(laf.shape[0] for laf in lafs_list)def _pad(t: torch.Tensor, n: int, fill: float = 0.0) -> torch.Tensor:pad_n = n - t.shape[0]diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex d4bec1ad4..93b25b0f3 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -500,6 +500,34 @@ class TestALIKEDForwardLAF(BaseTester):assert responses.ndim == 3 # (B, N, 1)assert descs.ndim == 3 # (B, N, D)+ @pytest.mark.parametrize("compute_affine", [True, False])+ @pytest.mark.parametrize("with_mask", [False, True])+ def test_empty_batch_6266(self, compute_affine, with_mask, device, dtype):+ """An empty batch gives empty LAFs, responses and descriptors with the dtypes of a non-empty batch."""+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()+ mask = torch.ones(0, 1, 64, 64, device=device, dtype=dtype) if with_mask else None+ lafs, responses, descs = aliked.forward_laf(+ torch.rand(0, 3, 64, 64, device=device, dtype=dtype), mask=mask, compute_affine=compute_affine+ )+ ref = aliked.forward_laf(torch.rand(1, 3, 64, 64, device=device, dtype=dtype), compute_affine=compute_affine)+ assert lafs.shape == (0, 0, 2, 3)+ assert responses.shape == (0, 0, 1)+ assert descs.shape == (0, 0, ref[2].shape[-1])+ assert [t.dtype for t in (lafs, responses, descs)] == [t.dtype for t in ref]+ assert all(t.device == ref[0].device for t in (lafs, responses, descs))+ # The empty outputs stay in the autograd graph, so a loss over an empty batch can still be backpropagated.+ assert [t.requires_grad for t in (lafs, responses, descs)] == [t.requires_grad for t in ref]+ (lafs.sum() + responses.sum() + descs.sum()).backward()++ @pytest.mark.parametrize("compute_affine", [True, False])+ def test_empty_batch_autocast_6266(self, compute_affine):+ """Under CPU bfloat16 autocast an empty batch gets the dtypes of a non-empty one (float32 responses)."""+ aliked = ALIKED(model_name="aliked-t16").eval()+ with torch.autocast("cpu", dtype=torch.bfloat16):+ empty = aliked.forward_laf(torch.rand(0, 3, 64, 64), compute_affine=compute_affine)+ ref = aliked.forward_laf(torch.rand(1, 3, 64, 64), compute_affine=compute_affine)+ assert [t.dtype for t in empty] == [t.dtype for t in ref]+def test_output_shapes(self, device, dtype):"""Shapes should be (B, N, 2, 3), (B, N, 1), (B, N, D)."""B, H, W = 2, 64, 64