π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): ALIKED() starts in eval mode (#5935)
Dmytro Mishkinb0e2176b9453
diff --git a/changelog.d/5935.breaking.md b/changelog.d/5935.breaking.mdnew file mode 100644index 000000000..045e5a8a0--- /dev/null+++ b/changelog.d/5935.breaking.md@@ -0,0 +1 @@+`ALIKED()` now starts in evaluation mode, like `ALIKED.from_pretrained()` and the reference implementation. It used to start in training mode, so `forward`, `forward_laf` and `extract_dense_map` normalised with batch statistics (each image's keypoints and descriptors depended on the rest of the batch), updated the BatchNorm running statistics on every call, and a single small image raised "Expected more than 1 value per channel when training". Call `.train()` to train.diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex bf4051558..c82659379 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -767,6 +767,11 @@ class ALIKED(nn.Module):.. image:: _static/img/ALIKED.pngConvention:+ - ``ALIKED()`` starts in evaluation mode, like :meth:`from_pretrained` and the reference implementation. In+ training mode BatchNorm would normalise with the statistics of the batch, so a keypoint or descriptor would+ depend on the rest of the batch, every call would update the running statistics, and a single small image+ would raise. Call ``.train()`` to opt in explicitly; the methods then behave as torch's training-mode+ BatchNorm does.- ``images`` are RGB in :math:`[0, 1]`, the range of the pretrained weights, and the network applies nonormalisation; a :math:`(B, 1, H, W)` image is repeated to three channels. Any ``H`` and ``W`` work: theimage is replicate-padded around its centre to multiples of 32 and the maps are cropped back, so the padding@@ -884,6 +889,8 @@ class ALIKED(nn.Module):scores_th=detection_threshold,n_limit=max_num_keypoints if max_num_keypoints > 0 else self.n_limit_max,)+ # like :meth:`from_pretrained` and the reference: the inference methods must not run BatchNorm in training mode+ self.eval()def _make_resblock(self, c_in: int, c_out: int, conv_type: str, mask: bool) -> ResBlock:return ResBlock(diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex 2a77c89eb..2afe7bea8 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -841,3 +841,56 @@ class TestConventionsALIKED(BaseTester):finally:pre.remove()hook.remove()+++class TestALIKEDEvalByDefault(BaseTester):+ """``ALIKED()`` starts in evaluation mode: BatchNorm uses its running statistics, not those of the batch."""++ @pytest.fixture(autouse=True)+ def _kernels(self, device, dtype):+ if not (supports_replicate_padding(device, dtype) and supports_bilinear_2d_grid_sample(device, dtype)):+ pytest.skip("ALIKED pads with replication and samples with bilinear grid_sample, absent for this dtype")++ @staticmethod+ def _model(device, dtype):+ # the default constructor, deliberately without .eval()+ return ALIKED(model_name="aliked-t16").to(device, dtype)++ def test_convention_aliked_starts_in_eval_mode(self, device, dtype):+ aliked = self._model(device, dtype)+ assert not aliked.training+ assert not any(m.training for m in aliked.modules())++ def test_convention_aliked_train_is_an_explicit_opt_in(self, device, dtype):+ aliked = self._model(device, dtype).train()+ assert aliked.training+ assert all(m.training for m in aliked.modules() if isinstance(m, torch.nn.BatchNorm2d))++ @pytest.mark.parametrize("method", ["forward", "extract_dense_map", "forward_laf"])+ def test_convention_aliked_inference_leaves_the_state_unchanged(self, method, device, dtype):+ aliked = self._model(device, dtype)+ before = {k: v.clone() for k, v in aliked.state_dict().items()}+ with torch.no_grad():+ getattr(aliked, method)(torch.rand(2, 3, 64, 64, device=device, dtype=dtype))+ after = aliked.state_dict()+ assert before.keys() == after.keys()+ for k, v in before.items():+ assert torch.equal(v, after[k]), k++ def test_convention_aliked_dense_map_does_not_depend_on_the_batch(self, device, dtype):+ aliked = self._model(device, dtype)+ a = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ b = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ with torch.no_grad():+ feat_a, score_a = aliked.extract_dense_map(a)+ feat_ab, score_ab = aliked.extract_dense_map(torch.cat([a, b]))+ self.assert_close(feat_ab[:1], feat_a)+ self.assert_close(score_ab[:1], score_a)++ def test_convention_aliked_accepts_a_single_small_image(self, device, dtype):+ # in training mode the 1 x 1 deepest map has one value per channel and BatchNorm raises+ aliked = self._model(device, dtype)+ with torch.no_grad():+ feat, score = aliked.extract_dense_map(torch.rand(1, 3, 16, 16, device=device, dtype=dtype))+ assert feat.shape[0] == 1+ assert score.shape == (1, 1, 16, 16)