π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(ci): cache the checkpoints tests request, and make the weight fallback work (#4054)
Dmytro Mishkinf91a96f93d53
diff --git a/.github/download-models-weights.py b/.github/download-models-weights.pyindex a48a4b831..e697f0782 100644--- a/.github/download-models-weights.py+++ b/.github/download-models-weights.py@@ -15,49 +15,161 @@# limitations under the License.#+"""Pre-populate the torch hub cache with the checkpoints CI needs.++CI restores the resulting ``weights/`` directory before the test and doctest+jobs, so a checkpoint listed here is never fetched from inside a test run. One+that is *missing* is fetched live by every matrix cell at once, which is how+unauthenticated jobs trip the rate limits of huggingface.co and github.com and+fail with what looks like a dead URL. ``tests/core/test_weights_prefetch.py``+guards against that: every checkpoint kornia can request must be listed here or+explicitly exempted there.++Keys are the **cache filename** kornia will look for, not a friendly name.+That is usually the basename of the primary URL, but not always -- LightGlue+pins names such as ``superpoint_lightglue_v0-1_arxiv-pth`` -- and a key that+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.+"""+import argparseimport loggingimport osimport torch-logging.basicConfig(level=logging.INFO, format="%(message)s")+from kornia.core.download import load_state_dict_from_url+logger = logging.getLogger(__name__)-# Models used in doctests and tests-# Format: "name": url-# All models use torch.hub.load_state_dict_from_url-MODELS = {- # SOLD2 - line detection- "sold2_wireframe": "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth",- # DexiNed - edge detection (used by EdgeDetector doctest)- "dexined": "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",- # DISK - feature extraction (used by DISK.from_pretrained doctest)- "disk_depth": "https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth",- # DeDoDe - feature detection/description (used by DeDoDe.from_pretrained doctest)- "dedode_detector_L_v2": "https://github.com/Parskatt/DeDoDe/releases/download/v2/dedode_detector_L_v2.pth",- "dedode_descriptor_B_SO2": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/B_SO2_Spread_descriptor_setting_C.pth",- "dedode_descriptor_B_upright": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_B.pth",- "dedode_descriptor_G_upright": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_G.pth",- # DINOv2 - used by DeDoDe encoder- "dinov2_vitl14": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth",- # YuNet - face detection- "yunet": "https://github.com/kornia/data/raw/main/yunet_final.pth",- # RT-DETR - object detection (used by RTDETR.from_pretrained doctest)- "rtdetr_r18vd": "https://github.com/lyuwenyu/storage/releases/download/v0.1/rtdetr_r18vd_dec3_6x_coco_from_paddle.pth",- # VisionTransformer - used by VisionTransformer.from_config doctest- "vit_b_16": "https://huggingface.co/kornia/vit_b16_augreg_i21k_r224/resolve/main/vit_b-16.pth",- # LocalFeatureMatcher - AffNet and HardNet (used by LocalFeatureMatcher doctest)- "affnet": "https://github.com/ducha-aiki/affnet/raw/master/pretrained/AffNet.pth",- "hardnet_liberty": "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth",- # LoFTR - feature matching (used by LoFTR doctest)- "loftr_outdoor": "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_outdoor.ckpt",- # MKD - descriptor (used by MKDDescriptor doctest)- "mkd_concat": "https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-concat-64.pth",+# Format: "<cache filename>": "<url>" | ["<primary url>", "<fallback url>"]+MODELS: dict[str, "str | list[str]"] = {+ # -- detectors, descriptors and orientation estimators -------------------+ # AffNet + OriNet: LAFAffNetShapeEstimator / LAFOrienter, and every composite+ # built on them (GFTTAffNetHardNet, KeyNetHardNet, KeyNetAffNetHardNet).+ "AffNet.pth": [+ "https://huggingface.co/kornia/affnet/resolve/main/AffNet.pth",+ "https://github.com/ducha-aiki/affnet/raw/master/pretrained/AffNet.pth",+ ],+ "OriNet.pth": [+ "https://huggingface.co/kornia/orinet/resolve/main/OriNet.pth",+ "https://github.com/ducha-aiki/affnet/raw/master/pretrained/OriNet.pth",+ ],+ # KeyNet detector: KeyNetDetector(True), used by KeyNetHardNet.+ "keynet_pytorch.pth": [+ "https://huggingface.co/kornia/keynet/resolve/main/keynet_pytorch.pth",+ "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth",+ ],+ # HardNet: the default descriptor of LAFDescriptor, so nearly every composite.+ "checkpoint_liberty_with_aug.pth": [+ "https://huggingface.co/kornia/hardnet/resolve/main/checkpoint_liberty_with_aug.pth",+ "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/"+ "checkpoint_liberty_with_aug.pth",+ ],+ # Patch descriptors with pretrained smoke/jit tests.+ "HyNet_LIB.pth": [+ "https://huggingface.co/kornia/hynet/resolve/main/HyNet_LIB.pth",+ "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_LIB.pth",+ ],+ "sosnet_32x32_liberty.pth": [+ "https://huggingface.co/kornia/sosnet/resolve/main/sosnet_32x32_liberty.pth",+ "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/sosnet_32x32_liberty.pth",+ ],+ "tfeat-liberty.params": [+ "https://huggingface.co/kornia/tfeat/resolve/main/tfeat-liberty.params",+ "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params",+ ],+ # MKD whitening models: TestMKDDescriptor parametrizes over all three kernels.+ "mkd-concat-64.pth": "https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-concat-64.pth",+ "mkd-polar-64.pth": "https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-polar-64.pth",+ "mkd-cart-64.pth": "https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-cart-64.pth",+ # DISK - feature extraction (DISK.from_pretrained doctest and tests)+ "depth-save.pth": [+ "https://huggingface.co/kornia/disk/resolve/main/depth-save.pth",+ "https://raw.githubusercontent.com/cvlab-epfl/disk/master/depth-save.pth",+ ],+ # -- matchers ------------------------------------------------------------+ # 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",+ ],+ "loftr_indoor.ckpt": [+ "https://huggingface.co/kornia/loftr/resolve/main/loftr_indoor.ckpt",+ "http://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": [+ "https://huggingface.co/kornia/lightglue/resolve/main/superpoint_lightglue.pth",+ "https://github.com/cvg/LightGlue/releases/download/v0.1_arxiv/superpoint_lightglue.pth",+ ],+ "doghardnet_v0-1_arxiv-pth": [+ "https://huggingface.co/kornia/lightglue/resolve/main/doghardnet_lightglue.pth",+ "https://github.com/cvg/LightGlue/releases/download/v0.1_arxiv/doghardnet_lightglue.pth",+ ],+ "disk_lightglue_v0-1_arxiv-pth": [+ "https://huggingface.co/kornia/lightglue/resolve/main/disk_lightglue.pth",+ "https://github.com/cvg/LightGlue/releases/download/v0.1_arxiv/disk_lightglue.pth",+ ],+ # -- DeDoDe --------------------------------------------------------------+ # Only the pair the ``DeDoDe.from_pretrained`` doctest builds: ``TestDeDoDe``+ # is skipped outright, so every other variant -- and the 1.2 GB DINOv2+ # backbone the G descriptor pulls -- would be cached for nothing.+ "dedode_detector_L_v2.pth": [+ "https://huggingface.co/kornia/dedode/resolve/main/dedode_detector_L_v2.pth",+ "https://github.com/Parskatt/DeDoDe/releases/download/v2/dedode_detector_L_v2.pth",+ ],+ "dedode_descriptor_B.pth": [+ "https://huggingface.co/kornia/dedode/resolve/main/dedode_descriptor_B.pth",+ "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_B.pth",+ ],+ # -- 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",+ ],+ "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",+ ],+ "yunet_final.pth": [+ "https://huggingface.co/kornia/yunet/resolve/main/yunet_final.pth",+ "https://github.com/kornia/data/raw/main/yunet_final.pth",+ ],+ "rtdetr_r18vd_dec3_6x_coco_from_paddle.pth": [+ "https://huggingface.co/kornia/rt_detr/resolve/main/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",+ ],+ "vit_b-16.pth": "https://huggingface.co/kornia/vit_b16_augreg_i21k_r224/resolve/main/vit_b-16.pth",+ # ALIKED and XFeat: no pytest job builds them pretrained, but+ # ``generate_examples.main`` does, once per docs build, and the docs job+ # restores this same cache.+ "aliked-n16.pth": [+ "https://huggingface.co/kornia/aliked/resolve/main/aliked-n16.pth",+ "https://github.com/Shiaoming/ALIKED/raw/main/models/aliked-n16.pth",+ ],+ "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",+ ],}if __name__ == "__main__":+ # Configured here rather than at import time: the drift guard imports this+ # file to read MODELS, and a test helper has no business installing a handler+ # on the root logger for the rest of the session.+ logging.basicConfig(level=logging.INFO, format="%(message)s")+parser = argparse.ArgumentParser("WeightsDownloader")parser.add_argument("--target_directory", "-t", required=False, default="weights")@@ -70,11 +182,28 @@ if __name__ == "__main__":logger.info(f"Downloading models to: {torch.hub.get_dir()}/checkpoints/")- for name, url in MODELS.items():- logger.info(f"Downloading `{name}` from `{url}`...")- # Don't pass model_dir - use the default from torch.hub.set_dir()- # This ensures files go to {hub_dir}/checkpoints/ matching test behavior- torch.hub.load_state_dict_from_url(url, map_location=torch.device("cpu"))+ # A failure is recorded rather than raised, so one run reports every dead+ # source instead of the first one and then stopping -- with two sources and+ # three attempts each behind every entry, finding them one push at a time is+ # expensive. The exit code still fails the job: ``actions/cache`` does not+ # save on a failed job, and the test matrix is gated on this one+ # (``needs: [pre-tests]``), so a missing checkpoint stops CI rather than+ # letting every matrix cell fetch it live.+ failed: list[str] = []+ for file_name, url in MODELS.items():+ logger.info(f"Downloading `{file_name}` from `{url if isinstance(url, str) else url[0]}`...")+ try:+ # 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)+ 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)++ if failed:+ logger.error(f"{len(failed)} of {len(MODELS)} checkpoints could not be downloaded: {failed}")+ raise SystemExit(1)logger.info("All models downloaded successfully!")raise SystemExit(0)diff --git a/docs/source/conf.py b/docs/source/conf.pyindex 3f450101a..a59998feb 100644--- a/docs/source/conf.py+++ b/docs/source/conf.py@@ -59,6 +59,23 @@ except AttributeError:sphinx_autodoc_defaultargs = None+# ``generate_examples.main`` builds four pretrained models (KeyNet, DISK, ALIKED+# and XFeat), so this build fetches checkpoints from the same rate-limited hosts+# the test jobs do. CI restores the shared ``weights/`` cache for this job, but+# nothing here is running under ``conftest.py``, which is what points torch at+# it for the test and doctest runs -- so point at it here too, or the cache is+# restored and then ignored. Sphinx executes this file with the working+# directory set to its own folder, hence the path off ``__file__``.+import torch.hub # noqa: E402++_weights_cache = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "weights")+# Only when there is a restored cache to use and the developer has not pointed+# torch somewhere themselves: a local ``pixi run build-docs`` in a fresh clone has+# neither, and redirecting it would re-download all four checkpoints past a warm+# ``~/.cache/torch/hub``.+if os.path.isdir(_weights_cache) and not os.environ.get("TORCH_HOME"):+ torch.hub.set_dir(_weights_cache)+# readthedocs generated the whole documentation in an isolated environment# by cloning the git repo. Thus, any on-the-fly operation will not effect# on the resulting documentation. We therefore need to import and run thediff --git a/kornia/core/download.py b/kornia/core/download.pyindex 954162bf3..216c374d3 100644--- a/kornia/core/download.py+++ b/kornia/core/download.py@@ -17,11 +17,17 @@from __future__ import annotations+import http.client+import mathimport osimport sys+import timeimport warnings+from datetime import UTC, datetime+from email.utils import parsedate_to_datetimefrom pathlib import Pathfrom typing import Any+from urllib.error import HTTPError, URLErrorfrom urllib.parse import urlparseimport torch@@ -47,6 +53,211 @@ def hf_url(repo: str, filename: str) -> str:return f"{_HF_KORNIA_BASE}/{repo}/resolve/main/{filename}"+_TRANSIENT_HTTP_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})+"""HTTP statuses worth another attempt: request timeout, too early, rate limit, server errors."""++_RATE_LIMIT_HTTP_STATUS = frozenset({403, 429})+"""Statuses a host may use to signal rate limiting.++429 is unambiguous and already transient above. 403 is not: GitHub documents it+as the *other* status it exceeds a rate limit with, while it is also the plain+"you may not have this file" answer that must never be retried. Only the+rate-limit headers separate the two, so 403 is transient exactly when they say+so -- see :func:`_rate_limited`.+"""++_MAX_ATTEMPTS = 3+"""Total attempts per URL, including the first."""++_BACKOFF_SECONDS = 1.0+"""Delay before the second attempt; doubled for each further one."""++_MAX_BACKOFF_SECONDS = 60.0+"""Ceiling on a single wait, including one a server asks for.++A host may name a delay of many minutes. Honouring it literally would hold a CI+job open far longer than refetching the checkpoint costs, so the request is+clamped: the wait is capped and the attempt made anyway.+"""++_MAX_CALL_SLEEP_SECONDS = 60.0+"""Ceiling on the *total* time one call may spend waiting between attempts.++Clamping each wait individually does not bound the call: two retries per URL+across a two-source list is four waits, so a host asking for the maximum on each+would hold a single :func:`load_state_dict_from_url` call open for+4 x :data:`_MAX_BACKOFF_SECONDS`, and a test module that builds the same model+five times would multiply that again. Retrying exists to ride out a *brief*+limit; once a call has spent this much of its life asleep the limit is not+brief, and failing over to the next source -- or out to the caller with the+cause named -- beats waiting longer. The budget is per call rather than per+process so that a long-lived process is never left permanently unable to retry.+"""+++class _SleepBudget:+ """The time a single call may spend waiting between attempts."""++ def __init__(self, seconds: float) -> None:+ self.remaining = seconds++ def sleep(self, delay: float) -> None:+ """Wait *delay* seconds and charge it to the budget."""+ self.remaining -= delay+ time.sleep(delay)+++def _rate_limited(exc: HTTPError) -> bool:+ """Return whether *exc*'s headers mark it as a rate-limit response.++ Args:+ exc: the HTTP error raised by a download attempt.++ Returns:+ ``True`` if the status is one hosts use for rate limiting *and* the+ response carries a header that only a rate limit sets.+ """+ if exc.code not in _RATE_LIMIT_HTTP_STATUS:+ return False+ headers = getattr(exc, "headers", None)+ if headers is None:+ return False+ if headers.get("Retry-After") is not None:+ return True+ remaining = headers.get("X-RateLimit-Remaining")+ return remaining is not None and remaining.strip() == "0"+++def _retry_after_seconds(value: str) -> float | None:+ """Parse a ``Retry-After`` header value into a delay in seconds.++ Args:+ value: the header value, either a number of seconds or an HTTP date.++ Returns:+ The delay in seconds, or ``None`` if the value parses as neither form.+ """+ value = value.strip()+ try:+ return _usable_delay(float(value))+ except ValueError:+ pass+ try:+ when = parsedate_to_datetime(value) # raises on a malformed date since 3.10+ except (TypeError, ValueError):+ return None+ if when.tzinfo is None: # an HTTP date is GMT even when it omits the offset+ when = when.replace(tzinfo=UTC)+ return _usable_delay((when - datetime.now(UTC)).total_seconds())+++def _usable_delay(seconds: float) -> float | None:+ """Return *seconds* if it is a delay worth waiting, else ``None``.++ ``Retry-After: nan`` parses as a float and would reach :func:`time.sleep`,+ which raises ``ValueError`` on a NaN -- from inside the retry handler, so the+ rate limit that sent the header would never be retried at all. A non-positive+ result is no guidance either: a date already in the past, or an+ ``X-RateLimit-Reset`` a host expressed as a delta rather than the epoch+ GitHub uses, would otherwise fire every remaining attempt back to back.+ """+ if not math.isfinite(seconds) or seconds <= 0.0:+ return None+ return seconds+++def _server_requested_delay(exc: BaseException) -> float | None:+ """Return the delay *exc*'s host asked for before the next request.++ Args:+ exc: the exception raised by a download attempt.++ Returns:+ The requested delay in seconds, or ``None`` if the response carried no+ usable guidance.+ """+ if not isinstance(exc, HTTPError):+ return None+ headers = getattr(exc, "headers", None)+ if headers is None:+ return None++ # ``Retry-After`` is defined for every status that can carry it -- 503 and 408+ # are its canonical uses, not just the rate limits -- so it is read whenever+ # the host sends one. A header that does not parse, or whose date has already+ # passed, is no guidance at all, so it falls through to the branch below+ # rather than answering ``None`` for the whole function.+ retry_after = headers.get("Retry-After")+ if retry_after is not None and (delay := _retry_after_seconds(retry_after)) is not None:+ return delay++ # ``X-RateLimit-Reset`` is different: GitHub attaches it to *every* response,+ # including ones nothing is limiting, and it points at the end of the current+ # window -- up to an hour out. Reading it off an unrelated 500 would turn a+ # one-second retry into the full clamp, so it speaks only for a response the+ # limit headers themselves mark as rate limited.+ if not _rate_limited(exc):+ return None+ reset = headers.get("X-RateLimit-Reset") # an epoch timestamp, GitHub's form+ if reset is None:+ return None+ try:+ return _usable_delay(float(reset.strip()) - time.time())+ except ValueError:+ return None+++def _retry_delay(exc: BaseException, attempt: int) -> float:+ """Return how long to wait before *attempt* + 1, honouring the server when it says.++ Exponential backoff is a guess; ``Retry-After`` and ``X-RateLimit-Reset`` are+ the host telling us when it will serve again. Retrying before then only+ spends another request against the same limit, and waiting far longer than+ asked wastes the job -- so the server's number wins where it is given,+ clamped to :data:`_MAX_BACKOFF_SECONDS`.++ Args:+ exc: the failure that is about to be retried.+ attempt: the 1-based number of the attempt that just failed.++ Returns:+ The delay in seconds.+ """+ requested = _server_requested_delay(exc)+ if requested is None:+ return _BACKOFF_SECONDS * 2 ** (attempt - 1)+ return min(requested, _MAX_BACKOFF_SECONDS)+++def _is_transient(exc: BaseException) -> bool:+ """Return whether *exc* is a temporary network condition worth retrying.++ Rate limiting is the motivating case. An unauthenticated CI matrix fans many+ jobs out at once, which regularly trips the anonymous request limits of+ huggingface.co and github.com even though the checkpoint is served normally a+ moment later.++ Every :class:`~urllib.error.URLError` counts, ``exc.reason`` included: DNS+ resolution and "network is unreachable" fail this way and are as often a+ momentary condition as a permanent one. The cost of not separating them is+ that an offline run with a cold cache waits out its retries before reporting+ the same error, which the per-call sleep budget bounds.++ Args:+ exc: the exception raised by a download attempt.++ Returns:+ ``True`` if another attempt could plausibly succeed.+ """+ if isinstance(exc, HTTPError): # a subclass of URLError, so it must be tested first+ return exc.code in _TRANSIENT_HTTP_STATUS or _rate_limited(exc)+ # IncompleteRead is a mid-transfer truncation of a chunked response. It+ # inherits from HTTPException alone -- neither URLError nor ConnectionError --+ # so it needs naming, or a truncation burns the fallback instead of retrying+ # the source that was already serving.+ return isinstance(exc, (URLError, TimeoutError, ConnectionError, http.client.IncompleteRead))++def _cached_file_path(url: str, kwargs: dict[str, Any]) -> str:"""Return the path :func:`torch.hub.load_state_dict_from_url` would cache *url* at.@@ -64,11 +275,15 @@ def _cached_file_path(url: str, kwargs: dict[str, Any]) -> str:model_dir = kwargs.get("model_dir")if model_dir is None:model_dir = os.path.join(torch.hub.get_dir(), "checkpoints")- filename = kwargs.get("file_name") or os.path.basename(urlparse(url).path)+ # ``is not None``, not truthiness: this must agree with torch, which pins the+ # name whenever ``file_name`` is not None, and with the pin in+ # :func:`load_state_dict_from_url`, which decides on the same test.+ file_name = kwargs.get("file_name")+ filename = file_name if file_name is not None else os.path.basename(urlparse(url).path)return os.path.join(model_dir, filename)-def _prefetch_to_cache(url: str, kwargs: dict[str, Any]) -> None:+def _prefetch_to_cache(url: str, kwargs: dict[str, Any]) -> bool:"""Download *url* into the torch hub cache if it is not already there.Doing the fetch here rather than letting :func:`torch.hub.load_state_dict_from_url`@@ -83,10 +298,15 @@ def _prefetch_to_cache(url: str, kwargs: dict[str, Any]) -> None:kwargs: the keyword arguments destined for the torch function;``model_dir``, ``file_name``, ``check_hash`` and ``progress`` arehonoured so the cache entry is identical to torch's.++ Returns:+ Whether a transfer happened. A cache hit returns ``False``, which is how+ :func:`load_state_dict_from_url` tells a source that was really fetched+ from one that was handed the file already on disk."""cached_file = _cached_file_path(url, kwargs)if os.path.exists(cached_file):- return+ return Falseos.makedirs(os.path.dirname(cached_file), exist_ok=True)@@ -98,6 +318,219 @@ def _prefetch_to_cache(url: str, kwargs: dict[str, Any]) -> None:# torch writes this to stdout; status output belongs on stderr.sys.stderr.write(f'Downloading: "{url}" to {cached_file}\n')torch.hub.download_url_to_file(url, cached_file, hash_prefix, progress=kwargs.get("progress", True))+ return True+++_DISCARDED_CACHE_PATHS: set[str] = set()+"""Cache paths already refetched once in this process; see :func:`_discard_cache_entry`."""++_QUARANTINE_SUFFIX = ".kornia-discarded"+"""Suffix a discarded cache entry is renamed with while its replacement is fetched.++Nothing ever reads a file under this name -- :func:`_prefetch_to_cache` looks+only at the real cache path -- so a process killed between the rename and+:func:`_settle_quarantine` leaves a stray file rather than a broken cache, and+the next discard of the same path overwrites it.+"""+++def _discard_cache_entry(url: str, kwargs: dict[str, Any]) -> str | None:+ """Move the cache entry for *url* aside, at most once per path per process.++ Every URL in a fallback list resolves to the same path, because the cache+ filename is pinned to the primary URL (see :func:`load_state_dict_from_url`).+ A single bad write -- a truncated transfer, or an HTML rate-limit page served+ with a 200 -- would therefore make :func:`_prefetch_to_cache` short-circuit on+ each remaining source and hand torch the same broken file every time. The+ fallback URLs could never take effect, and because the bad file survives the+ process, the failure would repeat on every later run until the cache was+ cleared by hand.++ The entry is *renamed*, not deleted, because a load failure cannot tell a+ corrupt cache entry from a healthy one that failed for an unrelated reason --+ a bad ``map_location``, a ``weights_only`` rejection -- and a delete would+ sometimes destroy an intact checkpoint, several of which are over a gigabyte.+ Renaming makes the discard reversible; :func:`_settle_quarantine` owns the+ decision and documents it. Within the same directory the rename is a metadata+ operation, so the size of the checkpoint does not matter.++ Gating the discard on the exception type instead was considered and does not+ work. The types do not separate the two classes (torch 2.9.1): an HTML+ rate-limit page served with a 200 -- the case that motivated this function --+ and a ``weights_only`` rejection of a perfectly good file both raise+ ``UnpicklingError``, while a truncated zip checkpoint raises a bare+ ``RuntimeError``. A gate would discard the healthy entry it was meant to+ spare and keep the commonest corruption there is.++ What is bounded instead is the *refetch*: one per cache path per process,+ tracked in :data:`_DISCARDED_CACHE_PATHS`. Without that, a failure the cache+ cannot fix would re-download the checkpoint on every call, once per test that+ builds the model -- the download storm this module exists to prevent, reached+ from the other side.++ Neither the ledger nor the rename is synchronised: two threads loading the+ same checkpoint through one poisoned entry can have one of them find the path+ already moved aside and fail where a single thread would have recovered. The+ entry itself is never left in a worse state, and nothing in kornia loads one+ checkpoint concurrently, so a lock is not worth its deadlock surface here.++ Args:+ url: the URL whose cache entry should be moved aside.+ kwargs: the keyword arguments destined for the torch function; only+ ``model_dir`` and ``file_name`` are consulted.++ Returns:+ The path the entry was moved to, or ``None`` if there was nothing to move+ or the bound is already spent. The caller needs this to hand to+ :func:`_settle_quarantine`, and to know which source was denied a real+ fetch by the entry that is now out of the way.+ """+ path = _cached_file_path(url, kwargs)+ if path in _DISCARDED_CACHE_PATHS:+ return None++ quarantine = f"{path}{_QUARANTINE_SUFFIX}"+ try:+ os.replace(path, quarantine)+ except FileNotFoundError:+ # The transfer itself failed, so there is nothing to set aside -- and+ # nothing was refetched either, so the one allowed discard stays unspent.+ return None+ except OSError as e:+ # A read-only cache, or a Windows reader holding the file open. Renaming+ # it again would fail the same way, so the ledger is marked either way,+ # but a fallback that can never be reached is worth saying out loud.+ warnings.warn(+ f"Could not discard the cache entry at {path}: {e}. If that file is corrupt, "+ f"the fallback sources cannot take effect until it is deleted by hand.",+ stacklevel=3,+ )+ # The entry is still there and still unloadable. Marking the ledger stops+ # a rename that can only fail the same way from being tried again, and a+ # re-attempt would just reload the very file that failed.+ _DISCARDED_CACHE_PATHS.add(path)+ return None++ _DISCARDED_CACHE_PATHS.add(path)+ return quarantine+++def _settle_quarantine(path: str, quarantine: str, *, loaded: bool, downloaded: bool) -> None:+ """Resolve a quarantined cache entry once every source has had its turn.++ The decision is the *outcome of the call*, never what happens to be sitting+ at *path*. Whether a file is there says only that some source wrote one, not+ that it is any good: a rate-limited mirror serving an HTML page with a 200+ puts a file there, and settling on its presence would drop the quarantined+ original in its favour -- destroying an intact multi-gigabyte checkpoint+ behind a ``map_location='cuda'`` failure on a CPU-only build, which is the+ very case renaming rather than deleting exists to survive.++ So:++ * *loaded*: whatever is at *path* is what just loaded, so the quarantined+ copy is the one that failed and is dropped.+ * not *loaded*: everything tried failed, including anything a source wrote,+ so nothing on disk is known-good and the pre-call state is the safest one+ to leave behind. The original is moved back over whatever is there, and+ the caller ends the call with the cache it started with.++ The bound in :data:`_DISCARDED_CACHE_PATHS` counts *successful refetches*, so+ a failed call releases it again unless a source really did transfer the file.+ Otherwise the first offline call in a process would spend the single allowed+ discard on a path it could not repair, and a later call -- with the network+ back -- could never clear a genuinely poisoned entry.++ Args:+ path: the cache path the entry was moved out of.+ quarantine: the path :func:`_discard_cache_entry` moved it to.+ loaded: whether the call is returning a state dict.+ downloaded: whether any source transferred the file during the call.+ """+ if loaded:+ try:+ os.remove(quarantine)+ except OSError as e: # pragma: no cover - a cache that cannot be written to+ warnings.warn(f"Could not remove the discarded cache entry at {quarantine}: {e}.", stacklevel=3)+ return++ try:+ os.replace(quarantine, path) # atomically overwrites whatever a source left there+ except OSError as e: # pragma: no cover - a cache that cannot be written to+ warnings.warn(+ f"Could not restore the cache entry at {path} from {quarantine}: {e}. "+ f"Move it back by hand to avoid re-downloading the checkpoint.",+ stacklevel=3,+ )+ return+ if not downloaded:+ _DISCARDED_CACHE_PATHS.discard(path)+++def _drop_failed_download(path: str) -> None:+ """Delete bytes the current source transferred and then failed to load.++ Nothing is quarantined here: the file did not exist before this source wrote+ it -- :func:`_prefetch_to_cache` only transfers into an empty path -- so there+ is no earlier state to preserve and nothing to weigh it against. Setting it+ aside instead would put it *back* in :func:`_settle_quarantine`, leaving the+ caller a poisoned entry where the call found none, with the one allowed+ discard spent on it, so no later call in the process could clear it. Deleting+ returns the path to the state the call found, which is also the empty path the+ next source needs in order to be fetched at all.++ Only called while a later source remains; see :func:`load_state_dict_from_url`+ for why the final source keeps what it wrote.++ Args:+ path: the cache path this source just wrote.+ """+ try:+ os.remove(path)+ except FileNotFoundError: # pragma: no cover - torch removed it itself+ pass+ except OSError as e: # pragma: no cover - a cache that cannot be written to+ warnings.warn(+ f"Could not remove the failed download at {path}: {e}. "+ f"Delete it by hand if the fallback sources stop taking effect.",+ stacklevel=3,+ )+++def _prefetch_with_retry(url: str, kwargs: dict[str, Any], budget: _SleepBudget) -> bool:+ """Run :func:`_prefetch_to_cache`, retrying transient failures with backoff.++ Args:+ url: the URL to fetch.+ kwargs: the keyword arguments destined for the torch function.+ budget: the waiting time the whole call has left; a retry that would+ exceed it is not taken.++ Returns:+ Whether a transfer happened; see :func:`_prefetch_to_cache`.++ Raises:+ Exception: the last failure, once the attempts are exhausted, the failure+ is not transient, or the call has no waiting time left.+ """+ for attempt in range(1, _MAX_ATTEMPTS + 1):+ try:+ return _prefetch_to_cache(url, kwargs)+ except Exception as e:+ if attempt == _MAX_ATTEMPTS or not _is_transient(e):+ raise+ delay = _retry_delay(e, attempt)+ if delay > budget.remaining:+ raise+ warnings.warn(+ f"Transient failure fetching {url!r}: {e}. Retrying in {delay:.0f}s "+ f"(attempt {attempt + 1} of {_MAX_ATTEMPTS}).",+ # 1 = here, 2 = load_state_dict_from_url, 3 = its caller, which is+ # the frame the sibling warning below also points at.+ stacklevel=3,+ )+ budget.sleep(delay)+ raise AssertionError("unreachable: the loop above always returns or raises") # pragma: no coverdef load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Any]:@@ -135,6 +568,38 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, Athe hash embedded in it β of the primary URL consistently across allfallback attempts.+ Because that one path is shared, a failed attempt moves the cache entry aside+ before the next URL is tried. Otherwise a single bad write would be handed+ straight back to torch by every remaining source -- and by every later+ process -- making the fallback URLs unreachable. If no source ends up+ transferring the file, the source the entry was moved aside for is tried once+ more, this time against an empty path, so a poisoned entry is repaired inside+ the call rather than after one guaranteed spurious failure -- which matters+ most for the single-source checkpoints, where there is no fallback to do it.+ Should the call still fail, the entry is put back, so a failure the cache+ could not have fixed never costs the caller a checkpoint it already had. A+ path is refetched at most once per process this way; see+ :func:`_discard_cache_entry` and :func:`_settle_quarantine`.++ Only an entry that *predates* the call is ever quarantined. Bytes a source+ transferred itself and then could not load are not something the caller had,+ so there is nothing to make reversible: they are deleted outright while a+ later source remains, which is what hands that source an empty path to fetch+ into (see :func:`_drop_failed_download`). After the last source they are left+ where they are -- deleting them would make every later call in the process+ transfer the file again, unbounded and up to 2.4 GB a time, to fail in the+ same way -- but no discard is spent on them either, so the next call can still+ move them aside and reach the sources behind them.++ Each URL is attempted up to :data:`_MAX_ATTEMPTS` times, with exponential+ backoff, when it fails with a transient network condition such as an HTTP+ 429. Unauthenticated CI matrices trip the rate limits of huggingface.co and+ github.com routinely, and a retry is far cheaper than a failed job. A+ response that names its own delay in ``Retry-After`` -- or, on a rate-limit+ response, ``X-RateLimit-Reset`` -- is honoured instead of the guess, clamped+ to :data:`_MAX_BACKOFF_SECONDS`, and the call as a whole never waits longer+ than :data:`_MAX_CALL_SLEEP_SECONDS`.+Args:url: a URL string, or a list of URL strings tried left-to-right.**kwargs: forwarded verbatim to@@ -145,7 +610,14 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, AThe loaded state dict.Raises:- RuntimeError: if every URL fails, chaining the last exception.+ RuntimeError: if every URL fails. The message carries the failing+ exception's type and text, the source it came from and the cache path in play, and the+ exception itself is chained; without them a rate limit is+ indistinguishable from a dead link in a CI failure summary, and a+ caller stuck behind a corrupt entry has no file to delete. Where a+ load failure set the cache entry aside and the refetch then failed+ too, the load failure is the one reported and chained, and the+ refetch failure rides along as context.Example:>>> sd = load_state_dict_from_url([ # doctest: +SKIP@@ -158,23 +630,98 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, A# 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:+ # ``is None`` rather than ``not in``: an explicit ``file_name=None`` means+ # "use the basename", which for a list of URLs is a *different* path per+ # source, while the quarantine below can only cover one. Pinning on the same+ # test :func:`_cached_file_path` uses is what makes the one-path claim true.+ if len(urls) > 1 and kwargs.get("file_name") is None:kwargs["file_name"] = Path(urlparse(urls[0]).path).name+ # Every URL resolves to this one path, so a single quarantine covers the call.+ cache_path = _cached_file_path(urls[0], kwargs)+ budget = _SleepBudget(_MAX_CALL_SLEEP_SECONDS)+ quarantine: str | None = None+ discarded_url: str | None = None+ discard_exc: Exception | None = None+ downloaded = Falselast_exc: Exception | None = None- for i, u in enumerate(urls):- try:- # Populate the cache ourselves so torch's stdout line is never reached.- _prefetch_to_cache(u, kwargs)- 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,- )+ last_url: str | None = None+ sources = urls+ re_attempted = False+ try:+ while True:+ for i, u in enumerate(sources):+ fetched = False+ more_sources = i < len(sources) - 1+ try:+ # Populate the cache ourselves so torch's stdout line is never reached.+ fetched = _prefetch_with_retry(u, kwargs, budget)+ downloaded |= fetched+ state_dict = torch.hub.load_state_dict_from_url(u, **kwargs)+ except Exception as e: # noqa: BLE001+ last_exc, last_url = e, u+ if fetched:+ # These bytes are this source's own transfer, not an entry+ # the call found, so there is nothing to preserve and the+ # quarantine -- which exists to make a discard reversible --+ # does not apply. Drop them when a later source can use the+ # emptied path; otherwise leave them, and leave the bound+ # unspent so a later call can still discard them.+ if more_sources:+ _drop_failed_download(cache_path)+ else:+ # Whatever is in the cache is not loadable, and every remaining+ # URL shares its path. Move it aside so the next source is really+ # fetched; it comes back below if none of them manages that.+ moved = _discard_cache_entry(u, kwargs)+ if moved is not None:+ quarantine, discarded_url, discard_exc = moved, u, e+ if more_sources:+ warnings.warn(+ f"Failed to load weights from {u!r}: {e}. Trying next source.",+ stacklevel=2,+ )+ continue+ if quarantine is not None:+ _settle_quarantine(cache_path, quarantine, loaded=True, downloaded=downloaded)+ quarantine = None+ return state_dict++ # A discard that nothing refetched is pure loss: the source it fired+ # for was handed the bad file instead of being fetched, and no later+ # source replaced it either -- the last URL of a list has nothing+ # after it, and a mirror that is dead or offline writes nothing. Give+ # that one source the fetch it never got. The ledger is already spent+ # on this path, so this stays one extra pass per path per process, and+ # a poisoned entry recovers inside the call rather than after one+ # guaranteed spurious failure.+ if re_attempted or discarded_url is None or downloaded:+ break+ sources = [discarded_url]+ re_attempted = True+ finally:+ if quarantine is not None:+ _settle_quarantine(cache_path, quarantine, loaded=False, downloaded=downloaded)++ # The re-attempt pass runs only when nothing transferred, so if it also failed+ # without transferring, ``last_exc`` is a refetch failure sitting on top of the+ # load failure that fired the discard -- and that load failure is the one thing+ # naming what actually went wrong. Reporting the network instead points the+ # caller at a checkpoint that is intact and, offline, restored by the ``finally``+ # above. The refetch failure is still worth stating, as context.+ refetch_note = ""+ if re_attempted and not downloaded and discard_exc is not None:+ refetch_note = (+ f" (the cache entry was set aside and refetching it from that same source "+ f"failed too: {type(last_exc).__name__}: {last_exc})"+ )+ last_exc, last_url = discard_exc, discarded_urlraise RuntimeError(- f"Failed to load weights from all {len(urls)} source(s). Last URL tried: {urls[-1]!r}"+ f"Failed to load weights from all {len(urls)} source(s). "+ f"Last URL tried: {last_url!r}. "+ f"Last error: {type(last_exc).__name__}: {last_exc}{refetch_note}. "+ # Unquoted: the point of naming the path is that it can be pasted into+ # ``rm``/``del``, and ``repr`` doubles every backslash of a Windows path.+ f"Cache path: {cache_path} -- delete it if it is corrupt and this repeats.") from last_excdiff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.pyindex e142512a4..16e109cfd 100644--- a/kornia/feature/dedode/encoder.py+++ b/kornia/feature/dedode/encoder.py@@ -24,6 +24,13 @@ from kornia.core.download import load_state_dict_from_urlfrom .vgg import vgg19_bn+# Module level, like every other weight registry in kornia, so the CI weights+# cache can enumerate it -- see tests/core/test_weights_prefetch.py. The DeDoDe+# G descriptor pulls this backbone in, so CI needs it cached.+urls: dict[str, str] = {+ "dinov2_vitl14": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth"+}+class VGG19(nn.Module):"""Implement the VGG19 encoder for feature encoding.@@ -76,9 +83,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 = load_state_dict_from_url(- "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth", map_location="cpu"- )+ dinov2_weights = load_state_dict_from_url(urls["dinov2_vitl14"], map_location="cpu")from .transformer import vit_largevit_kwargs = dict(diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.pyindex f1a4c8c6a..8dbcba1a9 100644--- a/kornia/feature/disk/disk.py+++ b/kornia/feature/disk/disk.py@@ -27,6 +27,19 @@ from ._unets import Unetfrom .detector import heatmap_to_keypointsfrom .structs import DISKFeatures+# Module level, like every other weight registry in kornia, so the CI weights+# cache can enumerate it -- see tests/core/test_weights_prefetch.py.+urls: dict[str, list[str]] = {+ "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",+ ],+}+class DISK(nn.Module):r"""nn.Module which detects and described local features in an image using the DISK method.@@ -144,17 +157,6 @@ class DISK(nn.Module):The pretrained model."""- urls = {- "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:raise ValueError(f"Unknown pretrained model: {checkpoint}")diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.pyindex ba853938b..9502f0ab1 100644--- a/kornia/models/sam/model.py+++ b/kornia/models/sam/model.py@@ -55,6 +55,19 @@ class SamModelType(Enum):mobile_sam = 3+# Module level, like every other weight registry in kornia, so the CI weights+# cache can enumerate it -- see tests/core/test_weights_prefetch.py.+urls: dict[SamModelType, str | list[str]] = {+ 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: [+ hf_url("mobile_sam", "mobile_sam.pt"),+ "https://github.com/ChaoningZhang/MobileSAM/raw/a509aac54fdd7af59f843135f2f7cee307283c88/weights/mobile_sam.pt",+ ],+}++@dataclassclass SamConfig:"""Encapsulate the Config to build a SAM model.@@ -225,15 +238,7 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):checkpoint = config.checkpointif config.pretrained:if checkpoint is None:- checkpoint = {- 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: [- hf_url("mobile_sam", "mobile_sam.pt"),- "https://github.com/ChaoningZhang/MobileSAM/raw/a509aac54fdd7af59f843135f2f7cee307283c88/weights/mobile_sam.pt",- ],- }[model_type]+ checkpoint = urls[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 aef4a06ce..dc5f77240 100644--- a/kornia/models/tiny_vit.py+++ b/kornia/models/tiny_vit.py@@ -658,6 +658,52 @@ class TinyViT(nn.Module):return {"5m": _tiny_vit_5m, "11m": _tiny_vit_11m, "21m": _tiny_vit_21m}[variant](pretrained, **kwargs)+# Module level, like every other weight registry in kornia, so the CI weights+# cache can enumerate it -- see tests/core/test_weights_prefetch.py.+urls: dict[str, dict[str, list[str]]] = {+ "5m": {+ "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",+ ],+ },+ "11m": {+ "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",+ ],+ },+ "21m": {+ "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",+ ],+ },+}++def _load_pretrained(model: TinyViT, url: str | list[str]) -> TinyViT:model_state_dict = model.state_dict()state_dict = load_state_dict_from_url(url)@@ -705,16 +751,7 @@ def _tiny_vit_5m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:if pretrained is True:pretrained = "in1k"- url = {- "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]+ url = urls["5m"][pretrained]model = _load_pretrained(model, url)return model@@ -734,16 +771,7 @@ def _tiny_vit_11m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:if pretrained is True:pretrained = "in1k"- url = {- "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]+ url = urls["11m"][pretrained]model = _load_pretrained(model, url)return model@@ -768,24 +796,7 @@ def _tiny_vit_21m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:if img_size >= 512:pretrained = "in1k_512"- url = {- "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]+ url = urls["21m"][pretrained]model = _load_pretrained(model, url)return modeldiff --git a/tests/core/test_download.py b/tests/core/test_download.pyindex 3ff2911c0..e61f66fcb 100644--- a/tests/core/test_download.py+++ b/tests/core/test_download.py@@ -17,18 +17,32 @@from __future__ import annotations+import http.client+import osimport sysimport threadingimport timeimport warnings+from email.message import Message+from email.utils import formatdatefrom unittest.mock import call, patch+from urllib.error import HTTPError, URLErrorimport pytestimport torch+from kornia.core import download as download_modfrom kornia.core.download import hf_url, load_state_dict_from_url[email protected](autouse=True)+def _clear_discard_ledger():+ """The one-discard-per-path bound is process-global; keep tests independent."""+ download_mod._DISCARDED_CACHE_PATHS.clear()+ yield+ download_mod._DISCARDED_CACHE_PATHS.clear()++class TestHfUrl:def test_format(self) -> None:assert hf_url("hardnet", "HardNetPP.pth") == (@@ -276,3 +290,833 @@ class TestConcurrentLoadsDoNotDisturbStdout:loader.join(timeout=10)assert "unrelated thread output" in "".join(written)+++def _http_error(url: str, code: int, headers: dict[str, str] | None = None) -> HTTPError:+ hdrs = None+ if headers is not None:+ hdrs = Message()+ for name, value in headers.items():+ hdrs[name] = value+ return HTTPError(url, code, "boom", hdrs=hdrs, fp=None)+++class _FakeTime:+ """Stand-in for the ``time`` module that records sleeps instead of taking them."""++ NOW = 1_700_000_000.0++ def __init__(self) -> None:+ self.slept: list[float] = []++ def sleep(self, seconds: float) -> None:+ self.slept.append(seconds)++ def time(self) -> float:+ return self.NOW+++class TestPoisonedCacheEntry:+ """A bad cache entry must not disable the fallback URLs.++ All URLs in a list share one cache path, because ``file_name`` is pinned to+ the primary. ``_prefetch_to_cache`` skips a path that already exists, so+ before the discard step a single bad write was handed straight back to torch+ by every remaining source -- the fallback URL was named in the error without+ ever being fetched -- and the bad file outlived the process, so every later+ run failed the same way until the cache was cleared by hand.+ """++ _PRIMARY = "http://primary.example.com/model.pth"+ _FALLBACK = "http://fallback.example.com/model.pth"+ _GOOD = {"weight": torch.zeros(1)}+ _MOCK_TARGET = "kornia.core.download.torch.hub.load_state_dict_from_url"++ @staticmethod+ def _cache(monkeypatch, tmp_path, bad_urls):+ """Point the hub cache at *tmp_path*; URLs in *bad_urls* download garbage."""+ transfers: list[str] = []+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))++ def fake_download(url, dst, hash_prefix=None, progress=True):+ transfers.append(url)+ if url in bad_urls:+ # A rate-limit page served with a 200, or a truncated transfer.+ with open(dst, "wb") as f:+ f.write(b"<html>429 Too Many Requests</html>")+ else:+ torch.save(TestPoisonedCacheEntry._GOOD, dst)++ monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ return transfers++ def test_fallback_recovers_from_bad_primary_download(self, monkeypatch, tmp_path) -> None:+ transfers = self._cache(monkeypatch, tmp_path, bad_urls={self._PRIMARY})++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ assert "weight" in result+ # The fallback was really fetched, not just named in an error message.+ assert transfers == [self._PRIMARY, self._FALLBACK]++ def test_fallback_recovers_from_preexisting_bad_cache_file(self, monkeypatch, tmp_path) -> None:+ transfers = self._cache(monkeypatch, tmp_path, bad_urls=set())+ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ cached.write_bytes(b"<html>429 Too Many Requests</html>")++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ assert "weight" in result+ # The primary short-circuits on the poisoned file, so only the fallback transfers.+ assert transfers == [self._FALLBACK]++ def test_bad_entry_never_survives_into_the_next_run(self, monkeypatch, tmp_path) -> None:+ """A run in which every source fails may leave its last write behind.++ The discard is bounded to one per cache path per process, so the file the+ final source wrote is still there afterwards. What must not survive is the+ *poisoning*: the next process spends its own discard on that path, so the+ fallback is reached again rather than being locked out for good.+ """+ bad = {self._PRIMARY, self._FALLBACK}+ transfers = self._cache(monkeypatch, tmp_path, bad_urls=bad)++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ cached = tmp_path / "checkpoints" / "model.pth"+ assert cached.read_bytes().startswith(b"<html>")++ # A later run, with the fallback healthy again: the ledger is per-process.+ download_mod._DISCARDED_CACHE_PATHS.clear()+ bad.discard(self._FALLBACK)+ transfers.clear()++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ assert "weight" in result+ assert transfers == [self._FALLBACK]++ def test_load_side_failure_refetches_once_not_once_per_call(self, monkeypatch, tmp_path) -> None:+ """An unloadable-but-intact cache entry must not re-download on every call.++ A failure the cache cannot fix -- a bad ``map_location``, a ``weights_only``+ rejection -- used to cost a full transfer of every source on each call,+ because the discard fired unconditionally and the entry never came back.+ Once per model construction across a matrix is the storm this module+ exists to prevent.+ """+ transfers = self._cache(monkeypatch, tmp_path, bad_urls=set())+ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ torch.save(self._GOOD, cached)++ def always_fails(url: str, **kwargs: object) -> dict:+ raise RuntimeError("Attempting to deserialize object on a CUDA device")++ with patch(self._MOCK_TARGET, side_effect=always_fails):+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ for _ in range(3):+ with pytest.raises(RuntimeError):+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ # One refetch in total, not one per source per call.+ assert transfers == [self._FALLBACK]++ def test_single_source_recovers_from_a_poisoned_entry_in_the_same_call(self, monkeypatch, tmp_path) -> None:+ """With no fallback to refetch the path, the failing URL must refetch it itself.++ Twenty-four of the library's checkpoints have a single source, so for+ them every URL is the last one. A discard with nothing after it deletes+ the entry and fetches nothing, leaving the call to fail and the recovery+ to the *next* process -- one guaranteed spurious failure per poisoned+ entry, on models where the fallback list cannot help.+ """+ transfers = self._cache(monkeypatch, tmp_path, bad_urls=set())+ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ cached.write_bytes(b"<html>429 Too Many Requests</html>")++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url(self._PRIMARY)++ assert "weight" in result+ assert transfers == [self._PRIMARY]++ def test_single_source_load_failure_leaves_the_cache_entry_in_place(self, monkeypatch, tmp_path) -> None:+ """A failure the cache cannot fix must not cost the caller its checkpoint.++ ``map_location='cuda'`` on a CPU-only build is the everyday trigger, and+ it is what ``ModelBase.load_checkpoint`` passes. An unpaired discard would+ delete an intact file -- up to 2.4 GB for ``sam.vit_h`` -- and refetch+ nothing, which on an offline machine turns a call that used to succeed+ into one that cannot.+ """+ transfers = self._cache(monkeypatch, tmp_path, bad_urls=set())+ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ torch.save(self._GOOD, cached)++ def always_fails(url: str, **kwargs: object) -> dict:+ raise RuntimeError("Attempting to deserialize object on a CUDA device")++ with patch(self._MOCK_TARGET, side_effect=always_fails):+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url(self._PRIMARY)++ # Within the failing call itself: the discard was paid for by a+ # refetch, so the caller ends it with the entry it started with.+ assert transfers == [self._PRIMARY]+ assert cached.exists()++ for _ in range(2):+ with pytest.raises(RuntimeError):+ load_state_dict_from_url(self._PRIMARY)++ # And the bound holds: one refetch per path per process, not one per call.+ assert transfers == [self._PRIMARY]+ assert cached.exists()++ def test_multi_source_load_failure_offline_leaves_the_cache_entry_in_place(self, monkeypatch, tmp_path) -> None:+ """A discard nothing could pay for is undone rather than left as a deletion.++ Pairing the discard with a refetch on the *last* URL alone left the+ primary's discard to be paid by the fallback, which offline writes+ nothing: ``DISK.from_pretrained('depth', device='cuda')`` on a CPU-only+ build destroyed an intact checkpoint, and the corrected ``device='cpu'``+ call -- which used to succeed offline -- then failed too.+ """+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ transfers: list[str] = []++ def offline(url, dst, hash_prefix=None, progress=True):+ transfers.append(url)+ raise URLError("network is unreachable")++ monkeypatch.setattr(torch.hub, "download_url_to_file", offline)++ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ torch.save(self._GOOD, cached)+ before = cached.read_bytes()++ def always_fails(url: str, **kwargs: object) -> dict:+ raise RuntimeError("Attempting to deserialize object on a CUDA device")++ with patch(self._MOCK_TARGET, side_effect=always_fails):+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ # The fallback really was tried, and each of its transient failures retried;+ # then, since nothing had replaced the path, the discarded primary was given+ # the fetch the entry had denied it. Both are bounded by the sleep budget.+ assert transfers == [self._FALLBACK] * download_mod._MAX_ATTEMPTS + [self._PRIMARY] * download_mod._MAX_ATTEMPTS+ assert cached.read_bytes() == before # and the caller kept its checkpoint+ assert not list(cached.parent.glob("*" + download_mod._QUARANTINE_SUFFIX))++ def test_a_failed_refetch_does_not_hide_the_load_failure(self, monkeypatch, tmp_path) -> None:+ """The refetch error is context; the failure that fired the discard is the cause.++ The re-attempt pass writes over ``last_exc``, so ``map_location='cuda'`` on+ a CPU-only build with the network down reported ``URLError`` and told the+ caller to delete an intact checkpoint -- up to 2.4 GB for ``sam.vit_h`` --+ while the one exception naming what actually went wrong was gone from both+ the message and ``__cause__``. Before the re-attempt existed this call+ raised the load error directly.+ """+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))+ monkeypatch.setattr(download_mod, "time", _FakeTime())++ def offline(url, dst, hash_prefix=None, progress=True):+ raise URLError("network is unreachable")++ monkeypatch.setattr(torch.hub, "download_url_to_file", offline)++ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ torch.save(self._GOOD, cached)++ def always_fails(url: str, **kwargs: object) -> dict:+ raise RuntimeError("Attempting to deserialize object on a CUDA device")++ with patch(self._MOCK_TARGET, side_effect=always_fails):+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError) as excinfo:+ load_state_dict_from_url(self._PRIMARY)++ message = str(excinfo.value)+ assert "Last error: RuntimeError: Attempting to deserialize object on a CUDA device" in message+ assert isinstance(excinfo.value.__cause__, RuntimeError)+ assert "CUDA device" in str(excinfo.value.__cause__)+ # The refetch failure is still reported, as context rather than as the cause.+ assert "URLError" in message+ assert cached.exists() # and the file the message points at is the intact one++ def test_a_discard_nothing_refetched_is_not_charged_to_the_bound(self, monkeypatch, tmp_path) -> None:+ """The bound counts refetches, so a call that fetched nothing must not spend it.++ Otherwise the first offline call in a process would use up the single+ allowed discard on a path it could not repair, and a later call -- with+ the network back -- could never clear a genuinely poisoned entry.+ """+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ offline = True+ transfers: list[str] = []++ def fake_download(url, dst, hash_prefix=None, progress=True):+ transfers.append(url)+ if offline:+ raise URLError("network is unreachable")+ torch.save(self._GOOD, dst)++ monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)++ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ cached.write_bytes(b"<html>429 Too Many Requests</html>")++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url(self._PRIMARY)++ assert cached.read_bytes() == b"<html>429 Too Many Requests</html>"++ offline = False+ result = load_state_dict_from_url(self._PRIMARY)++ assert "weight" in result++ def test_a_bad_fallback_download_does_not_destroy_the_healthy_entry(self, monkeypatch, tmp_path) -> None:+ """Settling on *path existence* kept whatever the network last wrote.++ The network being up but rate limited is this PR's own common case: the+ fallback answers with an HTML page and a 200, which lands at the shared+ cache path. Deciding by "is there a file there?" then dropped the intact+ quarantined checkpoint in favour of that page -- so a ``map_location``+ mistake, which every ``ModelBase.load_checkpoint`` caller can make, cost+ the caller a checkpoint of up to 2.4 GB *and* poisoned the entry, and the+ corrected call failed too. The call's outcome decides instead: nothing+ loaded, so nothing on disk is trusted and the original goes back.+ """+ self._cache(monkeypatch, tmp_path, bad_urls={self._FALLBACK})+ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ torch.save(self._GOOD, cached)+ before = cached.read_bytes()++ def cuda_on_a_cpu_build(url: str, **kwargs: object) -> dict:+ raise RuntimeError("Attempting to deserialize object on a CUDA device")++ with patch(self._MOCK_TARGET, side_effect=cuda_on_a_cpu_build):+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ assert cached.read_bytes() == before+ assert not list(cached.parent.glob("*" + download_mod._QUARANTINE_SUFFIX))++ # And the corrected call -- the whole point of not destroying the file --+ # succeeds without touching the network.+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ assert "weight" in load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ def test_poisoned_entry_recovers_when_the_mirror_is_dead(self, monkeypatch, tmp_path) -> None:+ """The primary is refetched even though it is not the last URL.++ A poisoned entry short-circuits the primary's prefetch, so the primary is+ never actually fetched; the discard it triggers is meant to be paid for by+ a later source, and a dead mirror -- ``cmp.felk.cvut.cz`` and the+ ``raw.githubusercontent.com`` copies are exactly the sources that go away+ -- pays nothing. Pairing the refetch with the *last* URL alone left the+ entry poisoned in every call of every process.+ """+ transfers = self._cache(monkeypatch, tmp_path, bad_urls=set())+ cached = tmp_path / "checkpoints" / "model.pth"+ cached.parent.mkdir(parents=True, exist_ok=True)+ cached.write_bytes(b"<html>429 Too Many Requests</html>")++ def fake_download(url, dst, hash_prefix=None, progress=True):+ transfers.append(url)+ if url == self._FALLBACK:+ raise HTTPError(url, 404, "Not Found", None, None)+ torch.save(self._GOOD, dst)++ monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ assert "weight" in result+ # The dead mirror was tried once (404 is permanent), then the primary was+ # fetched for real against the emptied path.+ assert transfers == [self._FALLBACK, self._PRIMARY]+ assert not list(cached.parent.glob("*" + download_mod._QUARANTINE_SUFFIX))++ def test_a_sources_own_bad_download_is_not_left_behind(self, monkeypatch, tmp_path) -> None:+ """A call must not leave a poisoned entry where it found none.++ Cold cache, the primary rate limited into serving an HTML page with a+ 200, the mirror offline. Quarantining the page -- bytes this very source+ had just written -- meant :func:`_settle_quarantine` put it back, so the+ call ended with an entry it had created and the one allowed discard+ already spent on it: if the primary recovered while the mirror stayed+ dead, every later call in the process short-circuited on the page and+ failed. There was nothing on disk to protect, so there is nothing to move+ aside.+ """+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ healthy = False++ def fake_download(url, dst, hash_prefix=None, progress=True):+ if url == self._FALLBACK:+ raise URLError("network is unreachable")+ if healthy:+ torch.save(self._GOOD, dst)+ else:+ with open(dst, "wb") as f:+ f.write(b"<html>429 Too Many Requests</html>")++ monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ cached = tmp_path / "checkpoints" / "model.pth"++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ assert not cached.exists()+ assert not list(cached.parent.glob("*" + download_mod._QUARANTINE_SUFFIX))+ # And the bound is unspent, since nothing was refetched to pay for it.+ assert not download_mod._DISCARDED_CACHE_PATHS++ # So the primary recovering is enough, with the mirror still dead.+ healthy = True+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ assert "weight" in load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ def test_a_cold_cache_load_side_failure_stays_bounded(self, monkeypatch, tmp_path) -> None:+ """Dropping every failed download unbounds the transfers it was meant to bound.++ On a cold cache a caller-side failure -- ``map_location='cuda'`` on a+ CPU-only build -- rejects a *healthy* file the source just fetched, and no+ exception type separates that from a corrupt one. Deleting whatever a+ source wrote would make every later call fetch it again to fail+ identically: 3 transfers over the three calls below rather than 2, and 6+ rather than 3 for a two-source list, once per test that builds the model,+ on checkpoints of up to 2.4 GB. After the last source the bytes stay, so+ the count is bounded per process however often the call is repeated.+ """+ transfers = self._cache(monkeypatch, tmp_path, bad_urls=set())+ cached = tmp_path / "checkpoints" / "model.pth"++ def always_fails(url: str, **kwargs: object) -> dict:+ raise RuntimeError("Attempting to deserialize object on a CUDA device")++ with patch(self._MOCK_TARGET, side_effect=always_fails):+ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ for _ in range(3):+ with pytest.raises(RuntimeError):+ load_state_dict_from_url(self._PRIMARY)++ # The first call's transfer, then the one discard this path is allowed.+ assert transfers == [self._PRIMARY, self._PRIMARY]+ assert cached.exists()++ def test_a_single_sources_own_bad_download_is_still_discardable(self, monkeypatch, tmp_path) -> None:+ """Twenty-four checkpoints have no mirror, so the recovery has to work there too.++ Bytes the last source wrote are kept, but they must not cost the path its+ discard: quarantining them spent the bound on an entry the call had just+ created, and the process could then never clear it. Nothing is spent, so+ the source recovering is enough.+ """+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))+ healthy = False+ transfers: list[str] = []++ def fake_download(url, dst, hash_prefix=None, progress=True):+ transfers.append(url)+ if healthy:+ torch.save(self._GOOD, dst)+ else:+ with open(dst, "wb") as f:+ f.write(b"<html>429 Too Many Requests</html>")++ monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ cached = tmp_path / "checkpoints" / "model.pth"++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url(self._PRIMARY)++ assert cached.read_bytes().startswith(b"<html>")+ assert not download_mod._DISCARDED_CACHE_PATHS++ # The rate limit lifts; the same process must be able to recover.+ healthy = True+ assert "weight" in load_state_dict_from_url(self._PRIMARY)++ # The poisoned write, then the one refetch this path is allowed.+ assert transfers == [self._PRIMARY, self._PRIMARY]++ def test_explicit_file_name_none_still_shares_one_cache_path(self, monkeypatch, tmp_path) -> None:+ """``file_name=None`` must mean the same thing as omitting it.++ Pinning on ``"file_name" not in kwargs`` while resolving the path with+ ``kwargs.get("file_name")`` split the two: each URL got its own cache+ path, but the single quarantine still covered only the primary's, so a+ failed call left the primary's slot holding the *fallback's* bytes and+ stranded a quarantine file next to it.+ """+ transfers = self._cache(monkeypatch, tmp_path, bad_urls={self._PRIMARY})+ other = "http://fallback.example.com/other.pth"++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url([self._PRIMARY, other], file_name=None)++ assert "weight" in result+ assert transfers == [self._PRIMARY, other]+ checkpoints = tmp_path / "checkpoints"+ assert {p.name for p in checkpoints.iterdir()} == {"model.pth"}++ def test_unremovable_entry_is_reported(self, monkeypatch, tmp_path) -> None:+ """A cache the process cannot write to locks the fallback out silently."""+ self._cache(monkeypatch, tmp_path, bad_urls=set())+ # A *pre-existing* poisoned entry: only those are moved aside, and only a+ # rename that fails leaves the fallback unreachable.+ cached_path = tmp_path / "checkpoints" / "model.pth"+ cached_path.parent.mkdir(parents=True, exist_ok=True)+ cached_path.write_bytes(b"<html>429 Too Many Requests</html>")++ # ``download_mod.os`` *is* the os module, so delegate everything that is+ # not this cache entry rather than break renaming process-wide.+ cached = str(cached_path)+ real_replace = os.replace++ def refuse(src: str, dst: str) -> None:+ if os.path.abspath(src) == cached:+ raise PermissionError(13, "Permission denied")+ real_replace(src, dst)++ monkeypatch.setattr(download_mod.os, "replace", refuse)++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url([self._PRIMARY, self._FALLBACK])++ assert any("Could not discard the cache entry" in str(w.message) for w in caught)+++class TestTransientRetry:+ """Rate limits are the common CI failure; a retry is cheaper than a failed job."""++ _URL = "http://example.com/model.pth"++ @staticmethod+ def _cache(monkeypatch, tmp_path, side_effects):+ """Each call pops one entry off *side_effects*: an exception to raise, or None."""+ attempts: list[str] = []+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))++ def fake_download(url, dst, hash_prefix=None, progress=True):+ attempts.append(url)+ outcome = side_effects.pop(0)+ if outcome is not None:+ raise outcome+ torch.save({"weight": torch.zeros(1)}, dst)++ monkeypatch.setattr(torch.hub, "download_url_to_file", fake_download)+ return attempts++ @pytest.mark.parametrize("code", [408, 425, 429, 500, 502, 503, 504])+ def test_transient_http_status_is_retried(self, monkeypatch, tmp_path, code) -> None:+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, code), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url(self._URL)++ assert "weight" in result+ assert len(attempts) == 2+ assert clock.slept == [1.0]++ @pytest.mark.parametrize("code", [400, 401, 403, 404, 410])+ def test_permanent_http_status_is_not_retried(self, monkeypatch, tmp_path, code) -> None:+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, code)])++ with pytest.raises(RuntimeError):+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 1+ assert clock.slept == []++ def test_connection_error_is_retried(self, monkeypatch, tmp_path) -> None:+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [URLError("dns"), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2++ def test_rate_limited_403_is_retried_and_honours_retry_after(self, monkeypatch, tmp_path) -> None:+ """GitHub answers a rate limit with 403 as well as 429, and says when to return.++ A bare 403 stays permanent -- it is also the "you may not have this file"+ answer -- so the rate-limit headers are what tells the two apart.+ """+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 403, {"Retry-After": "5"}), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url(self._URL)++ assert "weight" in result+ assert len(attempts) == 2+ assert clock.slept == [5.0] # the server's number, not the 1s guess++ def test_rate_limit_reset_header_is_honoured(self, monkeypatch, tmp_path) -> None:+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ headers = {"X-RateLimit-Remaining": "0", "X-RateLimit-Reset": str(int(_FakeTime.NOW) + 7)}+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 403, headers), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2+ assert clock.slept == [7.0]++ def test_an_unusable_retry_after_falls_through_to_the_reset_header(self, monkeypatch, tmp_path) -> None:+ """An unparsable ``Retry-After`` is no guidance, not an answer for the function.++ Returning its ``None`` outright skipped the ``X-RateLimit-Reset`` branch+ below it, so a rate limit that sent both headers was retried on the 1s/2s+ guess -- inside the window it had just been told to wait out.+ """+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ headers = {+ "Retry-After": "garbage",+ "X-RateLimit-Remaining": "0",+ "X-RateLimit-Reset": str(int(_FakeTime.NOW) + 40),+ }+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 403, headers), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2+ assert clock.slept == [40.0] # the window the host named, not the guess++ def test_retry_after_accepts_an_http_date(self, monkeypatch, tmp_path) -> None:+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ when = formatdate(time.time() + 4, usegmt=True) # the other form RFC 9110 allows+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 429, {"Retry-After": when}), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2+ assert clock.slept[0] == pytest.approx(4.0, abs=1.5)++ def test_server_requested_delay_is_clamped(self, monkeypatch, tmp_path) -> None:+ """A host may name minutes; holding a CI job open that long costs more than a refetch."""+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 429, {"Retry-After": "3600"}), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2+ assert clock.slept == [download_mod._MAX_BACKOFF_SECONDS]++ def test_unparseable_retry_after_still_marks_the_failure_transient(self, monkeypatch, tmp_path) -> None:+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 403, {"Retry-After": "soon"}), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2+ assert clock.slept == [1.0] # falls back to the exponential guess++ def test_incomplete_read_is_retried(self, monkeypatch, tmp_path) -> None:+ """A truncated chunked response is neither a URLError nor a ConnectionError."""+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [http.client.IncompleteRead(b"partial"), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2++ def test_attempts_are_capped_with_exponential_backoff(self, monkeypatch, tmp_path) -> None:+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 429)] * 3)++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url(self._URL)++ assert len(attempts) == download_mod._MAX_ATTEMPTS == 3+ assert clock.slept == [1.0, 2.0] # no sleep after the final attempt++ def test_every_url_gets_its_own_retries(self, monkeypatch, tmp_path) -> None:+ primary = "http://primary.example.com/model.pth"+ fallback = "http://fallback.example.com/model.pth"+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(+ monkeypatch, tmp_path, [_http_error(primary, 429)] * 3 + [_http_error(fallback, 429), None]+ )++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url([primary, fallback])++ assert "weight" in result+ assert attempts == [primary] * 3 + [fallback] * 2++ @pytest.mark.parametrize("code", [408, 500, 503])+ def test_retry_after_is_honoured_on_any_transient_status(self, monkeypatch, tmp_path, code) -> None:+ """``Retry-After`` is defined for 503 and 408 too, not only for the rate limits."""+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, code, {"Retry-After": "10"}), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2+ assert clock.slept == [10.0] # the server's number, not the 1s guess++ def test_rate_limit_reset_is_ignored_on_an_unrelated_failure(self, monkeypatch, tmp_path) -> None:+ """GitHub sends the window's end on every response, limited or not."""+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ headers = {"X-RateLimit-Remaining": "57", "X-RateLimit-Reset": str(int(_FakeTime.NOW) + 3000)}+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 500, headers), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ load_state_dict_from_url(self._URL)++ assert len(attempts) == 2+ assert clock.slept == [1.0]++ @pytest.mark.parametrize("value", ["nan", "inf", "-5", "0"])+ def test_unusable_retry_after_falls_back_to_the_guess(self, monkeypatch, tmp_path, value) -> None:+ """``time.sleep(nan)`` raises, from inside the handler, so the 429 is never retried."""+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ attempts = self._cache(monkeypatch, tmp_path, [_http_error(self._URL, 429, {"Retry-After": value}), None])++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ result = load_state_dict_from_url(self._URL)++ assert "weight" in result+ assert len(attempts) == 2+ assert clock.slept == [1.0]++ def test_a_call_stops_waiting_once_its_sleep_budget_is_gone(self, monkeypatch, tmp_path) -> None:+ """Clamping each wait does not bound the call: four waits at the clamp is four minutes."""+ primary = "http://primary.example.com/model.pth"+ fallback = "http://fallback.example.com/model.pth"+ clock = _FakeTime()+ monkeypatch.setattr(download_mod, "time", clock)+ limited = _http_error(primary, 429, {"Retry-After": "3600"})+ attempts = self._cache(monkeypatch, tmp_path, [limited] * 6)++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError):+ load_state_dict_from_url([primary, fallback])++ assert sum(clock.slept) <= download_mod._MAX_CALL_SLEEP_SECONDS+ # Two attempts on the primary -- the second is what the one wait bought --+ # then one on the fallback, which has nothing left to wait with.+ assert attempts == [primary] * 2 + [fallback]+++class TestFailureMessageCarriesCause:+ """A CI failure summary shows only the exception's own message.++ Without the cause in that line, a rate limit, a DNS failure and a dead link+ are indistinguishable -- which is what made the OriNet CI failures read as+ broken URLs that were in fact serving fine.+ """++ def test_message_names_the_underlying_error(self, monkeypatch, tmp_path) -> None:+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))+ monkeypatch.setattr(+ torch.hub,+ "download_url_to_file",+ lambda url, dst, *a, **k: (_ for _ in ()).throw(_http_error(url, 429)),+ )+ monkeypatch.setattr(download_mod, "time", _FakeTime())++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError) as excinfo:+ load_state_dict_from_url(["http://a.example.com/m.pth", "http://b.example.com/m.pth"])++ message = str(excinfo.value)+ assert "Failed to load weights from all 2 source" in message+ assert "HTTPError" in message+ assert "429" in message+ # And the cache path, verbatim, so a caller stuck behind a corrupt entry can+ # paste it into ``rm``/``del`` -- which a repr-escaped Windows path is not.+ assert os.path.join(str(tmp_path), "checkpoints", "m.pth") in message+ # The original exception stays chained for a full traceback.+ assert isinstance(excinfo.value.__cause__, HTTPError)diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.pynew file mode 100644index 000000000..76b81b668--- /dev/null+++ b/tests/core/test_weights_prefetch.py@@ -0,0 +1,444 @@+# 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.+#++"""Guard the CI weights cache against drifting away from the library.++``.github/download-models-weights.py`` fills the ``weights/`` cache that CI+restores before the test and doctest jobs. A checkpoint missing from it is+downloaded live by every matrix cell at once, which trips the anonymous rate+limits of huggingface.co and github.com and surfaces as a ``Failed to load+weights from all N source(s)`` error naming a URL that is in fact serving fine.+That list had not been touched since the HF mirrors landed in #3655, so OriNet+and sixteen other checkpoints were never cached.++Adding a checkpoint to kornia therefore fails this test until it is either+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 both -- ``huggingface_hub.hf_hub_download``+(``kornia/models/{kimi_vl,siglip2}/builder.py``) 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.++``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.+"""++from __future__ import annotations++import functools+import importlib.util+import re+from pathlib import Path+from types import ModuleType+from typing import Any, get_args, get_type_hints+from urllib.parse import urlparse++import pytest++from kornia.feature import affine_shape, defmo, hardnet, hynet, keynet, mkd, orientation, sosnet, tfeat, xfeat+from kornia.feature import lightglue as lightglue_mod+from kornia.feature.aliked import aliked+from kornia.feature.dedode import dedode+from kornia.feature.dedode import encoder as dedode_encoder+from kornia.feature.disk import disk+from kornia.feature.lightglue import LightGlue+from kornia.feature.loftr import loftr+from kornia.feature.sold2 import sold2, sold2_detector+from kornia.filters import dexined+from kornia.models import dexined as dexined_model+from kornia.models import tiny_vit, vit+from kornia.models.efficient_vit import model as efficient_vit+from kornia.models.rt_detr import model as rt_detr+from kornia.models.sam import model as sam+from kornia.models.yunet import model as yunet++_REPO_ROOT = Path(__file__).resolve().parents[2]+_SCRIPT = _REPO_ROOT / ".github" / "download-models-weights.py"++[email protected]_cache(maxsize=1)+def _load_prefetch_script() -> Any:+ """Import the prefetch script for its ``MODELS`` table.++ Cached: the parametrized coverage test asks for it once per checkpoint, and+ re-executing a script for every case is pure overhead.+ """+ spec = importlib.util.spec_from_file_location("_download_models_weights", _SCRIPT)+ if spec is None or spec.loader is None: # pragma: no cover - defensive+ pytest.fail(f"could not load {_SCRIPT}")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++# Every weight source in the library. A registry maps a variant name to the URL+# (or ordered fallback list) that variant loads from.+#+# Most are module-level dicts. The rest build their URLs from a template or a+# helper, and are reconstructed below from the very constants the library+# formats -- never transcribed, or this file would drift the way the prefetch+# list it guards did. ``test_every_prefetched_entry_is_still_requested`` is what+# holds this table to "every": a checkpoint CI caches but no entry here accounts+# for is a hole in the enumeration.+# Each entry pairs the module the URLs live in with the registry itself, so the+# call-site scan below and the coverage checks read one list rather than two --+# 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]]] = {+ "affine_shape": (affine_shape, affine_shape.urls),+ "orientation": (orientation, orientation.urls),+ "hardnet": (hardnet, hardnet.urls),+ "hynet": (hynet, hynet.urls),+ "sosnet": (sosnet, sosnet.urls),+ "tfeat": (tfeat, tfeat.urls),+ "mkd": (mkd, mkd.urls),+ "defmo": (defmo, defmo.urls),+ "loftr": (loftr, loftr.urls),+ "sold2": (sold2, sold2.urls),+ "sold2_detector": (sold2_detector, sold2_detector.urls),+ "disk": (disk, disk.urls),+ "dedode": (dedode, dedode.urls),+ "rt_detr": (rt_detr, rt_detr.URLs),+ "keynet": (keynet, {"keynet": keynet.KeyNet_URL}),+ "yunet": (yunet, {"yunet": yunet.url}),+ # Two independent registries, identical today, both loading the same cache+ # name -- which is what hides the models copy from the coverage check: the+ # filters copy accounts for the name either way. Holding both to MODELS also+ # holds the two copies equal to each other.+ "dexined": (dexined, {"dexined": dexined.url}),+ "dexined_model": (dexined_model, {"dexined": dexined_model.url}),+ "xfeat": (xfeat, {"xfeat": xfeat.XFeat.weights_url}),+ "dedode_encoder": (dedode_encoder, dedode_encoder.urls),+ "tiny_vit": (tiny_vit, tiny_vit.urls),+ "sam": (sam, {variant.name: url for variant, url in sam.urls.items()}),+ # ALIKED formats one template pair per backbone configuration.+ "aliked": (aliked, {name: [t.format(name) for t in aliked._CHECKPOINT_URLS] for name in aliked._ALIKED_CFGS}),+ # ViT and EfficientViT compute their URL from the variant.+ "vit": (vit, {variant: vit._get_weight_url(variant) for variant in vit._AVAILABLE_WEIGHTS}),+ "efficient_vit": (+ efficient_vit,+ {+ f"{model_type}-r{resolution}": efficient_vit._get_base_url(model_type, resolution)+ for model_type in get_args(get_type_hints(efficient_vit._get_base_url)["model_type"])+ for resolution in get_args(get_type_hints(efficient_vit._get_base_url)["resolution"])+ },+ ),+}++# The modules :data:`WEIGHT_REGISTRIES` reads from, as repository-relative paths.+# ``test_every_download_call_site_is_enumerated`` holds the table to its "every+# weight source" claim by checking this set against the files that actually call+# ``load_state_dict_from_url``: a new model with weights is then a failure here+# rather than a checkpoint nothing in this file can see.+_ENUMERATED_MODULE_PATHS = tuple(+ dict.fromkeys(Path(module.__file__).resolve() for module, _ in WEIGHT_REGISTRIES.values())+)++# The call-site scan reads ``kornia/`` from the checkout, so it can only speak+# for a kornia imported from that same checkout. An installed copy is a legitimate+# way to run the suite; it just makes this one check meaningless rather than+# failing, so it is skipped there instead of turning the whole file into a+# collection error on a path that is not relative to the repository.+_KORNIA_IS_THE_CHECKOUT = all(path.is_relative_to(_REPO_ROOT) for path in _ENUMERATED_MODULE_PATHS)+_ENUMERATED_MODULES = (+ {path.relative_to(_REPO_ROOT).as_posix() for path in _ENUMERATED_MODULE_PATHS} if _KORNIA_IS_THE_CHECKOUT else set()+)++# Modules that call ``load_state_dict_from_url`` without being a registry of+# their own, with the reason they need no entry above.+_DOWNLOAD_CALL_ALLOWLIST = {+ "kornia/core/download.py": "defines the function",+ "kornia/core/__init__.py": "re-exports it",+ "kornia/feature/lightglue.py": "builds its URLs in __init__; captured by _lightglue_sources",+ "kornia/models/base.py": "loads whatever checkpoint the config it is handed carries",+}++# Checkpoints deliberately left out of the CI cache, with the reason. A variant+# belongs here when nothing CI runs instantiates it; the cost of caching every+# variant of every model is paid on every job, so only what CI runs is cached.+#+# "What CI runs" is wider than the pytest matrix. The docs job restores the same+# cache and then builds the API reference, and ``docs/generate_examples.py``+# constructs KeyNet, DISK, ALIKED and XFeat pretrained with no download guard --+# so a reason phrased only in terms of tests and doctests can be true and still+# leave a checkpoint being fetched live on every documentation build.+NOT_PREFETCHED: dict[str, str] = {+ # Alternative training sets -- tests only ever build the liberty variants.+ "HardNetPP.pth": "HardNet++ weights; no test or doctest requests them",+ "hardnet8v2.pt": "HardNet8(pretrained=True); tests build HardNet8() untrained",+ "HyNet_ND.pth": "notredame variant; tests use the liberty default",+ "HyNet_YOS.pth": "yosemite variant; tests use the liberty default",+ "sosnet_32x32_hpatches_a.pth": "hpatches variant; tests use the liberty default",+ "tfeat-notredame.params": "notredame variant; tests use the liberty default",+ "tfeat-yosemite.params": "yosemite variant; tests use the liberty default",+ # Model variants no test selects.+ "loftr_indoor_ds_new.ckpt": "tests instantiate LoFTR('indoor') and LoFTR('outdoor') only",+ "sold2_wireframe.tar": "every SOLD2_detector in the suite passes pretrained=False",+ "epipolar-save.pth": "tests call DISK.from_pretrained(checkpoint='depth')",+ # LightGlue heads: tests build the disk and doghardnet matchers, and the+ # suite also reaches the superpoint head. The rest are unused.+ "aliked_lightglue_v0-1_arxiv-pth": "no test selects the aliked LightGlue head",+ "sift_lightglue_v0-1_arxiv-pth": "no test selects the sift LightGlue head",+ "keynet_affnet_hardnet_lightglue.pth": "no test selects the keynet_affnet_hardnet LightGlue head",+ "dedodeb_lightglue.pth": "no test selects the dedodeb LightGlue head",+ "dedodeg_lightglue.pth": "no test selects the dedodeg LightGlue head",+ "raco_aliked_lightglue_v0-1_arxiv-pth": "no test selects the raco-aliked LightGlue head",+ "xfeat-lighterglue.pt": "no test selects the xfeat LightGlue head",+ "rtdetr_r34vd_dec4_6x_coco_from_paddle.pth": "only the r18vd variant is tested",+ "rtdetr_r50vd_6x_coco_from_paddle.pth": "only the r18vd variant is tested",+ "rtdetr_r50vd_m_6x_coco_from_paddle.pth": "only the r18vd variant is tested",+ "rtdetr_r101vd_6x_coco_from_paddle.pth": "only the r18vd variant is tested",+ # DeDoDe: ``TestDeDoDe`` is class-level ``@pytest.mark.skip`` ("DeDoDe is+ # ummaintained"), so the scheduled slow run does not reach it either. The only+ # DeDoDe construction CI performs is the ``DeDoDe.from_pretrained`` doctest,+ # which selects the ``L-C4-v2`` detector and the ``B-upright`` descriptor --+ # those two are prefetched and every other variant is dead weight in the+ # cache. ``dedode_descriptor_G`` and the DINOv2 backbone it pulls are 2.2 GB+ # of it.+ "dedode_detector_L.pth": "superseded by the L_v2 detector the doctest uses",+ "dedode_detector_C4.pth": "steerer variant nothing in CI selects",+ "dedode_detector_SO2.pth": "steerer variant nothing in CI selects",+ "B_C4_Perm_descriptor_setting_C.pth": "steerer variant nothing in CI selects",+ "B_SO2_Spread_descriptor_setting_C.pth": "steerer variant nothing in CI selects",+ "G_C4_Perm_descriptor_setting_C.pth": "steerer variant nothing in CI selects",+ "G_SO2_Spread_descriptor_setting_C.pth": "steerer variant nothing in CI selects",+ "dedode_descriptor_G.pth": "only TestDeDoDe builds the G descriptor, and it is skipped",+ "dinov2_vitl14_pretrain.pth": "reachable only through the G descriptor, which nothing in CI builds",+ # Whole-model checkpoints whose only pretrained test carries+ # ``@pytest.mark.slow``, and which nothing in the docs build constructs. The+ # PR matrix leaves KORNIA_TEST_RUNSLOW unset and deselects them; the+ # scheduled run that does select them fetches these live, which is the+ # pre-existing state and not what the OriNet failures were.+ "tiny_vit_5m_22kto1k_distill.pth": "TinyViT.from_config('5m', pretrained=True) is slow-marked",+ "tiny_vit_11m_22kto1k_distill.pth": "TinyViT.from_config('11m', pretrained=True) is slow-marked",+ "tiny_vit_21m_22kto1k_distill.pth": "TinyViT.from_config('21m', pretrained=True) is slow-marked",+ "sam_vit_b_01ec64.pth": "Sam.from_config(SamConfig('vit_b', pretrained=True)) is slow-marked",+ "mobile_sam.pt": "Sam.from_config(SamConfig('mobile_sam', pretrained=True)) is slow-marked",+ "b1-r224.pt": "EfficientViT.from_config(EfficientViTConfig()) is slow-marked",+ # Variants of those models that no test selects at all.+ "aliked-t16.pth": "tests build ALIKED(model_name='aliked-t16') untrained",+ "aliked-n16rot.pth": "no test loads pretrained weights for this ALIKED variant",+ "aliked-n32.pth": "no test loads pretrained weights for this ALIKED variant",+ "tiny_vit_5m_22k_distill.pth": "in22k variant; pretrained=True selects in1k",+ "tiny_vit_11m_22k_distill.pth": "in22k variant; pretrained=True selects in1k",+ "tiny_vit_21m_22k_distill.pth": "in22k variant; pretrained=True selects in1k",+ "tiny_vit_21m_22kto1k_384_distill.pth": "img_size>=384 variant; no test asks for it",+ "tiny_vit_21m_22kto1k_512_distill.pth": "img_size>=512 variant; no test asks for it",+ "sam_vit_l_0b3195.pth": "only vit_b and mobile_sam have a pretrained test",+ "sam_vit_h_4b8939.pth": "only vit_b and mobile_sam have a pretrained test",+ "b2-r224.pt": "test_config only checks the URL string; nothing downloads it",+ "b3-r224.pt": "test_config only checks the URL string; nothing downloads it",+ "b1-r256.pt": "test_config only checks the URL string; nothing downloads it",+ "b2-r256.pt": "test_config only checks the URL string; nothing downloads it",+ "b3-r256.pt": "test_config only checks the URL string; nothing downloads it",+ "b1-r288.pt": "test_config only checks the URL string; nothing downloads it",+ "b2-r288.pt": "test_config only checks the URL string; nothing downloads it",+ "b3-r288.pt": "test_config only checks the URL string; nothing downloads it",+ # ViT: the from_config doctest builds vit_b/16, which is prefetched.+ "vit_l-16.pth": "no test or doctest selects this ViT variant",+ "vit_s-16.pth": "no test or doctest selects this ViT variant",+ "vit_ti-16.pth": "no test or doctest selects this ViT variant",+ "vit_b-32.pth": "no test or doctest selects this ViT variant",+ "vit_s-32.pth": "no test or doctest selects this ViT variant",+}+++def _as_list(url: str | list[str]) -> list[str]:+ """Normalise a registry value to the ordered source list it stands for."""+ return [url] if isinstance(url, str) else list(url)+++def _pinned_cache_name(url: str | list[str]) -> str:+ """Return the cache filename :func:`load_state_dict_from_url` would use.++ A list pins the basename of its **first** entry for every attempt, so the+ fallback source shares one cache slot with the primary.+ """+ return Path(urlparse(_as_list(url)[0]).path).name+++# LightGlue does not expose a registry: it derives both the URL and the cache+# name inside ``__init__``, and that name is *not* the URL basename -- the+# superpoint head loads ``superpoint_lightglue.pth`` but looks for it under+# ``superpoint_lightglue_v0-1_arxiv-pth``. A prefetch entry keyed by the+# basename would store the file where nothing reads it, so the names are+# captured from the class itself rather than written down twice.+LIGHTGLUE_FEATURES = tuple(sorted(LightGlue.features))+++def _lightglue_sources(monkeypatch) -> dict[str, tuple[str, list[str]]]:+ """Return ``{feature: (cache filename, source urls)}`` without downloading anything."""+ captured: dict[str, tuple[str, list[str]]] = {}+ pending: list[str] = []++ def _capture(url: Any, **kwargs: Any) -> dict[str, Any]:+ captured[pending[-1]] = (kwargs["file_name"], _as_list(url))+ raise _Captured++ monkeypatch.setattr(lightglue_mod, "load_state_dict_from_url", _capture)+ for feature in LIGHTGLUE_FEATURES:+ pending.append(feature)+ try:+ LightGlue(feature)+ except _Captured:+ pass+ return captured+++def _lightglue_cache_names(monkeypatch) -> dict[str, str]:+ """Return ``{feature: cache filename}`` without downloading anything."""+ return {feature: name for feature, (name, _) in _lightglue_sources(monkeypatch).items()}+++class _Captured(Exception):+ """Raised to stop LightGlue's ``__init__`` once the cache name is known."""+++def _iter_checkpoints():+ """Yield ``(label, cache filename, source urls)`` for every checkpoint the library requests."""+ for registry, (_, entries) in WEIGHT_REGISTRIES.items():+ for variant, url in entries.items():+ if isinstance(url, dict): # dedode nests detector/descriptor tables+ for sub, sub_url in url.items():+ yield f"{registry}.{variant}.{sub}", _pinned_cache_name(sub_url), _as_list(sub_url)+ else:+ yield f"{registry}.{variant}", _pinned_cache_name(url), _as_list(url)+++_CHECKPOINTS = list(_iter_checkpoints())+_CHECKPOINT_IDS = [label for label, _, _ in _CHECKPOINTS]+++class TestWeightsPrefetchCoverage:+ def test_script_is_importable(self) -> None:+ assert _SCRIPT.is_file(), f"{_SCRIPT} is missing"+ assert _load_prefetch_script().MODELS++ @pytest.mark.parametrize(+ ("label", "cache_name"), [(label, name) for label, name, _ in _CHECKPOINTS], ids=_CHECKPOINT_IDS+ )+ def test_checkpoint_is_prefetched_or_exempt(self, label: str, cache_name: str) -> None:+ prefetched = _load_prefetch_script().MODELS+ assert cache_name in prefetched or cache_name in NOT_PREFETCHED, (+ f"{label} loads {cache_name!r}, which CI neither prefetches nor exempts. "+ f"Add it to MODELS in {_SCRIPT.relative_to(_REPO_ROOT)} (keyed by this exact "+ f"cache filename), or to NOT_PREFETCHED here with the reason it is not needed."+ )++ def test_prefetched_urls_match_the_library(self) -> None:+ """The cache is keyed by filename, so a repointed URL is invisible to the check above.++ ``MODELS`` is a second copy of the registries in ``kornia/``, and nothing+ else holds the two equal. Repoint a registry at a new revision or swap a+ dead mirror without touching the prefetch list and the key is unchanged:+ the coverage check stays green while CI caches the *old* bytes under the+ exact name every job looks for, so either the prefetch job hard-fails on a+ dead link or every matrix cell loads a stale checkpoint from a silent+ cache hit -- no download, no warning.+ """+ prefetched = _load_prefetch_script().MODELS+ drifted = [+ f"{label}: library {urls} != prefetch {_as_list(prefetched[cache_name])}"+ for label, cache_name, urls in _CHECKPOINTS+ if cache_name in prefetched and _as_list(prefetched[cache_name]) != urls+ ]+ assert not drifted, (+ "the prefetch list no longer mirrors the registries it copies:\n "+ + "\n ".join(drifted)+ + f"\nUpdate MODELS in {_SCRIPT.relative_to(_REPO_ROOT)}."+ )++ def test_exemptions_are_still_reachable(self, monkeypatch) -> None:+ """A stale exemption hides a checkpoint that no longer exists."""+ live = {name for _, name, _ in _iter_checkpoints()}+ live |= set(_lightglue_cache_names(monkeypatch).values())+ stale = sorted(set(NOT_PREFETCHED) - live)+ assert not stale, f"NOT_PREFETCHED lists checkpoints the library no longer requests: {stale}"++ def test_lightglue_heads_are_prefetched_or_exempt(self, monkeypatch) -> None:+ prefetched = _load_prefetch_script().MODELS+ sources = _lightglue_sources(monkeypatch)+ assert set(sources) == set(LIGHTGLUE_FEATURES), "a LightGlue head stopped loading weights"+ for feature, (cache_name, urls) in sorted(sources.items()):+ assert cache_name in prefetched or cache_name in NOT_PREFETCHED, (+ f"LightGlue({feature!r}) looks for {cache_name!r}, which CI neither "+ f"prefetches nor exempts. Note this is not the URL basename."+ )+ if cache_name in prefetched:+ assert _as_list(prefetched[cache_name]) == urls, (+ f"LightGlue({feature!r}) loads {cache_name!r} from {urls}, but CI "+ f"prefetches it from {_as_list(prefetched[cache_name])}. A head prefetched "+ f"from fewer sources than it loads from has no fallback in the one job "+ f"that runs before the matrix."+ )++ def test_every_prefetched_entry_is_still_requested(self, monkeypatch) -> None:+ """A cached checkpoint no registry accounts for is a hole in the enumeration.++ The other direction of the guard. Without it :data:`WEIGHT_REGISTRIES` --+ itself hand-maintained -- can miss a weight source entirely, and every+ checkpoint that source loads is then invisible: the prefetch list can go+ stale exactly the way OriNet's did and this file stays green.+ """+ live = {name for _, name, _ in _iter_checkpoints()}+ live |= set(_lightglue_cache_names(monkeypatch).values())+ orphaned = sorted(set(_load_prefetch_script().MODELS) - live)+ assert not orphaned, (+ f"CI prefetches {orphaned}, which no registry here accounts for. Add the "+ f"weight source to WEIGHT_REGISTRIES so the entry is guarded in both directions."+ )++ def test_every_download_call_site_is_enumerated(self) -> None:+ """Nothing else holds :data:`WEIGHT_REGISTRIES` to "every weight source in the library".++ The two directions above both start from this table, so a source missing+ from it is invisible to all of them -- and a duplicated cache name hides+ the miss even from ``test_every_prefetched_entry_is_still_requested``,+ which is exactly how the second DexiNed registry in ``kornia/models``+ went unenumerated. Checking the call sites closes the class rather than+ the instance: the next model that loads weights fails here until its+ registry is listed.+ """+ if not _KORNIA_IS_THE_CHECKOUT:+ pytest.skip("kornia is imported from outside this checkout; the call-site scan cannot match it")+ call = re.compile(r"\bload_state_dict_from_url\s*\(")+ callers = {+ path.relative_to(_REPO_ROOT).as_posix()+ for path in sorted((_REPO_ROOT / "kornia").rglob("*.py"))+ if call.search(path.read_text(encoding="utf-8"))+ }+ unaccounted = sorted(callers - _ENUMERATED_MODULES - set(_DOWNLOAD_CALL_ALLOWLIST))+ assert not unaccounted, (+ f"these modules download weights but no entry in WEIGHT_REGISTRIES reads their "+ f"URLs, so their checkpoints are invisible to every check in this file: "+ f"{unaccounted}. Add the registry to WEIGHT_REGISTRIES, or the module to "+ f"_DOWNLOAD_CALL_ALLOWLIST with the reason it has no registry of its own."+ )++ def test_no_entry_is_both_prefetched_and_exempt(self) -> None:+ prefetched = _load_prefetch_script().MODELS+ overlap = sorted(set(prefetched) & set(NOT_PREFETCHED))+ assert not overlap, f"listed as both cached and exempt: {overlap}"diff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.pyindex d6c927c89..76e2bcbf0 100644--- a/tests/feature/test_sold2.py+++ b/tests/feature/test_sold2.py@@ -47,7 +47,10 @@ class TestSOLD2_detector(BaseTester):def test_jit(self, device, dtype):B, C, H, W = 2, 1, 128, 128img = torch.ones(B, C, H, W, device=device, dtype=dtype)- model = SOLD2_detector().to(img.device, img.dtype).eval()+ # pretrained=False: scripting does not need the weights, and the CI cache+ # deliberately does not carry ``sold2_wireframe.tar`` -- see+ # ``NOT_PREFETCHED`` in tests/core/test_weights_prefetch.py.+ model = SOLD2_detector(pretrained=False).to(img.device, img.dtype).eval()model_jit = torch.jit.script(model)self.assert_close(model(img), model_jit(img))