π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(models): pretrained builders return eval mode; TinyViT attention bias no longer cached (#6014)
Dmytro Mishkincd34cf60f5de
diff --git a/changelog.d/6014.breaking.md b/changelog.d/6014.breaking.mdnew file mode 100644index 000000000..cb0f6031b--- /dev/null+++ b/changelog.d/6014.breaking.md@@ -0,0 +1 @@+`YuNet(phase, pretrained=False)` returns the randomly initialised model in training mode; it returned it in evaluation mode. Call `.eval()` before inference, for example after loading your own weights. `FaceDetector`, which loads the weights, is unaffected.diff --git a/changelog.d/6014.fixed.md b/changelog.d/6014.fixed.mdnew file mode 100644index 000000000..2cf3314f8--- /dev/null+++ b/changelog.d/6014.fixed.md@@ -0,0 +1 @@+The weighted builders of `kornia.models` return the model in evaluation mode: `Sam.from_config` with `pretrained=True` or a `checkpoint` (and so `VisualPrompter` with such a config), `RTDETR.from_pretrained`, `RTDETR.from_config` with a `checkpoint`, `TinyViT.from_config` with `pretrained` and the checkpoint's class count, `EfficientViT.from_config`, `VisionTransformer.from_config(pretrained=True)`, `SigLip2Builder.from_pretrained_hf` and `KimiVLBuilder.from_pretrained_hf`. They returned training mode, so MobileSAM, RT-DETR, TinyViT and EfficientViT normalised with batch statistics, an image's output depended on the rest of the batch, and inference overwrote the BatchNorm running statistics; TinyViT-11M and -21M also dropped residual paths at random. Randomly initialised models stay in training mode, and so does a pretrained TinyViT whose classification head is reset to zeros because `num_classes` differs from the checkpoint's, including `pretrained="in22k"` (a 21841-class head) with the default `num_classes=1000`: pass `num_classes=21841`, or call `.eval()` before extracting features. Code that fine-tunes a model returned by one of these builders must now call `.train()` first, or BatchNorm keeps its running statistics frozen and, in TinyViT-11M and -21M, DropPath stays off. After loading your own weights, call `.eval()`. TinyViT's attention bias is no longer cached at `eval()`, so `load_state_dict`, a parameter update, or `.to()` / `.half()` / `.bfloat16()` after `eval()` no longer gives a stale bias (wrong logits) or a device/dtype error. The cache was filled without gradient, so in evaluation mode `attention_biases` received none, and fine-tuning with BatchNorm frozen through `.eval()` silently froze them; they now get gradients.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex b3c3c18a7..ee34d414a 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -1271,6 +1271,21 @@ For example, from the ``pt``, ``size`` and ``angle`` of ``cv2.SIFT`` keypoints:lafs = KF.laf_from_center_scale_ori(pt[None], 3.0 * size.view(1, -1, 1, 1), -angle.view(1, -1, 1))assert torch.allclose(-KF.get_laf_orientation(lafs).flatten() % 360.0, angle)+.. _pretrained-models-conventions:++Pretrained models+-----------------++- A model built with complete pretrained weights comes back in evaluation mode (``model.training`` is ``False``).+ A randomly initialised model stays in PyTorch's default training mode. So does a model whose weights are only partly+ pretrained, such as a pretrained backbone with a newly initialised classification head. Call ``.train()`` to+ fine-tune a pretrained model, and ``.eval()`` before running inference on a random one.+- Constructors, ``from_config``, ``from_pretrained`` and the builders set the mode once, when they build the model.+ ``load_checkpoint`` and ``load_state_dict`` on an existing module leave its mode as it is: after loading your own+ weights, call ``.eval()``.+- Task wrappers that take a model (``ObjectDetector``, ``EdgeDetector``, ``SuperResolution``, ``SemanticSegmentation``)+ put that model in evaluation mode: they run inference.+Pitfall checklist-----------------diff --git a/docs/source/models/segment_anything.rst b/docs/source/models/segment_anything.rstindex a13c22055..c9295bb98 100644--- a/docs/source/models/segment_anything.rst+++ b/docs/source/models/segment_anything.rst@@ -248,8 +248,9 @@ If a URL is passed, the model automatically downloads and caches the weights usi# Load/build the modelsam_model = Sam.from_config(SamConfig(model_type))- # Load the checkpoint+ # Load the checkpoint; loading keeps the module's mode, so switch to evaluation mode for inferencesam_model.load_checkpoint(checkpoint, device)+ sam_model.eval().. Mask Generatordiff --git a/docs/source/models/tiny_vit.rst b/docs/source/models/tiny_vit.rstindex 219338329..505ba36a8 100644--- a/docs/source/models/tiny_vit.rst+++ b/docs/source/models/tiny_vit.rst@@ -43,8 +43,10 @@ Run it``'in1k_512'`` checkpoints; pass ``img_size=`` to run at another resolution and the attention biases areinterpolated. The ImageNet-22k checkpoint carries a 21841-class head, so load it with``TinyViT.from_config("5m", pretrained="in22k", num_classes=21841)``: with the default ``num_classes=1000`` the-head does not match, is reset to zeros with a warning and the model returns all-zero logits. For feature extraction-replace the head instead: ``model.head = torch.nn.Identity()`` makes the model return the pooled embedding.+head does not match, is reset to zeros with a warning, the model returns all-zero logits, and it stays in training+mode as a backbone to fine-tune. For feature extraction replace the head and switch to evaluation mode:+``model.head = torch.nn.Identity()`` makes the model return the pooled embedding, and ``model.eval()`` makes it+independent of the rest of the batch.Paper-----diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.pyindex 6a42745aa..5c104c442 100644--- a/kornia/core/mixin/onnx.py+++ b/kornia/core/mixin/onnx.py@@ -227,9 +227,8 @@ class ONNXExportMixin:onnx_model = onnx.load(tmp_path)finally:# The flag is set directly on purpose: ``train()`` recurses into the children, which would lose a mixed- # state. It also skips ``train()`` overrides: TinyViT's ``Attention.train(True)`` would drop the attention- # bias cached in eval mode, which is harmless because a training-mode forward does not read it. Check any- # new ``train()`` override with side effects against this restore.+ # state. It also skips ``train()`` overrides: check any new ``train()`` override with side effects against+ # this restore.for submodule, training in modes:submodule.training = trainingdiff --git a/kornia/models/efficient_vit/model.py b/kornia/models/efficient_vit/model.pyindex 57c2ed0d8..ba2c1d8df 100644--- a/kornia/models/efficient_vit/model.py+++ b/kornia/models/efficient_vit/model.py@@ -76,7 +76,8 @@ class EfficientViT(ModelBase[EfficientViTConfig]):config: EfficientViT configuration object. See :class:`EfficientViTConfig`.Returns:- EfficientViT: the EfficientViT model.+ EfficientViT: the EfficientViT model, in evaluation mode, since it always loads ``config.checkpoint``+ (see :ref:`pretrained-models-conventions`)."""# load the model from the checkpoint; expand ``~`` first, or a ``~`` path reaches the URL loader, which@@ -104,7 +105,7 @@ class EfficientViT(ModelBase[EfficientViTConfig]):state_dict = {key[len("backbone.") :]: val for key, val in model_file.items() if key.startswith("backbone.")}model.load_state_dict(state_dict or model_file, strict=True)- return EfficientViT(backbone=model)+ return EfficientViT(backbone=model).eval()def forward(self, images: torch.Tensor) -> torch.Tensor:"""Extract features from the input images.diff --git a/kornia/models/kimi_vl/builder.py b/kornia/models/kimi_vl/builder.pyindex 6e76c1aaf..e9d4ece3e 100644--- a/kornia/models/kimi_vl/builder.py+++ b/kornia/models/kimi_vl/builder.py@@ -90,7 +90,8 @@ class KimiVLBuilder:checkpoint is cached.Returns:- KimiVLModel instance with pretrained weights.+ KimiVLModel instance with pretrained weights, in evaluation mode, since it always loads weights (see+ :ref:`pretrained-models-conventions`)... note::Only Kimi-VL-A3B-Instruct is currently supported.@@ -98,4 +99,4 @@ class KimiVLBuilder:state_dict = _download_weights(_KIMI_VL_A3B_INSTRUCT_REPO_ID, cache_dir)model = KimiVLBuilder.from_config(_kimi_vl_a3b_instruct_config())model.load_state_dict(state_dict, strict=True)- return model+ return model.eval()diff --git a/kornia/models/rt_detr/model.py b/kornia/models/rt_detr/model.pyindex c67bad6e9..d889ec96c 100644--- a/kornia/models/rt_detr/model.py+++ b/kornia/models/rt_detr/model.py@@ -154,6 +154,9 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):def from_config(config: RTDETRConfig) -> RTDETR:"""Construct RT-DETR Object Detection model from a config object.+ Returns the model in evaluation mode when ``config.checkpoint`` loads weights and in training mode otherwise+ (see :ref:`pretrained-models-conventions`).+Args:config: configuration object for RT-DETR.@@ -234,12 +237,16 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):if config.checkpoint:model.load_checkpoint(config.checkpoint)+ model.eval()return model@staticmethoddef from_pretrained(model_name: str) -> RTDETR:"""Load model from pretrained weights.+ Returns the model in evaluation mode, since it always loads weights (see+ :ref:`pretrained-models-conventions`).+Args:model_name: 'rtdetr_r18vd', 'rtdetr_r34vd', 'rtdetr_r50vd_m', 'rtdetr_r50vd', 'rtdetr_r101vd'.@@ -284,7 +291,7 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):model = RTDETR.from_name(model_name, num_classes=80)model.load_state_dict(_state_dict_proc(state_dict))- return model+ return model.eval()@staticmethoddef from_name(model_name: str, num_classes: int = 80) -> RTDETR:diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.pyindex 51d0114f4..eafa4112b 100644--- a/kornia/models/sam/model.py+++ b/kornia/models/sam/model.py@@ -151,7 +151,8 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):the parameters set.Returns:- The respective SAM model+ The respective SAM model, in evaluation mode when it loads weights (``config.pretrained`` or+ ``config.checkpoint``) and in training mode otherwise (see :ref:`pretrained-models-conventions`).Example:>>> from kornia.models.sam import SamConfig@@ -243,6 +244,7 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):if checkpoint:model.load_checkpoint(checkpoint)+ model.eval()return modeldiff --git a/kornia/models/siglip2/builder.py b/kornia/models/siglip2/builder.pyindex fe2565671..bf9ea5152 100644--- a/kornia/models/siglip2/builder.py+++ b/kornia/models/siglip2/builder.py@@ -138,7 +138,8 @@ class SigLip2Builder:is cached.Returns:- SigLip2Model instance with pretrained weights.+ SigLip2Model instance with pretrained weights, in evaluation mode, since it always loads weights (see+ :ref:`pretrained-models-conventions`)... note::The repository must publish its weights as a single@@ -163,4 +164,4 @@ class SigLip2Builder:model = SigLip2Model(config)model.load_state_dict(state_dict, strict=True)- return model+ return model.eval()diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.pyindex d5070cab1..bfe9b7f3c 100644--- a/kornia/models/tiny_vit.py+++ b/kornia/models/tiny_vit.py@@ -292,7 +292,6 @@ class Attention(nn.Module):self.attention_biases = nn.Parameter(torch.zeros(num_heads, attn_offset_size))self.register_buffer("attention_bias_idxs", indices, persistent=False)self.attention_bias_idxs: torch.Tensor- self.ab: Optional[torch.Tensor] = None@staticmethoddef build_attention_bias(resolution: tuple[int, int]) -> tuple[torch.Tensor, int]:@@ -320,22 +319,6 @@ class Attention(nn.Module):attn_offset_size = unique_keys.numel()return indices, attn_offset_size- # is this really necessary?- @torch.no_grad()- def train(self, mode: bool = True) -> Attention:- """Switch training/evaluation mode and refresh cached attention bias.-- Args:- mode: ``True`` for training mode, ``False`` for evaluation mode.-- Returns:- ``self`` after updating the module mode. In evaluation mode the- relative attention bias lookup is cached for reuse.- """- super().train(mode)- self.ab = None if (mode and self.ab is not None) else self.attention_biases[:, self.attention_bias_idxs]- return self-def forward(self, x: torch.Tensor) -> torch.Tensor:"""Apply relative-position self-attention to token features.@@ -353,7 +336,7 @@ class Attention(nn.Module):qkv = qkv.view(B, N, self.num_heads, -1).permute(0, 2, 1, 3)q, k, v = qkv.split([self.key_dim, self.key_dim, self.d], dim=3)- bias = self.attention_biases[:, self.attention_bias_idxs] if self.training else self.ab+ bias = self.attention_biases[:, self.attention_bias_idxs]attn = (q @ k.transpose(-2, -1)) * self.scale + biasattn = attn.softmax(dim=-1)@@ -639,6 +622,9 @@ class TinyViT(nn.Module):def from_config(variant: str, pretrained: bool | str = False, **kwargs: Any) -> TinyViT:"""Create a TinyViT model from pre-defined variants.+ Returns the model in evaluation mode when ``pretrained`` loads the complete weights, classification head+ included, and in training mode otherwise (see :ref:`pretrained-models-conventions`).+Args:variant: TinyViT variant. Possible values: ``'5m'``, ``'11m'``, ``'21m'``.pretrained: whether to use pre-trained weights. Possible values: ``False``, ``True``, ``'in22k'``,@@ -650,6 +636,12 @@ class TinyViT(nn.Module):attention biases. When using ``pretrained=True``, ImageNet-1k checkpoint (``'in1k'``) is used.For feature extraction or fine-tuning, ImageNet-22k checkpoint (``'in22k'``) is preferred.+ With ``pretrained`` and a ``num_classes`` other than the checkpoint's, the classification head is reset to+ zeros, and the model, a pretrained backbone to fine-tune, stays in training mode. The ``'in22k'``+ checkpoints have a 21841-class head: pass ``num_classes=21841`` to get the complete model in evaluation+ mode. With the default ``num_classes=1000`` the head is reset and the model stays in training mode, so call+ ``.eval()`` before extracting features.+"""KORNIA_CHECK(variant in ("5m", "11m", "21m"), "Only variant 5m, 11m, and 21m are supported")return {"5m": _tiny_vit_5m, "11m": _tiny_vit_11m, "21m": _tiny_vit_21m}[variant](pretrained, **kwargs)@@ -728,13 +720,18 @@ def _load_pretrained(model: TinyViT, url: str | list[str]) -> TinyViT:attention_biases = F.interpolate(attention_biases, size=(S2, S2), mode="bicubic")state_dict[k] = attention_biases.view(n_heads2, L2)- if state_dict["head.weight"].shape[0] != model.head.out_features:+ head_loaded = state_dict["head.weight"].shape[0] == model.head.out_features+ if not head_loaded:msg = "Number of classes does not match pre-trained checkpoint's. Resetting classification head to zeros"warnings.warn(msg, stacklevel=1)state_dict["head.weight"] = torch.zeros_like(model.head.weight)state_dict["head.bias"] = torch.zeros_like(model.head.bias)model.load_state_dict(state_dict)+ # Complete weights are returned in evaluation mode. A reset head leaves a pretrained backbone to fine-tune, which+ # stays in training mode.+ if head_loaded:+ model.eval()return modeldiff --git a/kornia/models/vit.py b/kornia/models/vit.pyindex cb5048276..2e6c4d2cd 100644--- a/kornia/models/vit.py+++ b/kornia/models/vit.py@@ -296,7 +296,8 @@ class VisionTransformer(nn.Module):kwargs: other keyword arguments that will be passed to :func:`kornia.models.vit.VisionTransformer`.Returns:- The respective ViT model+ The respective ViT model, in evaluation mode when ``pretrained=True`` loads weights and in training mode+ otherwise (see :ref:`pretrained-models-conventions`).Example:>>> from kornia.models.vit import VisionTransformer@@ -321,6 +322,7 @@ class VisionTransformer(nn.Module):url = _get_weight_url(variant)state_dict = load_state_dict_from_url(url)model.load_state_dict(state_dict)+ model.eval()return modeldiff --git a/kornia/models/yunet/model.py b/kornia/models/yunet/model.pyindex 7982a7dae..a1515fe72 100644--- a/kornia/models/yunet/model.py+++ b/kornia/models/yunet/model.py@@ -66,7 +66,8 @@ class YuNet(nn.Module):Args:phase: the phase of the model, either "train" or "test".- pretrained: if True, loads pretrained weights from the official repository.+ pretrained: if True, loads pretrained weights from the official repository and returns the model in+ evaluation mode; otherwise the random weights stay in training mode.Example:>>> model = YuNet("test", pretrained=True)@@ -111,7 +112,7 @@ class YuNet(nn.Module):if pretrained:pretrained_dict = load_state_dict_from_url(_url, map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)- self.eval()+ self.eval()def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:"""Run YuNet face detection heads over an input image batch.diff --git a/tests/contrib/test_face_detection.py b/tests/contrib/test_face_detection.pyindex c06138fdd..a28b39c42 100644--- a/tests/contrib/test_face_detection.py+++ b/tests/contrib/test_face_detection.py@@ -22,6 +22,7 @@ import torchimport korniafrom kornia.contrib.face_detection import FaceKeypoint+from kornia.models.yunet import YuNetfrom testing.base import BaseTester@@ -108,6 +109,15 @@ class TestFaceDetection(BaseTester):)assert model_path.is_file()+ @pytest.mark.device_agnostic+ def test_yunet_mode(self, monkeypatch):+ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ assert {m.training for m in YuNet("test", pretrained=False).modules()} == {True}++ state_dict = YuNet("test", pretrained=False).state_dict()+ monkeypatch.setattr("kornia.models.yunet.model.load_state_dict_from_url", lambda *args, **kwargs: state_dict)+ assert {m.training for m in YuNet("test", pretrained=True).modules()} == {False}+def test_exception(self, face_detector, device, dtype):img = torch.rand(1, 4, 320, 320, device=device, dtype=dtype)diff --git a/tests/contrib/test_visual_prompter.py b/tests/contrib/test_visual_prompter.pyindex 3a3f13c91..2235a6fef 100644--- a/tests/contrib/test_visual_prompter.py+++ b/tests/contrib/test_visual_prompter.py@@ -92,6 +92,31 @@ class TestVisualPrompter(BaseTester):assert results.logits.shape == (1, 3, 256, 256)assert results.scores.shape == (1, 3)+ @pytest.mark.device_agnostic+ def test_weighted_config_holds_an_eval_model(self, monkeypatch):+ monkeypatch.setattr(Sam, "load_checkpoint", lambda self, checkpoint, device=None: None)++ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ weighted = VisualPrompter(SamConfig("mobile_sam", pretrained=True)).model+ assert {m.training for m in weighted.modules()} == {False}+ random_init = VisualPrompter(SamConfig("mobile_sam")).model+ assert {m.training for m in random_init.modules()} == {True}++ @pytest.mark.slow+ def test_weighted_config_runs_in_half(self, monkeypatch, device, dtype):+ # A weighted config comes back in evaluation mode, and VisualPrompter casts the model after that.+ if dtype not in (torch.float16, torch.bfloat16):+ pytest.skip("guards the cast of an evaluation-mode model to a half dtype")+ monkeypatch.setattr(Sam, "load_checkpoint", lambda self, checkpoint, device=None: None)+ prompter = VisualPrompter(SamConfig("mobile_sam", pretrained=True), device=device, dtype=dtype)++ prompter.set_image(torch.rand(3, 77, 128, device=device, dtype=dtype))++ # SAM's 1024-pixel input over its 16-pixel patches gives a 64 x 64 grid of 256-channel (``prompt_embed_dim``)+ # embeddings.+ assert prompter.image_embeddings.shape == (1, 256, 64, 64)+ assert prompter.image_embeddings.dtype == dtype+def test_gradcheck(self, device):pytest.skip("Gradcheck is not currently applicable for VisualPrompter inference.")diff --git a/tests/models/test_efficient_vit.py b/tests/models/test_efficient_vit.pyindex 673fd0521..5e4aa3189 100644--- a/tests/models/test_efficient_vit.py+++ b/tests/models/test_efficient_vit.py@@ -144,6 +144,36 @@ class TestEfficientViT:for key, val in state_dict.items():assert torch.equal(loaded[key], val)+ def test_load_pretrained_returns_eval_mode(self, monkeypatch):+ state_dict = self._fake_checkpoint()+ monkeypatch.setattr(+ "kornia.models.efficient_vit.model.load_state_dict_from_url",+ lambda *args, **kwargs: {"state_dict": state_dict},+ )++ model = EfficientViT.from_config(EfficientViTConfig.from_pretrained("b1", 224))++ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ assert {m.training for m in model.modules()} == {False}++ @pytest.mark.slow+ def test_load_pretrained_is_batch_independent(self):+ model = EfficientViT.from_config(EfficientViTConfig.from_pretrained("b1", 224))+ running_means = [m.running_mean.clone() for m in model.modules() if isinstance(m, torch.nn.BatchNorm2d)]+ generator = torch.Generator().manual_seed(0)+ x1 = torch.rand(1, 3, 224, 256, generator=generator)+ x2 = torch.rand(1, 3, 224, 256, generator=generator)++ with torch.no_grad():+ alone = model(x1)["stage_final"][0]+ batched = model(torch.cat([x1, x2]))["stage_final"][0]++ # In evaluation mode sample 0 does not see sample 1; only the kernels' summation order may change with the+ # batch size, so the float32 tolerance is widened to 1e-4.+ torch.testing.assert_close(alone, batched, rtol=1e-4, atol=1e-4)+ after = [m.running_mean for m in model.modules() if isinstance(m, torch.nn.BatchNorm2d)]+ assert all(torch.equal(a, b) for a, b in zip(after, running_means))+def _test_smoke(self, device, dtype, img_size: int, expected_resolution: int, model_name: str):model = getattr(vit, f"efficientvit_backbone_{model_name}")()model = model.to(device=device, dtype=dtype)diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.pyindex dd2c49ba4..711a46bf1 100644--- a/tests/models/test_kimi_vl.py+++ b/tests/models/test_kimi_vl.py@@ -78,6 +78,9 @@ class TestKimiVLBuilder(BaseTester):assert isinstance(actual, KimiVLModel)assert actual.config is configmock_download.assert_called_once_with(kimi_vl_builder._KIMI_VL_A3B_INSTRUCT_REPO_ID, "cache")+ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ assert {m.training for m in actual.modules()} == {False}+ assert {m.training for m in KimiVLBuilder.from_config(config).modules()} == {True}def test_download_weights_uses_kornias_downloader(self, tmp_path):"""No optional package: kornia's own downloader, then its own safetensors reader."""diff --git a/tests/models/test_model_base.py b/tests/models/test_model_base.pyindex 5e7adb6c3..8e7f35053 100644--- a/tests/models/test_model_base.py+++ b/tests/models/test_model_base.py@@ -258,3 +258,16 @@ class TestModelBaseLoadCheckpoint(BaseTester):self.assert_close(model.linear.weight, source.linear.weight)self.assert_close(model.linear.bias, source.linear.bias)++ def test_load_checkpoint_keeps_the_mode(self, tmp_path) -> None:+ path = tmp_path / "model.pth"+ torch.save(_TinyModel().state_dict(), path)++ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ model = _TinyModel()+ model.load_checkpoint(str(path))+ assert {m.training for m in model.modules()} == {True}++ model.eval()+ model.load_checkpoint(str(path))+ assert {m.training for m in model.modules()} == {False}diff --git a/tests/models/test_rt_detr.py b/tests/models/test_rt_detr.pyindex fa18e99b4..81862152d 100644--- a/tests/models/test_rt_detr.py+++ b/tests/models/test_rt_detr.py@@ -112,6 +112,37 @@ class TestRTDETR(BaseTester):assert logits.shape == (shape[0], num_queries, num_classes)assert boxes.shape == (shape[0], num_queries, 4)+ @pytest.mark.device_agnostic+ def test_from_pretrained_mode(self, monkeypatch):+ monkeypatch.setattr(+ "kornia.models.rt_detr.model.load_state_dict_from_url", lambda *args, **kwargs: {"ema": {"module": {}}}+ )+ monkeypatch.setattr(RTDETR, "load_state_dict", lambda self, state_dict, *args, **kwargs: None)+ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ assert {m.training for m in RTDETR.from_pretrained("rtdetr_r18vd").modules()} == {False}++ monkeypatch.setattr(RTDETR, "load_checkpoint", lambda self, checkpoint, device=None: None)+ from_checkpoint = RTDETR.from_config(RTDETRConfig("resnet18d", 10, checkpoint="x.pt"))+ assert {m.training for m in from_checkpoint.modules()} == {False}++ assert {m.training for m in RTDETR.from_config(RTDETRConfig("resnet18d", 10)).modules()} == {True}+ assert {m.training for m in RTDETR.from_name("rtdetr_r18vd").modules()} == {True}++ @pytest.mark.slow+ def test_from_pretrained_is_batch_independent(self):+ model = RTDETR.from_pretrained("rtdetr_r18vd")+ generator = torch.Generator().manual_seed(0)+ x1 = torch.rand(1, 3, 256, 320, generator=generator)+ x2 = torch.rand(1, 3, 256, 320, generator=generator)++ with torch.no_grad():+ alone = model(x1)[0][0]+ batched = model(torch.cat([x1, x2]))[0][0]++ # In evaluation mode image 0 does not see image 1; only the kernels' summation order may change with the+ # batch size, so the float32 tolerance is widened to 1e-4.+ self.assert_close(alone, batched, rtol=1e-4, atol=1e-4)+@pytest.mark.skip("Unnecessary")def test_exception(self): ...diff --git a/tests/models/test_sam.py b/tests/models/test_sam.pyindex a3a28ca43..54f95cfc9 100644--- a/tests/models/test_sam.py+++ b/tests/models/test_sam.py@@ -18,6 +18,7 @@import pytestimport torchimport torch.nn.functional as F+from torch import nnfrom kornia.models.sam import Sam, SamConfig@@ -117,3 +118,39 @@ class TestSam(BaseTester):@pytest.mark.parametrize("model_type", ["vit_b", "mobile_sam"])def test_pretrained(self, model_type):Sam.from_config(SamConfig(model_type, pretrained=True))++ @pytest.mark.device_agnostic+ def test_from_config_mode(self, monkeypatch):+ loaded = []+ monkeypatch.setattr(Sam, "load_checkpoint", lambda self, checkpoint, device=None: loaded.append(checkpoint))++ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ weighted = Sam.from_config(SamConfig("mobile_sam", pretrained=True))+ assert {m.training for m in weighted.modules()} == {False}+ from_checkpoint = Sam.from_config(SamConfig("mobile_sam", checkpoint="x.pt"))+ assert {m.training for m in from_checkpoint.modules()} == {False}+ assert len(loaded) == 2+ assert loaded[1] == "x.pt"++ assert {m.training for m in Sam.from_config(SamConfig("mobile_sam")).modules()} == {True}+ assert {m.training for m in Sam.from_name("mobile_sam").modules()} == {True}+ assert len(loaded) == 2++ @pytest.mark.slow+ def test_mobile_sam_pretrained_is_batch_independent(self):+ encoder = Sam.from_config(SamConfig("mobile_sam", pretrained=True)).image_encoder+ running_means = [m.running_mean.clone() for m in encoder.modules() if isinstance(m, nn.BatchNorm2d)]+ # The image encoder takes only its square 1024 input; VisualPrompter pads every image to it.+ generator = torch.Generator().manual_seed(0)+ x1 = torch.rand(1, 3, 1024, 1024, generator=generator)+ x2 = torch.rand(1, 3, 1024, 1024, generator=generator)++ with torch.no_grad():+ alone = encoder(x1)[0]+ batched = encoder(torch.cat([x1, x2]))[0]++ # In evaluation mode sample 0 does not see sample 1; only the kernels' summation order may change with the+ # batch size, so the float32 tolerance is widened to 1e-4.+ self.assert_close(alone, batched, rtol=1e-4, atol=1e-4)+ after = [m.running_mean for m in encoder.modules() if isinstance(m, nn.BatchNorm2d)]+ assert all(torch.equal(a, b) for a, b in zip(after, running_means))diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.pyindex 42c3d0bcc..46aa25dee 100644--- a/tests/models/test_siglip2.py+++ b/tests/models/test_siglip2.py@@ -24,7 +24,7 @@ import pytestimport torchimport kornia.models.siglip2.builder as siglip2_builder-from kornia.models.siglip2 import SigLip2Config, SigLip2Model, SigLip2Result+from kornia.models.siglip2 import SigLip2Builder, SigLip2Config, SigLip2Model, SigLip2Resultfrom kornia.models.siglip2.attention import SigLip2Attentionfrom kornia.models.siglip2.config import SigLip2TextConfig, SigLip2VisionConfigfrom kornia.models.siglip2.preprocessor import SigLip2ImagePreprocessor@@ -104,6 +104,18 @@ class TestSigLip2Builder:assert repos == ["google/siglip2-base-patch16-224", "google/siglip2-base-patch16-256"]+ def test_from_pretrained_hf_returns_eval_mode(self, monkeypatch, config):+ monkeypatch.setattr(SigLip2Config, "from_name", staticmethod(lambda model_name: config))+ state_dict = SigLip2Model(config).state_dict()+ monkeypatch.setattr(siglip2_builder, "_download_weights", lambda model_name, cache_dir: state_dict)++ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ weighted = SigLip2Builder.from_pretrained_hf("google/siglip2-base-patch16-224")+ assert {m.training for m in weighted.modules()} == {False}+ named = SigLip2Builder.from_name("google/siglip2-base-patch16-224")+ assert {m.training for m in named.modules()} == {True}+ assert {m.training for m in SigLip2Builder.from_config(config).modules()} == {True}+def test_a_missing_checkpoint_is_reported_with_the_model_name(self, tmp_path):with (patch.object(siglip2_builder, "download_hf_file", return_value="cached.safetensors"),diff --git a/tests/models/test_tiny_vit.py b/tests/models/test_tiny_vit.pyindex 529293bef..8960f1232 100644--- a/tests/models/test_tiny_vit.py+++ b/tests/models/test_tiny_vit.py@@ -15,16 +15,51 @@# limitations under the License.#+import copyimport sysimport pytestimport torch+from torch import nn-from kornia.models.tiny_vit import TinyViT+from kornia.models.tiny_vit import Attention, TinyViTfrom testing.base import BaseTester+def _attentions(model: nn.Module) -> list[Attention]:+ return [m for m in model.modules() if isinstance(m, Attention)]+++def _random_biases(model: TinyViT) -> TinyViT:+ # ``attention_biases`` starts as zeros, so a bias read from a stale copy would still be right. Seeded N(0, 1)+ # values make every relative-position bias table distinct from its initial value.+ generator = torch.Generator().manual_seed(0)+ with torch.no_grad():+ for attention in _attentions(model):+ attention.attention_biases.copy_(torch.randn(attention.attention_biases.shape, generator=generator))+ return model+++def _modes(model: nn.Module) -> set[bool]:+ # The ``training`` flags of the model and every submodule: ``{False}`` is evaluation mode throughout.+ return {m.training for m in model.modules()}+++def _fake_5m_checkpoint(url: str | list[str], *args: object, **kwargs: object) -> dict[str, torch.Tensor]:+ # Stands in for ``load_state_dict_from_url``. The ImageNet-22k checkpoints (``*_22k_distill.pth``) carry a+ # 21841-class head and the ImageNet-1k ones (``*_22kto1k_distill.pth``) a 1000-class head+ # (docs/source/models/tiny_vit.rst).+ candidates = [url] if isinstance(url, str) else url+ num_classes = 21841 if any("_22k_distill" in candidate for candidate in candidates) else 1000+ return TinyViT.from_config("5m", num_classes=num_classes).state_dict()+++def _image(batch_size: int = 1, seed: int = 0) -> torch.Tensor:+ # TinyViT takes only its square ``img_size`` (224 by default).+ return torch.rand(batch_size, 3, 224, 224, generator=torch.Generator().manual_seed(seed))++class TestTinyViT(BaseTester):# 128 is not a multiple of the 7-pixel attention window at any stage, so it takes the padded# window-attention path; 224 divides evenly and takes the unpadded one. Both belong here: the@@ -87,3 +122,118 @@ class TestTinyViT(BaseTester):out = model(data)assert out.shape == (batch_size, 256, img_size // 16, img_size // 16)++ @pytest.mark.device_agnostic+ def test_eval_bias_follows_load_state_dict(self):+ src = _random_biases(TinyViT.from_config("5m"))+ dst = TinyViT.from_config("5m").eval()+ x = _image()+ with torch.no_grad():+ dst(x) # an evaluation-mode forward before the load, so a bias kept from it would go stale+ dst.load_state_dict(src.state_dict())+ src.eval()++ with torch.no_grad():+ assert torch.equal(dst(x), src(x))++ @pytest.mark.device_agnostic+ def test_eval_mode_bias_gets_gradients(self):+ model = _random_biases(TinyViT.from_config("5m")).eval()++ model(_image()).sum().backward()++ for attention in _attentions(model):+ assert attention.attention_biases.grad is not None+ assert attention.attention_biases.grad.abs().sum() > 0++ @pytest.mark.device_agnostic+ def test_eval_bias_follows_parameter_update(self):+ model = _random_biases(TinyViT.from_config("5m")).eval()+ x = _image()+ with torch.no_grad():+ y0 = model(x)+ # Doubling N(0, 1) biases changes the gaps between the logits of a row, which the softmax keeps; a+ # constant shift of every bias would cancel in the softmax and could not show a stale bias.+ for attention in _attentions(model):+ attention.attention_biases.mul_(2.0)+ y1 = model(x)++ fresh = TinyViT.from_config("5m")+ fresh.load_state_dict(model.state_dict())+ expected = fresh.eval()(x)++ self.assert_close(y1, expected)+ # The update moves the logits by 0.11 at most; float32 rounding alone moves them by about 4e-7.+ assert (y1 - y0).abs().max() > 1e-2++ def test_eval_then_cast_matches_cast_then_eval(self, device, dtype):+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ evaluated_first = _random_biases(TinyViT.from_config("5m"))+ cast_first = copy.deepcopy(evaluated_first)+ evaluated_first.eval().to(device, dtype)+ cast_first.to(device, dtype).eval()+ x = _image().to(device, dtype)++ with torch.no_grad():+ assert torch.equal(evaluated_first(x), cast_first(x))++ @pytest.mark.device_agnostic+ def test_from_config_mode(self, monkeypatch):+ assert _modes(TinyViT.from_config("5m")) == {True}+ assert _modes(TinyViT.from_config("5m", pretrained=False)) == {True}++ monkeypatch.setattr("kornia.models.tiny_vit.load_state_dict_from_url", _fake_5m_checkpoint)+ assert _modes(TinyViT.from_config("5m", pretrained=True)) == {False}+ assert _modes(TinyViT.from_config("5m", pretrained="in1k", num_classes=1000)) == {False}+ assert _modes(TinyViT.from_config("5m", pretrained="in22k", num_classes=21841)) == {False}++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize(+ ("pretrained", "num_classes"),+ [(True, 8), (True, 1001), ("in22k", 1000)],+ ids=["head-narrower", "head-wider", "in22k-default-classes"],+ )+ def test_from_config_partial_weights_mode(self, monkeypatch, pretrained, num_classes):+ monkeypatch.setattr("kornia.models.tiny_vit.load_state_dict_from_url", _fake_5m_checkpoint)++ # A class count other than the checkpoint's (1000 for in1k, 21841 for in22k) re-initialises the head: a+ # pretrained backbone to fine-tune, so training mode.+ with pytest.warns(UserWarning, match="Resetting classification head"):+ model = TinyViT.from_config("5m", pretrained=pretrained, num_classes=num_classes)+ assert model.head.out_features == num_classes+ assert not model.head.weight.any()+ assert not model.head.bias.any()+ assert _modes(model) == {True}++ @pytest.mark.skipif(sys.version_info.major == 3 and sys.version_info.minor == 8, reason="not working for py3.8")+ def test_dynamo_eval_mode(self, device, dtype, torch_optimizer):+ if device.type == "mps" and dtype == torch.float64:+ pytest.skip("MPS does not support float64")+ # Evaluation mode first, then the cast: the order of a pretrained model moved to its device.+ op = _random_biases(TinyViT.from_config("5m")).eval().to(device, dtype)+ img = _image().to(device, dtype)++ op_optimized = torch_optimizer(op)+ # Inductor keeps fused intermediates in float32 where eager rounds every op to the half dtype. Over the network+ # the two differ on MPS by up to 1.1e-3 in float16 and 1.6e-2 (two bfloat16 steps at the logit scale of 2) in+ # bfloat16, past the default tolerances of 1e-3 and 7.8e-3.+ tol = {torch.float16: 1e-2, torch.bfloat16: 5e-2}.get(dtype)+ with torch.no_grad():+ self.assert_close(op(img), op_optimized(img), rtol=tol, atol=tol)++ @pytest.mark.slow+ def test_pretrained_is_batch_independent(self):+ model = TinyViT.from_config("5m", pretrained=True)+ running_means = [m.running_mean.clone() for m in model.modules() if isinstance(m, nn.BatchNorm2d)]+ x1, x2 = _image(seed=0), _image(seed=1)++ with torch.no_grad():+ alone = model(x1)[0]+ batched = model(torch.cat([x1, x2]))[0]++ # In evaluation mode sample 0 does not see sample 1; only the kernels' summation order may change with the+ # batch size, so the float32 tolerance is widened to 1e-4.+ self.assert_close(alone, batched, rtol=1e-4, atol=1e-4)+ after = [m.running_mean for m in model.modules() if isinstance(m, nn.BatchNorm2d)]+ assert all(torch.equal(a, b) for a, b in zip(after, running_means))diff --git a/tests/models/test_vision_transformer.py b/tests/models/test_vision_transformer.pyindex 318075997..64f39d855 100644--- a/tests/models/test_vision_transformer.py+++ b/tests/models/test_vision_transformer.py@@ -77,3 +77,13 @@ class TestVisionTransformer(BaseTester):with torch.no_grad():out = model(torch.rand(1, 3, 224, 224))assert out.shape == (1, 50, 384)++ @pytest.mark.device_agnostic+ def test_from_config_mode(self, monkeypatch):+ state_dict = VisionTransformer.from_config("vit_ti/16").state_dict()+ monkeypatch.setattr("kornia.models.vit.load_state_dict_from_url", lambda *args, **kwargs: state_dict)++ # ``training`` of the model and of every submodule: ``{False}`` is evaluation mode throughout.+ assert {m.training for m in VisionTransformer.from_config("vit_ti/16", pretrained=True).modules()} == {False}+ assert {m.training for m in VisionTransformer.from_config("vit_ti/16").modules()} == {True}+ assert {m.training for m in VisionTransformer.from_config("vit_ti/16", pretrained=False).modules()} == {True}