π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature)!: learned models default to pretrained weights; random init stays in training mode (#6017)
Dmytro Mishkin5a7d50aa7138
diff --git a/.github/download-models-weights.py b/.github/download-models-weights.pyindex e413bc386..1158e95a0 100644--- a/.github/download-models-weights.py+++ b/.github/download-models-weights.py@@ -97,6 +97,11 @@ MODELS: dict[str, "str | list[str]"] = {"checkpoint_liberty_with_aug.pth"),],+ # HardNet8: HardNet8() loads these by default, as test_pretrained_mode.py does.+ "hardnet8v2.pt": [+ "https://huggingface.co/kornia/hardnet/resolve/main/hardnet8v2.pt",+ "https://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt",+ ],# Patch descriptors with pretrained smoke/jit tests."HyNet_LIB.pth": ["https://huggingface.co/kornia/hynet/resolve/main/HyNet_LIB.pth",@@ -175,9 +180,9 @@ MODELS: dict[str, "str | list[str]"] = {# ViT-S/32: TestVisionTransformer.test_from_config_pretrained. Its Hub repository is the# one ViT repository off the naming pattern, so the cached copy also guards that URL."vit_s-32.pth": "https://huggingface.co/kornia/vit_s32_i21k_augreg_i21k_r224/resolve/main/vit_s-32.pth",- # ALIKED and XFeat: no pytest job builds them pretrained, but- # ``generate_examples.main`` does, once per docs build, and the docs job- # restores this same cache.+ # ALIKED and XFeat: ``tests/feature/test_pretrained_mode.py`` builds them+ # pretrained, and so does ``generate_examples.main``, once per docs build;+ # the docs job restores this same cache."aliked-n16.pth": ["https://huggingface.co/kornia/aliked/resolve/main/aliked-n16.pth","https://github.com/Shiaoming/ALIKED/raw/main/models/aliked-n16.pth",diff --git a/changelog.d/5693.fixed.md b/changelog.d/5693.fixed.mdindex 8fed97b73..0572e5057 100644--- a/changelog.d/5693.fixed.md+++ b/changelog.d/5693.fixed.md@@ -1,3 +1,3 @@-`HardNet8()` without pretrained weights now gives distinct, trainable descriptors. Its placeholder PCA projection+`HardNet8(pretrained=False)` now gives distinct, trainable descriptors. Its placeholder PCA projectionwas an all-ones matrix, which mapped every patch to the same descriptor up to sign; it now keeps the first 128 of the512 features until the pretrained weights replace it.diff --git a/changelog.d/5926.breaking.md b/changelog.d/5926.breaking.mddeleted file mode 100644index 4b3a62f39..000000000--- a/changelog.d/5926.breaking.md+++ /dev/null@@ -1 +0,0 @@-`XFeat()` now starts in evaluation mode, like `XFeat.from_pretrained()` and the reference implementation. It used to start in training mode, so `detectAndCompute`, `detectAndComputeDense` and the `match_*` methods normalised with batch statistics (each keypoint depended on the rest of the batch), updated the BatchNorm running statistics on every call, and a single match raised "Expected more than 1 value per channel when training". Call `.train()` to train.diff --git a/changelog.d/5935.breaking.md b/changelog.d/5935.breaking.mddeleted file mode 100644index 045e5a8a0..000000000--- a/changelog.d/5935.breaking.md+++ /dev/null@@ -1 +0,0 @@-`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/changelog.d/6017.breaking.md b/changelog.d/6017.breaking.mdnew file mode 100644index 000000000..d97274b2a--- /dev/null+++ b/changelog.d/6017.breaking.md@@ -0,0 +1,3 @@+`HardNet`, `HardNet8`, `HyNet`, `SOSNet`, `TFeat`, `OriNet`, `LAFAffNetShapeEstimator`, `KeyNet`, `KeyNetDetector` and `DeFMO` default to `pretrained=True`. Constructing one downloads its weights (once) and returns the trained model in evaluation mode; for `KeyNetDetector` that is its `KeyNet` network, while the detector itself keeps its mode, so an `ori_module` or `aff_module` you pass is not switched. They defaulted to random weights, returned in evaluation mode with BatchNorm, where the network has any, on its initial statistics. Pass `pretrained=False` for random weights. An architecture argument the checkpoint does not fit now needs `pretrained=False` as well: with the default, `HyNet` with another `is_bias` or `dim_desc`, and `KeyNet` or `KeyNetDetector` with a `keynet_conf` of another `num_levels` or `kernel_size`, raise `RuntimeError` from the strict weight load, and `HyNet(is_bias_FRN=False)` loads the weights but leaves their trained FRN biases unused.++Randomly initialised models are returned in training mode: `pretrained=False` on those classes, `SOLD2(pretrained=False)`, `SOLD2_detector(pretrained=False)` and `LoFTR(pretrained=None)`. They were returned in evaluation mode. Call `.eval()` before inference, and after loading your own weights into one of them. A random `LoFTR` in training mode runs its supervised training branch, so its forward raises without ground-truth matches until `.eval()` is called.diff --git a/changelog.d/6017.fixed.md b/changelog.d/6017.fixed.mdnew file mode 100644index 000000000..35540eff4--- /dev/null+++ b/changelog.d/6017.fixed.md@@ -0,0 +1 @@+`LightGlue` built with complete learned weights (a `features` name, or a local `weights` file) now comes back in evaluation mode, like the other `kornia.feature` models built with pretrained weights. Missing derived buffers do not prevent evaluation mode, but checkpoints missing learned parameters leave the model in training mode, as does `LightGlue(features=None)` without weights. Its output does not depend on the mode.diff --git a/docs/source/_extra/llms-full.txt b/docs/source/_extra/llms-full.txtindex d3988746b..22c7574a6 100644--- a/docs/source/_extra/llms-full.txt+++ b/docs/source/_extra/llms-full.txt@@ -15,6 +15,7 @@ These conventions hold library-wide; per-function docs note any exception.- **Transformation matrices:** batched. Homographies are `(B, 3, 3)`, affine matrices `(B, 2, 3)`. They act on pixel coordinates unless the function name or a flag says `normalized`. To apply a `(3, 3)` matrix, add the batch dim: `M[None]`.- **`align_corners`:** `warp_perspective` and `warp_affine` default to `align_corners=True`; `resize` defaults to `align_corners=None` (PyTorch's native default per interpolation mode). When mixing Kornia warps with `torch.nn.functional.interpolate` or `grid_sample`, pass `align_corners` explicitly everywhere.- **Devices/dtypes:** ops run on whatever device/dtype the input tensors carry; there is no implicit `.cuda()` or `.float()`.+- **Pretrained models:** in `kornia.models` and `kornia.feature` alike, a model built with complete pretrained weights comes back in eval mode, and a randomly initialised or only partly pretrained one in training mode; call `.eval()` before inference on random weights, and after loading your own weights. In `kornia.feature`, `HardNet`, `HardNet8`, `HyNet`, `SOSNet`, `TFeat`, `OriNet`, `LAFAffNetShapeEstimator`, `KeyNet`, `KeyNetDetector` (its `KeyNet` network; the detector itself keeps its mode), `DeFMO`, `SOLD2`, `SOLD2_detector`, `LoFTR` and `LightGlue` load their pretrained weights by default (`pretrained=False`, or `None` for `LoFTR` and `LightGlue`, gives random ones), and `DISK`, `DeDoDe`, `ALIKED` and `XFeat` load them with `from_pretrained`.Full conventions reference with runnable proofs: <https://kornia.readthedocs.io/en/latest/get-started/conventions.html>Stability: the core modules (geometry, augmentation, color, filters, enhance, losses, metrics, morphology, io, image) follow a written deprecation policy β public symbols warn for at least one minor release before breaking: <https://kornia.readthedocs.io/en/latest/get-started/stability.html>diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex ee34d414a..88ad6d73e 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -1208,6 +1208,17 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homogLocal features--------------+The learned models in ``kornia.feature`` that take a ``pretrained`` flag (``HardNet``, ``HardNet8``, ``HyNet``,+``SOSNet``, ``TFeat``, ``OriNet``, ``LAFAffNetShapeEstimator``, ``KeyNet``, ``KeyNetDetector``, ``DeFMO``,+``SOLD2``, ``SOLD2_detector``) default to their pretrained weights, downloaded on first use. ``KeyNetDetector`` puts+only its ``KeyNet`` network in evaluation mode: the detector itself stays in training mode, and an ``ori_module`` or+``aff_module`` you pass keeps its own mode. ``DISK``, ``DeDoDe``, ``ALIKED`` and ``XFeat`` build their learned+weights at random in their constructor and load them with ``from_pretrained``. ``DeDoDe`` with its default ``G``+descriptor also downloads a frozen, pretrained DINOv2 backbone in its constructor, and ``DeDoDe.detect`` and+``describe`` switch the model to evaluation mode themselves. ``LoFTR(pretrained=None)`` and+``LightGlue(features=None)`` are random. Until ``.eval()`` is called, a random ``LoFTR`` runs its supervised training+branch, which raises without ground-truth matches. See :ref:`pretrained-models-conventions` for the shared mode rule.+A local affine frame (LAF) describes a keypoint by a ``2 x 3`` matrix ``[A | c]``, and a set of them is a``(B, N, 2, 3)`` tensor. The centre ``c = (x, y)`` is in the pixel frame of:ref:`Coordinates and sizes <coordinate-conventions>`, with pixel centres at integers: the centre of a 5-pixel axis isdiff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 3cebe044e..a6d203e74 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -284,7 +284,7 @@ class LAFAffNetShapeEstimator(nn.Module):"""- def __init__(self, pretrained: bool = False, preserve_orientation: bool = True) -> None:+ def __init__(self, pretrained: bool = True, preserve_orientation: bool = True) -> None:super().__init__()self.features = nn.Sequential(nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),@@ -315,8 +315,8 @@ class LAFAffNetShapeEstimator(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(urls["affnet"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"], strict=False)+ self.eval()self.preserve_orientation = preserve_orientation- self.eval()@staticmethoddef _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex 6f8ea77e1..a70dbeeb5 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -771,11 +771,9 @@ 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.+ - ``ALIKED()`` builds random weights in training mode, where BatchNorm normalises with the batch, updates its+ running statistics on every call, and a single small image raises; call ``.eval()`` for inference.+ :meth:`from_pretrained` returns the trained model in evaluation mode.- ``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@@ -894,8 +892,6 @@ 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/kornia/feature/defmo.py b/kornia/feature/defmo.pyindex 828a55abf..f72a4a0dc 100644--- a/kornia/feature/defmo.py+++ b/kornia/feature/defmo.py@@ -383,7 +383,7 @@ class DeFMO(nn.Module):``k / 23``, each with red, green, blue and alpha channels in :math:`[0, 1]` after a sigmoid.Args:- pretrained: Download and set pretrained weights to the model. Default: false.+ pretrained: Download and set pretrained weights to the model. Default: True.Returns:Temporal super-resolution without background.@@ -394,12 +394,12 @@ class DeFMO(nn.Module):Examples:>>> import kornia>>> input = torch.rand(2, 6, 240, 320)- >>> defmo = kornia.feature.DeFMO()+ >>> defmo = kornia.feature.DeFMO(pretrained=False).eval()>>> tsr_nobgr = defmo(input) # 2x24x4x240x320"""- def __init__(self, pretrained: bool = False) -> None:+ def __init__(self, pretrained: bool = True) -> None:super().__init__()self.encoder = EncoderDeFMO()self.rendering = RenderingDeFMO()@@ -410,7 +410,7 @@ class DeFMO(nn.Module):self.encoder.load_state_dict(pretrained_dict, strict=True)pretrained_dict_ren = load_state_dict_from_url(urls["defmo_rendering"], map_location=torch.device("cpu"))self.rendering.load_state_dict(pretrained_dict_ren, strict=True)- self.eval()+ self.eval()def forward(self, input_data: torch.Tensor) -> torch.Tensor:"""Deblur a fast-moving object into a sequence of RGBA sub-frames.diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex 8d7d102f1..276f1f2c0 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -58,9 +58,12 @@ class HardNet(nn.Module):``1e-5`` to the variance, so for SOSNet and TFeat a low-contrast patch in ``[0, 1]`` can already give adifferent descriptor than the same patch in ``[0, 255]``. HyNet is invariant to a scale only; see itsConvention block.- - The descriptors have unit L2 norm, except TFeat's (see its Convention block); with ``pretrained=False``,- HardNet and HardNet8 map a flat patch to an all-zero descriptor.- - ``pretrained=False``, the default, leaves the weights randomly initialised.+ - The descriptors have unit L2 norm, except TFeat's (see its Convention block); with ``pretrained=False``+ and ``.eval()`` (the initial BatchNorm statistics), HardNet and HardNet8 map a flat patch to an all-zero+ descriptor.+ - ``pretrained=True``, the default, downloads the trained weights (Liberty with augmentation for HardNet,+ ``hardnet8v2`` for HardNet8) and returns the model in evaluation mode. ``pretrained=False`` gives random+ weights in training mode; call ``.eval()`` before inference.Args:pretrained: Download and set pretrained weights to the model.@@ -74,14 +77,14 @@ class HardNet(nn.Module):Examples:>>> input = torch.rand(16, 1, 32, 32)- >>> hardnet = HardNet()+ >>> hardnet = HardNet(pretrained=False).eval()>>> descs = hardnet(input) # 16x128"""patch_size = 32- def __init__(self, pretrained: bool = False) -> None:+ def __init__(self, pretrained: bool = True) -> None:super().__init__()self.features = nn.Sequential(nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False),@@ -111,7 +114,7 @@ class HardNet(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(urls["liberty_aug"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"], strict=True)- self.eval()+ self.eval()@staticmethoddef _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:@@ -171,14 +174,14 @@ class HardNet8(nn.Module):Examples:>>> input = torch.rand(16, 1, 32, 32)- >>> hardnet = HardNet8()+ >>> hardnet = HardNet8(pretrained=False).eval()>>> descs = hardnet(input) # 16x128"""patch_size = 32- def __init__(self, pretrained: bool = False) -> None:+ def __init__(self, pretrained: bool = True) -> None:super().__init__()self.features = nn.Sequential(nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False),@@ -216,7 +219,7 @@ class HardNet8(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(urls["hardnet8v2"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)- self.eval()+ self.eval()@staticmethoddef weights_init(m: object) -> None:diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.pyindex 80dd3aaa6..df21278a3 100644--- a/kornia/feature/hynet.py+++ b/kornia/feature/hynet.py@@ -219,7 +219,10 @@ class HyNet(nn.Module):non-negative intensities such as ``[0, 1]`` or ``[0, 255]``, not mean-subtracted or standardised patches.Args:- pretrained: Download and set pretrained weights to the model.+ pretrained: Download and set pretrained weights to the model. The weights fit the default ``is_bias``,+ ``is_bias_FRN`` and ``dim_desc`` only, so pass ``pretrained=False`` with another value: the strict load+ raises ``RuntimeError`` for another ``is_bias`` or ``dim_desc``, and ``is_bias_FRN=False`` loads the+ weights but leaves their trained FRN biases unused.is_bias: use bias in the convolution layers (the final 8 x 8 convolution has none either way)is_bias_FRN: use bias in FRN layersdim_desc: descriptor dimensionality,@@ -239,7 +242,7 @@ class HyNet(nn.Module):Examples:>>> input = torch.rand(16, 1, 32, 32)- >>> hynet = HyNet()+ >>> hynet = HyNet(pretrained=False).eval()>>> descs = hynet(input) # 16x128"""@@ -248,7 +251,7 @@ class HyNet(nn.Module):def __init__(self,- pretrained: bool = False,+ pretrained: bool = True,is_bias: bool = True,is_bias_FRN: bool = True,dim_desc: int = 128,@@ -307,7 +310,7 @@ class HyNet(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(urls["liberty"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)- self.eval()+ self.eval()def forward(self, x: torch.Tensor) -> torch.Tensor:"""Compute HyNet descriptors from grayscale image patches.diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.pyindex 796e7e902..b22f17bd6 100644--- a/kornia/feature/keynet.py+++ b/kornia/feature/keynet.py@@ -152,7 +152,9 @@ class KeyNet(nn.Module):Args:pretrained: Download and set pretrained weights to the model.- keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing.+ keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing. A+ ``num_levels`` or ``kernel_size`` other than the default changes the architecture: pass+ ``pretrained=False`` with it, since the strict load of the weights raises ``RuntimeError``.Returns:KeyNet response score.@@ -163,7 +165,7 @@ class KeyNet(nn.Module):"""- def __init__(self, pretrained: bool = False, keynet_conf: Optional[KeyNet_conf] = None) -> None:+ def __init__(self, pretrained: bool = True, keynet_conf: Optional[KeyNet_conf] = None) -> None:super().__init__()if keynet_conf is None:keynet_conf = keynet_default_config@@ -184,7 +186,7 @@ class KeyNet(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(KeyNet_URL, map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"], strict=True)- self.eval()+ self.eval()def forward(self, x: torch.Tensor) -> torch.Tensor:"""X - input image."""@@ -214,7 +216,9 @@ class KeyNetDetector(MultiResolutionDetector):Args:pretrained: Download and set pretrained weights to the model.num_features: Number of features to detect.- keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing.+ keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing. A+ ``num_levels`` or ``kernel_size`` other than the default changes the architecture: pass+ ``pretrained=False`` with it, since the strict load of the weights raises ``RuntimeError``.ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,@@ -228,7 +232,7 @@ class KeyNetDetector(MultiResolutionDetector):def __init__(self,- pretrained: bool = False,+ pretrained: bool = True,num_features: int = 2048,keynet_conf: Optional[KeyNet_conf] = None,ori_module: Optional[nn.Module] = None,diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex 850547acc..f22c48409 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -485,6 +485,8 @@ class LightGlue(nn.Module):using a series of transformer layers and an adaptive pruning mechanism.Convention:+ - Complete learned weights return the model in evaluation mode, even if derived buffers are absent from+ the checkpoint. Random or partially loaded learned weights leave it in training mode.- The ``keypoints`` of each image are ``(x, y)`` pixels and ``image_size`` is ``(W, H)``; an ``image``tensor gives the size from its last two dimensions instead. ``forward`` normalises the keypoints to``(k - size / 2) / (max(size) / 2)``, as the reference implementation does, and raises for a keypoint@@ -698,7 +700,11 @@ class LightGlue(nn.Module):state_dict = {k.replace(*pattern): v for k, v in state_dict.items()}pattern = f"cross_attn.{i}", f"transformers.{i}.cross_attn"state_dict = {k.replace(*pattern): v for k, v in state_dict.items()}- self.load_state_dict(state_dict, strict=False)+ incompatible = self.load_state_dict(state_dict, strict=False)+ # Missing derived buffers are harmless, but partial learned weights leave a model to train.+ parameters = dict(self.named_parameters())+ if not any(name in parameters for name in incompatible.missing_keys):+ self.eval()# static lengths LightGlue is compiled for (only used with torch.compile)self.static_lengths = Nonediff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.pyindex 25c692f17..dbaf6569b 100644--- a/kornia/feature/loftr/loftr.py+++ b/kornia/feature/loftr/loftr.py@@ -106,8 +106,10 @@ class LoFTR(nn.Module):pretrained: Download and set pretrained weights to the model. Options: 'outdoor', 'indoor', 'indoor_new'.'outdoor' is trained on the MegaDepth dataset and 'indoor' and 'indoor_new'on the ScanNet. 'indoor_new' also switches the positional encoding of the copy- to ``temp_bug_fix=True``, which is what its checkpoint was trained with. ``None`` loads no- weights.+ to ``temp_bug_fix=True``, which is what its checkpoint was trained with. The weighted model+ comes back in evaluation mode. ``None`` builds random weights in training mode, where+ ``CoarseMatching`` runs its supervised training branch and needs ground-truth data; call+ ``.eval()`` for inference, also after loading your own weights.Returns:Dictionary with image correspondences and confidence scores.@@ -149,7 +151,7 @@ class LoFTR(nn.Module):pretrained_dict = load_state_dict_from_url(urls[pretrained], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"])- self.eval()+ self.eval()def extract_features(self, image: torch.Tensor) -> dict[str, torch.Tensor]:r"""Compute the features of images that do not depend on the image they are matched with.@@ -168,7 +170,7 @@ class LoFTR(nn.Module):default config this is 128 channels, about 96 MB in float32 for a 1024 x 736 image.Example:- >>> loftr = LoFTR(None)+ >>> loftr = LoFTR(None).eval()>>> images = [torch.rand(1, 1, 64, 80), torch.rand(1, 1, 72, 64), torch.rand(1, 1, 64, 64)]>>> features = [loftr.extract_features(image) for image in images]>>> out = loftr({"features0": features[0], "features1": features[1]})diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex 894271311..03b6671f2 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -222,12 +222,12 @@ class OriNet(nn.Module):Examples:>>> input = torch.rand(16, 1, 32, 32)- >>> orinet = OriNet()+ >>> orinet = OriNet(pretrained=False).eval()>>> angle = orinet(input) # 16"""- def __init__(self, pretrained: bool = False, eps: float = 1e-8) -> None:+ def __init__(self, pretrained: bool = True, eps: float = 1e-8) -> None:super().__init__()self.features = nn.Sequential(nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),@@ -258,7 +258,7 @@ class OriNet(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(urls["orinet"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"], strict=False)- self.eval()+ self.eval()@staticmethoddef _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.pyindex d3b775ce2..751c59bb8 100644--- a/kornia/feature/sold2/sold2.py+++ b/kornia/feature/sold2/sold2.py@@ -95,13 +95,14 @@ class SOLD2(nn.Module):pretrained_dict = load_state_dict_from_url(urls["wireframe"], map_location=torch.device("cpu"))state_dict = self.adapt_state_dict(pretrained_dict["model_state_dict"])self.model.load_state_dict(state_dict)- self.eval()# Initialize the line detectorself.line_detector = LineSegmentDetectionModule(self.config.line_detector_cfg)# Initialize the line matcherself.line_matcher = WunschLineMatcher(self.config.line_matcher_cfg)+ if pretrained:+ self.eval()def forward(self, img: torch.Tensor) -> Dict[str, Any]:"""Run forward.diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.pyindex 3392454d3..945b3e6a4 100644--- a/kornia/feature/sold2/sold2_detector.py+++ b/kornia/feature/sold2/sold2_detector.py@@ -62,7 +62,7 @@ class SOLD2_detector(nn.Module):Example:>>> img = torch.rand(1, 1, 128, 128)- >>> sold2_detector = SOLD2_detector(pretrained=False)+ >>> sold2_detector = SOLD2_detector(pretrained=False).eval()>>> line_segments = sold2_detector(img)["line_segments"]"""@@ -91,10 +91,11 @@ class SOLD2_detector(nn.Module):pretrained_dict = load_state_dict_from_url(urls["wireframe"], map_location=torch.device("cpu"))state_dict = self.adapt_state_dict(pretrained_dict["model_state_dict"])self.model.load_state_dict(state_dict)- self.eval()# Initialize the line detector with a configuration from the dataclassself.line_detector = LineSegmentDetectionModule(self.config.line_detector_cfg)+ if pretrained:+ self.eval()def adapt_state_dict(self, state_dict: Dict[str, Any]) -> Dict[str, Any]:"""Adapt pretrained checkpoint keys to this module implementation.diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex 5e288c448..0a1ad6fbd 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -57,14 +57,14 @@ class SOSNet(nn.Module):Examples:>>> input = torch.rand(8, 1, 32, 32)- >>> sosnet = SOSNet()+ >>> sosnet = SOSNet(pretrained=False).eval()>>> descs = sosnet(input) # 8x128"""patch_size = 32- def __init__(self, pretrained: bool = False) -> None:+ def __init__(self, pretrained: bool = True) -> None:super().__init__()self.layers = _DescriptorSequential(nn.InstanceNorm2d(1, affine=False),@@ -95,7 +95,7 @@ class SOSNet(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(urls["lib"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)- self.eval()+ self.eval()def forward(self, input: torch.Tensor, eps: float = 1e-10) -> torch.Tensor:"""Compute SOSNet descriptors for grayscale 32x32 patches.diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.pyindex 86a47a147..623f83361 100644--- a/kornia/feature/tfeat.py+++ b/kornia/feature/tfeat.py@@ -63,14 +63,14 @@ class TFeat(nn.Module):Examples:>>> input = torch.rand(16, 1, 32, 32)- >>> tfeat = TFeat()+ >>> tfeat = TFeat(pretrained=False).eval()>>> descs = tfeat(input) # 16x128"""patch_size = 32- def __init__(self, pretrained: bool = False) -> None:+ def __init__(self, pretrained: bool = True) -> None:super().__init__()self.features = nn.Sequential(nn.InstanceNorm2d(1, affine=False),@@ -85,7 +85,7 @@ class TFeat(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(urls["liberty"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)- self.eval()+ self.eval()def forward(self, input: torch.Tensor) -> torch.Tensor:"""Compute TFeat descriptors for grayscale 32x32 patches.diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.pyindex 3950ba7bd..4fed6845c 100644--- a/kornia/feature/xfeat.py+++ b/kornia/feature/xfeat.py@@ -301,11 +301,10 @@ class XFeat(nn.Module):Convention:- XFeat defines no ``forward``: call :meth:`detectAndCompute` or :meth:`detectAndComputeDense`.- - ``XFeat()`` starts in evaluation mode, like :meth:`from_pretrained` and the reference implementation. The- inference methods are run under ``torch.inference_mode``; in training mode BatchNorm would normalise with- the statistics of the batch, so a keypoint or match would depend on the rest of the batch, update its- running statistics on every call, and raise on a single match. Call ``.train()`` to opt in explicitly; the- methods then behave as torch's training-mode BatchNorm does.+ - ``XFeat()`` builds random weights in training mode, where BatchNorm normalises with the batch, updates its+ running statistics on every call, and matching a single small image pair raises; call ``.eval()`` for+ inference. :meth:`from_pretrained` returns the trained model in evaluation mode. The inference methods+ run under ``torch.inference_mode``.- The image is :math:`(B, C, H, W)` with any channel count. Each extraction resizes the image it getsbilinearly to :math:`(H', W')`: ``H`` and ``W`` rounded down to multiples of 32, with a minimum of 32.:class:`XFeatModel` then averages the channels and instance-normalises the result, so an affine change of the@@ -352,7 +351,7 @@ class XFeat(nn.Module):every candidate of the reference that kornia leaves out lies in that border strip.Example:- >>> model = XFeat()+ >>> model = XFeat.from_pretrained()>>> img = torch.rand(1, 3, 256, 256)>>> out = model.detectAndCompute(img)>>> out[0]['keypoints'].shape@@ -369,8 +368,6 @@ class XFeat(nn.Module):self.interpolator = InterpolateSparse2d("bicubic")self._nearest = InterpolateSparse2d("nearest")self._bilinear = InterpolateSparse2d("bilinear")- # like :meth:`from_pretrained` and the reference: the inference methods must not run BatchNorm in training mode- self.eval()@classmethoddef from_pretrained(cls, top_k: int = 4096, detection_threshold: float = 0.05) -> XFeat:diff --git a/tests/contrib/test_image_stitcher.py b/tests/contrib/test_image_stitcher.pyindex 7798213b8..aef250e96 100644--- a/tests/contrib/test_image_stitcher.py+++ b/tests/contrib/test_image_stitcher.py@@ -400,7 +400,7 @@ class TestImageStitcher(BaseTester):sample1 = torch.rand(B, C, H, W, device=device, dtype=dtype)sample2 = torch.rand(B, C, H, W, device=device, dtype=dtype)# NOTE: This will need to download the pretrained weights.- matcher = kornia.feature.LoFTR(None)+ matcher = kornia.feature.LoFTR(None).eval()with pytest.raises(NotImplementedError):stitcher = kornia.contrib.ImageStitcher(matcher, estimator="random").to(device=device, dtype=dtype)diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.pyindex 5c432631b..64bc04fcd 100644--- a/tests/core/test_weights_prefetch.py+++ b/tests/core/test_weights_prefetch.py@@ -215,7 +215,6 @@ _DOWNLOAD_CALL_ALLOWLIST = {NOT_PREFETCHED: dict[str, str] = {# Alternative training sets -- tests only ever build the liberty variants."HardNetPP.pth": "HardNet++ weights; no test or doctest requests them",- "hardnet8v2.pt": "HardNet8(pretrained=True); tests build HardNet8() untrained","HyNet_ND.pth": "notredame variant; tests use the liberty default","HyNet_YOS.pth": "yosemite variant; tests use the liberty default","sosnet_32x32_hpatches_a.pth": "hpatches variant; tests use the liberty default",@@ -223,7 +222,9 @@ NOT_PREFETCHED: dict[str, str] = {"tfeat-yosemite.params": "yosemite variant; tests use the liberty default",# Model variants no test selects."loftr_indoor_ds_new.ckpt": "tests instantiate LoFTR('indoor') and LoFTR('outdoor') only",- "sold2_wireframe.tar": "every SOLD2_detector in the suite passes pretrained=False",+ "sold2_wireframe.tar": (+ "the suite builds SOLD2_detector random, or weighted through the prefetched, byte-identical sold2_wireframe.pth"+ ),"epipolar-save.pth": "tests call DISK.from_pretrained(checkpoint='depth')",# LightGlue heads: tests build the disk and doghardnet matchers, and the# suite also reaches the superpoint head. The rest are unused.diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.pyindex 4f1256967..1d49c6d6d 100644--- a/tests/feature/test_affine_shape_estimator.py+++ b/tests/feature/test_affine_shape_estimator.py@@ -481,7 +481,7 @@ class TestLAFAffNetShapeEstimator(BaseTester):def test_singular_prediction_falls_back_upright(self, device, dtype):img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)laf = torch.tensor([[[[0.0, 8.0, 16.0], [-8.0, 0.0, 16.0]]]], device=device, dtype=dtype)- aff = LAFAffNetShapeEstimator(preserve_orientation=False).to(device, dtype)+ aff = LAFAffNetShapeEstimator(pretrained=False, preserve_orientation=False).to(device, dtype).eval()aff.features = SingularAffNetOutput()out = aff(laf, img)self.assert_close(out, make_upright(laf))@@ -493,7 +493,11 @@ class TestLAFAffNetShapeEstimator(BaseTester):# make_upright(laf), so the image region is frame @ P: an identity prediction keeps the input shape.img = torch.rand(1, 1, 48, 64, device=device, dtype=dtype)laf = _laf_with_shape(_SKEWED_SHAPE, (30.0, 22.0), device, dtype)- aff = LAFAffNetShapeEstimator(preserve_orientation=preserve_orientation).to(device, dtype)+ aff = (+ LAFAffNetShapeEstimator(pretrained=False, preserve_orientation=preserve_orientation)+ .to(device, dtype)+ .eval()+ )aff.features = ConstantAffNetOutput(xy)out = aff(laf, img)frame = make_upright(laf)[0, 0, :, :2].cpu().double()@@ -529,7 +533,11 @@ class TestLAFAffNetShapeEstimator(BaseTester):pytest.skip("MPS autocast changes the effective dtype")img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)laf = torch.tensor([[[[0.0, 0.0, 16.0], [0.0, 0.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)- aff = LAFAffNetShapeEstimator(pretrained=False, preserve_orientation=preserve_orientation).to(device, dtype)+ aff = (+ LAFAffNetShapeEstimator(pretrained=False, preserve_orientation=preserve_orientation)+ .to(device, dtype)+ .eval()+ )aff.features = SingularAffNetOutput()out = aff(laf, img)@@ -560,12 +568,12 @@ class TestLAFAffNetShapeEstimator(BaseTester):def test_shape_batch(self, device):inp = torch.rand(2, 1, 32, 32, device=device)laf = torch.rand(2, 5, 2, 3, device=device)- ori = LAFAffNetShapeEstimator().to(device).eval()+ ori = LAFAffNetShapeEstimator(pretrained=False).to(device).eval()out = ori(laf, inp)assert out.shape == laf.shapedef test_print(self, device):- sift = LAFAffNetShapeEstimator()+ sift = LAFAffNetShapeEstimator(pretrained=False)sift.__repr__()def test_toy(self, device, dtype):@@ -611,7 +619,11 @@ class TestLAFAffNetShapeEstimator(BaseTester):xy = (0.2, -0.3, -0.4)img = torch.rand(1, 1, 96, 128, device=device, dtype=dtype)laf = _laf_with_shape(_LARGE_SHAPE, (70.0, 41.0), device, dtype)- aff = LAFAffNetShapeEstimator(preserve_orientation=preserve_orientation).to(device, dtype)+ aff = (+ LAFAffNetShapeEstimator(pretrained=False, preserve_orientation=preserve_orientation)+ .to(device, dtype)+ .eval()+ )aff.features = ConstantAffNetOutput(xy)out = aff(laf, img)assert out.dtype == dtypediff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex 645c849ef..fe5cb9bb2 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -245,7 +245,7 @@ class TestDeformConv2d(BaseTester):class TestALIKED(BaseTester):def test_smoke(self, dtype, device):- aliked = ALIKED().to(device, dtype)+ aliked = ALIKED().to(device, dtype).eval()inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)output = aliked(inp)assert isinstance(output, list)@@ -253,7 +253,7 @@ class TestALIKED(BaseTester):assert isinstance(output[0], ALIKEDFeatures)def test_smoke_batch(self, dtype, device):- aliked = ALIKED().to(device, dtype)+ aliked = ALIKED().to(device, dtype).eval()inp = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)output = aliked(inp)assert len(output) == 2@@ -261,14 +261,14 @@ class TestALIKED(BaseTester):def test_grayscale_input(self, dtype, device):"""1-channel input should be broadcast to 3 channels automatically."""- aliked = ALIKED().to(device, dtype)+ aliked = ALIKED().to(device, dtype).eval()inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)output = aliked(inp)assert isinstance(output[0], ALIKEDFeatures)def test_output_shapes(self, dtype, device):"""Keypoints should be (N,2), descriptors (N,D), scores (N,)."""- aliked = ALIKED(model_name="aliked-t16").to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)output = aliked(inp)feat = output[0]@@ -279,7 +279,7 @@ class TestALIKED(BaseTester):def test_descriptor_normalized(self, dtype, device):"""Descriptors should be L2-normalised."""- aliked = ALIKED(model_name="aliked-t16").to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)output = aliked(inp)feat = output[0]@@ -297,7 +297,7 @@ class TestALIKED(BaseTester):def test_keypoints_in_image(self, dtype, device):"""Keypoints should lie within the image boundaries."""H, W = 64, 64- aliked = ALIKED(model_name="aliked-t16").to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()inp = torch.rand(1, 3, H, W, device=device, dtype=dtype)output = aliked(inp)feat = output[0]@@ -310,7 +310,7 @@ class TestALIKED(BaseTester):@pytest.mark.parametrize("model_name", ["aliked-t16", "aliked-n16", "aliked-n32"])def test_model_configs(self, device, model_name):"""All model configurations should run without error."""- aliked = ALIKED(model_name=model_name).to(device)+ aliked = ALIKED(model_name=model_name).to(device).eval()inp = torch.rand(1, 3, 64, 64, device=device)output = aliked(inp)assert len(output) == 1@@ -370,7 +370,7 @@ class TestALIKEDHalfPrecisionCoordinates(BaseTester):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")torch.manual_seed(0)- aliked = ALIKED(model_name="aliked-t16").to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()image = torch.rand(1, 3, 96, 400, generator=torch.Generator().manual_seed(0)).to(device, dtype)with torch.no_grad():(feats,) = aliked(image)@@ -390,7 +390,7 @@ class TestALIKEDForwardLAF(BaseTester):def test_smoke(self, device, dtype):"""forward_laf should return the three expected tensors."""- aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=32).to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=32).to(device, dtype).eval()inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)lafs, responses, descs = aliked.forward_laf(inp, compute_affine=False)assert lafs.ndim == 4 # (B, N, 2, 3)@@ -401,7 +401,7 @@ class TestALIKEDForwardLAF(BaseTester):"""Shapes should be (B, N, 2, 3), (B, N, 1), (B, N, D)."""B, H, W = 2, 64, 64top_k = 20- aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype).eval()inp = torch.rand(B, 3, H, W, device=device, dtype=dtype)lafs, responses, descs = aliked.forward_laf(inp, compute_affine=False)N = lafs.shape[1]@@ -414,7 +414,7 @@ class TestALIKEDForwardLAF(BaseTester):"""LAF centres (col 2) should lie within image bounds."""H, W = 64, 64top_k = 30- aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype).eval()inp = torch.rand(1, 3, H, W, device=device, dtype=dtype)lafs, responses, _ = aliked.forward_laf(inp, compute_affine=False)# Only check keypoints with positive response (non-padding).@@ -429,7 +429,7 @@ class TestALIKEDForwardLAF(BaseTester):def test_batch_padding(self, device, dtype):"""All images in the batch should share the same N (padded to max)."""B = 3- aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=25).to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=25).to(device, dtype).eval()inp = torch.rand(B, 3, 64, 64, device=device, dtype=dtype)lafs, responses, descs = aliked.forward_laf(inp, compute_affine=False)assert lafs.shape[0] == B@@ -439,7 +439,7 @@ class TestALIKEDForwardLAF(BaseTester):def test_laf_with_mask(self, device, dtype):"""Providing a mask should suppress keypoints in the masked region."""H, W = 64, 64- aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=40).to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=40).to(device, dtype).eval()inp = torch.rand(1, 3, H, W, device=device, dtype=dtype)# Suppress the entire image except the bottom-right quarter.mask = torch.zeros(1, 1, H, W, device=device, dtype=dtype)@@ -455,7 +455,7 @@ class TestALIKEDForwardLAF(BaseTester):half-precision dtypes) which is slower than the identity-affine path."""top_k = 20- aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype).eval()inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)lafs, responses, _ = aliked.forward_laf(inp, compute_affine=True)valid = responses[0, :, 0] > 0@@ -908,8 +908,12 @@ class TestConventionsALIKED(BaseTester):hook.remove()-class TestALIKEDEvalByDefault(BaseTester):- """``ALIKED()`` starts in evaluation mode: BatchNorm uses its running statistics, not those of the batch."""+class TestALIKEDModes(BaseTester):+ """``ALIKED()`` builds random weights in training mode and ``ALIKED.from_pretrained`` returns evaluation mode.++ In evaluation mode BatchNorm uses its running statistics, not those of the batch; the inference pins below run a+ random model after ``.eval()``.+ """@pytest.fixture(autouse=True)def _kernels(self, device, dtype):@@ -918,18 +922,25 @@ class TestALIKEDEvalByDefault(BaseTester):@staticmethoddef _model(device, dtype):- # the default constructor, deliberately without .eval()- return ALIKED(model_name="aliked-t16").to(device, dtype)+ return ALIKED(model_name="aliked-t16").to(device, dtype).eval()- def test_convention_aliked_starts_in_eval_mode(self, device, dtype):- aliked = self._model(device, dtype)+ def test_convention_aliked_random_init_is_training_mode(self, device, dtype):+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype)+ assert aliked.training+ assert all(m.training for m in aliked.modules())++ def test_convention_aliked_from_pretrained_is_eval_mode(self, device, dtype, monkeypatch):+ weights = ALIKED(model_name="aliked-t16").state_dict()+ monkeypatch.setattr("kornia.feature.aliked.aliked.load_state_dict_from_url", lambda urls, **kwargs: weights)+ aliked = ALIKED.from_pretrained("aliked-t16", device=device)assert not aliked.trainingassert 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+ def test_convention_aliked_eval_is_the_explicit_opt_in_for_random_weights(self, device, dtype):+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype)assert all(m.training for m in aliked.modules() if isinstance(m, torch.nn.BatchNorm2d))+ aliked.eval()+ assert not any(m.training for m in aliked.modules())@pytest.mark.parametrize("method", ["forward", "extract_dense_map", "forward_laf"])def test_convention_aliked_inference_leaves_the_state_unchanged(self, method, device, dtype):diff --git a/tests/feature/test_defmo.py b/tests/feature/test_defmo.pyindex a9e9bc2c5..128647469 100644--- a/tests/feature/test_defmo.py+++ b/tests/feature/test_defmo.py@@ -90,7 +90,7 @@ class TestDeFMO(BaseTester):@pytest.mark.slowdef test_shape(self, device, dtype):inp = torch.ones(1, 6, 128, 160, device=device, dtype=dtype)- defmo = DeFMO().to(device, dtype)+ defmo = DeFMO(pretrained=False).to(device, dtype)defmo.eval() # batchnorm with size 1 is not allowed in train modeout = defmo(inp)assert out.shape == (1, 24, 4, 128, 160)@@ -98,7 +98,7 @@ class TestDeFMO(BaseTester):@pytest.mark.slowdef test_shape_batch(self, device, dtype):inp = torch.ones(2, 6, 128, 160, device=device, dtype=dtype)- defmo = DeFMO().to(device, dtype)+ defmo = DeFMO(pretrained=False).to(device, dtype).eval()out = defmo(inp)with torch.no_grad():assert out.shape == (2, 24, 4, 128, 160)@@ -106,7 +106,7 @@ class TestDeFMO(BaseTester):@pytest.mark.slowdef test_gradcheck(self, device):patches = torch.rand(2, 6, 64, 64, device=device, dtype=torch.float64)- defmo = DeFMO().to(patches.device, patches.dtype)+ defmo = DeFMO(pretrained=False).to(patches.device, patches.dtype).eval()self.gradcheck(defmo, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)@pytest.mark.slow@@ -144,7 +144,7 @@ class TestConventionsDeFMO(BaseTester):# matters to the trained weights and is not visible here.with torch.random.fork_rng(devices=[]):torch.manual_seed(0)- model = DeFMO().eval()+ model = DeFMO(pretrained=False).eval()model = model.to(device, dtype)values = torch.tensor([-3.0, -1.0, 0.5, 4.0], device=device, dtype=dtype)model.rendering.net = _RecordingRenderer(values)diff --git a/tests/feature/test_descriptor_normalization.py b/tests/feature/test_descriptor_normalization.pyindex 520c7d6bf..99ddd50d2 100644--- a/tests/feature/test_descriptor_normalization.py+++ b/tests/feature/test_descriptor_normalization.py@@ -31,7 +31,7 @@ class TestDescriptorNormalization(BaseTester):@pytest.mark.parametrize("model_cls", [SOSNet, HyNet])@pytest.mark.parametrize("model_dtype", [torch.float32, torch.float16])def test_dynamo_laf_descriptor(self, device, torch_optimizer, model_cls, model_dtype):- model = model_cls().to(device)+ model = model_cls(pretrained=False).to(device).eval()norm = [layer for layer in model.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]norm.running_var.fill_(1e5)model.to(model_dtype)@@ -49,7 +49,7 @@ class TestDescriptorNormalization(BaseTester):try:torch.set_default_dtype(torch.float16)with torch.device(device):- model = model_cls()+ model = model_cls(pretrained=False).eval()finally:torch.set_default_dtype(default_dtype)norm = [layer for layer in model.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]@@ -63,7 +63,7 @@ class TestDescriptorNormalization(BaseTester):@pytest.mark.parametrize("model_dtype", [torch.float32, torch.float16])@pytest.mark.parametrize("scripted", [False, True])def test_laf_descriptor_half_statistics(self, device, model_cls, model_dtype, scripted):- model = model_cls().to(device)+ model = model_cls(pretrained=False).to(device).eval()norm = [layer for layer in model.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]norm.running_var.copy_(torch.linspace(1e5, 5e6, norm.num_features, device=device))model = model.to(model_dtype)@@ -104,7 +104,7 @@ class TestDescriptorNormalization(BaseTester):@pytest.mark.parametrize("model_cls", [SOSNet, HyNet])@pytest.mark.parametrize("convert", ["half", "to"])def test_half_preserves_running_statistics(self, device, model_cls, convert):- model = model_cls().to(device)+ model = model_cls(pretrained=False).to(device).eval()norm = [layer for layer in model.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]# The published SOSNet and HyNet checkpoints contain variances up to 1.2e5 and 5.3e6.norm.running_var.copy_(torch.linspace(1e5, 5e6, norm.num_features, device=device))@@ -172,15 +172,15 @@ class TestDescriptorNormalization(BaseTester):@pytest.mark.parametrize("model_cls", [SOSNet, HyNet])def test_half_load_state_dict(self, device, model_cls):- source = model_cls().to(device)+ source = model_cls(pretrained=False).to(device).eval()norm = [layer for layer in source.modules() if isinstance(layer, torch.nn.BatchNorm2d)][-1]norm.running_var.fill_(1e5)- target = model_cls().to(device).half()+ target = model_cls(pretrained=False).to(device).eval().half()target.load_state_dict(source.state_dict(), strict=True)source.half()patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float16)self.assert_close(target(patches), source(patches), rtol=0.0, atol=0.0)- restored = model_cls().to(device).half()+ restored = model_cls(pretrained=False).to(device).eval().half()restored.load_state_dict(target.state_dict(), strict=True)self.assert_close(restored(patches), target(patches), rtol=0.0, atol=0.0)@@ -208,7 +208,7 @@ class TestDescriptorNormalization(BaseTester):@pytest.mark.parametrize("model_cls", [SOSNet, HyNet])@pytest.mark.parametrize("selection", [slice(None), slice(None, -1), slice(1, None), slice(0, 0), slice(None, 3)])def test_sequential_slices(self, device, model_cls, selection):- model = model_cls().to(device)+ model = model_cls(pretrained=False).to(device).eval()block = model.layers if model_cls is SOSNet else model.layer7block[-1].running_var.fill_(1e5)sliced = block[selection]@@ -229,7 +229,7 @@ class TestDescriptorNormalization(BaseTester):@pytest.mark.parametrize("model_cls", [SOSNet, HyNet])def test_slicing_does_not_change_source_statistics(self, device, model_cls):- model = model_cls().to(device).half()+ model = model_cls(pretrained=False).to(device).eval().half()block = model.layers if model_cls is SOSNet else model.layer7before = dict(model.named_buffers())patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float16)diff --git a/tests/feature/test_hardnet.py b/tests/feature/test_hardnet.pyindex 0ccf60e25..d5a5e5ca3 100644--- a/tests/feature/test_hardnet.py+++ b/tests/feature/test_hardnet.py@@ -28,7 +28,7 @@ class TestHardNet(BaseTester):@pytest.mark.slowdef test_shape(self, device):inp = torch.ones(1, 1, 32, 32, device=device)- hardnet = HardNet().to(device)+ hardnet = HardNet(pretrained=False).to(device)hardnet.eval() # batchnorm with size 1 is not allowed in train modeout = hardnet(inp)assert out.shape == (1, 128)@@ -36,48 +36,48 @@ class TestHardNet(BaseTester):@pytest.mark.slowdef test_shape_batch(self, device):inp = torch.ones(4, 1, 32, 32, device=device)- hardnet = HardNet().to(device)+ hardnet = HardNet(pretrained=False).to(device).eval()out = hardnet(inp)assert out.shape == (4, 128)def test_gradcheck(self, device):patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)- hardnet = HardNet().to(patches.device, patches.dtype)+ hardnet = HardNet(pretrained=False).to(patches.device, patches.dtype).eval()self.gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)def test_jit(self, device, dtype):B, C, H, W = 2, 1, 32, 32patches = torch.ones(B, C, H, W, device=device, dtype=dtype)- model = HardNet().to(patches.device, patches.dtype).eval()- model_jit = torch.jit.script(HardNet().to(patches.device, patches.dtype).eval())+ model = HardNet(pretrained=False).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(HardNet(pretrained=False).to(patches.device, patches.dtype).eval())self.assert_close(model(patches), model_jit(patches))class TestHardNet8(BaseTester):def test_shape(self, device):inp = torch.ones(1, 1, 32, 32, device=device)- hardnet = HardNet8().to(device)+ hardnet = HardNet8(pretrained=False).to(device)hardnet.eval() # batchnorm with size 1 is not allowed in train modeout = hardnet(inp)assert out.shape == (1, 128)def test_shape_batch(self, device):inp = torch.ones(4, 1, 32, 32, device=device)- hardnet = HardNet8().to(device)+ hardnet = HardNet8(pretrained=False).to(device).eval()out = hardnet(inp)assert out.shape == (4, 128)@pytest.mark.skip("jacobian not well computed")def test_gradcheck(self, device):patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float32)- hardnet = HardNet8().to(patches.device, patches.dtype)+ hardnet = HardNet8(pretrained=False).to(patches.device, patches.dtype).eval()self.gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4)def test_jit(self, device, dtype):B, C, H, W = 2, 1, 32, 32patches = torch.ones(B, C, H, W, device=device, dtype=dtype)- model = HardNet8().to(patches.device, patches.dtype).eval()- model_jit = torch.jit.script(HardNet8().to(patches.device, patches.dtype).eval())+ model = HardNet8(pretrained=False).to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(HardNet8(pretrained=False).to(patches.device, patches.dtype).eval())self.assert_close(model(patches), model_jit(patches))def test_untrained_descriptors_are_distinct_5692(self, device, dtype):@@ -86,7 +86,7 @@ class TestHardNet8(BaseTester):pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")torch.manual_seed(0)patches = torch.rand(8, 1, 32, 32, device=device, dtype=dtype)- out = HardNet8().to(device, dtype)(patches)+ out = HardNet8(pretrained=False).eval().to(device, dtype)(patches)assert out.shape == (8, 128)self.assert_close(out.norm(dim=1), torch.ones(8, device=device, dtype=dtype))cos = out @ out.T@@ -98,7 +98,7 @@ class TestHardNet8(BaseTester):pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")torch.manual_seed(0)patches = torch.rand(4, 1, 32, 32, device=device, dtype=dtype)- model = HardNet8().to(device, dtype)+ model = HardNet8(pretrained=False).to(device, dtype).eval()features = model.features(model._normalize_input(patches)).view(4, -1)expected = torch.nn.functional.normalize(torch.nn.functional.normalize(features, dim=1)[:, :128], dim=1)self.assert_close(model(patches), expected)@@ -109,7 +109,7 @@ class TestHardNet8(BaseTester):pytest.skip("half-precision rounding leaves a noise gradient on the degenerate placeholder as well")torch.manual_seed(0)patches = torch.rand(4, 1, 32, 32, device=device, dtype=dtype)- model = HardNet8().to(device, dtype)+ model = HardNet8(pretrained=False).to(device, dtype).eval()target = torch.randn(4, 128, device=device, dtype=dtype)(model(patches) * target).sum().backward()grad = model.features[0].weight.grad@@ -118,7 +118,7 @@ class TestHardNet8(BaseTester):def test_checkpoint_layout_is_unchanged_5692(self, device):# The pretrained checkpoint loads with strict=True, so the buffer names and shapes must stay.- model = HardNet8().to(device)+ model = HardNet8(pretrained=False).to(device)state = model.state_dict()assert state["components"].shape == (512, 128)assert state["mean"].shape == (512,)@@ -142,7 +142,7 @@ class TestHardNetConstantPatchIsFinite(BaseTester):# The descriptor is a stack of convolutions; torch 2.1.2 has no float16 CPU kernel.pytest.skip(f"no conv2d kernel for {desc_dtype} on {device.type}")patches = torch.zeros(2, 1, 32, 32, device=device, dtype=desc_dtype)- out = model().to(device, desc_dtype)(patches)+ out = model(pretrained=False).eval().to(device, desc_dtype)(patches)assert torch.isfinite(out).all()@@ -150,11 +150,11 @@ class TestHardNetConstantPatchIsFinite(BaseTester):# pads with mode="replicate" (its gradient filters). MKD runs unwhitened, which needs no download either and returns# the full 238-dimensional concat embedding._PATCH_DESCRIPTORS = {- "HardNet": (HardNet, 32, 128, False),- "HardNet8": (HardNet8, 32, 128, False),- "HyNet": (HyNet, 32, 128, False),- "SOSNet": (SOSNet, 32, 128, False),- "TFeat": (TFeat, 32, 128, False),+ "HardNet": (lambda: HardNet(pretrained=False).eval(), 32, 128, False),+ "HardNet8": (lambda: HardNet8(pretrained=False).eval(), 32, 128, False),+ "HyNet": (lambda: HyNet(pretrained=False).eval(), 32, 128, False),+ "SOSNet": (lambda: SOSNet(pretrained=False).eval(), 32, 128, False),+ "TFeat": (lambda: TFeat(pretrained=False).eval(), 32, 128, False),"MKDDescriptor": (lambda: MKDDescriptor(whitening=None), 32, 238, True),"SIFTDescriptor": (lambda: SIFTDescriptor(32), 32, 128, True),}diff --git a/tests/feature/test_hynet.py b/tests/feature/test_hynet.pyindex a31722dd3..76fbedaee 100644--- a/tests/feature/test_hynet.py+++ b/tests/feature/test_hynet.py@@ -35,7 +35,7 @@ class TestHyNet(BaseTester):def test_shape(self, device):inp = torch.ones(1, 1, 32, 32, device=device)- hynet = HyNet().to(device)+ hynet = HyNet(pretrained=False).to(device).eval()out = hynet(inp)assert out.shape == (1, 128)@@ -43,17 +43,17 @@ class TestHyNet(BaseTester):def test_wrong_patch_shape_is_rejected_5724(self, device, shape):# without the check a 40x40 patch silently produced a (2, 1152) descriptorwith pytest.raises(ShapeError):- HyNet().to(device)(torch.ones(*shape, device=device))+ HyNet(pretrained=False).to(device).eval()(torch.ones(*shape, device=device))def test_shape_batch(self, device):inp = torch.ones(4, 1, 32, 32, device=device)- hynet = HyNet().to(device)+ hynet = HyNet(pretrained=False).to(device).eval()out = hynet(inp)assert out.shape == (4, 128)def test_gradcheck(self, device):patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)- hynet = HyNet().to(patches.device, patches.dtype)+ hynet = HyNet(pretrained=False).to(patches.device, patches.dtype).eval()self.gradcheck(hynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)@pytest.mark.parametrize("patch_value", [0.0, 0.5])@@ -66,7 +66,7 @@ class TestHyNet(BaseTester):# float32's exponent range and never had that failure, but on CPU both half dtypes used to# raise out of `avg_pool3d` before reaching the division at all, so both are pinned here.patches = torch.full((2, 1, 32, 32), patch_value, device=device, dtype=dtype)- hynet = HyNet(is_bias=is_bias).to(device, dtype).eval()+ hynet = HyNet(pretrained=False, is_bias=is_bias).to(device, dtype).eval()descriptors = hynet(patches)assert torch.isfinite(descriptors).all(), (f"{int((~torch.isfinite(descriptors)).sum())} non-finite descriptor entries"@@ -79,7 +79,7 @@ class TestHyNet(BaseTester):# NaN if the branch is dropped. `cudnn_tf32_follows_option` is what makes the float32 leg# meaningful on CUDA; see its docstring.patches = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)- model = HyNet().to(device, dtype).eval()+ model = HyNet(pretrained=False).to(device, dtype).eval()op = torch_optimizer(model)self.assert_close(op(patches), model(patches))@@ -88,7 +88,7 @@ class TestHyNet(BaseTester):# `export-support.rst` publishes HyNet as capturable with zero graph breaks. The dtype branch# reads static metadata and must not become the thing that breaks the graph.patches = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)- model = HyNet().to(device, dtype).eval()+ model = HyNet(pretrained=False).to(device, dtype).eval()expected = model(patches)torch._dynamo.reset()compiled = torch.compile(model, fullgraph=True)@@ -97,7 +97,7 @@ class TestHyNet(BaseTester):def test_jit(self, device, dtype):B, C, H, W = 2, 1, 32, 32patches = torch.rand(B, C, H, W, device=device, dtype=dtype)- model = HyNet().to(patches.device, patches.dtype).eval()+ model = HyNet(pretrained=False).to(patches.device, patches.dtype).eval()model_jit = torch.jit.script(model)self.assert_close(model(patches), model_jit(patches))@@ -113,7 +113,7 @@ class TestConventionsHyNet(BaseTester):if not supports_conv2d(device, dtype):pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")torch.manual_seed(0)- model = HyNet().to(device, dtype)+ model = HyNet(pretrained=False).to(device, dtype).eval()patches = torch.rand(4, 1, 32, 32, device=device, dtype=dtype)desc = model(patches)self.assert_close(model(255 * patches), desc)diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex 50656a36f..85ea25b0d 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -445,7 +445,7 @@ class TestDescriptorModuleIsNotModified(BaseTester):# device than the image (a device cast)image_dtype = torch.float64 if torch.device(device).type == "cpu" else torch.float32img, lafs = self._inputs(device, image_dtype)- plain = HardNet(False)+ plain = HardNet(False).eval()scripted = torch.jit.script(copy.deepcopy(plain))before = self._state(scripted)get_laf_descriptors(img, lafs, plain, 32).sum().backward()@@ -693,14 +693,14 @@ class TestDoGHardNet(BaseTester):from kornia.feature import HardNet, LAFAffNetShapeEstimatordef affnet(pretrained=False, preserve_orientation=True):- module = LAFAffNetShapeEstimator(False, preserve_orientation)+ module = LAFAffNetShapeEstimator(False, preserve_orientation).eval()head = module.features[-3]with torch.no_grad():head.weight.zero_()head.bias.copy_(torch.tensor([0.5, 0.3, -0.3]))return module- monkeypatch.setattr("kornia.feature.integrated.HardNet", lambda pretrained=False: HardNet(False))+ monkeypatch.setattr("kornia.feature.integrated.HardNet", lambda pretrained=False: HardNet(False).eval())monkeypatch.setattr("kornia.feature.integrated.LAFAffNetShapeEstimator", affnet)@staticmethod@@ -1246,13 +1246,17 @@ class TestConventionsLocalFeature(BaseTester):from kornia.feature import KeyNetDetector, LAFAffNetShapeEstimator, OriNetintegrated = "kornia.feature.integrated"- monkeypatch.setattr(f"{integrated}.HardNet", lambda pretrained=False: HardNet(False))+ monkeypatch.setattr(f"{integrated}.HardNet", lambda pretrained=False: HardNet(False).eval())monkeypatch.setattr(f"{integrated}.LAFAffNetShapeEstimator",- lambda pretrained=False, preserve_orientation=True: LAFAffNetShapeEstimator(False, preserve_orientation),+ lambda pretrained=False, preserve_orientation=True: LAFAffNetShapeEstimator(+ False, preserve_orientation+ ).eval(),+ )+ monkeypatch.setattr(f"{integrated}.OriNet", lambda pretrained=False, eps=1e-8: OriNet(False).eval())+ monkeypatch.setattr(+ f"{integrated}.KeyNetDetector", lambda pretrained=False, **kw: KeyNetDetector(False, **kw).eval())- monkeypatch.setattr(f"{integrated}.OriNet", lambda pretrained=False, eps=1e-8: OriNet(False))- monkeypatch.setattr(f"{integrated}.KeyNetDetector", lambda pretrained=False, **kw: KeyNetDetector(False, **kw))spec = self._PRESETS[preset]detector, num_features, mr_size, response, orienter, orienter_size, affine, descriptor, patch_size = speccls = getattr(kornia.feature, preset)diff --git a/tests/feature/test_keynet.py b/tests/feature/test_keynet.pyindex c30556bd7..5077d970f 100644--- a/tests/feature/test_keynet.py+++ b/tests/feature/test_keynet.py@@ -33,24 +33,24 @@ def _skip_without_half_padding(device: torch.device, dtype: torch.dtype) -> Noneclass TestKeyNet(BaseTester):def test_dynamo(self, device, dtype, torch_optimizer):inp = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)- model = KeyNet().to(device, dtype)+ model = KeyNet(pretrained=False).to(device, dtype).eval()self.assert_close(torch_optimizer(model)(inp), model(inp))def test_shape(self, device, dtype):inp = torch.rand(1, 1, 16, 16, device=device, dtype=dtype)- keynet = KeyNet().to(device, dtype)+ keynet = KeyNet(pretrained=False).to(device, dtype).eval()out = keynet(inp)assert out.shape == inp.shapedef test_shape_batch(self, device, dtype):inp = torch.ones(16, 1, 16, 16, device=device, dtype=dtype)- keynet = KeyNet().to(device, dtype)+ keynet = KeyNet(pretrained=False).to(device, dtype).eval()out = keynet(inp)assert out.shape == inp.shapedef test_gradcheck(self, device):patches = torch.rand(2, 1, 16, 16, device=device, dtype=torch.float64)- keynet = KeyNet().to(patches.device, patches.dtype)+ keynet = KeyNet(pretrained=False).to(patches.device, patches.dtype).eval()self.gradcheck(keynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)@@ -63,7 +63,7 @@ class TestConventionsKeyNet(BaseTester):_skip_without_half_padding(device, dtype)with torch.random.fork_rng(devices=[]):torch.manual_seed(0)- model = KeyNet()+ model = KeyNet(pretrained=False).eval()with torch.no_grad():model.last_conv[0].bias.fill_(-0.01)img = torch.rand(2, 1, 37, 53, generator=torch.Generator().manual_seed(0)).to(device, dtype)diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.pyindex 9ebae8e0f..43f6d56c3 100644--- a/tests/feature/test_local_features_orientation.py+++ b/tests/feature/test_local_features_orientation.py@@ -281,7 +281,7 @@ class TestOrientationKernelBuffer(BaseTester):class TestOriNet(BaseTester):def test_shape(self, device):inp = torch.rand(1, 1, 32, 32, device=device)- ori = OriNet().to(device=device, dtype=inp.dtype).eval()+ ori = OriNet(pretrained=False).to(device=device, dtype=inp.dtype).eval()ang = ori(inp)assert ang.shape == torch.Size([1])@@ -298,7 +298,7 @@ class TestOriNet(BaseTester):assert ang.shape == torch.Size([2])def test_print(self, device):- sift = OriNet(32)+ sift = OriNet(pretrained=False)sift.__repr__()def test_toy(self, device):@@ -313,7 +313,7 @@ class TestOriNet(BaseTester):def test_gradcheck(self, device):batch_size, channels, height, width = 2, 1, 32, 32patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)- ori = OriNet().to(device=device, dtype=patches.dtype)+ ori = OriNet(pretrained=False).to(device=device, dtype=patches.dtype).eval()self.gradcheck(ori, (patches,), fast_mode=False)def test_jit(self, device, dtype):@@ -422,7 +422,7 @@ class TestConventionsOrientation(BaseTester):# float64.with torch.random.fork_rng(devices=[]):torch.manual_seed(0)- model = OriNet()+ model = OriNet(pretrained=False).eval()patches = torch.rand(3, 1, 32, 32, generator=torch.Generator().manual_seed(1)).to(device, dtype)model = model.to(device, dtype)# half precision rounds the returned angle: bfloat16 spaces the angles here (-1.78 to -1.94 rad) by 1 / 128diff --git a/tests/feature/test_loftr.py b/tests/feature/test_loftr.pyindex a7d6999ac..bd3f5ba50 100644--- a/tests/feature/test_loftr.py+++ b/tests/feature/test_loftr.py@@ -44,7 +44,7 @@ def _loftr_matching_every_cell(device, dtype):cfg["match_coarse"]["thr"] = 0.0cfg["match_coarse"]["border_rm"] = 0torch.manual_seed(0)- return LoFTR(pretrained=None, config=cfg).to(device, dtype)+ return LoFTR(pretrained=None, config=cfg).to(device, dtype).eval()class TestLoFTR(BaseTester):@@ -119,7 +119,7 @@ class TestLoFTR(BaseTester):cfg["match_coarse"]["border_rm"] = 0gen = torch.Generator(device=device).manual_seed(3)patches = torch.rand(1, 1, 64, 64, device=device, generator=gen)- loftr = LoFTR(pretrained=None, config=cfg).to(device)+ loftr = LoFTR(pretrained=None, config=cfg).to(device).eval()mask = torch.ones(1, 64, 64, device=device)mask[..., :16] = 0 # the left quarter of both images is paddingwith torch.no_grad():@@ -1190,7 +1190,7 @@ class TestConventionsLoFTR(BaseTester):return feat0, feat1, datatorch.manual_seed(0)- model = LoFTR(pretrained=None).to(device, dtype)+ model = LoFTR(pretrained=None).to(device, dtype).eval()model.coarse_matching.register_forward_pre_hook(coarse_features)model.fine_matching.register_forward_pre_hook(fine_features)return modeldiff --git a/tests/feature/test_pretrained_mode.py b/tests/feature/test_pretrained_mode.pynew file mode 100644index 000000000..94525e155--- /dev/null+++ b/tests/feature/test_pretrained_mode.py@@ -0,0 +1,202 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++"""The mode in which the learned models of ``kornia.feature`` are constructed.++A model built with complete pretrained weights comes back in evaluation mode; a randomly initialised one stays in+PyTorch's default training mode. The classes with a ``pretrained`` flag default to their pretrained weights.+"""++from __future__ import annotations++import inspect++import pytest+import torch+from torch import nn++from kornia.feature import (+ ALIKED,+ DISK,+ SOLD2,+ DeDoDe,+ DeFMO,+ HardNet,+ HardNet8,+ HyNet,+ KeyNet,+ KeyNetAffNetHardNet,+ KeyNetDetector,+ LAFAffNetShapeEstimator,+ LAFDescriptor,+ LightGlue,+ LoFTR,+ OriNet,+ SOLD2_detector,+ SOSNet,+ TFeat,+ XFeat,+)+from kornia.feature.sold2 import sold2, sold2_detector++from testing.base import BaseTester++# The classes whose constructor takes a ``pretrained`` flag.+_FLAG_CLASSES = [+ HardNet,+ HardNet8,+ HyNet,+ SOSNet,+ TFeat,+ OriNet,+ LAFAffNetShapeEstimator,+ KeyNet,+ KeyNetDetector,+ DeFMO,+]++# Constructions that load no weights, each of which must stay in training mode.+_RANDOM_INIT = [+ *[pytest.param(lambda cls=cls: cls(pretrained=False), id=cls.__name__) for cls in _FLAG_CLASSES],+ pytest.param(lambda: SOLD2(pretrained=False), id="SOLD2"),+ pytest.param(lambda: SOLD2_detector(pretrained=False), id="SOLD2_detector"),+ pytest.param(lambda: LoFTR(pretrained=None), id="LoFTR"),+ pytest.param(XFeat, id="XFeat"),+ pytest.param(lambda: ALIKED(model_name="aliked-n16"), id="ALIKED"),+ pytest.param(DISK, id="DISK", marks=pytest.mark.slow),+ # The B descriptor: the default G one downloads the DINOv2 backbone in its constructor.+ pytest.param(lambda: DeDoDe(descriptor_model="B"), id="DeDoDe", marks=pytest.mark.slow),+]++# Factories that load weights, each of which must return the model in evaluation mode.+_WEIGHTED = [+ pytest.param(SOLD2, id="SOLD2"),+ pytest.param(SOLD2_detector, id="SOLD2_detector"),+ pytest.param(lambda: LoFTR("outdoor"), id="LoFTR"),+ pytest.param(XFeat.from_pretrained, id="XFeat"),+ pytest.param(lambda: ALIKED.from_pretrained("aliked-n16"), id="ALIKED"),+ pytest.param(DISK.from_pretrained, id="DISK", marks=pytest.mark.slow),+ # The pair of the DeDoDe.from_pretrained doctest, which CI prefetches; the default G descriptor is 2.2 GB.+ pytest.param(+ lambda: DeDoDe.from_pretrained(detector_weights="L-C4-v2", descriptor_weights="B-upright"),+ id="DeDoDe",+ marks=pytest.mark.slow,+ ),+]+++def _network(model: nn.Module) -> nn.Module:+ """Return the learned network: ``KeyNetDetector`` holds its ``KeyNet`` as ``.model`` and sets no mode itself."""+ return model.model if isinstance(model, KeyNetDetector) else model+++class TestPretrainedMode(BaseTester):+ @pytest.mark.parametrize("cls", _FLAG_CLASSES, ids=lambda cls: cls.__name__)+ def test_flag_classes_default_to_pretrained_and_eval(self, cls):+ assert inspect.signature(cls).parameters["pretrained"].default is True+ default = _network(cls())+ assert not default.training+ assert not any(m.training for m in default.modules())+ expected = _network(cls(pretrained=True)).state_dict()+ actual = default.state_dict()+ assert actual.keys() == expected.keys()+ for key, value in expected.items():+ assert torch.equal(actual[key], value), key++ @pytest.mark.parametrize("factory", _RANDOM_INIT)+ def test_random_init_is_training_mode(self, factory):+ model = _network(factory())+ assert model.training is True+ assert all(m.training for m in model.modules())++ @pytest.mark.parametrize("factory", _WEIGHTED)+ def test_weighted_factories_are_eval(self, factory, monkeypatch):+ # SOLD2_detector fetches the wireframe checkpoint from a URL whose file CI does not prefetch; SOLD2's mirror+ # serves the same bytes and is prefetched.+ monkeypatch.setitem(sold2_detector.urls, "wireframe", sold2.urls["wireframe"])+ model = factory()+ assert not model.training+ assert not any(m.training for m in model.modules())++ def test_non_default_architecture_needs_pretrained_false(self):+ # The liberty checkpoint has convolution biases, so it cannot load strictly into bias-free convolutions.+ with pytest.raises(RuntimeError):+ HyNet(is_bias=False)+ model = HyNet(pretrained=False, is_bias=False)+ assert model.layer2[0].bias is None++ def test_lightglue_mode(self, monkeypatch):+ assert LightGlue(features=None).training+ # "superpoint" keeps the default architecture, so a fresh default model provides a complete state dict.+ weights = LightGlue(features=None).state_dict()+ monkeypatch.setattr("kornia.feature.lightglue.load_state_dict_from_url", lambda url, **kwargs: dict(weights))+ model = LightGlue("superpoint")+ assert not model.training+ assert not any(m.training for m in model.modules())+ # weights count as loaded only when the state dict holds any+ monkeypatch.setattr("kornia.feature.lightglue.load_state_dict_from_url", lambda url, **kwargs: {})+ assert LightGlue("superpoint").training++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("source", ["url", "file"])+ @pytest.mark.parametrize(+ "checkpoint_kind", ["complete", "missing_buffer", "missing_parameter", "buffers_only", "empty"]+ )+ def test_lightglue_checkpoint_completeness_controls_mode(self, monkeypatch, tmp_path, source, checkpoint_kind):+ config = {"input_dim": 256, "descriptor_dim": 32, "n_layers": 2, "flash": False}+ weights = LightGlue(features=None, **config).state_dict()+ if checkpoint_kind == "missing_buffer":+ # Reference checkpoints omit this derived buffer, but still contain every learned parameter.+ del weights["confidence_thresholds"]+ elif checkpoint_kind == "missing_parameter":+ del weights["posenc.Wr.weight"]+ elif checkpoint_kind == "buffers_only":+ weights = {"confidence_thresholds": weights["confidence_thresholds"]}+ elif checkpoint_kind == "empty":+ weights = {}++ if source == "url":+ monkeypatch.setattr(+ "kornia.feature.lightglue.load_state_dict_from_url", lambda *args, **kwargs: dict(weights)+ )+ model = LightGlue("superpoint", **config)+ else:+ # Local checkpoints are resolved relative to lightglue.py's weights directory.+ monkeypatch.setattr("kornia.feature.lightglue.__file__", str(tmp_path / "lightglue.py"))+ (tmp_path / "weights").mkdir()+ torch.save(weights, tmp_path / "weights" / "checkpoint.pth")+ model = LightGlue(features=None, weights="checkpoint", **config)++ expected_training = checkpoint_kind not in ("complete", "missing_buffer")+ assert {module.training for module in model.modules()} == {expected_training}+ for name, value in weights.items():+ self.assert_close(model.state_dict()[name], value)++ @pytest.mark.slow+ def test_composites_build_pretrained_eval_modules(self):+ # The containers (LocalFeature, KeyNetDetector, LAFOrienter, LAFDescriptor) never set their own mode; the+ # learned networks they hold are built with their weights and come back in evaluation mode.+ learned = (HardNet, OriNet, LAFAffNetShapeEstimator, KeyNet)+ composite = KeyNetAffNetHardNet(num_features=8)+ networks = [m for m in composite.modules() if isinstance(m, learned)]+ assert {type(m) for m in networks} == set(learned)+ assert not any(m.training for net in networks for m in net.modules())++ descriptor = LAFDescriptor(None)+ networks = [m for m in descriptor.modules() if isinstance(m, learned)]+ assert [type(m) for m in networks] == [HardNet]+ assert not any(m.training for m in networks[0].modules())diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 1fbe0d73e..80f8a2d3a 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -896,7 +896,7 @@ class TestMultiResolutionDetector(BaseTester):g = torch.Generator().manual_seed(0)img = torch.nn.functional.avg_pool2d(torch.rand(1, 1, 300, 420, generator=g), 5, 1, 2).to(device, dtype)torch.manual_seed(1) # random KeyNet weights; those of seed 0 give no positive response maximum at all- lafs, responses = KeyNetDetector(False, num_features=100).to(device, dtype)(img)+ lafs, responses = KeyNetDetector(False, num_features=100).eval().to(device, dtype)(img)assert lafs.dtype == torch.float32assert responses.dtype == dtypex = lafs[0, :, 0, 2]@@ -1799,7 +1799,7 @@ class TestConventionsMultiResolutionDetector(BaseTester):det = MultiResolutionDetector(response, num_features=4, config=cfg)else: # the KeyNet response is replaced by the same peaks through a forward hookconf = {**kornia.feature.keynet.keynet_default_config, "Detector_conf": cfg}- det = kornia.feature.KeyNetDetector(False, num_features=4, keynet_conf=conf)+ det = kornia.feature.KeyNetDetector(False, num_features=4, keynet_conf=conf).eval()det.model.register_forward_hook(lambda module, args, output, response=response: response(args[0]))lafs, resps = det.to(device, dtype)(torch.zeros(1, 1, *size, device=device, dtype=dtype))self.assert_close(resps, torch.tensor([[1.0, 0.5, 0.0, 0.0]], device=device, dtype=dtype))diff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.pyindex 4db4d5838..1f75208ed 100644--- a/tests/feature/test_sold2.py+++ b/tests/feature/test_sold2.py@@ -33,7 +33,7 @@ class TestSOLD2_detector(BaseTester):@pytest.mark.parametrize("batch_size", [1, 2])def test_shape(self, device, batch_size, dtype):inp = torch.ones(batch_size, 1, 64, 64, device=device, dtype=dtype)- sold2 = SOLD2_detector(pretrained=False).to(device, dtype)+ sold2 = SOLD2_detector(pretrained=False).to(device, dtype).eval()out = sold2(inp)assert out["junction_heatmap"].shape == (batch_size, 64, 64)assert out["line_heatmap"].shape == (batch_size, 64, 64)@@ -41,7 +41,7 @@ class TestSOLD2_detector(BaseTester):@pytest.mark.skip("Takes ages to run")def test_gradcheck(self, device):img = torch.rand(2, 1, 128, 128, device=device, dtype=torch.float64)- sold2 = SOLD2_detector(pretrained=False).to(img.device, img.dtype)+ sold2 = SOLD2_detector(pretrained=False).to(img.device, img.dtype).eval()def proxy_forward(x):return sold2.forward(x)["junction_heatmap"]@@ -156,14 +156,14 @@ class TestSOLD2(BaseTester):@pytest.mark.parametrize("batch_size", [1, 2])def test_shape(self, device, batch_size, dtype):inp = torch.ones(batch_size, 1, 64, 64, device=device, dtype=dtype)- sold2 = SOLD2(pretrained=False).to(device, dtype)+ sold2 = SOLD2(pretrained=False).to(device, dtype).eval()out = sold2(inp)assert out["dense_desc"].shape == (batch_size, 128, 16, 16)@pytest.mark.skip("Takes ages to run")def test_gradcheck(self, device):img = torch.rand(2, 1, 256, 256, device=device, dtype=torch.float64)- sold2 = SOLD2(pretrained=False).to(img.device, img.dtype)+ sold2 = SOLD2(pretrained=False).to(img.device, img.dtype).eval()def proxy_forward(x):return sold2.forward(x)["dense_desc"]@@ -200,7 +200,7 @@ class TestSOLD2(BaseTester):assert detector.config.use_descriptor is Falsedef test_match_keeps_torch_diag_5722(self, device, dtype):- sold2 = SOLD2(pretrained=False).to(device, dtype)+ sold2 = SOLD2(pretrained=False).to(device, dtype).eval()diag = torch.diagseg1 = torch.tensor([[[10.0, 10.0], [60.0, 90.0]], [[20.0, 70.0], [80.0, 20.0]]], device=device, dtype=dtype)desc = torch.randn(1, 128, 24, 32, device=device, dtype=dtype)@@ -214,7 +214,7 @@ class TestSOLD2(BaseTester):def test_match_segment_dtype_differs_from_descriptors_5722(self, device, dtype):# SOLD2.forward returns float32 segments whatever the model dtype, so match must accept segments whose# dtype differs from the descriptor map's, in both directions.- sold2 = SOLD2(pretrained=False).to(device, dtype)+ sold2 = SOLD2(pretrained=False).to(device, dtype).eval()seg = torch.tensor([[[10.0, 10.0], [60.0, 90.0]], [[20.0, 70.0], [80.0, 20.0]], [[85.0, 5.0], [85.0, 120.0]]], device=device)@@ -379,7 +379,7 @@ class TestConventionsSOLD2(BaseTester):unrefined = DetectorCfg(line_detector_cfg=LineDetectorCfg(use_junction_refinement=False))junctions = torch.tensor([[[30.0, 100.0], [70.0, 20.0]]], device=device)for config in (unrefined, None):- model = model_cls(pretrained=False, config=config).to(device, dtype)+ model = model_cls(pretrained=False, config=config).to(device, dtype).eval()per_score_order = []for scores in ((0.5, 1.0), (1.0, 0.5)):maps = self._maps((100, 30), (20, 70), *scores, device, dtype)@@ -393,7 +393,7 @@ class TestConventionsSOLD2(BaseTester):assert torch.equal(per_score_order[0], per_score_order[1])# relabelling: the transposed maps give the transposed endpoints, (row, col) in the transposed image, where the# other endpoint now has the smaller row and comes first- model = model_cls(pretrained=False, config=unrefined).to(device, dtype)+ model = model_cls(pretrained=False, config=unrefined).to(device, dtype).eval()maps = self._maps((30, 100), (70, 20), 0.5, 1.0, device, dtype, h=128, w=96)segments = self._segments(model, maps, image.transpose(-1, -2))self.assert_close(segments.float(), junctions.flip(-1).flip(1), rtol=0.0, atol=0.0)@@ -404,7 +404,7 @@ class TestConventionsSOLD2(BaseTester):# the second set of segments per segment of the first, or -1.# The detection threshold is raised above any probability, so that the line detector, which this pin does not# read, has no junctions of the random network to connect.- model = SOLD2(pretrained=False, config=DetectorCfg(detection_thresh=2.0)).to(device, dtype)+ model = SOLD2(pretrained=False, config=DetectorCfg(detection_thresh=2.0)).to(device, dtype).eval()image = torch.rand(2, 1, 64, 96, device=device, dtype=dtype)with torch.no_grad():out = model(image)@@ -428,7 +428,7 @@ class TestConventionsSOLD2(BaseTester):def test_convention_sold2_match_returns_int64_when_a_set_of_segments_is_empty(self, device, dtype):# SOLD2.match returns an int64 index per segment of line_seg1, also when either set of segments is empty:# an empty tensor when image 1 has no segments, -1 per segment when image 2 has none (#5915).- model = SOLD2(pretrained=False)+ model = SOLD2(pretrained=False).eval()segments = torch.tensor([[[10.0, 10.0], [50.0, 90.0]], [[20.0, 70.0], [55.0, 20.0]]], device=device)maps = torch.rand(2, 1, 128, 16, 24, device=device, dtype=dtype)for line_seg1, line_seg2, expected in (diff --git a/tests/feature/test_sosnet.py b/tests/feature/test_sosnet.pyindex a62e75974..187623b7a 100644--- a/tests/feature/test_sosnet.py+++ b/tests/feature/test_sosnet.py@@ -33,14 +33,14 @@ class TestSOSNet(BaseTester):def test_shape_batch(self, device):inp = torch.ones(16, 1, 32, 32, device=device)- sosnet = SOSNet(pretrained=False).to(device)+ sosnet = SOSNet(pretrained=False).to(device).eval()out = sosnet(inp)assert out.shape == (16, 128)@pytest.mark.skip("jacobian not well computed")def test_gradcheck(self, device):patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)- sosnet = SOSNet(pretrained=False).to(patches.device, patches.dtype)+ sosnet = SOSNet(pretrained=False).to(patches.device, patches.dtype).eval()self.gradcheck(sosnet, (patches,), eps=1e-4, atol=1e-4)@pytest.mark.parametrize("patch_value", [0.0, 0.5])@@ -53,7 +53,7 @@ class TestSOSNet(BaseTester):# that failure, but on CPU both half dtypes used to raise out of `avg_pool3d` before reaching# the division at all, so both are pinned here.patches = torch.full((2, 1, 32, 32), patch_value, device=device, dtype=dtype)- sosnet = SOSNet().to(device, dtype).eval()+ sosnet = SOSNet(pretrained=False).to(device, dtype).eval()descriptors = sosnet(patches)assert torch.isfinite(descriptors).all(), (f"{int((~torch.isfinite(descriptors)).sum())} non-finite descriptor entries"@@ -66,7 +66,7 @@ class TestSOSNet(BaseTester):# NaN if the branch is dropped. `cudnn_tf32_follows_option` is what makes the float32 leg# meaningful on CUDA; see its docstring.patches = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)- model = SOSNet().to(device, dtype).eval()+ model = SOSNet(pretrained=False).to(device, dtype).eval()op = torch_optimizer(model)self.assert_close(op(patches), model(patches))@@ -75,7 +75,7 @@ class TestSOSNet(BaseTester):# `export-support.rst` publishes SOSNet as capturable with zero graph breaks. The dtype branch# reads static metadata and must not become the thing that breaks the graph.patches = torch.rand(2, 1, 32, 32, device=device, dtype=dtype)- model = SOSNet().to(device, dtype).eval()+ model = SOSNet(pretrained=False).to(device, dtype).eval()expected = model(patches)torch._dynamo.reset()compiled = torch.compile(model, fullgraph=True)@@ -89,6 +89,6 @@ class TestSOSNet(BaseTester):# network's output non-degenerate; scripting the same instance is what makes the two sides# comparable at all. See TestHyNet::test_jit for the pattern.patches = torch.rand(B, C, H, W, device=device, dtype=dtype)- model = SOSNet().to(patches.device, patches.dtype).eval()+ model = SOSNet(pretrained=False).to(patches.device, patches.dtype).eval()model_jit = torch.jit.script(model)self.assert_close(model(patches), model_jit(patches))diff --git a/tests/feature/test_tfeat.py b/tests/feature/test_tfeat.pyindex 4a5b86779..ad8ecdd0e 100644--- a/tests/feature/test_tfeat.py+++ b/tests/feature/test_tfeat.py@@ -26,7 +26,7 @@ from testing.base import BaseTester, supports_conv2dclass TestTFeat(BaseTester):def test_shape(self, device):inp = torch.ones(1, 1, 32, 32, device=device)- tfeat = TFeat().to(device)+ tfeat = TFeat(pretrained=False).to(device)tfeat.eval() # batchnorm with size 1 is not allowed in train modeout = tfeat(inp)assert out.shape == (1, 128)@@ -41,14 +41,14 @@ class TestTFeat(BaseTester):def test_shape_batch(self, device):inp = torch.ones(4, 1, 32, 32, device=device)- tfeat = TFeat().to(device)+ tfeat = TFeat(pretrained=False).to(device).eval()out = tfeat(inp)assert out.shape == (4, 128)@pytest.mark.skip("jacobian not well computed")def test_gradcheck(self, device):patches = torch.rand(2, 1, 32, 32, device=device, dtype=torch.float64)- tfeat = TFeat().to(patches.device, patches.dtype)+ tfeat = TFeat(pretrained=False).to(patches.device, patches.dtype).eval()self.gradcheck(tfeat, (patches,), eps=1e-2, atol=1e-2)@pytest.mark.slow@@ -70,7 +70,7 @@ class TestConventionsTFeat(BaseTester):if not supports_conv2d(device, dtype):pytest.skip(f"no conv2d kernel for {dtype} on {device.type}")torch.manual_seed(0)- model = TFeat().to(device, dtype)+ model = TFeat(pretrained=False).to(device, dtype).eval()out = model(torch.rand(6, 1, 32, 32, device=device, dtype=dtype))assert out.shape == (6, 128)assert out.abs().max() <= 1.0diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.pyindex 5b06f98d5..ab2a4ab1e 100644--- a/tests/feature/test_xfeat.py+++ b/tests/feature/test_xfeat.py@@ -150,7 +150,7 @@ class TestInterpolateSparse2d(BaseTester):class TestXFeat(BaseTester):def test_smoke(self, device, dtype):- model = XFeat().to(device)+ model = XFeat().to(device).eval()x = torch.rand(1, 3, 64, 64, device=device)out = model.detectAndCompute(x)assert isinstance(out, list)@@ -160,7 +160,7 @@ class TestXFeat(BaseTester):assert "descriptors" in out[0]def test_cardinality(self, device, dtype):- model = XFeat().to(device)+ model = XFeat().to(device).eval()B = 2x = torch.rand(B, 3, 64, 64, device=device)out = model.detectAndCompute(x)@@ -171,7 +171,7 @@ class TestXFeat(BaseTester):assert item["descriptors"].shape == (N, 64)def test_exception(self, device, dtype):- model = XFeat().to(device)+ model = XFeat().to(device).eval()with pytest.raises(Exception):model.detectAndCompute(torch.rand(3, 64, 64, device=device)) # missing batch dim@@ -179,7 +179,7 @@ class TestXFeat(BaseTester):def test_wart_half_weights_raise_5957(self, half, device):# Known defect #5957: _preprocess_tensor calls x.float(), so half-precision weights meet float32 input.# CPU: "expected scalar type Float but found Half"; MPS and CUDA: "Input type (...) and weight type (...)".- model = XFeat().to(device, half)+ model = XFeat().to(device, half).eval()with pytest.raises(RuntimeError, match=r"expected scalar type Float but found|Input type \(.*\) and weight type"):@@ -192,7 +192,7 @@ class TestXFeat(BaseTester):pass # inference_mode and dynamic NMS control flow; not torch.compile compatibledef test_descriptors_normalized(self, device, dtype):- model = XFeat().to(device)+ model = XFeat().to(device).eval()x = torch.rand(1, 3, 64, 64, device=device)out = model.detectAndCompute(x)if out[0]["descriptors"].numel() == 0:@@ -202,14 +202,14 @@ class TestXFeat(BaseTester):def test_top_k_respected(self, device, dtype):top_k = 16- model = XFeat(top_k=top_k).to(device)+ model = XFeat(top_k=top_k).to(device).eval()x = torch.rand(1, 3, 128, 128, device=device)out = model.detectAndCompute(x, top_k=top_k)assert out[0]["keypoints"].shape[0] <= top_kdef test_keypoint_coordinates_in_image(self, device, dtype):H, W = 64, 96- model = XFeat().to(device)+ model = XFeat().to(device).eval()x = torch.rand(1, 3, H, W, device=device)out = model.detectAndCompute(x)if out[0]["keypoints"].numel() == 0:@@ -222,7 +222,7 @@ class TestXFeat(BaseTester):def test_dense_output_shapes(self, device, dtype):top_k = 32- model = XFeat(top_k=top_k).to(device)+ model = XFeat(top_k=top_k).to(device).eval()x = torch.rand(1, 3, 64, 64, device=device)out = model.detectAndComputeDense(x, top_k=top_k, multiscale=False)assert "keypoints" in out@@ -233,7 +233,7 @@ class TestXFeat(BaseTester):assert out["keypoints"].shape[1] == out["descriptors"].shape[1]def test_match_xfeat_returns_paired_keypoints(self, device, dtype):- model = XFeat().to(device)+ model = XFeat().to(device).eval()img1 = torch.rand(1, 3, 64, 64, device=device)img2 = torch.rand(1, 3, 64, 64, device=device)mkpts0, mkpts1 = model.match_xfeat(img1, img2)@@ -672,14 +672,14 @@ class TestConventionsXFeat(BaseTester):xfeat.detectAndComputeDense(image, 5)assert len(sizes) == 2- def test_convention_xfeat_default_constructor_is_in_eval_mode_and_inference_does_not_touch_batchnorm_stats(- self, device, dtype- ):- # XFeat() starts in eval mode like XFeat.from_pretrained and the reference: BatchNorm would otherwise use batch+ def test_convention_xfeat_random_init_is_training_and_eval_inference_keeps_batchnorm_stats(self, device, dtype):+ # XFeat() builds random weights and stays in PyTorch's training mode, where BatchNorm would use batch# statistics (each keypoint depends on the rest of the batch), update its running statistics on every- # inference call, and raise on a single match.+ # inference call, and raise on a single match. XFeat.from_pretrained returns evaluation mode; .eval() on the+ # random model gives the same inference semantics.torch.manual_seed(0)- xfeat = XFeat()+ xfeat = XFeat().eval()+ assert XFeat().trainingassert not xfeat.trainingxfeat = xfeat.to(device)image = torch.rand(2, 3, 64, 64, device=device)@@ -693,7 +693,7 @@ class TestConventionsXFeat(BaseTester):def test_smoke_xfeat_star_default_constructor_top_k_1_batched(self, device, dtype):torch.manual_seed(0)- xfeat = XFeat().to(device)+ xfeat = XFeat().to(device).eval()image = torch.rand(2, 3, 64, 64, device=device)matches = xfeat.match_xfeat_star(image, image, top_k=1)assert len(matches) == 2@@ -705,7 +705,7 @@ class TestConventionsXFeat(BaseTester):if torch.device(device).type != "cpu":pytest.skip("CPU autocast")torch.manual_seed(0)- xfeat = XFeat().to(device)+ xfeat = XFeat().to(device).eval()image = torch.rand(2, 3, 64, 64, device=device)with torch.autocast("cpu", dtype=torch.bfloat16):small = xfeat.detectAndComputeDense(image, 4)@@ -820,6 +820,6 @@ class TestConventionsXFeat(BaseTester):else:segments = torch.tensor([[[10.0, 10.0], [50.0, 90.0]], [[20.0, 70.0], [55.0, 20.0]]])maps = torch.rand(2, 1, 128, 24, 32, dtype=dtype)- SOLD2(pretrained=False).match(segments, segments + 1.0, maps[0], maps[1])+ SOLD2(pretrained=False).eval().match(segments, segments + 1.0, maps[0], maps[1])assert callsassert set(calls) == {(dtype, dtype)}diff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.pyindex da53a8e63..5833a4a35 100644--- a/tests/tracking/test_planar_tracking.py+++ b/tests/tracking/test_planar_tracking.py@@ -103,7 +103,7 @@ class TestHomographyTrackerCaching:assert shapes == [(1, 1, 70, 90)]def test_loftr_target_features_are_extracted_once(self):- loftr = LoFTR(None)+ loftr = LoFTR(None).eval()calls = []loftr.backbone.register_forward_hook(lambda mod, inp, out: calls.append(tuple(inp[0].shape)))tracker = HomographyTracker(self._sift_matcher(), loftr, minimum_inliers_num=10)@@ -116,7 +116,7 @@ class TestHomographyTrackerCaching:def test_loftr_without_cached_features_gets_image0(self):# A target assigned directly, without set_target, has no cached features0, so LoFTR needs image0.- loftr = LoFTR(None)+ loftr = LoFTR(None).eval()keys = []loftr.register_forward_pre_hook(lambda mod, args: keys.append(sorted(args[0])))tracker = HomographyTracker(loftr, self._sift_matcher(), minimum_inliers_num=10)@@ -129,7 +129,7 @@ class TestHomographyTrackerCaching:# itself and gets its own features0 (not image0 next to it, which LoFTR rejects).tracker = HomographyTracker(self._sift_matcher(), self._sift_matcher(), minimum_inliers_num=10)tracker.set_target(_texture(64, 80))- loftr = LoFTR(None)+ loftr = LoFTR(None).eval()inputs = []loftr.register_forward_pre_hook(lambda mod, args: inputs.append(dict(args[0])))tracker.fast_matcher = loftr@@ -146,7 +146,7 @@ class TestHomographyTrackerCaching:config["match_coarse"]["thr"] = 1e-4with torch.random.fork_rng():torch.manual_seed(seed)- return LoFTR(None, config)+ return LoFTR(None, config).eval()def test_loftr_swapped_after_set_target_matches_an_uncached_call(self):# A LoFTR swapped in after set_target was fed the old LoFTR's cached features0.