π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix: load local EfficientViT checkpoints (#5385)
Karnajeet Gosavia88d1031b820
diff --git a/changelog.d/5385.fixed.md b/changelog.d/5385.fixed.mdnew file mode 100644index 000000000..29d3bba18--- /dev/null+++ b/changelog.d/5385.fixed.md@@ -0,0 +1 @@+`EfficientViT.from_config` now loads local checkpoint paths as well as checkpoint URLs.diff --git a/kornia/models/efficient_vit/model.py b/kornia/models/efficient_vit/model.pyindex af9278f63..57c2ed0d8 100644--- a/kornia/models/efficient_vit/model.py+++ b/kornia/models/efficient_vit/model.py@@ -17,6 +17,7 @@from __future__ import annotations+import osfrom dataclasses import dataclass, fieldfrom typing import Literal@@ -78,14 +79,20 @@ class EfficientViT(ModelBase[EfficientViTConfig]):EfficientViT: the EfficientViT model."""- # load the model from the checkpoint+ # load the model from the checkpoint; expand ``~`` first, or a ``~`` path reaches the URL loader, which+ # resolves a file name already in the hub cache to that cached file instead of the local one+ checkpoint = os.path.expanduser(config.checkpoint)try:- model_file = load_state_dict_from_url(config.checkpoint, map_location="cpu")+ if os.path.isfile(checkpoint):+ with open(checkpoint, "rb") as f:+ model_file = torch.load(f, map_location="cpu", weights_only=True)+ else:+ model_file = load_state_dict_from_url(config.checkpoint, map_location="cpu")model_file = model_file.get("state_dict", model_file)- except RuntimeError:- raise RuntimeError(f"Unable to load the model from {config.checkpoint}.") from None+ except RuntimeError as exc:+ raise RuntimeError(f"Unable to load the model from {config.checkpoint}.") from exc- file_name = config.checkpoint.split("/")[-1]+ file_name = os.path.basename(checkpoint)model_type = file_name.split("-")[0]if model_type not in ["b0", "b1", "b2", "b3", "l0", "l1", "l2", "l3"]:diff --git a/tests/models/test_efficient_vit.py b/tests/models/test_efficient_vit.pyindex 88449174a..673fd0521 100644--- a/tests/models/test_efficient_vit.py+++ b/tests/models/test_efficient_vit.py@@ -16,6 +16,8 @@#+import pickle+import pytestimport torch@@ -24,6 +26,10 @@ from kornia.models.efficient_vit import EfficientViT, EfficientViTConfigfrom kornia.models.efficient_vit import backbone as vit+class _NotAWeight:+ """An arbitrary class, which ``torch.load(..., weights_only=True)`` refuses to unpickle."""++class TestEfficientViT:@staticmethoddef _fake_checkpoint() -> dict[str, torch.Tensor]:@@ -52,6 +58,62 @@ class TestEfficientViT:if key.startswith("backbone."):assert torch.equal(model.backbone.state_dict()[key[len("backbone.") :]], val)+ def test_load_local_checkpoint(self, tmp_path, monkeypatch):+ state_dict = self._fake_checkpoint()+ checkpoint = tmp_path / "b1-local.pt"+ torch.save(state_dict, checkpoint)+ monkeypatch.setattr(+ "kornia.models.efficient_vit.model.load_state_dict_from_url",+ lambda *args, **kwargs: pytest.fail("local checkpoints must not be downloaded"),+ )++ model = EfficientViT.from_config(EfficientViTConfig(checkpoint=str(checkpoint)))++ for key, val in state_dict.items():+ if key.startswith("backbone."):+ assert torch.equal(model.backbone.state_dict()[key[len("backbone.") :]], val)++ def test_load_local_checkpoint_expands_user(self, tmp_path, monkeypatch):+ # a ``~`` path must not reach the URL loader, which resolves a name already in the hub cache to that file+ state_dict = self._fake_checkpoint()+ torch.save(state_dict, tmp_path / "b1-r224.pt")+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ monkeypatch.setattr(+ "kornia.models.efficient_vit.model.load_state_dict_from_url",+ lambda *args, **kwargs: pytest.fail("local checkpoints must not be downloaded"),+ )++ model = EfficientViT.from_config(EfficientViTConfig(checkpoint="~/b1-r224.pt"))++ key = "input_stem.op_list.0.conv.weight"+ assert torch.equal(model.backbone.state_dict()[key], state_dict[f"backbone.{key}"])++ def test_load_local_checkpoint_is_weights_only(self, tmp_path, monkeypatch):+ # a local file is unpickled with weights_only=True, as the URL path and ModelBase.load_checkpoint do+ checkpoint = tmp_path / "b1-local.pt"+ torch.save({"payload": _NotAWeight()}, checkpoint)+ monkeypatch.setattr(+ "kornia.models.efficient_vit.model.load_state_dict_from_url",+ lambda *args, **kwargs: pytest.fail("local checkpoints must not be downloaded"),+ )++ with pytest.raises(pickle.UnpicklingError):+ EfficientViT.from_config(EfficientViTConfig(checkpoint=str(checkpoint)))++ def test_load_failure_preserves_cause(self, monkeypatch):+ cause = RuntimeError("download failed")++ def fail_download(*args, **kwargs):+ raise cause++ monkeypatch.setattr("kornia.models.efficient_vit.model.load_state_dict_from_url", fail_download)++ with pytest.raises(RuntimeError, match="Unable to load the model") as exc_info:+ EfficientViT.from_config(EfficientViTConfig())++ assert exc_info.value.__cause__ is cause+@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