Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

test: load the data_test reference tensors from safetensors, not pickle (#5234)

Dmytro Mishkin0ca2c5f4f182
diff --git a/.github/download-models-weights.py b/.github/download-models-weights.py
index f8f461342..3da534111 100644
--- a/.github/download-models-weights.py
+++ b/.github/download-models-weights.py
@@ -32,6 +32,10 @@ disagrees stores the file where nothing looks for it, leaving the cache
silently useless. Values mirror the URL list in kornia, so the fallback source
and the retry/backoff of :func:`kornia.core.download.load_state_dict_from_url`
apply to the prefetch too.
+
+A ``.safetensors`` key is fetched with :func:`kornia.core.download_file_from_url`
+and checked with :func:`kornia.core.check_safetensors`, as kornia reads it; every
+other key is a pickle, loaded with ``load_state_dict_from_url``.
"""
import argparse
@@ -40,8 +44,8 @@ import os
import torch
+from kornia.core import check_safetensors, download_file_from_url
from kornia.core.download import load_state_dict_from_url
-from kornia.feature import DISKFeatures
logger = logging.getLogger(__name__)
@@ -49,22 +53,25 @@ logger = logging.getLogger(__name__)
MODELS: dict[str, "str | list[str]"] = {
# Reference tensors used by conftest.py's data fixture. Prefetch these once
# before the matrix so every job does not download them on a cold cache.
- "loftr_outdoor_and_homography_data.pt": (
+ "loftr_outdoor_and_homography_data.safetensors": (
"https://raw.githubusercontent.com/kornia/data_test/"
- "cb8f42bf28b9f347df6afba5558738f62a11f28a/loftr_outdoor_and_homography_data.pt"
+ "4ffed08df3d82af85aa9012d3104f19ca4b62604/loftr_outdoor_and_homography_data.safetensors"
),
- "loftr_indoor_and_fundamental_data.pt": (
+ "loftr_indoor_and_fundamental_data.safetensors": (
"https://raw.githubusercontent.com/kornia/data_test/"
- "cb8f42bf28b9f347df6afba5558738f62a11f28a/loftr_indoor_and_fundamental_data.pt"
+ "4ffed08df3d82af85aa9012d3104f19ca4b62604/loftr_indoor_and_fundamental_data.safetensors"
),
- "adalam_test.pt": (
- "https://raw.githubusercontent.com/kornia/data_test/f7d8da661701424babb64850e03c5e8faec7ea62/adalam_test.pt"
+ "adalam_test.safetensors": (
+ "https://raw.githubusercontent.com/kornia/data_test/"
+ "4ffed08df3d82af85aa9012d3104f19ca4b62604/adalam_test.safetensors"
),
- "knchurch_disk.pt": (
- "https://raw.githubusercontent.com/kornia/data_test/8b98f44abbe92b7a84631ed06613b08fee7dae14/knchurch_disk.pt"
+ "knchurch_disk.safetensors": (
+ "https://raw.githubusercontent.com/kornia/data_test/"
+ "4ffed08df3d82af85aa9012d3104f19ca4b62604/knchurch_disk.safetensors"
),
- "xfeat_reference.pt": (
- "https://raw.githubusercontent.com/kornia/data_test/279e95e411f2d3926953dea3842347242190f4da/xfeat_reference.pt"
+ "xfeat_reference.safetensors": (
+ "https://raw.githubusercontent.com/kornia/data_test/"
+ "4ffed08df3d82af85aa9012d3104f19ca4b62604/xfeat_reference.safetensors"
),
# -- detectors, descriptors and orientation estimators -------------------
# AffNet + OriNet: LAFAffNetShapeEstimator / LAFOrienter, and every composite
@@ -212,9 +219,9 @@ 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.
- # ``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]):
+ if file_name.endswith(".safetensors"):
+ download_file_from_url(url, file_name=file_name, validate=check_safetensors)
+ else:
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}")
diff --git a/conftest.py b/conftest.py
index ed6dc2f7f..3650e5775 100644
--- a/conftest.py
+++ b/conftest.py
@@ -41,7 +41,7 @@ from testing.half_precision_ci import (
seed_test_rng,
)
from testing.known_failures import mark_known_failures
-from testing.reference_data import TEST_DATA_URLS
+from testing.reference_data import TEST_CHECKPOINT_URLS, TEST_DATA_URLS, load_reference_data
try:
import torch._dynamo
@@ -1046,9 +1046,8 @@ def data(request):
Use with @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
"""
- if request.param not in TEST_DATA_URLS:
- raise ValueError(f"Unknown test data: {request.param}. Available: {list(TEST_DATA_URLS.keys())}")
- # ``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"))
+ if request.param in TEST_DATA_URLS:
+ return load_reference_data(request.param)
+ if request.param in TEST_CHECKPOINT_URLS:
+ return load_state_dict_from_url(TEST_CHECKPOINT_URLS[request.param], map_location=torch.device("cpu"))
+ raise ValueError(f"Unknown test data: {request.param}. Available: {[*TEST_DATA_URLS, *TEST_CHECKPOINT_URLS]}")
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 3692856cb..3b3bb8349 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -129,8 +129,10 @@ def main():
BASE_IMAGE_URL4: str = "https://raw.githubusercontent.com/kornia/data/main/baby_giraffe.png" # morphology
BASE_IMAGE_URL5: str = "https://raw.githubusercontent.com/kornia/data/main/persistencia_memoria.jpg" # filters
BASE_IMAGE_URL6: str = "https://raw.githubusercontent.com/kornia/data/main/delorean.png" # geometry
- hash1 = "8b98f44abbe92b7a84631ed06613b08fee7dae14"
- BASE_IMAGEOUTDOOR_URL7: str = f"https://github.com/kornia/data_test/raw/{hash1}/knchurch_disk.pt" # image matching
+ hash1 = "4ffed08df3d82af85aa9012d3104f19ca4b62604"
+ BASE_IMAGEOUTDOOR_URL7: str = ( # image matching
+ f"https://github.com/kornia/data_test/raw/{hash1}/knchurch_disk.safetensors"
+ )
BASE_IMAGEOUTDOOR_URL8: str = ( # Response functions
"https://github.com/kornia/data/raw/main/kornia_banner_pixie.png"
)
@@ -669,12 +671,8 @@ def main():
print(f"Generated image example for {fn_name}. {sig}")
# Image Matching and local features
- # 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"]
+ img_matching_path = K.core.download_file_from_url(BASE_IMAGEOUTDOOR_URL7, validate=K.core.check_safetensors)
+ img_outdoor = K.core.load_safetensors(img_matching_path)["img2"]
print("Generating local feature detections ")
disk = K.feature.DISK.from_pretrained("depth")
with torch.no_grad():
diff --git a/docs/generate_model_examples.py b/docs/generate_model_examples.py
index 1d17c74be..37466cc7a 100644
--- a/docs/generate_model_examples.py
+++ b/docs/generate_model_examples.py
@@ -51,7 +51,7 @@ torch.manual_seed(0)
OUT = Path(__file__).absolute().parent / "source/_static/img/models"
DATA = "https://raw.githubusercontent.com/kornia/data/main/"
-KNCHURCH = "https://github.com/kornia/data_test/raw/8b98f44abbe92b7a84631ed06613b08fee7dae14/knchurch_disk.pt"
+KNCHURCH = "https://github.com/kornia/data_test/raw/4ffed08df3d82af85aa9012d3104f19ca4b62604/knchurch_disk.safetensors"
IMAGENET_CLASSES = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"
FIGURES: dict = {}
@@ -69,9 +69,7 @@ def sample(name: str, size: tuple[int, int] | None = None) -> torch.Tensor:
def knchurch() -> tuple[torch.Tensor, torch.Tensor]:
- # 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)
+ d = K.core.load_safetensors(K.core.download_file_from_url(KNCHURCH, validate=K.core.check_safetensors))
return d["img1"], d["img2"]
diff --git a/testing/reference_data.py b/testing/reference_data.py
index 23a66a12d..020c8d1c3 100644
--- a/testing/reference_data.py
+++ b/testing/reference_data.py
@@ -24,34 +24,65 @@ enumerate it in ``WEIGHT_REGISTRIES`` next to the library's own weight tables:
every entry must be prefetched by ``.github/download-models-weights.py`` under
the exact cache name the fixture looks up, from the exact source list.
-URLs are commit-pinned ``raw.githubusercontent.com`` links, which avoid the
-GitHub blob-page redirect the ``?raw=true`` spelling goes through.
+The reference tensors are ``.safetensors`` files in ``kornia/data_test``, read
+without unpickling anything. Their URLs are commit-pinned
+``raw.githubusercontent.com`` links, which avoid the GitHub blob-page redirect
+the ``?raw=true`` spelling goes through.
"""
from __future__ import annotations
+from typing import Any
+
+from kornia.core import check_safetensors, download_file_from_url, load_safetensors
+from kornia.feature import DISKFeatures
from kornia.filters import dexined as _dexined
-# Test data commit hashes from the kornia/data_test repository.
-DATA_TEST_SHA: dict[str, str] = {
- "loftr": "cb8f42bf28b9f347df6afba5558738f62a11f28a",
- "adalam": "f7d8da661701424babb64850e03c5e8faec7ea62",
- "disk": "8b98f44abbe92b7a84631ed06613b08fee7dae14",
- "xfeat": "279e95e411f2d3926953dea3842347242190f4da",
-}
+# The kornia/data_test commit that carries every ``.safetensors`` reference file.
+DATA_TEST_SHA = "4ffed08df3d82af85aa9012d3104f19ca4b62604"
-_RAW = "https://raw.githubusercontent.com/kornia/data_test"
+_RAW = f"https://raw.githubusercontent.com/kornia/data_test/{DATA_TEST_SHA}"
+# Reference tensors, read by :func:`load_reference_data`.
TEST_DATA_URLS: dict[str, str | list[str]] = {
- "loftr_homo": f"{_RAW}/{DATA_TEST_SHA['loftr']}/loftr_outdoor_and_homography_data.pt",
- "loftr_fund": f"{_RAW}/{DATA_TEST_SHA['loftr']}/loftr_indoor_and_fundamental_data.pt",
- "adalam_idxs": f"{_RAW}/{DATA_TEST_SHA['adalam']}/adalam_test.pt",
- "lightglue_idxs": f"{_RAW}/{DATA_TEST_SHA['adalam']}/adalam_test.pt",
- "disk_outdoor": f"{_RAW}/{DATA_TEST_SHA['disk']}/knchurch_disk.pt",
- "xfeat_outdoor": f"{_RAW}/{DATA_TEST_SHA['xfeat']}/xfeat_reference.pt",
- # The library's own DexiNed checkpoint, from the library's own source list, so the
- # fixture shares its cache entry, its fallback mirror and its prefetch guard.
+ "loftr_homo": f"{_RAW}/loftr_outdoor_and_homography_data.safetensors",
+ "loftr_fund": f"{_RAW}/loftr_indoor_and_fundamental_data.safetensors",
+ "adalam_idxs": f"{_RAW}/adalam_test.safetensors",
+ "lightglue_idxs": f"{_RAW}/adalam_test.safetensors",
+ "disk_outdoor": f"{_RAW}/knchurch_disk.safetensors",
+ "xfeat_outdoor": f"{_RAW}/xfeat_reference.safetensors",
+}
+
+# Library checkpoints the fixture serves as they are: the library's own source list,
+# loaded the library's way, so the fixture shares its cache entry, its fallback
+# mirror and its prefetch guard.
+TEST_CHECKPOINT_URLS: dict[str, str | list[str]] = {
"dexined": list(_dexined.url),
}
-__all__ = ["DATA_TEST_SHA", "TEST_DATA_URLS"]
+# Entries whose file stores ``list[DISKFeatures]`` values of length 1, flattened to
+# ``<key>.keypoints``, ``<key>.descriptors`` and ``<key>.detection_scores``.
+_DISK_FEATURES: dict[str, tuple[str, ...]] = {
+ "disk_outdoor": ("disk1", "disk2"),
+}
+
+
+def load_reference_data(name: str) -> dict[str, Any]:
+ """Download and read the reference tensors of the ``TEST_DATA_URLS`` entry *name*.
+
+ A truncated cache entry fails ``check_safetensors`` and is fetched again
+ rather than read.
+
+ Returns:
+ The file's tensors by key, on CPU, with each flattened ``DISKFeatures``
+ rebuilt into the one-element list the tests index.
+ """
+ path = download_file_from_url(TEST_DATA_URLS[name], validate=check_safetensors)
+ data: dict[str, Any] = load_safetensors(path)
+ for key in _DISK_FEATURES.get(name, ()):
+ fields = ("keypoints", "descriptors", "detection_scores")
+ data[key] = [DISKFeatures(*(data.pop(f"{key}.{field}") for field in fields))]
+ return data
+
+
+__all__ = ["DATA_TEST_SHA", "TEST_CHECKPOINT_URLS", "TEST_DATA_URLS", "load_reference_data"]
diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.py
index 4a10ce3e6..8207bdb75 100644
--- a/tests/core/test_weights_prefetch.py
+++ b/tests/core/test_weights_prefetch.py
@@ -30,32 +30,32 @@ prefetched or listed in :data:`NOT_PREFETCHED` with a reason.
Scope: this guards the checkpoints that go through
:func:`kornia.core.download.load_state_dict_from_url`, which is what the
-``weights/`` cache holds. Two other download paths live in ``kornia/`` and are
-invisible to the prefetch list -- its sibling
-:func:`kornia.core.download.download_file_from_url`, which the vision-language
-builders (``kornia/models/{kimi_vl,siglip2}/builder.py``) fetch a
-``model.safetensors`` with, and ``CachedDownloader`` into
+``weights/`` cache holds, and the ``.safetensors`` reference tensors that
+``conftest.py``'s ``data`` fixture fetches into the same cache with its sibling
+:func:`kornia.core.download.download_file_from_url` (``testing/reference_data.py``,
+enumerated in :data:`WEIGHT_REGISTRIES`). Two other download paths live in
+``kornia/`` and are invisible to the prefetch list -- ``download_file_from_url``
+as the vision-language builders (``kornia/models/{kimi_vl,siglip2}/builder.py``)
+call it, to fetch a ``model.safetensors``, and ``CachedDownloader`` into
``.kornia_hub/`` (``kornia/models/small_sr.py``, ``kornia/contrib/super_resolution.py``,
``kornia/onnx/utils.py``, ``kornia/models/_hf_models/hf_onnx_community.py``,
``kornia/feature/lightglue_onnx/utils/download.py``). Nothing in the PR matrix
downloads through either today; a test that did would fetch live from every
matrix cell with this file still green.
-``download_file_from_url`` does share the ``weights/`` cache, so its callers
-could in principle be prefetched -- they are not, for a reason the checkpoints
-above do not have: SigLIP2 takes the repository as an *argument*, so there is no
-fixed set of variants to enumerate, and the two checkpoints in play are hundreds
-of megabytes for a pair of integration tests. The call-site scan below covers
-both functions, so a model that starts downloading through either is caught here
-either way.
-
-``docs/generate_examples.py`` also fetches one non-checkpoint tensor
-(``knchurch_disk.pt``, the image pair the matching examples are drawn on)
-straight through ``torch.hub.load_state_dict_from_url``. It lands in the same
-``weights/`` cache under the same name as the ``disk_outdoor`` reference tensor
-``conftest.py``'s ``data`` fixture loads, so the prefetch of that fixture's table
-(``testing/reference_data.py``, enumerated in :data:`WEIGHT_REGISTRIES`) serves the
-docs build too -- provided the two copies of the commit hash agree, which
+Those builders' checkpoints could in principle be prefetched as the reference
+tensors are -- they are not, for a reason the checkpoints above do not have:
+SigLIP2 takes the repository as an *argument*, so there is no fixed set of
+variants to enumerate, and the two checkpoints in play are hundreds of megabytes
+for a pair of integration tests. The call-site scan below covers both functions,
+so a model that starts downloading through either is caught here either way.
+
+``docs/generate_examples.py`` and ``docs/generate_model_examples.py`` also fetch one
+non-checkpoint file (``knchurch_disk.safetensors``, the image pair the matching examples
+are drawn on) through ``download_file_from_url``. It lands in the same ``weights/`` cache
+under the same name as the ``disk_outdoor`` reference tensors ``conftest.py``'s ``data``
+fixture loads, so the prefetch of that fixture's table serves the docs build too --
+provided every copy of the commit hash agrees, which
``test_docs_reference_data_matches_the_fixture_table`` holds them to.
"""
@@ -126,6 +126,8 @@ WEIGHT_REGISTRIES: dict[str, tuple[ModuleType, dict[str, Any]]] = {
# Not a weight source: the reference tensors conftest.py's ``data`` fixture loads
# into the same cache. Listed here so the same two-way guard covers them.
"reference_data": (reference_data, reference_data.TEST_DATA_URLS),
+ # The library checkpoints the same fixture serves, from the library's own source lists.
+ "reference_checkpoints": (reference_data, reference_data.TEST_CHECKPOINT_URLS),
"affine_shape": (affine_shape, affine_shape.urls),
"orientation": (orientation, orientation.urls),
"hardnet": (hardnet, hardnet.urls),
@@ -509,13 +511,14 @@ class TestWeightsPrefetchCoverage:
f"_DOWNLOAD_CALL_ALLOWLIST with the reason it has no registry of its own."
)
- def test_docs_reference_data_matches_the_fixture_table(self) -> None:
- """``docs/generate_examples.py`` spells its own copy of a ``data_test`` commit hash.
+ @pytest.mark.parametrize("script", ["generate_examples.py", "generate_model_examples.py"])
+ def test_docs_reference_data_matches_the_fixture_table(self, script: str) -> None:
+ """Each docs generator spells its own copy of a ``data_test`` commit hash.
The cache is keyed by basename, so a docs URL that drifts to another
revision of the same file is served the fixture's prefetched bytes
without a download, silently. Hold every ``data_test`` URL in the docs
- script to a (commit, file) pair the fixture table pins.
+ scripts to a (commit, file) pair the fixture table pins.
"""
pinned = {
(m.group(1), m.group(2))
@@ -523,12 +526,12 @@ class TestWeightsPrefetchCoverage:
for m in [_DATA_TEST_URL.search(_as_list(url)[0])]
if m is not None
}
- docs = (_REPO_ROOT / "docs" / "generate_examples.py").read_text(encoding="utf-8")
+ docs = (_REPO_ROOT / "docs" / script).read_text(encoding="utf-8")
refs = _data_test_refs(docs)
- assert refs, "docs/generate_examples.py no longer fetches from kornia/data_test; retire this check"
+ assert refs, f"docs/{script} no longer fetches from kornia/data_test; drop it from this check"
unpinned = sorted(refs - pinned)
assert not unpinned, (
- f"docs/generate_examples.py fetches data_test files the fixture table does not pin: {unpinned}. "
+ f"docs/{script} fetches data_test files the fixture table does not pin: {unpinned}. "
f"Update DATA_TEST_SHA in testing/reference_data.py, or the docs script, so the two agree."
)
diff --git a/tests/feature/test_xfeat.py b/tests/feature/test_xfeat.py
index 4d849c3d4..b9cc132f2 100644
--- a/tests/feature/test_xfeat.py
+++ b/tests/feature/test_xfeat.py
@@ -358,7 +358,7 @@ def test_lighterglue_pretrained_smoke():
# ---------------------------------------------------------------------------
-# Reference-data tests (kornia/data_test xfeat_reference.pt)
+# Reference-data tests (kornia/data_test xfeat_reference.safetensors)
# ---------------------------------------------------------------------------