Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): load pretrained weights with weights_only=True and fetch fallbacks over https (#5225)

Dmytro Mishkin71e015388589
diff --git a/.github/download-models-weights.py b/.github/download-models-weights.py
index ea7a1ef89..f8f461342 100644
--- a/.github/download-models-weights.py
+++ b/.github/download-models-weights.py
@@ -41,6 +41,7 @@ import os
import torch
from kornia.core.download import load_state_dict_from_url
+from kornia.feature import DISKFeatures
logger = logging.getLogger(__name__)
@@ -115,11 +116,11 @@ MODELS: dict[str, "str | list[str]"] = {
# LoFTR: tests instantiate both the outdoor and indoor weights.
"loftr_outdoor.ckpt": [
"https://huggingface.co/kornia/loftr/resolve/main/loftr_outdoor.ckpt",
- "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_outdoor.ckpt",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/loftr_outdoor.ckpt",
],
"loftr_indoor.ckpt": [
"https://huggingface.co/kornia/loftr/resolve/main/loftr_indoor.ckpt",
- "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt",
],
# LightGlue pins its own cache names; these keys are not the URL basenames.
"superpoint_lightglue_v0-1_arxiv-pth": [
@@ -149,11 +150,11 @@ MODELS: dict[str, "str | list[str]"] = {
# -- line, edge and object models ---------------------------------------
"sold2_wireframe.pth": [
"https://huggingface.co/kornia/sold2/resolve/main/sold2_wireframe.pth",
- "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth",
],
"DexiNed_BIPED_10.pth": [
"https://huggingface.co/kornia/dexined/resolve/main/DexiNed_BIPED_10.pth",
- "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",
],
"yunet_final.pth": [
"https://huggingface.co/kornia/yunet/resolve/main/yunet_final.pth",
@@ -174,14 +175,8 @@ MODELS: dict[str, "str | list[str]"] = {
"xfeat.pt": "https://github.com/verlab/accelerated_features/raw/main/weights/xfeat.pt",
# -- deblurring ----------------------------------------------------------
# DeFMO(True): smoke and jit tests instantiate both halves.
- "encoder_best.pt": [
- "https://huggingface.co/kornia/defmo/resolve/main/encoder_best.pt",
- "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/encoder_best.pt",
- ],
- "rendering_best.pt": [
- "https://huggingface.co/kornia/defmo/resolve/main/rendering_best.pt",
- "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/rendering_best.pt",
- ],
+ "encoder_best.pt": "https://huggingface.co/kornia/defmo/resolve/main/encoder_best.pt",
+ "rendering_best.pt": "https://huggingface.co/kornia/defmo/resolve/main/rendering_best.pt",
}
@@ -217,7 +212,10 @@ if __name__ == "__main__":
# Don't pass model_dir - use the default from torch.hub.set_dir()
# This ensures files go to {hub_dir}/checkpoints/ matching test behavior.
# file_name is pinned so the entry lands where kornia will look for it.
- load_state_dict_from_url(url, map_location=torch.device("cpu"), file_name=file_name)
+ # ``knchurch_disk.pt`` (reference data for the ``data`` fixture) stores ``DISKFeatures``, which
+ # ``weights_only`` loading accepts only once it is allowlisted, as ``conftest.py`` does.
+ with torch.serialization.safe_globals([DISKFeatures]):
+ load_state_dict_from_url(url, map_location=torch.device("cpu"), file_name=file_name)
except Exception as e: # noqa: BLE001 - report every failure, not just the first
logger.error(f"Failed to download `{file_name}`: {type(e).__name__}: {e}")
failed.append(file_name)
diff --git a/changelog.d/5225.breaking.md b/changelog.d/5225.breaking.md
new file mode 100644
index 000000000..89f47a8cd
--- /dev/null
+++ b/changelog.d/5225.breaking.md
@@ -0,0 +1,20 @@
+`kornia.core.load_state_dict_from_url` now loads checkpoints with `weights_only=True` unless the caller passes
+`weights_only=False`, and so does every `pretrained=True` model built on it. The loaders that call `torch.load`
+directly pass `weights_only=True` as well: `ModelBase.load_checkpoint` for a local file, `SmallSRNet`,
+`RRDBNetBuilder` and LightGlue's local weights. Previously the wrapper forwarded the `weights_only=False` default of
+`torch.hub.load_state_dict_from_url` on every supported torch, and the direct calls used `torch.load`'s default, which
+is `False` before torch 2.6, so loading a checkpoint unpickled whatever objects it stored. Now only tensors, primitive
+types and plain containers load. A checkpoint holding any other type fails with `pickle.UnpicklingError`, which
+`load_state_dict_from_url` chains to its `RuntimeError`. To load such a file through any of these loaders, allowlist
+its types with `torch.serialization.safe_globals([...])` around the call. `load_state_dict_from_url` also accepts
+`weights_only=False`, which the other loaders do not; pass it only for a file you trust. All of kornia's pretrained
+checkpoints load under the new default, on torch 2.14 and 2.5.1, without an allowlist. On torch before 2.10,
+`weights_only=True` does not guarantee that a checkpoint runs no code: PyTorch's advisories
+[GHSA-53q9-r3pm-6pq6](https://github.com/pytorch/pytorch/security/advisories/GHSA-53q9-r3pm-6pq6) (before 2.6) and
+[GHSA-63cw-57p8-fm3p](https://github.com/pytorch/pytorch/security/advisories/GHSA-63cw-57p8-fm3p) (before 2.10)
+report checkpoints crafted to run code despite it. Load a checkpoint from a source you do not trust only on torch 2.10
+or later.
+
+The fallback download sources on `cmp.felk.cvut.cz` (HardNet8, LoFTR, SOLD2, DexiNed and three LightGlue heads) are
+now fetched over `https` instead of `http`. DeFMO's `http` fallback on `ptak.felk.cvut.cz` has no usable `https`
+equivalent and is removed, so DeFMO loads from its Hugging Face mirror only.
diff --git a/conftest.py b/conftest.py
index 2c73351b9..ed6dc2f7f 100644
--- a/conftest.py
+++ b/conftest.py
@@ -1048,4 +1048,7 @@ def data(request):
"""
if request.param not in TEST_DATA_URLS:
raise ValueError(f"Unknown test data: {request.param}. Available: {list(TEST_DATA_URLS.keys())}")
- return load_state_dict_from_url(TEST_DATA_URLS[request.param], map_location=torch.device("cpu"))
+ # ``disk_outdoor`` stores its reference outputs as ``DISKFeatures``, a type ``weights_only`` loading accepts
+ # only once it is allowlisted.
+ with torch.serialization.safe_globals([kornia.feature.DISKFeatures]):
+ return load_state_dict_from_url(TEST_DATA_URLS[request.param], map_location=torch.device("cpu"))
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index ad537aa2a..3692856cb 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -669,7 +669,11 @@ def main():
print(f"Generated image example for {fn_name}. {sig}")
# Image Matching and local features
- img_matching_data = torch.hub.load_state_dict_from_url(BASE_IMAGEOUTDOOR_URL7, map_location=torch.device("cpu"))
+ # The file also stores DISK reference outputs, which ``weights_only`` accepts once their type is allowlisted.
+ with torch.serialization.safe_globals([K.feature.DISKFeatures]):
+ img_matching_data = torch.hub.load_state_dict_from_url(
+ BASE_IMAGEOUTDOOR_URL7, map_location=torch.device("cpu"), weights_only=True
+ )
img_outdoor = img_matching_data["img2"]
print("Generating local feature detections ")
disk = K.feature.DISK.from_pretrained("depth")
diff --git a/docs/generate_model_examples.py b/docs/generate_model_examples.py
index df8c72752..1d17c74be 100644
--- a/docs/generate_model_examples.py
+++ b/docs/generate_model_examples.py
@@ -69,7 +69,9 @@ def sample(name: str, size: tuple[int, int] | None = None) -> torch.Tensor:
def knchurch() -> tuple[torch.Tensor, torch.Tensor]:
- d = torch.hub.load_state_dict_from_url(KNCHURCH, map_location="cpu")
+ # The file also stores DISK reference outputs, which ``weights_only`` accepts once their type is allowlisted.
+ with torch.serialization.safe_globals([K.feature.DISKFeatures]):
+ d = torch.hub.load_state_dict_from_url(KNCHURCH, map_location="cpu", weights_only=True)
return d["img1"], d["img2"]
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index 28db938dd..95aed6571 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -300,7 +300,8 @@ class RRDBNetBuilder:
model_path = CachedDownloader.download_to_cache(
url, model_name, download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir
)
- model.load_state_dict(torch.load(model_path, map_location=torch.device("cpu"))["params_ema"], strict=True)
+ state_dict = torch.load(model_path, map_location=torch.device("cpu"), weights_only=True)
+ model.load_state_dict(state_dict["params_ema"], strict=True)
model.eval()
return SuperResolution(
diff --git a/kornia/core/download.py b/kornia/core/download.py
index 04fd2639f..6fefe1af2 100644
--- a/kornia/core/download.py
+++ b/kornia/core/download.py
@@ -594,12 +594,36 @@ def _prefetch_with_retry(url: str, kwargs: dict[str, Any], budget: _SleepBudget)
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.
-
- Progress reporting is written to :data:`sys.stderr`. This is the one
+ Replacement for :func:`torch.hub.load_state_dict_from_url` that also accepts
+ 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. It
+ deliberately differs from the torch function in two ways, both described
+ below: the ``weights_only`` default and where progress is reported.
+
+ The checkpoint is loaded with ``weights_only=True`` unless the caller passes
+ ``weights_only=False``, whereas the torch function defaults to ``False`` on
+ every torch version kornia supports; ``weights_only=True`` is
+ ``torch.load``'s own default since torch 2.6. ``torch.load`` then unpickles
+ only tensors, primitive types and plain containers, and refuses a pickled
+ callable instead of running it. A checkpoint that stores any other type
+ fails with a :class:`RuntimeError` chained to the
+ :class:`pickle.UnpicklingError` that names the type. Allowlist the type for
+ the call with ``torch.serialization.safe_globals([...])``, or pass
+ ``weights_only=False``, but only for a file you trust, because unpickling it
+ can run arbitrary code.
+
+ On older torch, ``weights_only=True`` narrows what a checkpoint can do but
+ does not guarantee that it runs no code. PyTorch's advisories report
+ checkpoints crafted to run code despite it before torch 2.6
+ (`GHSA-53q9-r3pm-6pq6
+ <https://github.com/pytorch/pytorch/security/advisories/GHSA-53q9-r3pm-6pq6>`__)
+ and to corrupt memory, potentially running code, before torch 2.10
+ (`GHSA-63cw-57p8-fm3p
+ <https://github.com/pytorch/pytorch/security/advisories/GHSA-63cw-57p8-fm3p>`__).
+ kornia supports torch 2.5.1 and later, so load a checkpoint from a source
+ you do not trust only on torch 2.10 or later, which fixes both.
+
+ Progress reporting is written to :data:`sys.stderr`. This is the second
deliberate deviation from the torch function, which since torch 2.x writes
its ``Downloading: "<url>" to <path>`` line to :data:`sys.stdout` (the
accompanying progress bar already goes to stderr). Status output on stdout
@@ -660,9 +684,9 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, A
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``, …).
+ **kwargs: forwarded to :func:`torch.hub.load_state_dict_from_url`
+ (``map_location``, ``check_hash``, ``file_name``, …), with
+ ``weights_only`` set to ``True`` unless it is passed as ``False``.
Returns:
The loaded state dict.
@@ -686,6 +710,12 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, A
"""
urls = [url] if isinstance(url, str) else list(url)
+ # The one torch call below loads from every source, the fallbacks and the
+ # refetch after a quarantine alike, so setting this once covers them all.
+ # ``None`` is included because torch 2.5 reads it as ``False``.
+ if kwargs.get("weights_only") is None:
+ kwargs["weights_only"] = True
+
# Pin the cache filename to the primary URL's basename so that all
# attempts share one cache slot and hash validation stays consistent.
# ``is None`` rather than ``not in``: an explicit ``file_name=None`` means
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index 22b33a6ac..33e9ab39f 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -22,15 +22,10 @@ from torch import nn
from kornia.core.download import hf_url, load_state_dict_from_url
+# One source: the authors' own copies are not served over verifiable https.
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",
-]
+urls["defmo_encoder"] = hf_url("defmo", "encoder_best.pt")
+urls["defmo_rendering"] = hf_url("defmo", "rendering_best.pt")
# conv1x1, conv3x3, Bottleneck, ResNet are taken from:
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 49382c5e4..96634576e 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -35,7 +35,7 @@ urls["liberty_aug"] = [
]
urls["hardnet8v2"] = [
hf_url("hardnet", "hardnet8v2.pt"),
- "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt",
+ "https://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt",
]
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 0e36f6d76..e8793eada 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -593,19 +593,19 @@ class LightGlue(nn.Module):
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",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/keynet_affnet_hardnet_lightlue.pth",
]
elif features in ["dedodeb"]:
fname = "dedodeb_lightglue.pth"
url = [
hf_url("lightglue", "dedodeb_lightglue.pth"),
- "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeb_lightglue.pth",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/dedodeb_lightglue.pth",
]
elif features in ["dedodeg"]:
fname = "dedodeg_lightglue.pth"
url = [
hf_url("lightglue", "dedodeg_lightglue.pth"),
- "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeg_lightglue.pth",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/dedodeg_lightglue.pth",
]
elif features == "xfeat":
fname = "xfeat-lighterglue.pt"
@@ -622,7 +622,7 @@ class LightGlue(nn.Module):
elif conf.weights is not None:
path = Path(__file__).parent
path = path / f"weights/{self.conf.weights}.pth"
- state_dict = torch.load(str(path), map_location="cpu")
+ state_dict = torch.load(str(path), map_location="cpu", weights_only=True)
if state_dict:
# xfeat-lighterglue weights are nested under a 'matcher.' prefix
prefix = "matcher."
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index e4d175f1c..00c797b4f 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -34,15 +34,15 @@ from .utils.position_encoding import PositionEncodingSine
urls: dict[str, str | list[str]] = {}
urls["outdoor"] = [
hf_url("loftr", "loftr_outdoor.ckpt"),
- "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_outdoor.ckpt",
+ "https://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",
+ "https://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",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt",
]
# Comments: the config below is the one corresponding to the pretrained models
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index f9280f8db..81f35c382 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -32,7 +32,7 @@ from .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, pr
urls: Dict[str, str | list[str]] = {}
urls["wireframe"] = [
hf_url("sold2", "sold2_wireframe.pth"),
- "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth",
]
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 3e7df66c5..71423530e 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -31,7 +31,7 @@ from kornia.core.download import hf_url, load_state_dict_from_url
url: str | list[str] = [
hf_url("dexined", "DexiNed_BIPED_10.pth"),
- "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",
]
diff --git a/kornia/models/base.py b/kornia/models/base.py
index a4996d5b1..9f7a01248 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -154,6 +154,10 @@ class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):
def load_checkpoint(self, checkpoint: str | list[str], device: Optional[torch.device] = None) -> None:
"""Load checkpoint from a given url or file.
+ Either way the file is loaded with ``weights_only=True``, so it may hold
+ tensors, primitive types and plain containers only; see
+ :func:`kornia.core.download.load_state_dict_from_url`.
+
Args:
checkpoint: The url or filepath for the respective checkpoint
device: The desired device to load the weights and move the model
@@ -161,7 +165,7 @@ class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):
"""
if isinstance(checkpoint, str) and os.path.isfile(checkpoint):
with open(checkpoint, "rb") as f:
- state_dict = torch.load(f, map_location=device)
+ 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 80c0822ef..36af62b77 100644
--- a/kornia/models/dexined.py
+++ b/kornia/models/dexined.py
@@ -34,7 +34,7 @@ __all__ = ["DexiNed"]
_url: str | list[str] = [
hf_url("dexined", "DexiNed_BIPED_10.pth"),
- "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",
+ "https://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",
]
diff --git a/kornia/models/small_sr.py b/kornia/models/small_sr.py
index f29f39fd1..b86f81514 100644
--- a/kornia/models/small_sr.py
+++ b/kornia/models/small_sr.py
@@ -62,7 +62,7 @@ class SmallSRNet(nn.Module):
model_path = CachedDownloader.download_to_cache(
path_file, "small_sr.pth", download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir
)
- pretrained_dict = torch.load(model_path, map_location=torch.device("cpu"))
+ pretrained_dict = torch.load(model_path, map_location=torch.device("cpu"), weights_only=True)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/testing/pickle_payload.py b/testing/pickle_payload.py
new file mode 100644
index 000000000..87f8af343
--- /dev/null
+++ b/testing/pickle_payload.py
@@ -0,0 +1,58 @@
+# 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.
+#
+
+"""A pickled object with an observable side effect, for tests of ``weights_only`` loading.
+
+Store a :class:`CreatesMarkerOnLoad` in a checkpoint and load it through the code under
+test with :func:`load_without_running_payload`. The only effect of unpickling the object is
+an empty marker file, so the marker existing afterwards means the loader executed a callable
+named in the file it was handed.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+from pathlib import Path
+
+__all__ = ["CreatesMarkerOnLoad", "create_marker", "load_without_running_payload"]
+
+
+def create_marker(path: str) -> None:
+ """Create an empty file at *path*; the only effect of unpickling :class:`CreatesMarkerOnLoad`."""
+ Path(path).touch()
+
+
+class CreatesMarkerOnLoad:
+ """An object whose unpickling calls :func:`create_marker`, standing in for any pickled callable."""
+
+ def __init__(self, marker: Path) -> None:
+ self.marker = marker
+
+ def __reduce__(self) -> tuple[object, tuple[str]]:
+ return (create_marker, (str(self.marker),))
+
+
+def load_without_running_payload(marker: Path, load: Callable[[], object]) -> object:
+ """Return ``load()``, failing if *marker* exists afterwards, whether ``load`` returned or raised.
+
+ Checking in ``finally`` puts the payload having run ahead of whatever the loader then
+ returns or raises, so a loader that executes it fails on exactly that.
+ """
+ try:
+ return load()
+ finally:
+ assert not marker.exists(), "loading the checkpoint ran a callable pickled into it"
diff --git a/tests/core/test_download.py b/tests/core/test_download.py
index 9d5422b48..64e4eac49 100644
--- a/tests/core/test_download.py
+++ b/tests/core/test_download.py
@@ -17,8 +17,12 @@
from __future__ import annotations
+import collections
import http.client
+import http.server
+import io
import os
+import pickle
import sys
import threading
import time
@@ -41,6 +45,9 @@ from kornia.core.download import (
load_state_dict_from_url,
)
+from testing.base import BaseTester
+from testing.pickle_payload import CreatesMarkerOnLoad, load_without_running_payload
+
@pytest.fixture(autouse=True)
def _clear_discard_ledger():
@@ -108,14 +115,14 @@ class TestLoadStateDictFromUrl:
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")
+ mock.assert_called_once_with("http://example.com/model.pth", weights_only=True)
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")
+ mock.assert_called_once_with("http://example.com/model.pth", weights_only=True)
def test_fallback_on_failure(self) -> None:
primary = "http://primary.example.com/model.pth"
@@ -156,7 +163,7 @@ class TestLoadStateDictFromUrl:
# 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")
+ assert fallback_call == call(fallback, file_name="weights-abc123.pth", weights_only=True)
def test_explicit_file_name_not_overridden(self) -> None:
primary = "http://primary.example.com/model.pth"
@@ -178,7 +185,7 @@ class TestLoadStateDictFromUrl:
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")
+ mock.assert_called_once_with("http://example.com/model.pth", map_location="cpu", weights_only=True)
class TestProgressGoesToStderr:
@@ -1158,6 +1165,145 @@ class TestFailureMessageCarriesCause:
assert isinstance(excinfo.value.__cause__, HTTPError)
+def local_server(monkeypatch):
+ """Serve in-memory files over HTTP from a thread bound to 127.0.0.1.
+
+ The transfer runs through ``torch.hub.download_url_to_file`` for real -- nothing is
+ stubbed between the socket and ``torch.load`` -- and nothing leaves the host. Yields
+ ``(files, url, hits)``: ``files`` maps a path such as ``"/model.pth"`` to the bytes
+ served for it (any other path answers 404), ``url(path)`` builds the URL, and ``hits``
+ counts the requests per path.
+ """
+ for var in ("http_proxy", "HTTP_PROXY", "all_proxy", "ALL_PROXY"):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("no_proxy", "127.0.0.1")
+ monkeypatch.setenv("NO_PROXY", "127.0.0.1")
+
+ files: dict[str, bytes] = {}
+ hits: collections.Counter[str] = collections.Counter()
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self) -> None:
+ hits[self.path] += 1
+ body = files.get(self.path)
+ self.send_response(404 if body is None else 200)
+ payload = b"not found" if body is None else body
+ self.send_header("Content-Length", str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ port = server.server_address[1]
+ try:
+ yield files, (lambda path: f"http://127.0.0.1:{port}{path}"), hits
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join()
+
+
+def _checkpoint_bytes(obj: object) -> bytes:
+ buffer = io.BytesIO()
+ torch.save(obj, buffer)
+ return buffer.getvalue()
+
+
+class TestWeightsOnly(BaseTester):
+ """A checkpoint is loaded as data: tensors and plain containers, never pickled callables.
+
+ ``torch.hub.load_state_dict_from_url`` defaults to ``weights_only=False`` on every
+ supported torch, and ``torch.load`` itself did before torch 2.6, so a wrapper that
+ only forwards its keyword arguments unpickles whatever a checkpoint names. The
+ wrapper defaults to ``weights_only=True`` instead, and a caller that trusts a file
+ that needs more opts out with ``weights_only=False`` explicitly.
+
+ The payload is an ordinary pickled callable in the current ``torch.save`` format. These
+ tests pin that the default reaches torch and that torch's restricted unpickler refuses
+ such a payload; they do not exercise the bypasses PyTorch has published for torch before
+ 2.10, which the wrapper's docstring describes.
+ """
+
+ @pytest.mark.parametrize(
+ "sources",
+ [["/model.pth"], ["/missing.pth", "/model.pth"]],
+ ids=["single_source", "fallback_after_a_dead_primary"],
+ )
+ def test_a_pickled_callable_is_refused_and_never_run(self, local_server, tmp_path, sources) -> None:
+ files, url, _ = local_server
+ marker = tmp_path / "marker"
+ files["/model.pth"] = _checkpoint_bytes({"weight": torch.zeros(2), "extra": CreatesMarkerOnLoad(marker)})
+
+ urls = [url(s) for s in sources]
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore") # the dead primary's "Trying next source"
+ with pytest.raises(RuntimeError) as excinfo:
+ load_without_running_payload(
+ marker, lambda: load_state_dict_from_url(urls, model_dir=str(tmp_path / "cache"))
+ )
+
+ assert isinstance(excinfo.value.__cause__, pickle.UnpicklingError)
+
+ def test_a_poisoned_cache_entry_is_refused_and_refetched(self, local_server, tmp_path, dtype) -> None:
+ """A cached file is loaded under the same rule as a downloaded one, and a refused entry is refetched."""
+ files, url, hits = local_server
+ marker = tmp_path / "marker"
+ good = {"weight": torch.arange(6, dtype=dtype).reshape(2, 3)}
+ files["/model.pth"] = _checkpoint_bytes(good)
+ cache = tmp_path / "cache"
+ cache.mkdir()
+ (cache / "model.pth").write_bytes(_checkpoint_bytes({"extra": CreatesMarkerOnLoad(marker)}))
+
+ result = load_without_running_payload(
+ marker, lambda: load_state_dict_from_url(url("/model.pth"), model_dir=str(cache))
+ )
+
+ self.assert_close(result["weight"], good["weight"])
+ assert hits["/model.pth"] == 1
+
+ def test_a_plain_state_dict_still_loads(self, local_server, tmp_path, dtype) -> None:
+ """Control: what a checkpoint normally holds is allowed, container types included."""
+ files, url, _ = local_server
+ state_dict = collections.OrderedDict(
+ [("weight", torch.arange(6, dtype=dtype).reshape(2, 3)), ("index", torch.tensor([3, 1, 2]))]
+ )
+ files["/model.pth"] = _checkpoint_bytes(
+ {"state_dict": state_dict, "epoch": 7, "lr": 0.5, "arch": "net", "shape": (2, 3), "flags": [True, None]}
+ )
+
+ result = load_state_dict_from_url(url("/model.pth"), model_dir=str(tmp_path / "cache"), map_location="cpu")
+
+ assert isinstance(result["state_dict"], collections.OrderedDict)
+ assert list(result["state_dict"]) == ["weight", "index"]
+ self.assert_close(result["state_dict"]["weight"], state_dict["weight"])
+ assert result["state_dict"]["weight"].dtype == dtype
+ assert torch.equal(result["state_dict"]["index"], state_dict["index"])
+ assert (result["epoch"], result["lr"], result["arch"], result["shape"], result["flags"]) == (
+ 7,
+ 0.5,
+ "net",
+ (2, 3),
+ [True, None],
+ )
+
+ @pytest.mark.parametrize(
+ ("kwargs", "forwarded"),
+ [({}, True), ({"weights_only": None}, True), ({"weights_only": True}, True), ({"weights_only": False}, False)],
+ ids=["omitted", "none", "true", "false"],
+ )
+ def test_weights_only_is_true_unless_the_caller_passes_false(self, kwargs, forwarded) -> None:
+ # ``None`` counts as omitted: torch 2.5 reads it as ``False``.
+ with patch("kornia.core.download._prefetch_to_cache", return_value=False):
+ with patch("kornia.core.download.torch.hub.load_state_dict_from_url", return_value={}) as mock:
+ load_state_dict_from_url("http://example.com/model.pth", **kwargs)
+ mock.assert_called_once_with("http://example.com/model.pth", weights_only=forwarded)
+
+
class TestDownloadFileFromUrl:
"""The path for checkpoints torch cannot unpickle -- a ``.safetensors`` file.
diff --git a/tests/core/test_weights_only_call_sites.py b/tests/core/test_weights_only_call_sites.py
new file mode 100644
index 000000000..178ae40df
--- /dev/null
+++ b/tests/core/test_weights_only_call_sites.py
@@ -0,0 +1,97 @@
+# 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.
+#
+
+"""Every place ``kornia/`` unpickles a file asks for ``weights_only=True``.
+
+A behavioural test of a direct ``torch.load`` call cannot guard it on a current torch: from
+torch 2.6 ``torch.load`` defaults to ``weights_only=True`` by itself, so dropping the keyword
+changes nothing there and only the torch 2.5 leg would notice. Reading the source does not
+depend on the torch version, and it also covers call sites added later.
+
+The rules:
+
+* every ``torch.load`` / ``torch.serialization.load`` call passes ``weights_only=True`` as a
+ literal keyword;
+* ``torch.hub.load_state_dict_from_url`` is called only by kornia's own wrapper in
+ ``kornia/core/download.py``, whose ``weights_only`` default ``TestWeightsOnly`` pins;
+* neither loader is imported by bare name, which would hide a call from the first two rules.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import kornia
+
+_KORNIA_ROOT = Path(kornia.__file__).resolve().parent
+_WRAPPER_MODULE = "core/download.py"
+_LOAD_CHAINS = {("torch", "load"), ("torch", "serialization", "load")}
+_HUB_CHAIN = ("torch", "hub", "load_state_dict_from_url")
+_BARE_IMPORTS = {("torch", "load"), ("torch.serialization", "load"), ("torch.hub", "load_state_dict_from_url")}
+
+
+def _chain(node: ast.AST, torch_names: set[str]) -> tuple[str, ...] | None:
+ """Return ``("torch", "hub", "x")`` for ``<torch alias>.hub.x``, or ``None`` for anything else."""
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name) and node.id in torch_names:
+ return ("torch", *reversed(parts))
+ return None
+
+
+def _scan() -> tuple[list[str], list[str], list[str]]:
+ """Return ``(torch.load sites, violations, hub sites)`` over every module under ``kornia/``."""
+ load_sites: list[str] = []
+ violations: list[str] = []
+ hub_sites: list[str] = []
+ for path in sorted(_KORNIA_ROOT.rglob("*.py")):
+ rel = path.relative_to(_KORNIA_ROOT).as_posix()
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ torch_names = {"torch"}
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ torch_names |= {alias.asname for alias in node.names if alias.name == "torch" and alias.asname}
+ elif isinstance(node, ast.ImportFrom) and node.module is not None:
+ for alias in node.names:
+ if (node.module, alias.name) in _BARE_IMPORTS:
+ violations.append(f"{rel}:{node.lineno} imports {node.module}.{alias.name} by bare name")
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ chain = _chain(node.func, torch_names)
+ where = f"{rel}:{node.lineno}"
+ if chain in _LOAD_CHAINS:
+ load_sites.append(where)
+ weights_only = next((kw.value for kw in node.keywords if kw.arg == "weights_only"), None)
+ if not (isinstance(weights_only, ast.Constant) and weights_only.value is True):
+ violations.append(f"{where} calls {'.'.join(chain)} without weights_only=True")
+ elif chain == _HUB_CHAIN:
+ hub_sites.append(where)
+ if rel != _WRAPPER_MODULE:
+ violations.append(f"{where} calls torch.hub.load_state_dict_from_url; use kornia's wrapper")
+ return load_sites, violations, hub_sites
+
+
+def test_every_unpickling_call_in_kornia_passes_weights_only() -> None:
+ load_sites, violations, hub_sites = _scan()
+ # The scan must see the calls it polices, or an empty result proves nothing.
+ assert load_sites, "found no torch.load call under kornia/; the scan no longer matches how kornia calls it"
+ assert hub_sites, f"found no torch.hub.load_state_dict_from_url call; the wrapper in {_WRAPPER_MODULE} moved"
+ assert not violations, "\n".join(violations)
diff --git a/tests/models/test_model_base.py b/tests/models/test_model_base.py
index f28cfcee7..3102720aa 100644
--- a/tests/models/test_model_base.py
+++ b/tests/models/test_model_base.py
@@ -18,12 +18,17 @@
from __future__ import annotations
import os
+import pickle
from unittest.mock import patch
import pytest
import torch
+from torch import nn
-from kornia.models.base import ModelBaseMixin
+from kornia.models.base import ModelBase, ModelBaseMixin
+
+from testing.base import BaseTester
+from testing.pickle_payload import CreatesMarkerOnLoad, load_without_running_payload
class DummyMixin(ModelBaseMixin):
@@ -207,3 +212,37 @@ class TestModelBaseMixinSaveWritesRealFiles:
written = sorted(p.name for p in tmp_path.iterdir())
assert len(written) == 2
assert all("_mask_" in name for name in written)
+
+
+class _TinyModel(ModelBase[None]):
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(2, 3)
+
+ @staticmethod
+ def from_config(config: None) -> _TinyModel:
+ return _TinyModel()
+
+
+class TestModelBaseLoadCheckpoint(BaseTester):
+ """A local checkpoint is loaded as data, as a downloaded one is (``weights_only=True``)."""
+
+ def test_a_pickled_callable_in_a_local_file_is_refused_and_never_run(self, tmp_path) -> None:
+ marker = tmp_path / "marker"
+ path = tmp_path / "model.pth"
+ torch.save({**_TinyModel().state_dict(), "extra": CreatesMarkerOnLoad(marker)}, path)
+
+ model = _TinyModel()
+ with pytest.raises(pickle.UnpicklingError):
+ load_without_running_payload(marker, lambda: model.load_checkpoint(str(path)))
+
+ def test_a_local_state_dict_loads(self, tmp_path, dtype) -> None:
+ source = _TinyModel().to(dtype)
+ path = tmp_path / "model.pth"
+ torch.save(source.state_dict(), path)
+
+ model = _TinyModel().to(dtype)
+ model.load_checkpoint(str(path))
+
+ self.assert_close(model.linear.weight, source.linear.weight)
+ self.assert_close(model.linear.bias, source.linear.bias)