π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
test: skip macOS RRDBNet export and prefetch reference data (#4515)
Dmytro Mishkin6baf3dabf088
diff --git a/.github/download-models-weights.py b/.github/download-models-weights.pyindex e697f0782..21bbe0bd3 100644--- a/.github/download-models-weights.py+++ b/.github/download-models-weights.py@@ -46,6 +46,25 @@ logger = logging.getLogger(__name__)# Format: "<cache filename>": "<url>" | ["<primary url>", "<fallback url>"]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": (+ "https://raw.githubusercontent.com/kornia/data_test/"+ "cb8f42bf28b9f347df6afba5558738f62a11f28a/loftr_outdoor_and_homography_data.pt"+ ),+ "loftr_indoor_and_fundamental_data.pt": (+ "https://raw.githubusercontent.com/kornia/data_test/"+ "cb8f42bf28b9f347df6afba5558738f62a11f28a/loftr_indoor_and_fundamental_data.pt"+ ),+ "adalam_test.pt": (+ "https://raw.githubusercontent.com/kornia/data_test/f7d8da661701424babb64850e03c5e8faec7ea62/adalam_test.pt"+ ),+ "knchurch_disk.pt": (+ "https://raw.githubusercontent.com/kornia/data_test/8b98f44abbe92b7a84631ed06613b08fee7dae14/knchurch_disk.pt"+ ),+ "xfeat_reference.pt": (+ "https://raw.githubusercontent.com/kornia/data_test/279e95e411f2d3926953dea3842347242190f4da/xfeat_reference.pt"+ ),# -- detectors, descriptors and orientation estimators -------------------# AffNet + OriNet: LAFAffNetShapeEstimator / LAFOrienter, and every composite# built on them (GFTTAffNetHardNet, KeyNetHardNet, KeyNetAffNetHardNet).diff --git a/conftest.py b/conftest.pyindex 61303d670..7c6237390 100644--- a/conftest.py+++ b/conftest.py@@ -36,6 +36,7 @@ except ImportError: # pragma: no coverfrom _pytest.runner import CallInfo # type: ignore[no-redef]import kornia+from kornia.core.download import load_state_dict_from_urlfrom testing.doctest_downloads import DOWNLOAD_ENV_VAR, downloads_allowed, install_download_guard, skip_reasonfrom testing.half_precision_ci import (@@ -46,6 +47,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_URLStry:import torch._dynamo@@ -1044,32 +1046,12 @@ def add_doctest_deps(doctest_namespace):doctest_namespace["kornia"] = kornia-# Test data commit hashes from kornia/data_test repository-_DATA_TEST_SHA = {- "loftr": "cb8f42bf28b9f347df6afba5558738f62a11f28a",- "adalam": "f7d8da661701424babb64850e03c5e8faec7ea62",- "disk": "8b98f44abbe92b7a84631ed06613b08fee7dae14",- "xfeat": "279e95e411f2d3926953dea3842347242190f4da",-}--# URLs for test data files-_TEST_DATA_URLS: dict[str, str] = {- "loftr_homo": f"https://github.com/kornia/data_test/blob/{_DATA_TEST_SHA['loftr']}/loftr_outdoor_and_homography_data.pt?raw=true",- "loftr_fund": f"https://github.com/kornia/data_test/blob/{_DATA_TEST_SHA['loftr']}/loftr_indoor_and_fundamental_data.pt?raw=true",- "adalam_idxs": f"https://github.com/kornia/data_test/blob/{_DATA_TEST_SHA['adalam']}/adalam_test.pt?raw=true",- "lightglue_idxs": f"https://github.com/kornia/data_test/blob/{_DATA_TEST_SHA['adalam']}/adalam_test.pt?raw=true",- "disk_outdoor": f"https://github.com/kornia/data_test/blob/{_DATA_TEST_SHA['disk']}/knchurch_disk.pt?raw=true",- "xfeat_outdoor": f"https://github.com/kornia/data_test/blob/{_DATA_TEST_SHA['xfeat']}/xfeat_reference.pt?raw=true",- "dexined": "https://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",-}--@pytest.fixture(scope="session")def data(request):"""Load test data from remote URL.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())}")- return torch.hub.load_state_dict_from_url(_TEST_DATA_URLS[request.param], map_location=torch.device("cpu"))+ 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"))diff --git a/testing/reference_data.py b/testing/reference_data.pynew file mode 100644index 000000000..23a66a12d--- /dev/null+++ b/testing/reference_data.py@@ -0,0 +1,57 @@+# 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.+#+++"""Reference tensors the ``data`` fixture in ``conftest.py`` loads.++The table lives here rather than in ``conftest.py`` so that+``tests/core/test_weights_prefetch.py`` can import it as an ordinary module and+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.+"""++from __future__ import annotations++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",+}++_RAW = "https://raw.githubusercontent.com/kornia/data_test"++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.+ "dexined": list(_dexined.url),+}++__all__ = ["DATA_TEST_SHA", "TEST_DATA_URLS"]diff --git a/tests/contrib/test_super_resolution.py b/tests/contrib/test_super_resolution.pyindex b1f04bdc9..4c45fca3e 100644--- a/tests/contrib/test_super_resolution.py+++ b/tests/contrib/test_super_resolution.py@@ -15,6 +15,8 @@# limitations under the License.#+import sys+import pytestimport torch@@ -24,6 +26,7 @@ from kornia.contrib.super_resolution import (SuperResolution,SuperResolutionConfig,)+from kornia.core._compat import torch_version_ltfrom testing.base import BaseTester@@ -87,7 +90,20 @@ class TestSuperResolutionBuilders(BaseTester):@pytest.mark.timeout(120)@pytest.mark.parametrize(("builder", "build_kwargs"),- [(SmallSRBuilder, {}), (RRDBNetBuilder, {"model_name": "RealESRGAN_x4plus_anime_6B"})],+ [+ (SmallSRBuilder, {}),+ pytest.param(+ RRDBNetBuilder,+ {"model_name": "RealESRGAN_x4plus_anime_6B"},+ # torch < 2.9 defaults ``torch.onnx.export`` to the TorchScript exporter, which walks this+ # graph in ~130 s on an Apple Silicon Mac and past the budget on the macOS runners; the+ # dynamo exporter (2.9+) takes ~6 s on the same machine.+ marks=pytest.mark.skipif(+ sys.platform == "darwin" and torch_version_lt(2, 9, 0),+ reason="TorchScript exporter (torch < 2.9) exceeds the 120-second timeout on macOS",+ ),+ ),+ ],ids=["SmallSRBuilder", "RRDBNetBuilder"],)def test_to_onnx_exports(self, builder, build_kwargs):diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.pyindex d18e94d15..4a10ce3e6 100644--- a/tests/core/test_weights_prefetch.py+++ b/tests/core/test_weights_prefetch.py@@ -52,8 +52,11 @@ 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 but comes from no registry, so it is outside this guard as-well; it is small, single-source and fetched once per docs build.+``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+``test_docs_reference_data_matches_the_fixture_table`` holds them to."""from __future__ import annotations@@ -85,6 +88,8 @@ from kornia.models.rt_detr import model as rt_detrfrom kornia.models.sam import model as samfrom kornia.models.yunet import model as yunet+from testing import reference_data+_REPO_ROOT = Path(__file__).resolve().parents[2]_SCRIPT = _REPO_ROOT / ".github" / "download-models-weights.py"@@ -118,6 +123,9 @@ def _load_prefetch_script() -> Any:# a second hand-written copy of these modules is exactly the drift this file# exists to catch.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),"affine_shape": (affine_shape, affine_shape.urls),"orientation": (orientation, orientation.urls),"hardnet": (hardnet, hardnet.urls),@@ -281,6 +289,28 @@ NOT_PREFETCHED: dict[str, str] = {}+# ``kornia/data_test`` file references. The fixture table spells the raw URL with a+# literal commit; a docs script spells ``github.com/.../raw/`` or ``blob/`` with the+# commit either literal or as an f-string field bound by a ``name = "<sha>"`` line.+_DATA_TEST_URL = re.compile(r"raw\.githubusercontent\.com/kornia/data_test/([0-9a-f]{40})/([^\s\"'?]+)")+_DATA_TEST_REF = re.compile(r"github\.com/kornia/data_test/(?:raw|blob)/(\{\w+\}|[0-9a-f]{40})/([^\s\"'?]+)")+_SHA_BINDING = re.compile(r"^\s*(\w+)\s*=\s*[\"']([0-9a-f]{40})[\"']", re.MULTILINE)+++def _data_test_refs(source: str) -> set[tuple[str, str]]:+ """Return every ``(commit, file)`` a script fetches from ``kornia/data_test``.++ An f-string field ``{name}`` resolves through the script's own ``name = "<sha>"``+ binding; one that has no binding is kept verbatim so it fails the comparison+ rather than vanishing from it.+ """+ bindings = dict(_SHA_BINDING.findall(source))+ return {+ (bindings.get(ref[1:-1], ref) if ref.startswith("{") else ref, file)+ for ref, file in _DATA_TEST_REF.findall(source)+ }++# ``download_file_from_url`` and its Hub wrapper ``download_hf_file`` fetch into# the same cache without loading what they fetched, so a checkpoint pulled# through either is as invisible to the prefetch list as one pulled through@@ -479,6 +509,29 @@ 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.++ 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.+ """+ pinned = {+ (m.group(1), m.group(2))+ for url in reference_data.TEST_DATA_URLS.values()+ 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")+ refs = _data_test_refs(docs)+ assert refs, "docs/generate_examples.py no longer fetches from kornia/data_test; retire 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"Update DATA_TEST_SHA in testing/reference_data.py, or the docs script, so the two agree."+ )+def test_no_entry_is_both_prefetched_and_exempt(self) -> None:prefetched = _load_prefetch_script().MODELSoverlap = sorted(set(prefetched) & set(NOT_PREFETCHED))diff --git a/tests/tracking/test_planar_tracking.py b/tests/tracking/test_planar_tracking.pyindex 878d98296..a73a35840 100644--- a/tests/tracking/test_planar_tracking.py+++ b/tests/tracking/test_planar_tracking.py@@ -186,12 +186,6 @@ class TestHomographyTrackerUnit:assert tracker.previous_homography is None # reset_tracking was called-def data_url():- url = "https://github.com/kornia/data_test/blob/main/loftr_outdoor_and_homography_data.pt?raw=true"- return url--class TestHomographyTracker(BaseTester):@pytest.mark.slowdef test_smoke(self, device):@@ -199,15 +193,14 @@ class TestHomographyTracker(BaseTester):assert tracker is not None@pytest.mark.slow- def test_nomatch(self, device, dtype, data_url):- data = torch.hub.load_state_dict_from_url(data_url)+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)+ def test_nomatch(self, device, dtype, data):+ # The fixture is session-scoped and shared; cast into a copy rather than in place.+ data = {k: v.to(device, dtype) if isinstance(v, torch.Tensor) else v for k, v in data.items()}# This is not unit test, but that is quite good integration testmatcher = LocalFeatureMatcher(SIFTFeature(100), DescriptorMatcher("smnn", 0.95)).to(device, dtype)tracker = HomographyTracker(matcher, matcher, minimum_inliers_num=100)- for k in data.keys():- if isinstance(data[k], torch.Tensor):- data[k] = data[k].to(device, dtype)tracker.set_target(data["image0"])torch.random.manual_seed(0)_, success = tracker(torch.zeros_like(data["image0"]))@@ -215,12 +208,11 @@ class TestHomographyTracker(BaseTester):@pytest.mark.slow@pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")- def test_real(self, device, dtype, data_url):- data = torch.hub.load_state_dict_from_url(data_url)+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)+ def test_real(self, device, dtype, data):+ # The fixture is session-scoped and shared; cast into a copy rather than in place.+ data = {k: v.to(device, dtype) if isinstance(v, torch.Tensor) else v for k, v in data.items()}# This is not unit test, but that is quite good integration test- for k in data.keys():- if isinstance(data[k], torch.Tensor):- data[k] = data[k].to(device, dtype)data["image0"] = rescale(data["image0"], 0.5, interpolation="bilinear", align_corners=False)data["image1"] = rescale(data["image1"], 0.5, interpolation="bilinear", align_corners=False)