Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): refuse a url without a scheme before the hub-cache lookup (#5410)

Dipak Chaudhari51420613b908
diff --git a/changelog.d/5410.fixed.md b/changelog.d/5410.fixed.md
new file mode 100644
index 000000000..b0e06fb60
--- /dev/null
+++ b/changelog.d/5410.fixed.md
@@ -0,0 +1,5 @@
+`kornia.core.download.load_state_dict_from_url` and `download_file_from_url` now raise `ValueError` for a
+`url` string without a scheme, such as a local path, before looking in the cache. The cache is keyed by the
+URL's base name, so a mistyped local path used to load whichever cached checkpoint shared that name. Load a
+local file with `torch.load`. `ModelBase.load_checkpoint` now expands `~` before checking for a local file.
+(#5410)
diff --git a/kornia/core/download.py b/kornia/core/download.py
index 1412c38ed..89002137c 100644
--- a/kornia/core/download.py
+++ b/kornia/core/download.py
@@ -324,7 +324,7 @@ def _url_list(url: object) -> list[str]:
Raises:
TypeError: if *url* is not a string or an iterable of strings.
- ValueError: if there is no URL, or one of them is empty.
+ ValueError: if there is no URL, or one of them is empty or has no scheme.
"""
expected = "url must be a URL string or a list of them"
if isinstance(url, (str, bytes, os.PathLike)):
@@ -344,6 +344,11 @@ def _url_list(url: object) -> list[str]:
raise TypeError(f"{expected}, got {type(u).__name__}.")
if not u:
raise ValueError(f"url must not be empty, got {url!r}.")
+ # The cache is looked up by the URL's base name before anything is
+ # fetched, so a local path here would load whichever cached file shares
+ # its name. A one-letter scheme is a Windows drive letter, not a URL.
+ if len(urlparse(u).scheme) <= 1:
+ raise ValueError(f"url must be a URL with a scheme, got {u!r}; to load a local file use torch.load.")
checked.append(u)
return checked
@@ -1106,7 +1111,8 @@ def load_state_dict_from_url(url: str | list[str], *, timeout: float | None = No
Raises:
TypeError: if ``url`` is not a URL string or a list of them, ``timeout``
is not a number, or a keyword is not one the torch function takes.
- ValueError: if ``url`` is empty; if ``timeout`` is not greater than 0 and
+ ValueError: if ``url`` is empty or has no scheme (a local path is not a
+ URL); if ``timeout`` is not greater than 0 and
at most ``threading.TIMEOUT_MAX``, or it is omitted and
``KORNIA_DOWNLOAD_TIMEOUT`` holds such a value or no number (the message
names which); if ``file_name`` is not a bare file name, or it is omitted
@@ -1321,7 +1327,8 @@ def download_file_from_url(
is not a number.
ValueError: if ``file_name`` is not a single path component, or it is
omitted and the first URL's path does not end in a file name; if
- ``url`` is empty; or if ``timeout`` is not greater than 0 and at most
+ ``url`` is empty or has no scheme (a local path is not a URL); or if
+ ``timeout`` is not greater than 0 and at most
``threading.TIMEOUT_MAX``, or it is omitted and
``KORNIA_DOWNLOAD_TIMEOUT`` holds such a value or no number (the message
names which).
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 71423530e..4ce0e294c 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -363,9 +363,11 @@ class DexiNed(nn.Module):
normalization use inference behavior.
Args:
- path_file: URL or local checkpoint identifier accepted by
- :func:`kornia.core.download.load_state_dict_from_url`, or a
- list of candidate URLs tried in order (HF-first fallback).
+ path_file: 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``.
"""
# use torch.hub to load pretrained model
pretrained_dict = load_state_dict_from_url(path_file, map_location=torch.device("cpu"))
diff --git a/kornia/models/base.py b/kornia/models/base.py
index 04919fb79..d26fdd7bd 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -152,8 +152,9 @@ class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):
device: The desired device to load the weights and move the model
"""
- if isinstance(checkpoint, str) and os.path.isfile(checkpoint):
- with open(checkpoint, "rb") as f:
+ local = os.path.expanduser(checkpoint) if isinstance(checkpoint, str) else None
+ if local is not None and os.path.isfile(local):
+ with open(local, "rb") as f:
state_dict = torch.load(f, map_location=device, weights_only=True)
else:
state_dict = load_state_dict_from_url(checkpoint, map_location=device)
diff --git a/kornia/models/dexined.py b/kornia/models/dexined.py
index 36af62b77..d4ce4267c 100644
--- a/kornia/models/dexined.py
+++ b/kornia/models/dexined.py
@@ -248,9 +248,11 @@ class DexiNed(ONNXExportMixin, nn.Module):
"""Load pretrained DexiNed weights and switch the module to evaluation mode.
Args:
- path_file: URL or local checkpoint path accepted by
+ path_file: URL accepted by
:func:`kornia.core.download.load_state_dict_from_url`, or a list
- of candidate URLs tried in order (HF-first fallback).
+ 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``.
"""
# use torch.hub to load pretrained model
pretrained_dict = load_state_dict_from_url(path_file, map_location=torch.device("cpu"))
diff --git a/tests/core/test_download.py b/tests/core/test_download.py
index da8724f18..cfa7bf709 100644
--- a/tests/core/test_download.py
+++ b/tests/core/test_download.py
@@ -2109,8 +2109,27 @@ class TestUrlArguments:
(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"),
+ ("/no/such/dir/w.pth", ValueError, "scheme"),
+ ("w.pth", ValueError, "scheme"),
+ ("~/typo/w.pth", ValueError, "scheme"),
+ (r"C:\no\such\w.pth", ValueError, "scheme"),
+ (["http://127.0.0.1:9/w.pth", "/no/such/dir/w.pth"], ValueError, "scheme"),
+ ],
+ ids=[
+ "empty_list",
+ "empty_str",
+ "empty_str_in_list",
+ "path",
+ "path_in_list",
+ "none",
+ "bytes",
+ "bytes_in_list",
+ "posix_path_str",
+ "bare_name",
+ "home_path_str",
+ "windows_path_str",
+ "path_str_in_list",
],
- ids=["empty_list", "empty_str", "empty_str_in_list", "path", "path_in_list", "none", "bytes", "bytes_in_list"],
)
@pytest.mark.parametrize("entry", list(_ENTRY_POINTS))
def test_a_value_that_is_not_a_url_is_refused(self, hub_dir_in_tmp, url, error, match, entry) -> None:
@@ -2119,6 +2138,16 @@ class TestUrlArguments:
assert not hub_dir_in_tmp.exists()
+ @pytest.mark.parametrize("entry", list(_ENTRY_POINTS))
+ def test_a_path_is_refused_even_when_the_cache_holds_its_name(self, hub_dir_in_tmp, entry) -> None:
+ """The cache is keyed by base name, so a mistyped path used to load the cached file (#5404)."""
+ cached = hub_dir_in_tmp / "checkpoints" / "x.pt"
+ cached.parent.mkdir(parents=True)
+ torch.save({"w": torch.zeros(2)}, cached)
+
+ with pytest.raises(ValueError, match="scheme"):
+ _ENTRY_POINTS[entry]("/no/such/dir/x.pt", progress=False)
+
class TestHfUrlEscaping:
"""``hf_url`` builds a URL, so its arguments are path segments, not URL syntax (#5219)."""
diff --git a/tests/models/test_model_base.py b/tests/models/test_model_base.py
index 3102720aa..b6be0daed 100644
--- a/tests/models/test_model_base.py
+++ b/tests/models/test_model_base.py
@@ -236,6 +236,18 @@ class TestModelBaseLoadCheckpoint(BaseTester):
with pytest.raises(pickle.UnpicklingError):
load_without_running_payload(marker, lambda: model.load_checkpoint(str(path)))
+ def test_a_home_relative_path_loads_the_local_file(self, tmp_path, monkeypatch, dtype) -> None:
+ source = _TinyModel().to(dtype)
+ torch.save(source.state_dict(), tmp_path / "x.pt")
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+
+ model = _TinyModel().to(dtype)
+ model.load_checkpoint("~/x.pt")
+
+ self.assert_close(model.linear.weight, source.linear.weight)
+ self.assert_close(model.linear.bias, source.linear.bias)
+
def test_a_local_state_dict_loads(self, tmp_path, dtype) -> None:
source = _TinyModel().to(dtype)
path = tmp_path / "model.pth"