π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(core): HF-first weight download with fallback + upload all model weights to HF (#3655)
Dmytro Mishkin4adbd7056299
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex bd40fefb1..65af84318 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -21,6 +21,7 @@ This subpackage provides core functionality, device management, and backend supp"""from . import external+from .download import hf_url, load_state_dict_from_urlfrom .mixin import (ImageModuleMixIn,ONNXExportMixin,@@ -40,5 +41,7 @@ __all__ = ["TensorWrapper","external","eye_like",+ "hf_url",+ "load_state_dict_from_url","vec_like",]diff --git a/kornia/core/download.py b/kornia/core/download.pynew file mode 100644index 000000000..0d3ff1645--- /dev/null+++ b/kornia/core/download.py@@ -0,0 +1,106 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++import warnings+from pathlib import Path+from typing import Any+from urllib.parse import urlparse++import torch++_HF_KORNIA_BASE = "https://huggingface.co/kornia"+++def hf_url(repo: str, filename: str) -> str:+ """Return the HuggingFace URL for a file in a kornia model repo.++ Args:+ repo: repository name under the ``kornia`` HF org (e.g. ``"hardnet"``).+ filename: file at the root of that repo (e.g. ``"HardNetPP.pth"``).++ Returns:+ A ``resolve/main`` URL that can be passed directly to+ :func:`load_state_dict_from_url`.++ Example:+ >>> hf_url("hardnet", "HardNetPP.pth")+ 'https://huggingface.co/kornia/hardnet/resolve/main/HardNetPP.pth'+ """+ return f"{_HF_KORNIA_BASE}/{repo}/resolve/main/{filename}"+++def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Any]:+ """Load a state dict from a URL, trying fallback URLs on failure.++ Drop-in replacement for :func:`torch.hub.load_state_dict_from_url` that+ accepts either a single URL string or an ordered list of URLs. Each URL is+ tried in turn; a :mod:`warnings` message is emitted for every failed+ attempt before the next source is tried.++ When multiple URLs are given and ``file_name`` is not already in *kwargs*,+ the basename of the **first** URL is used as the local cache filename for+ all attempts. This guarantees that:++ * a file successfully downloaded from the primary source is found on the+ next call without re-downloading;+ * hash validation (``check_hash=True``) uses the filename β and therefore+ the hash embedded in it β of the primary URL consistently across all+ fallback attempts.++ Args:+ url: a URL string, or a list of URL strings tried left-to-right.+ **kwargs: forwarded verbatim to+ :func:`torch.hub.load_state_dict_from_url`+ (``map_location``, ``check_hash``, ``file_name``, β¦).++ Returns:+ The loaded state dict.++ Raises:+ RuntimeError: if every URL fails, chaining the last exception.++ Example:+ >>> sd = load_state_dict_from_url([ # doctest: +SKIP+ ... hf_url("hardnet", "HardNetPP.pth"), # primary (HF mirror)+ ... "https://github.com/DagnyT/hardnet/raw/master/"+ ... "pretrained/pretrained_all_datasets/HardNet%2B%2B.pth", # fallback+ ... ])+ """+ urls = [url] if isinstance(url, str) else list(url)++ # Pin the cache filename to the primary URL's basename so that all+ # attempts share one cache slot and hash validation stays consistent.+ if len(urls) > 1 and "file_name" not in kwargs:+ kwargs["file_name"] = Path(urlparse(urls[0]).path).name++ last_exc: Exception | None = None+ for i, u in enumerate(urls):+ try:+ return torch.hub.load_state_dict_from_url(u, **kwargs)+ except Exception as e: # noqa: BLE001+ last_exc = e+ if i < len(urls) - 1:+ warnings.warn(+ f"Failed to load weights from {u!r}: {e}. Trying next source.",+ stacklevel=2,+ )++ raise RuntimeError(+ f"Failed to load weights from all {len(urls)} source(s). Last URL tried: {urls[-1]!r}"+ ) from last_excdiff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex e60374954..d76d2c9cb 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -22,6 +22,7 @@ import torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.filters.kernels import get_gaussian_kernel2dfrom kornia.filters.sobel import SpatialGradient@@ -35,8 +36,11 @@ from .laf import (set_laf_orientation,)-urls: Dict[str, str] = {}-urls["affnet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/AffNet.pth"+urls: Dict[str, str | list[str]] = {}+urls["affnet"] = [+ hf_url("affnet", "AffNet.pth"),+ "https://github.com/ducha-aiki/affnet/raw/master/pretrained/AffNet.pth",+]class PatchAffineShapeEstimator(nn.Module):@@ -202,7 +206,7 @@ class LAFAffNetShapeEstimator(nn.Module):self.patch_size = 32# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["affnet"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["affnet"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"], strict=False)self.preserve_orientation = preserve_orientationself.eval()diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex a72b10ecb..cd3d26e7f 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -64,6 +64,7 @@ from torch import nnfrom torch.nn.modules.utils import _pairfrom kornia.color import grayscale_to_rgb+from kornia.core.download import load_state_dict_from_urlfrom kornia.geometry.subpix import nms2dfrom .deform_conv2d import deform_conv2d@@ -739,7 +740,10 @@ _ALIKED_CFGS: dict[str, tuple[int, int, int, int, int, int, int]] = {"aliked-n32": (16, 32, 64, 128, 128, 3, 32),}-_CHECKPOINT_URL = "https://github.com/Shiaoming/ALIKED/raw/main/models/{}.pth"+_CHECKPOINT_URLS = [+ "https://huggingface.co/kornia/aliked/resolve/main/{}.pth",+ "https://github.com/Shiaoming/ALIKED/raw/main/models/{}.pth",+]class ALIKED(nn.Module):@@ -1028,8 +1032,8 @@ class ALIKED(nn.Module):detection_threshold=detection_threshold,nms_radius=nms_radius,).to(device)- url = _CHECKPOINT_URL.format(model_name)- state_dict = torch.hub.load_state_dict_from_url(url, map_location=device)+ urls = [t.format(model_name) for t in _CHECKPOINT_URLS]+ state_dict = load_state_dict_from_url(urls, map_location=device)model.load_state_dict(state_dict, strict=False)model.eval()return modeldiff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.pyindex b05e8e3cc..45437f433 100644--- a/kornia/feature/dedode/dedode.py+++ b/kornia/feature/dedode/dedode.py@@ -22,6 +22,7 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.enhance.normalize import Normalizefrom .dedode_models import DeDoDeDescriptor, DeDoDeDetector, get_descriptor, get_detector@@ -29,18 +30,48 @@ from .utils import dedode_denormalize_pixel_coordinates, sample_keypointsurls: Dict[str, Dict[str, str]] = {"detector": {- "L-upright": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_detector_L.pth",- "L-C4": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/dedode_detector_C4.pth",- "L-SO2": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/dedode_detector_SO2.pth",- "L-C4-v2": "https://github.com/Parskatt/DeDoDe/releases/download/v2/dedode_detector_L_v2.pth",+ "L-upright": [+ hf_url("dedode", "dedode_detector_L.pth"),+ "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_detector_L.pth",+ ],+ "L-C4": [+ hf_url("dedode", "dedode_detector_C4.pth"),+ "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/dedode_detector_C4.pth",+ ],+ "L-SO2": [+ hf_url("dedode", "dedode_detector_SO2.pth"),+ "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/dedode_detector_SO2.pth",+ ],+ "L-C4-v2": [+ hf_url("dedode", "dedode_detector_L_v2.pth"),+ "https://github.com/Parskatt/DeDoDe/releases/download/v2/dedode_detector_L_v2.pth",+ ],},"descriptor": {- "B-upright": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_B.pth",- "B-C4": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/B_C4_Perm_descriptor_setting_C.pth",- "B-SO2": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/B_SO2_Spread_descriptor_setting_C.pth",- "G-upright": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_G.pth",- "G-C4": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/G_C4_Perm_descriptor_setting_C.pth",- "G-SO2": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/G_SO2_Spread_descriptor_setting_C.pth",+ "B-upright": [+ hf_url("dedode", "dedode_descriptor_B.pth"),+ "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_B.pth",+ ],+ "B-C4": [+ hf_url("dedode", "B_C4_Perm_descriptor_setting_C.pth"),+ "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/B_C4_Perm_descriptor_setting_C.pth",+ ],+ "B-SO2": [+ hf_url("dedode", "B_SO2_Spread_descriptor_setting_C.pth"),+ "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/B_SO2_Spread_descriptor_setting_C.pth",+ ],+ "G-upright": [+ hf_url("dedode", "dedode_descriptor_G.pth"),+ "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_G.pth",+ ],+ "G-C4": [+ hf_url("dedode", "G_C4_Perm_descriptor_setting_C.pth"),+ "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/G_C4_Perm_descriptor_setting_C.pth",+ ],+ "G-SO2": [+ hf_url("dedode", "G_SO2_Spread_descriptor_setting_C.pth"),+ "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/G_SO2_Spread_descriptor_setting_C.pth",+ ],},}@@ -255,10 +286,10 @@ class DeDoDe(nn.Module):amp_dtype=amp_dtype,)model.detector.load_state_dict(- torch.hub.load_state_dict_from_url(urls["detector"][detector_weights], map_location=torch.device("cpu"))+ load_state_dict_from_url(urls["detector"][detector_weights], map_location=torch.device("cpu")))model.descriptor.load_state_dict(- torch.hub.load_state_dict_from_url(urls["descriptor"][descriptor_weights], map_location=torch.device("cpu"))+ load_state_dict_from_url(urls["descriptor"][descriptor_weights], map_location=torch.device("cpu")))model.eval()return modeldiff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.pyindex a39768d26..e142512a4 100644--- a/kornia/feature/dedode/encoder.py+++ b/kornia/feature/dedode/encoder.py@@ -20,6 +20,8 @@ from typing import Any, Optional, Tupleimport torchfrom torch import nn+from kornia.core.download import load_state_dict_from_url+from .vgg import vgg19_bn@@ -74,7 +76,7 @@ class FrozenDINOv2(nn.Module):def __init__(self, amp: bool = True, amp_dtype: torch.dtype = torch.float16, dinov2_weights: Optional[Any] = None):super().__init__()if dinov2_weights is None:- dinov2_weights = torch.hub.load_state_dict_from_url(+ dinov2_weights = load_state_dict_from_url("https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth", map_location="cpu")from .transformer import vit_largediff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.pyindex 88edf559e..dc90d815c 100644--- a/kornia/feature/defmo.py+++ b/kornia/feature/defmo.py@@ -20,9 +20,17 @@ from typing import Callable, Dict, List, Optional, Typeimport torchfrom torch import nn-urls: Dict[str, str] = {}-urls["defmo_encoder"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/encoder_best.pt"-urls["defmo_rendering"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/rendering_best.pt"+from kornia.core.download import hf_url, load_state_dict_from_url++urls: Dict[str, str | list[str]] = {}+urls["defmo_encoder"] = [+ hf_url("defmo", "encoder_best.pt"),+ "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/encoder_best.pt",+]+urls["defmo_rendering"] = [+ hf_url("defmo", "rendering_best.pt"),+ "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/rendering_best.pt",+]# conv1x1, conv3x3, Bottleneck, ResNet are taken from:@@ -392,13 +400,9 @@ class DeFMO(nn.Module):# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(- urls["defmo_encoder"], map_location=torch.device("cpu")- )+ pretrained_dict = load_state_dict_from_url(urls["defmo_encoder"], map_location=torch.device("cpu"))self.encoder.load_state_dict(pretrained_dict, strict=True)- pretrained_dict_ren = torch.hub.load_state_dict_from_url(- urls["defmo_rendering"], map_location=torch.device("cpu")- )+ pretrained_dict_ren = load_state_dict_from_url(urls["defmo_rendering"], map_location=torch.device("cpu"))self.rendering.load_state_dict(pretrained_dict_ren, strict=True)self.eval()diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.pyindex 06da385a8..82e5cf24e 100644--- a/kornia/feature/disk/disk.py+++ b/kornia/feature/disk/disk.py@@ -21,6 +21,8 @@ import torchimport torch.nn.functional as Ffrom torch import nn+from kornia.core.download import hf_url, load_state_dict_from_url+from ._unets import Unetfrom .detector import heatmap_to_keypointsfrom .structs import DISKFeatures@@ -143,8 +145,14 @@ class DISK(nn.Module):"""urls = {- "depth": "https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth",- "epipolar": "https://raw.githubusercontent.com/cvlab-epfl/disk/master/epipolar-save.pth",+ "depth": [+ hf_url("disk", "depth-save.pth"),+ "https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth",+ ],+ "epipolar": [+ hf_url("disk", "epipolar-save.pth"),+ "https://raw.githubusercontent.com/cvlab-epfl/disk/master/epipolar-save.pth",+ ],}if checkpoint not in urls:@@ -152,7 +160,7 @@ class DISK(nn.Module):if device is None:device = torch.device("cpu")- pretrained_dict = torch.hub.load_state_dict_from_url(urls[checkpoint], map_location=device)+ pretrained_dict = load_state_dict_from_url(urls[checkpoint], map_location=device)model: DISK = cls().to(device)model.load_state_dict(pretrained_dict["extractor"])diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex ca36c6e44..24b41e203 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -22,14 +22,22 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.core.utils import is_mps_tensor_safe-urls: Dict[str, str] = {}-urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"-urls["liberty_aug"] = (- "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth"-)-urls["hardnet8v2"] = "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt"+urls: Dict[str, str | list[str]] = {}+urls["hardnet++"] = [+ hf_url("hardnet", "HardNetPP.pth"),+ "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth",+]+urls["liberty_aug"] = [+ hf_url("hardnet", "checkpoint_liberty_with_aug.pth"),+ "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth",+]+urls["hardnet8v2"] = [+ hf_url("hardnet", "hardnet8v2.pt"),+ "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt",+]class HardNet(nn.Module):@@ -85,7 +93,7 @@ class HardNet(nn.Module):# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["liberty_aug"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["liberty_aug"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"], strict=True)self.eval()@@ -177,7 +185,7 @@ class HardNet8(nn.Module):# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["hardnet8v2"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["hardnet8v2"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)self.eval()diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.pyindex b5ee2ab8b..dc99c6c3b 100644--- a/kornia/feature/hynet.py+++ b/kornia/feature/hynet.py@@ -20,10 +20,21 @@ from typing import Dictimport torchfrom torch import nn-urls: Dict[str, str] = {}-urls["liberty"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_LIB.pth" # pylint: disable-urls["notredame"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_ND.pth" # pylint: disable-urls["yosemite"] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_YOS.pth" # pylint: disable+from kornia.core.download import hf_url, load_state_dict_from_url++urls: Dict[str, str | list[str]] = {}+urls["liberty"] = [+ hf_url("hynet", "HyNet_LIB.pth"),+ "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_LIB.pth",+] # pylint: disable+urls["notredame"] = [+ hf_url("hynet", "HyNet_ND.pth"),+ "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_ND.pth",+] # pylint: disable+urls["yosemite"] = [+ hf_url("hynet", "HyNet_YOS.pth"),+ "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_YOS.pth",+] # pylint: disableclass FilterResponseNorm2d(nn.Module):@@ -272,7 +283,7 @@ class HyNet(nn.Module):self.desc_norm = nn.LocalResponseNorm(2 * self.dim_desc, 2.0 * self.dim_desc, 0.5, 0.0)# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["liberty"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["liberty"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)self.eval()diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.pyindex 5a4f5c7a5..61b82881e 100644--- a/kornia/feature/keynet.py+++ b/kornia/feature/keynet.py@@ -22,6 +22,7 @@ import torch.nn.functional as Ffrom torch import nnfrom typing_extensions import TypedDict+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.filters import SpatialGradientfrom kornia.geometry.transform import pyrdown@@ -51,7 +52,10 @@ keynet_default_config: KeyNet_conf = {"Detector_conf": get_default_detector_config(),}-KeyNet_URL = "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth"+KeyNet_URL = [+ hf_url("keynet", "keynet_pytorch.pth"),+ "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth",+]class _FeatureExtractor(nn.Module):@@ -172,7 +176,7 @@ class KeyNet(nn.Module):)# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(KeyNet_URL, map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(KeyNet_URL, map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"], strict=True)self.eval()diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex bb8e7aef7..35f941076 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -26,6 +26,7 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.feature.laf import laf_to_three_points, scale_laftry:@@ -612,20 +613,35 @@ class LightGlue(nn.Module):if features == "dog_affnet_hardnet":features = "doghardnet" # new dog model is better for affnet as wellif features in ["keynet_affnet_hardnet"]:- fname = "keynet_affnet_hardnet_lightlue.pth"- url = "http://cmp.felk.cvut.cz/~mishkdmy/models/keynet_affnet_hardnet_lightlue.pth"+ fname = "keynet_affnet_hardnet_lightglue.pth"+ url = [+ hf_url("lightglue", "keynet_affnet_hardnet_lightglue.pth"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/keynet_affnet_hardnet_lightlue.pth",+ ]elif features in ["dedodeb"]:fname = "dedodeb_lightglue.pth"- url = "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeb_lightglue.pth"+ url = [+ hf_url("lightglue", "dedodeb_lightglue.pth"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeb_lightglue.pth",+ ]elif features in ["dedodeg"]:fname = "dedodeg_lightglue.pth"- url = "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeg_lightglue.pth"+ url = [+ hf_url("lightglue", "dedodeg_lightglue.pth"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeg_lightglue.pth",+ ]elif features == "xfeat":fname = "xfeat-lighterglue.pt"- url = "https://github.com/verlab/accelerated_features/raw/main/weights/xfeat-lighterglue.pt"+ url = [+ hf_url("lightglue", "xfeat-lighterglue.pt"),+ "https://github.com/verlab/accelerated_features/raw/main/weights/xfeat-lighterglue.pt",+ ]else:- url = self.url.format(self.version, features.replace("-", "_"))- state_dict = torch.hub.load_state_dict_from_url(url, file_name=fname)+ url = [+ hf_url("lightglue", f"{features.replace('-', '_')}_lightglue.pth"),+ self.url.format(self.version, features.replace("-", "_")),+ ]+ state_dict = load_state_dict_from_url(url, file_name=fname)elif conf.weights is not None:path = Path(__file__).parentpath = path / f"weights/{self.conf.weights}.pth"diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.pyindex 0718ffdcc..e4d175f1c 100644--- a/kornia/feature/loftr/loftr.py+++ b/kornia/feature/loftr/loftr.py@@ -22,6 +22,7 @@ from typing import Any, Optionalimport torchfrom torch import nn+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.geometry import resizefrom .backbone import build_backbone@@ -30,10 +31,19 @@ from .utils.coarse_matching import CoarseMatchingfrom .utils.fine_matching import FineMatchingfrom .utils.position_encoding import PositionEncodingSine-urls: dict[str, str] = {}-urls["outdoor"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_outdoor.ckpt"-urls["indoor_new"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor_ds_new.ckpt"-urls["indoor"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt"+urls: dict[str, str | list[str]] = {}+urls["outdoor"] = [+ hf_url("loftr", "loftr_outdoor.ckpt"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_outdoor.ckpt",+]+urls["indoor_new"] = [+ hf_url("loftr", "loftr_indoor_ds_new.ckpt"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor_ds_new.ckpt",+]+urls["indoor"] = [+ hf_url("loftr", "loftr_indoor.ckpt"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt",+]# Comments: the config below is the one corresponding to the pretrained models# Some do not change there anything, unless you want to retrain it.@@ -114,7 +124,7 @@ class LoFTR(nn.Module):if pretrained not in urls.keys():raise ValueError(f"pretrained should be None or one of {urls.keys()}")- pretrained_dict = torch.hub.load_state_dict_from_url(urls[pretrained], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls[pretrained], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"])self.eval()diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.pyindex e86d5d81b..82be3e17b 100644--- a/kornia/feature/mkd.py+++ b/kornia/feature/mkd.py@@ -22,6 +22,7 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.constants import pi+from kornia.core.download import load_state_dict_from_urlfrom kornia.filters import GaussianBlur2d, SpatialGradientfrom kornia.geometry.conversions import cart2polfrom kornia.geometry.grid import create_meshgrid@@ -608,9 +609,7 @@ class MKDDescriptor(nn.Module):# Load supervised(lw)/unsupervised(pca) model trained on training_set.if self.whitening is not None:- whitening_models = torch.hub.load_state_dict_from_url(- urls[self.kernel_type], map_location=torch.device("cpu")- )+ whitening_models = load_state_dict_from_url(urls[self.kernel_type], map_location=torch.device("cpu"))whitening_model = whitening_models[training_set]self.whitening_layer = Whitening(whitening, whitening_model, in_dims=self.odims, output_dims=self.output_dims@@ -668,7 +667,7 @@ class MKDDescriptor(nn.Module):def load_whitening_model(kernel_type: str, training_set: str) -> Dict[str, Any]:"""Load whitening model."""- whitening_models = torch.hub.load_state_dict_from_url(urls[kernel_type], map_location=torch.device("cpu"))+ whitening_models = load_state_dict_from_url(urls[kernel_type], map_location=torch.device("cpu"))whitening_model = whitening_models[training_set]return whitening_modeldiff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex 18af248c3..3c7f93185 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -23,13 +23,17 @@ from torch import nnfrom kornia.constants import pifrom kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.filters import SpatialGradient, get_gaussian_discrete_kernel1d, get_gaussian_kernel2dfrom kornia.geometry import rad2degfrom .laf import extract_patches_from_pyramid, get_laf_orientation, set_laf_orientation-urls: Dict[str, str] = {}-urls["orinet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/OriNet.pth"+urls: Dict[str, str | list[str]] = {}+urls["orinet"] = [+ hf_url("orinet", "OriNet.pth"),+ "https://github.com/ducha-aiki/affnet/raw/master/pretrained/OriNet.pth",+]class PassLAF(nn.Module):@@ -184,7 +188,7 @@ class OriNet(nn.Module):self.eps = eps# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["orinet"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["orinet"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict["state_dict"], strict=False)self.eval()diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.pyindex 352fe8d8f..6a7392334 100644--- a/kornia/feature/sold2/sold2.py+++ b/kornia/feature/sold2/sold2.py@@ -22,6 +22,7 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.core.utils import dataclass_to_dict, dict_to_dataclassfrom kornia.feature.sold2.structures import DetectorCfg, LineMatcherCfgfrom kornia.geometry.conversions import normalize_pixel_coordinates@@ -29,8 +30,11 @@ from kornia.geometry.conversions import normalize_pixel_coordinatesfrom .backbones import SOLD2Netfrom .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions-urls: Dict[str, str] = {}-urls["wireframe"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth"+urls: Dict[str, str | list[str]] = {}+urls["wireframe"] = [+ hf_url("sold2", "sold2_wireframe.pth"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth",+]class SOLD2(nn.Module):@@ -74,7 +78,7 @@ class SOLD2(nn.Module):# Load the pre-trained modelself.model = SOLD2Net(dataclass_to_dict(self.config))if pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["wireframe"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["wireframe"], map_location=torch.device("cpu"))state_dict = self.adapt_state_dict(pretrained_dict["model_state_dict"])self.model.load_state_dict(state_dict)self.eval()diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.pyindex b2797cbd1..459130e51 100644--- a/kornia/feature/sold2/sold2_detector.py+++ b/kornia/feature/sold2/sold2_detector.py@@ -23,6 +23,7 @@ import torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.download import load_state_dict_from_urlfrom kornia.core.utils import dataclass_to_dict, dict_to_dataclassfrom kornia.feature.sold2.structures import DetectorCfg, HeatMapRefineCfg, JunctionRefineCfg, LineDetectorCfgfrom kornia.geometry.bbox import nms@@ -76,7 +77,7 @@ class SOLD2_detector(nn.Module):self.model = SOLD2Net(dataclass_to_dict(self.config))if pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["wireframe"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["wireframe"], map_location=torch.device("cpu"))state_dict = self.adapt_state_dict(pretrained_dict["model_state_dict"])self.model.load_state_dict(state_dict)self.eval()diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pyindex c6bb9d053..d390f9abe 100644--- a/kornia/feature/sosnet.py+++ b/kornia/feature/sosnet.py@@ -21,10 +21,17 @@ import torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.download import hf_url, load_state_dict_from_url-urls: Dict[str, str] = {}-urls["lib"] = "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/sosnet_32x32_liberty.pth"-urls["hp_a"] = "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/sosnet_32x32_hpatches_a.pth"+urls: Dict[str, str | list[str]] = {}+urls["lib"] = [+ hf_url("sosnet", "sosnet_32x32_liberty.pth"),+ "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/sosnet_32x32_liberty.pth",+]+urls["hp_a"] = [+ hf_url("sosnet", "sosnet_32x32_hpatches_a.pth"),+ "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/sosnet_32x32_hpatches_a.pth",+]class SOSNet(nn.Module):@@ -78,7 +85,7 @@ class SOSNet(nn.Module):self.desc_norm = nn.Sequential(nn.LocalResponseNorm(256, alpha=256.0, beta=0.5, k=0.0))# load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["lib"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["lib"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)self.eval()diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.pyindex 31fc77edf..c4aa0f418 100644--- a/kornia/feature/tfeat.py+++ b/kornia/feature/tfeat.py@@ -21,11 +21,21 @@ import torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK_SHAPE--urls: Dict[str, str] = {}-urls["liberty"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params" # pylint: disable-urls["notredame"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-notredame.params" # pylint: disable-urls["yosemite"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-yosemite.params" # pylint: disable+from kornia.core.download import hf_url, load_state_dict_from_url++urls: Dict[str, str | list[str]] = {}+urls["liberty"] = [+ hf_url("tfeat", "tfeat-liberty.params"),+ "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params",+] # pylint: disable+urls["notredame"] = [+ hf_url("tfeat", "tfeat-notredame.params"),+ "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-notredame.params",+] # pylint: disable+urls["yosemite"] = [+ hf_url("tfeat", "tfeat-yosemite.params"),+ "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-yosemite.params",+] # pylint: disableclass TFeat(nn.Module):@@ -67,7 +77,7 @@ class TFeat(nn.Module):self.descr = nn.Sequential(nn.Linear(64 * 8 * 8, 128), nn.Tanh())# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(urls["liberty"], map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(urls["liberty"], map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)self.eval()diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.pyindex 29d48864b..45262942d 100644--- a/kornia/filters/dexined.py+++ b/kornia/filters/dexined.py@@ -27,8 +27,12 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK+from kornia.core.download import hf_url, load_state_dict_from_url-url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"+url: str | list[str] = [+ hf_url("dexined", "DexiNed_BIPED_10.pth"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",+]def weight_init(m: nn.Module) -> None:@@ -352,19 +356,20 @@ class DexiNed(nn.Module):else:self.apply(weight_init)- def load_from_file(self, path_file: str) -> None:+ def load_from_file(self, path_file: str | list[str]) -> None:"""Load pretrained DexiNed weights and switch the module to eval mode.- The checkpoint is loaded on CPU through ``torch.hub`` and then applied- with strict key matching. After loading, ``eval()`` is called so layers- such as batch normalization use inference behavior.+ The checkpoint is loaded on CPU and then applied with strict key+ matching. After loading, ``eval()`` is called so layers such as batch+ normalization use inference behavior.Args:path_file: URL or local checkpoint identifier accepted by- :func:`torch.hub.load_state_dict_from_url`.+ :func:`kornia.core.download.load_state_dict_from_url`, or a+ list of candidate URLs tried in order (HF-first fallback)."""# use torch.hub to load pretrained model- pretrained_dict = torch.hub.load_state_dict_from_url(path_file, map_location=torch.device("cpu"))+ 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/base.py b/kornia/models/base.pyindex 21a9852b1..7b84a8e0a 100644--- a/kornia/models/base.py+++ b/kornia/models/base.py@@ -26,6 +26,7 @@ from typing import Any, Generic, List, Optional, TypeVar, Union, castimport torchfrom torch import nn+from kornia.core.download import load_state_dict_from_urlfrom kornia.core.external import PILImage as Imagefrom kornia.image.utils import tensor_to_imagefrom kornia.io import write_image@@ -113,7 +114,7 @@ class ModelBaseMixin:class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):"""Abstract model class with some utilities function."""- def load_checkpoint(self, checkpoint: str, device: Optional[torch.device] = None) -> None:+ def load_checkpoint(self, checkpoint: str | list[str], device: Optional[torch.device] = None) -> None:"""Load checkpoint from a given url or file.Args:@@ -121,11 +122,11 @@ class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):device: The desired device to load the weights and move the model"""- if os.path.isfile(checkpoint):+ if isinstance(checkpoint, str) and os.path.isfile(checkpoint):with open(checkpoint, "rb") as f:state_dict = torch.load(f, map_location=device)else:- state_dict = torch.hub.load_state_dict_from_url(checkpoint, map_location=device)+ state_dict = load_state_dict_from_url(checkpoint, map_location=device)self.load_state_dict(state_dict)diff --git a/kornia/models/dexined.py b/kornia/models/dexined.pyindex d3116ddee..164d6eff3 100644--- a/kornia/models/dexined.py+++ b/kornia/models/dexined.py@@ -27,11 +27,15 @@ import torch.nn.functional as Ffrom torch import nnfrom kornia.core.check import KORNIA_CHECK+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.core.mixin.onnx import ONNXExportMixin__all__ = ["DexiNed"]-url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"+url: str | list[str] = [+ hf_url("dexined", "DexiNed_BIPED_10.pth"),+ "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",+]def weight_init(m: nn.Module) -> None:@@ -241,15 +245,16 @@ class DexiNed(ONNXExportMixin, nn.Module):else:self.apply(weight_init)- def load_from_file(self, path_file: str) -> None:+ def load_from_file(self, path_file: str | list[str]) -> None:"""Load pretrained DexiNed weights and switch the module to evaluation mode.Args:path_file: URL or local checkpoint path accepted by- :func:`torch.hub.load_state_dict_from_url`.+ :func:`kornia.core.download.load_state_dict_from_url`, or a list+ of candidate URLs tried in order (HF-first fallback)."""# use torch.hub to load pretrained model- pretrained_dict = torch.hub.load_state_dict_from_url(path_file, map_location=torch.device("cpu"))+ 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/efficient_vit/model.py b/kornia/models/efficient_vit/model.pyindex d1c4cf08f..48cc4c075 100644--- a/kornia/models/efficient_vit/model.py+++ b/kornia/models/efficient_vit/model.py@@ -22,6 +22,7 @@ from typing import Literalimport torch+from kornia.core.download import load_state_dict_from_urlfrom kornia.models.base import ModelBasefrom kornia.models.efficient_vit import backbone as vit@@ -79,7 +80,7 @@ class EfficientViT(ModelBase[EfficientViTConfig]):"""# load the model from the checkpointtry:- model_file = torch.hub.load_state_dict_from_url(config.checkpoint, map_location="cpu")+ model_file = load_state_dict_from_url(config.checkpoint, map_location="cpu")model_file = model_file["state_dict"] if "state_dict" in model_file else model_fileexcept RuntimeError:raise RuntimeError(f"Unable to load the model from {config.checkpoint}.") from Nonediff --git a/kornia/models/rt_detr/model.py b/kornia/models/rt_detr/model.pyindex 8d5244cf8..d1c0b6b65 100644--- a/kornia/models/rt_detr/model.py+++ b/kornia/models/rt_detr/model.py@@ -26,6 +26,7 @@ from typing import Any, Optionalimport torch+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.core.mixin.onnx import ONNXExportMixinfrom kornia.models.base import ModelBasefrom kornia.models.rt_detr.architecture.hgnetv2 import PPHGNetV2@@ -34,11 +35,26 @@ from kornia.models.rt_detr.architecture.resnet_d import ResNetDfrom kornia.models.rt_detr.architecture.rtdetr_head import RTDETRHeadURLs = {- "rtdetr_r18vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r18vd_dec3_6x_coco_from_paddle.pth",- "rtdetr_r34vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r34vd_dec4_6x_coco_from_paddle.pth",- "rtdetr_r50vd_m": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r50vd_m_6x_coco_from_paddle.pth",- "rtdetr_r50vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r50vd_6x_coco_from_paddle.pth",- "rtdetr_r101vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r101vd_6x_coco_from_paddle.pth",+ "rtdetr_r18vd": [+ hf_url("rt_detr", "rtdetr_r18vd_dec3_6x_coco_from_paddle.pth"),+ "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r18vd_dec3_6x_coco_from_paddle.pth",+ ],+ "rtdetr_r34vd": [+ hf_url("rt_detr", "rtdetr_r34vd_dec4_6x_coco_from_paddle.pth"),+ "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r34vd_dec4_6x_coco_from_paddle.pth",+ ],+ "rtdetr_r50vd_m": [+ hf_url("rt_detr", "rtdetr_r50vd_m_6x_coco_from_paddle.pth"),+ "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r50vd_m_6x_coco_from_paddle.pth",+ ],+ "rtdetr_r50vd": [+ hf_url("rt_detr", "rtdetr_r50vd_6x_coco_from_paddle.pth"),+ "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r50vd_6x_coco_from_paddle.pth",+ ],+ "rtdetr_r101vd": [+ hf_url("rt_detr", "rtdetr_r101vd_6x_coco_from_paddle.pth"),+ "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r101vd_6x_coco_from_paddle.pth",+ ],}@@ -231,7 +247,7 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):if model_name not in URLs:raise ValueError(f"No pretrained model for '{model_name}'. Please select from {list(URLs.keys())}.")- state_dict = torch.hub.load_state_dict_from_url(+ state_dict = load_state_dict_from_url(URLs[model_name], map_location="cuda:0" if torch.cuda.is_available() else "cpu")diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.pyindex c7d31a466..ba853938b 100644--- a/kornia/models/sam/model.py+++ b/kornia/models/sam/model.py@@ -34,6 +34,7 @@ from typing import Any, Optionalimport torchfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE+from kornia.core.download import hf_urlfrom kornia.core.mixin.onnx import ONNXExportMixinfrom kornia.models.base import ModelBasefrom kornia.models.sam.architecture.common import LayerNorm@@ -228,7 +229,10 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):SamModelType.vit_b: "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth",SamModelType.vit_l: "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth",SamModelType.vit_h: "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth",- SamModelType.mobile_sam: "https://github.com/ChaoningZhang/MobileSAM/raw/a509aac54fdd7af59f843135f2f7cee307283c88/weights/mobile_sam.pt",+ SamModelType.mobile_sam: [+ hf_url("mobile_sam", "mobile_sam.pt"),+ "https://github.com/ChaoningZhang/MobileSAM/raw/a509aac54fdd7af59f843135f2f7cee307283c88/weights/mobile_sam.pt",+ ],}[model_type]else:warnings.warn("checkpoint is not None. pretrained=True is ignored", stacklevel=1)diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.pyindex aa12ba3ca..aef4a06ce 100644--- a/kornia/models/tiny_vit.py+++ b/kornia/models/tiny_vit.py@@ -29,6 +29,7 @@ from torch import nnfrom torch.utils import checkpointfrom kornia.core.check import KORNIA_CHECK+from kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.models.common import DropPath, LayerNorm2d, window_partition, window_unpartition@@ -657,9 +658,9 @@ class TinyViT(nn.Module):return {"5m": _tiny_vit_5m, "11m": _tiny_vit_11m, "21m": _tiny_vit_21m}[variant](pretrained, **kwargs)-def _load_pretrained(model: TinyViT, url: str) -> TinyViT:+def _load_pretrained(model: TinyViT, url: str | list[str]) -> TinyViT:model_state_dict = model.state_dict()- state_dict = torch.hub.load_state_dict_from_url(url)+ state_dict = load_state_dict_from_url(url)# official checkpoint has "model" keyif "model" in state_dict:@@ -705,10 +706,14 @@ def _tiny_vit_5m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:pretrained = "in1k"url = {- "in22k": (- "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22k_distill.pth"- ),- "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22kto1k_distill.pth",+ "in22k": [+ hf_url("tiny_vit", "tiny_vit_5m_22k_distill.pth"),+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22k_distill.pth",+ ],+ "in1k": [+ hf_url("tiny_vit", "tiny_vit_5m_22kto1k_distill.pth"),+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22kto1k_distill.pth",+ ],}[pretrained]model = _load_pretrained(model, url)@@ -730,10 +735,14 @@ def _tiny_vit_11m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:pretrained = "in1k"url = {- "in22k": (- "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22k_distill.pth"- ),- "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22kto1k_distill.pth",+ "in22k": [+ hf_url("tiny_vit", "tiny_vit_11m_22k_distill.pth"),+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22k_distill.pth",+ ],+ "in1k": [+ hf_url("tiny_vit", "tiny_vit_11m_22kto1k_distill.pth"),+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22kto1k_distill.pth",+ ],}[pretrained]model = _load_pretrained(model, url)@@ -760,12 +769,22 @@ def _tiny_vit_21m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:pretrained = "in1k_512"url = {- "in22k": (- "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22k_distill.pth"- ),- "in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_distill.pth",- "in1k_384": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_384_distill.pth",- "in1k_512": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_512_distill.pth",+ "in22k": [+ hf_url("tiny_vit", "tiny_vit_21m_22k_distill.pth"),+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22k_distill.pth",+ ],+ "in1k": [+ hf_url("tiny_vit", "tiny_vit_21m_22kto1k_distill.pth"),+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_distill.pth",+ ],+ "in1k_384": [+ hf_url("tiny_vit", "tiny_vit_21m_22kto1k_384_distill.pth"),+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_384_distill.pth",+ ],+ "in1k_512": [+ hf_url("tiny_vit", "tiny_vit_21m_22kto1k_512_distill.pth"),+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_512_distill.pth",+ ],}[pretrained]model = _load_pretrained(model, url)diff --git a/kornia/models/vit.py b/kornia/models/vit.pyindex f0b7cf14c..c31d325bf 100644--- a/kornia/models/vit.py+++ b/kornia/models/vit.py@@ -32,6 +32,7 @@ import torchfrom torch import nnfrom kornia.core.check import KORNIA_CHECK+from kornia.core.download import load_state_dict_from_url__all__ = ["VisionTransformer"]@@ -320,7 +321,7 @@ class VisionTransformer(nn.Module):if pretrained:url = _get_weight_url(variant)- state_dict = torch.hub.load_state_dict_from_url(url)+ state_dict = load_state_dict_from_url(url)model.load_state_dict(state_dict)return modeldiff --git a/kornia/models/yunet/model.py b/kornia/models/yunet/model.pyindex cd4f1b519..8c62d3acb 100644--- a/kornia/models/yunet/model.py+++ b/kornia/models/yunet/model.py@@ -16,15 +16,20 @@## based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa-from typing import Dict+from typing import Dict, List, Unionimport torchimport torch.nn.functional as Ffrom torch import nn+from kornia.core.download import hf_url, load_state_dict_from_url+__all__ = ["YuNet"]-url: str = "https://github.com/kornia/data/raw/main/yunet_final.pth"+url: Union[str, List[str]] = [+ hf_url("yunet", "yunet_final.pth"),+ "https://github.com/kornia/data/raw/main/yunet_final.pth",+]class ConvDPUnit(nn.Sequential):@@ -104,7 +109,7 @@ class YuNet(nn.Module):# use torch.hub to load pretrained modelif pretrained:- pretrained_dict = torch.hub.load_state_dict_from_url(url, map_location=torch.device("cpu"))+ pretrained_dict = load_state_dict_from_url(url, 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.pynew file mode 100644index 000000000..258e097d6--- /dev/null+++ b/tests/core/test_download.py@@ -0,0 +1,117 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++import warnings+from unittest.mock import call, patch++import pytest++from kornia.core.download import hf_url, load_state_dict_from_url+++class TestHfUrl:+ def test_format(self) -> None:+ assert hf_url("hardnet", "HardNetPP.pth") == (+ "https://huggingface.co/kornia/hardnet/resolve/main/HardNetPP.pth"+ )++ def test_subdirectory(self) -> None:+ url = hf_url("loftr", "loftr_outdoor.ckpt")+ assert url.startswith("https://huggingface.co/kornia/loftr/resolve/main/")+++class TestLoadStateDictFromUrl:+ _SD = {"weight": 1}+ _MOCK_TARGET = "kornia.core.download.torch.hub.load_state_dict_from_url"++ def test_single_url_success(self) -> None:+ with patch(self._MOCK_TARGET, return_value=self._SD) as mock:+ result = load_state_dict_from_url("http://example.com/model.pth")+ assert result == self._SD+ mock.assert_called_once_with("http://example.com/model.pth")++ def test_list_single_url_success(self) -> None:+ # A single-element list behaves like a plain str β no file_name injection+ with patch(self._MOCK_TARGET, return_value=self._SD) as mock:+ result = load_state_dict_from_url(["http://example.com/model.pth"])+ assert result == self._SD+ mock.assert_called_once_with("http://example.com/model.pth")++ def test_fallback_on_failure(self) -> None:+ primary = "http://primary.example.com/model.pth"+ fallback = "http://fallback.example.com/model.pth"++ def side_effect(url: str, **kwargs: object) -> dict:+ if url == primary:+ raise OSError("primary down")+ return self._SD++ with patch(self._MOCK_TARGET, side_effect=side_effect) as mock:+ with warnings.catch_warnings(record=True) as w:+ warnings.simplefilter("always")+ result = load_state_dict_from_url([primary, fallback])++ assert result == self._SD+ assert mock.call_count == 2+ assert any("primary down" in str(warning.message) for warning in w)++ def test_all_fail_raises_runtime_error(self) -> None:+ with patch(self._MOCK_TARGET, side_effect=OSError("down")):+ with pytest.raises(RuntimeError, match="Failed to load weights from all 2 source"):+ load_state_dict_from_url(["http://a.com/m.pth", "http://b.com/m.pth"])++ def test_file_name_pinned_to_primary(self) -> None:+ primary = "http://primary.example.com/weights-abc123.pth"+ fallback = "http://fallback.example.com/weights.pth"++ def side_effect(url: str, **kwargs: object) -> dict:+ if url == primary:+ raise OSError("primary down")+ return self._SD++ with patch(self._MOCK_TARGET, side_effect=side_effect) as mock:+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url([primary, fallback])++ # fallback call must carry the primary's filename, not the fallback's+ fallback_call = mock.call_args_list[1]+ assert fallback_call == call(fallback, file_name="weights-abc123.pth")++ def test_explicit_file_name_not_overridden(self) -> None:+ primary = "http://primary.example.com/model.pth"+ fallback = "http://fallback.example.com/model.pth"++ def side_effect(url: str, **kwargs: object) -> dict:+ if url == primary:+ raise OSError("primary down")+ return self._SD++ with patch(self._MOCK_TARGET, side_effect=side_effect) as mock:+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url([primary, fallback], file_name="custom.pth")++ for c in mock.call_args_list:+ assert c.kwargs.get("file_name") == "custom.pth"++ def test_kwargs_forwarded(self) -> None:+ with patch(self._MOCK_TARGET, return_value=self._SD) as mock:+ load_state_dict_from_url("http://example.com/model.pth", map_location="cpu")+ mock.assert_called_once_with("http://example.com/model.pth", map_location="cpu")