π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): point local-file advice at torch.load and let DexiNed.load_from_file read a local file (#5520)
εΊζ’η302854b62b45
diff --git a/changelog.d/5520.fixed.md b/changelog.d/5520.fixed.mdnew file mode 100644index 000000000..9d5fb712b--- /dev/null+++ b/changelog.d/5520.fixed.md@@ -0,0 +1,5 @@+`kornia.core.download.load_state_dict_from_url` and `download_file_from_url` no longer advise passing+`path.as_uri()` when given a `pathlib.Path`: a `file://` URL is cached by its base name like any other URL, so a+cached checkpoint of the same name, when there was one, was loaded instead of the local file. The `TypeError` now says+to load a local file with `torch.load`. `DexiNed.load_from_file` in `kornia.filters` and `kornia.models` now reads a+string that names an existing file with `torch.load(..., weights_only=True)`. (#5477)diff --git a/kornia/core/download.py b/kornia/core/download.pyindex 89002137c..b932708ca 100644--- a/kornia/core/download.py+++ b/kornia/core/download.py@@ -339,7 +339,7 @@ def _url_list(url: object) -> list[str]:checked: list[str] = []for u in urls:if isinstance(u, os.PathLike):- raise TypeError(f"{expected}, got a {type(u).__name__}; for a local file pass its path.as_uri().")+ raise TypeError(f"{expected}, got a {type(u).__name__}; to load a local file use torch.load.")if not isinstance(u, str):raise TypeError(f"{expected}, got {type(u).__name__}.")if not u:@@ -1094,7 +1094,10 @@ def load_state_dict_from_url(url: str | list[str], *, timeout: float | None = No``model_dir`` is expanded.Args:- url: a URL string, or a list of URL strings tried left-to-right.+ url: a URL string, or a list of URL strings tried left-to-right. A+ ``file://`` URL is cached by its base name like any other URL, so a+ cache entry of that name is returned instead of the local file; load+ a local file with :func:`torch.load`.timeout: seconds a connection attempt or a single read may stall before theattempt fails; it bounds each wait, not the whole transfer. ``None``uses the ``KORNIA_DOWNLOAD_TIMEOUT`` environment variable, read at@@ -1295,7 +1298,10 @@ def download_file_from_url(names it in every error it raises for the same reason.Args:- url: a URL string, or a list of URL strings tried left-to-right.+ url: a URL string, or a list of URL strings tried left-to-right. A+ ``file://`` URL is cached by its base name like any other URL, so a+ cache entry of that name is returned instead of the local file; read+ a local file directly.file_name: name to cache the file under. Defaults to the basename of theURL -- of the *first* URL when several are given, so that everysource shares one cache slot. Pass it explicitly whenever thatdiff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex 4ce0e294c..ab443829e 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -19,6 +19,7 @@from __future__ import annotations+import osfrom collections import OrderedDictfrom typing import ClassVar, Optional@@ -363,14 +364,19 @@ class DexiNed(nn.Module):normalization use inference behavior.Args:- path_file: URL accepted by+ path_file: path of a local checkpoint file, a URL accepted by:func:`kornia.core.download.load_state_dict_from_url`, or a list- of candidate URLs tried in order (HF-first fallback). A local- path is refused; load a local checkpoint with :func:`torch.load`- and pass it to ``load_state_dict``.+ of candidate URLs tried in order (HF-first fallback). A string+ naming an existing file (a leading ``~`` is expanded) is read with+ :func:`torch.load` and ``weights_only=True``; anything else goes+ through the hub cache, which is keyed by base name."""- # use torch.hub to load pretrained model- pretrained_dict = load_state_dict_from_url(path_file, map_location=torch.device("cpu"))+ local = os.path.expanduser(path_file) if isinstance(path_file, str) else None+ if local is not None and os.path.isfile(local):+ with open(local, "rb") as f:+ pretrained_dict = torch.load(f, map_location=torch.device("cpu"), weights_only=True)+ else:+ pretrained_dict = load_state_dict_from_url(path_file, map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)self.eval()diff --git a/kornia/models/dexined.py b/kornia/models/dexined.pyindex d4ce4267c..dab192ab8 100644--- a/kornia/models/dexined.py+++ b/kornia/models/dexined.py@@ -19,6 +19,7 @@from __future__ import annotations+import osfrom collections import OrderedDictfrom typing import ClassVar, Optional@@ -248,14 +249,19 @@ class DexiNed(ONNXExportMixin, nn.Module):"""Load pretrained DexiNed weights and switch the module to evaluation mode.Args:- path_file: URL accepted by+ path_file: path of a local checkpoint file, a URL accepted by:func:`kornia.core.download.load_state_dict_from_url`, or a list- of candidate URLs tried in order (HF-first fallback). A local- path is refused; load a local checkpoint with :func:`torch.load`- and pass it to ``load_state_dict``.+ of candidate URLs tried in order (HF-first fallback). A string+ naming an existing file (a leading ``~`` is expanded) is read with+ :func:`torch.load` and ``weights_only=True``; anything else goes+ through the hub cache, which is keyed by base name."""- # use torch.hub to load pretrained model- pretrained_dict = load_state_dict_from_url(path_file, map_location=torch.device("cpu"))+ local = os.path.expanduser(path_file) if isinstance(path_file, str) else None+ if local is not None and os.path.isfile(local):+ with open(local, "rb") as f:+ pretrained_dict = torch.load(f, map_location=torch.device("cpu"), weights_only=True)+ else:+ pretrained_dict = load_state_dict_from_url(path_file, map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)self.eval()diff --git a/tests/core/test_download.py b/tests/core/test_download.pyindex cfa7bf709..2b2d72047 100644--- a/tests/core/test_download.py+++ b/tests/core/test_download.py@@ -2104,8 +2104,8 @@ class TestUrlArguments:([], ValueError, "at least one URL"),("", ValueError, "empty"),(["http://127.0.0.1:9/w.pth", ""], ValueError, "empty"),- (Path("w.pth"), TypeError, "as_uri"),- ([Path("w.pth")], TypeError, "as_uri"),+ (Path("w.pth"), TypeError, "torch.load"),+ ([Path("w.pth")], TypeError, "torch.load"),(None, TypeError, "URL string"),(b"http://127.0.0.1:9/w.pth", TypeError, "URL string"),([b"http://127.0.0.1:9/w.pth"], TypeError, "URL string"),diff --git a/tests/models/test_dexined.py b/tests/models/test_dexined.pyindex 4ad08b1f4..2f9ce23be 100644--- a/tests/models/test_dexined.py+++ b/tests/models/test_dexined.py@@ -15,12 +15,16 @@# limitations under the License.#+import pickle+import pytestimport torch+from kornia.filters.dexined import DexiNed as FilterDexiNedfrom kornia.models.dexined import DexiNedfrom testing.base import BaseTester+from testing.pickle_payload import CreatesMarkerOnLoad, load_without_running_payloadclass TestDexiNed(BaseTester):@@ -54,3 +58,69 @@ class TestDexiNed(BaseTester):@pytest.mark.skip(reason="DexiNed do not compile with dynamo.")def test_dynamo(self, device, dtype, torch_optimizer): ...++[email protected]("cls", [FilterDexiNed, DexiNed], ids=["filters", "models"])+class TestDexiNedLoadFromFile:+ """``load_from_file`` reads a local file itself; the hub cache is keyed by base name (#5477)."""++ @staticmethod+ def _hub_with_a_cached_decoy(tmp_path, monkeypatch, name):+ hub = tmp_path / "hub"+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(hub))+ (hub / "checkpoints").mkdir(parents=True)+ torch.save({"w": torch.zeros(3)}, hub / "checkpoints" / name)++ @staticmethod+ def _record_load_state_dict(model, monkeypatch):+ loaded = []+ monkeypatch.setattr(+ model, "load_state_dict", lambda state_dict, strict=True: loaded.append((state_dict, strict))+ )+ return loaded++ @pytest.mark.parametrize("spelling", ["absolute", "home"])+ def test_a_local_file_is_loaded_even_when_the_cache_holds_its_name(self, cls, spelling, tmp_path, monkeypatch):+ self._hub_with_a_cached_decoy(tmp_path, monkeypatch, "dexined.pth")+ local = tmp_path / "weights" / "dexined.pth"+ local.parent.mkdir()+ torch.save({"w": torch.ones(3)}, local)+ if spelling == "home":+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ path_file = "~/weights/dexined.pth"+ else:+ path_file = str(local)+ model = cls(pretrained=False).train()+ loaded = self._record_load_state_dict(model, monkeypatch)++ model.load_from_file(path_file)++ assert len(loaded) == 1+ state_dict, strict = loaded[0]+ assert strict is True+ assert torch.equal(state_dict["w"], torch.ones(3))+ assert not model.training++ def test_a_string_that_names_no_file_is_still_treated_as_a_url(self, cls, tmp_path, monkeypatch):+ self._hub_with_a_cached_decoy(tmp_path, monkeypatch, "dexined.pth")+ model = cls(pretrained=False)+ loaded = self._record_load_state_dict(model, monkeypatch)++ with pytest.raises(ValueError, match="scheme"):+ model.load_from_file(str(tmp_path / "missing" / "dexined.pth"))++ assert loaded == []++ def test_a_pickled_callable_in_a_local_file_is_refused_and_never_run(self, cls, tmp_path, monkeypatch):+ # The local branch loads with ``weights_only=True``, as the hub branch does.+ marker = tmp_path / "marker"+ path = tmp_path / "dexined.pth"+ torch.save({"w": torch.ones(3), "extra": CreatesMarkerOnLoad(marker)}, path)+ model = cls(pretrained=False)+ loaded = self._record_load_state_dict(model, monkeypatch)++ with pytest.raises(pickle.UnpicklingError):+ load_without_running_payload(marker, lambda: model.load_from_file(str(path)))++ assert loaded == []