Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(models): load the pretrained EfficientViT backbone weights (#5283)

niukanen1fa0e4688b633
diff --git a/changelog.d/5283.fixed.md b/changelog.d/5283.fixed.md
new file mode 100644
index 000000000..fe6cb9846
--- /dev/null
+++ b/changelog.d/5283.fixed.md
@@ -0,0 +1 @@
+`EfficientViT.from_config` now loads the pretrained backbone weights: the hosted checkpoints store them under a `backbone.` prefix, which the previous non-strict load silently dropped, so every "pretrained" model was randomly initialised. The load is now strict: a checkpoint whose backbone entries do not match the model raises `RuntimeError` instead of returning a partly loaded model. A state dict saved from the backbone itself, without the prefix, still loads.
diff --git a/docs/source/_static/img/models/efficient_vit.jpg b/docs/source/_static/img/models/efficient_vit.jpg
index c5f90b36f..146c479e8 100644
Binary files a/docs/source/_static/img/models/efficient_vit.jpg and b/docs/source/_static/img/models/efficient_vit.jpg differ
diff --git a/kornia/models/efficient_vit/model.py b/kornia/models/efficient_vit/model.py
index dd02dd3e8..f55239879 100644
--- a/kornia/models/efficient_vit/model.py
+++ b/kornia/models/efficient_vit/model.py
@@ -91,9 +91,11 @@ class EfficientViT(ModelBase[EfficientViTConfig]):
if model_type not in ["b0", "b1", "b2", "b3", "l0", "l1", "l2", "l3"]:
raise ValueError(f"Unknown model type: {model_type}.")
- # create and load the model weights without strict until we polish the model files
model = getattr(vit, f"efficientvit_backbone_{model_type}")()
- model.load_state_dict(model_file, strict=False)
+ # The hosted checkpoints hold the backbone under a "backbone." prefix, next to a "head." classifier the
+ # backbone has no slot for. A state dict saved from the backbone itself has no prefix and loads as it is.
+ 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)
diff --git a/tests/models/test_efficient_vit.py b/tests/models/test_efficient_vit.py
index c5d6dd402..88449174a 100644
--- a/tests/models/test_efficient_vit.py
+++ b/tests/models/test_efficient_vit.py
@@ -25,6 +25,63 @@ from kornia.models.efficient_vit import backbone as vit
class TestEfficientViT:
+ @staticmethod
+ def _fake_checkpoint() -> dict[str, torch.Tensor]:
+ """Mimic the hosted checkpoints: backbone weights under a ``backbone.`` prefix plus a ``head.`` classifier."""
+ model = vit.efficientvit_backbone_b1()
+ state_dict = {
+ f"backbone.{key}": val.clone()
+ for key, val in model.state_dict().items()
+ if "num_batches_tracked" not in key
+ }
+ state_dict["head.classifier.weight"] = torch.randn(1000, 128)
+ state_dict["head.classifier.bias"] = torch.randn(1000)
+ return state_dict
+
+ def test_load_pretrained_loads_the_checkpoint_weights(self, monkeypatch):
+ # GH#5276: strict=False over the raw checkpoint silently loaded no weight at all
+ 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())
+
+ for key, val in state_dict.items():
+ if key.startswith("backbone."):
+ assert torch.equal(model.backbone.state_dict()[key[len("backbone.") :]], val)
+
+ @pytest.mark.parametrize("drift", ["missing", "unexpected"])
+ def test_load_pretrained_is_strict(self, monkeypatch, drift):
+ # a checkpoint that lacks a backbone entry, or holds one the backbone has no slot for, raises
+ state_dict = self._fake_checkpoint()
+ if drift == "missing":
+ del state_dict["backbone.input_stem.op_list.0.conv.weight"]
+ else:
+ state_dict["backbone.input_stem.extra.weight"] = torch.zeros(1)
+ monkeypatch.setattr(
+ "kornia.models.efficient_vit.model.load_state_dict_from_url",
+ lambda *args, **kwargs: {"state_dict": state_dict},
+ )
+
+ with pytest.raises(RuntimeError, match=f"{drift.capitalize()} key"):
+ EfficientViT.from_config(EfficientViTConfig())
+
+ def test_load_pretrained_accepts_a_backbone_state_dict(self, monkeypatch):
+ # a state dict saved from the backbone itself has no "backbone." prefix
+ state_dict = {key: val + 1 for key, val in vit.efficientvit_backbone_b1().state_dict().items()}
+ monkeypatch.setattr(
+ "kornia.models.efficient_vit.model.load_state_dict_from_url", lambda *args, **kwargs: state_dict
+ )
+
+ model = EfficientViT.from_config(EfficientViTConfig())
+
+ loaded = model.backbone.state_dict()
+ assert loaded.keys() == state_dict.keys()
+ for key, val in state_dict.items():
+ assert torch.equal(loaded[key], val)
+
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)