π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(core): let download_file_from_url validate and re-fetch a cache entry (#4332)
Dipak Chaudhari206e06234261
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f297b6986..14cb45845 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -421,6 +421,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0The buffers are non-persistent, so `state_dict()` is unchanged and existing checkpoints stillload. (#4323, #4330)+* `download_file_from_url` and `download_hf_file` take an optional `validate=` callable, and+ `kornia.core.check_safetensors` is the one the KimiVL and SigLIP2 builders pass. A transfer cut+ short after a 2xx status leaves a truncated file in the cache, which was then returned as a cache+ hit on every later call -- `from_pretrained_hf()` failed until the user deleted it by hand.+ `validate` gives a download-only call the quarantine `load_state_dict_from_url` gets from its load+ step: a rejected entry is moved aside, the next source is tried, and the discarded source is+ re-fetched once. Without `validate` the behaviour is unchanged. (#4309, #4332)+* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its renderingtime-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` nevermoved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, sodiff --git a/docs/source/core.rst b/docs/source/core.rstindex b907ea1f2..47c4eb01f 100644--- a/docs/source/core.rst+++ b/docs/source/core.rst@@ -19,7 +19,8 @@ Helpers for fetching and reading pretrained weights. :func:`load_state_dict_fromis the one models load a ``torch.load``-able checkpoint with;:func:`download_hf_file` (or :func:`download_file_from_url`) and:func:`load_safetensors` are the two halves of the same job for a-``.safetensors`` checkpoint.+``.safetensors`` checkpoint; :func:`check_safetensors` is the ``validate=``+callable that lets the download half reject a truncated cache entry... autofunction:: hf_url@@ -30,3 +31,5 @@ is the one models load a ``torch.load``-able checkpoint with;.. autofunction:: download_hf_file.. autofunction:: load_safetensors++.. autofunction:: check_safetensorsdiff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex 439edcd6b..e122ad120 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -30,7 +30,7 @@ from .mixin import ()from .module import ImageModule, ImageSequentialfrom .ops import eye_like, vec_like-from .safetensors import load_safetensors+from .safetensors import check_safetensors, load_safetensorsfrom .tensor_wrapper import TensorWrapper__all__ = [@@ -41,6 +41,7 @@ __all__ = ["ONNXMixin","ONNXRuntimeMixin","TensorWrapper",+ "check_safetensors","download_file_from_url","download_hf_file","external",diff --git a/kornia/core/download.py b/kornia/core/download.pyindex 985478fbe..99d3dde5b 100644--- a/kornia/core/download.py+++ b/kornia/core/download.py@@ -23,6 +23,7 @@ import osimport sysimport timeimport warnings+from collections.abc import Callablefrom datetime import UTC, datetimefrom email.utils import parsedate_to_datetimefrom pathlib import Path@@ -786,6 +787,7 @@ def download_file_from_url(file_name: str | None = None,model_dir: str | None = None,progress: bool = True,+ validate: Callable[[str], None] | None = None,) -> str:"""Download a file into the torch hub cache and return its path, without loading it.@@ -797,13 +799,20 @@ def download_file_from_url(announcing a transfer on :data:`sys.stderr` rather than stdout. A filealready in the cache is returned as it is, with no request made.- It does *not* quarantine an existing cache entry the way- :func:`load_state_dict_from_url` does, because it never reads the file: a- corrupt entry is only discovered by the caller, one step later, and nothing- here can tell it apart from an intact one. The path is returned to the caller- and named in the failure message so that a file which turns out to be- unreadable can be deleted; :func:`kornia.core.load_safetensors` names it in- every error it raises for the same reason.+ Pass ``validate`` to get :func:`load_state_dict_from_url`'s quarantine as+ well. That function hooks its quarantine on the *load* step, which a+ download-only function does not have: without one, nothing here can tell a+ truncated cache entry from an intact one, so a bad file is handed back as a+ cache hit on every later call and the caller keeps failing until it is+ deleted by hand. ``validate`` supplies the missing step -- it is called with+ the cache path after each attempt, and raising from it is treated exactly as+ a load failure is: the entry is quarantined, the next source is tried, and+ the discarded source is re-fetched once.++ Without ``validate`` nothing is quarantined, as before. The path is returned+ to the caller and named in the failure message so that a file which turns+ out to be unreadable can be deleted; :func:`kornia.core.load_safetensors`+ names it in every error it raises for the same reason.Args:url: a URL string, or a list of URL strings tried left-to-right.@@ -819,6 +828,10 @@ def download_file_from_url(model_dir: directory to cache the file in. Defaults to torch's``<hub dir>/checkpoints``, which is the cache CI restores.progress: whether to display a progress bar during a transfer.+ validate: called with the cache path after each attempt, to decide+ whether what is there is usable. Raising rejects the entry. Keep it+ cheap -- a header parse, not a full read -- since it runs on cache+ hits too.Returns:The path of the cached file.@@ -845,26 +858,61 @@ def download_file_from_url(file_name = Path(urlparse(urls[0]).path).namekwargs: dict[str, Any] = {"model_dir": model_dir, "file_name": file_name, "progress": progress}+ # 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+ downloaded = Falselast_exc: Exception | None = Nonelast_url: str | None = None- for i, u in enumerate(urls):- more_sources = i < len(urls) - 1- try:- _prefetch_with_retry(u, kwargs, budget)- except Exception as e: # noqa: BLE001- last_exc, last_url = e, u- if more_sources:- # Anything at the cache path was written by this failed attempt:- # a cache hit returns without transferring and without raising,- # so reaching here means the path was empty when the attempt- # started. Clearing it is what lets the next source transfer into- # it rather than be handed a partial file as a cache hit.- _drop_failed_download(cache_path)- warnings.warn(f"Failed to download {u!r}: {e}. Trying next source.", stacklevel=2)- continue- return cache_path+ sources = urls+ re_attempted = False+ try:+ while True:+ for i, u in enumerate(sources):+ fetched = False+ more_sources = i < len(sources) - 1+ try:+ fetched = _prefetch_with_retry(u, kwargs, budget)+ downloaded |= fetched+ if validate is not None:+ validate(cache_path)+ 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 does not apply. Drop them when a later source+ # can use the emptied path.+ if more_sources:+ _drop_failed_download(cache_path)+ else:+ # Either nothing transferred, or -- the case this whole+ # branch exists for -- a cache hit was handed back and+ # ``validate`` rejected it. Move it aside so the next+ # source really fetches; it comes back below if none does.+ moved = _discard_cache_entry(u, kwargs)+ if moved is not None:+ quarantine, discarded_url = moved, u+ if more_sources:+ warnings.warn(f"Failed to download {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 cache_path++ # 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. Give that one source the fetch it never got.+ 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)raise RuntimeError(f"Failed to download the file from all {len(urls)} source(s). "@@ -876,7 +924,14 @@ def download_file_from_url() from last_exc-def download_hf_file(repo: str, filename: str, *, model_dir: str | None = None, progress: bool = True) -> str:+def download_hf_file(+ repo: str,+ filename: str,+ *,+ model_dir: str | None = None,+ progress: bool = True,+ validate: Callable[[str], None] | None = None,+) -> str:"""Download one file from a HuggingFace repo and return the path it is cached at.:func:`download_file_from_url` with the two decisions a Hub file needs@@ -893,6 +948,10 @@ def download_hf_file(repo: str, filename: str, *, model_dir: str | None = None,model_dir: directory to cache the file in. Defaults to torch's``<hub dir>/checkpoints``, which is the cache CI restores.progress: whether to display a progress bar during a transfer.+ validate: forwarded to :func:`download_file_from_url`, which documents+ it. Pass :func:`kornia.core.check_safetensors` for a checkpoint, so+ that a truncated cache entry is re-fetched rather than handed back+ on every later call.Returns:The path of the cached file. Read a ``.safetensors`` one with@@ -913,4 +972,5 @@ def download_hf_file(repo: str, filename: str, *, model_dir: str | None = None,file_name=_hf_cache_file_name(repo, filename),model_dir=model_dir,progress=progress,+ validate=validate,)diff --git a/kornia/core/safetensors.py b/kornia/core/safetensors.pyindex 5507a513f..ca0d3f12d 100644--- a/kornia/core/safetensors.py+++ b/kornia/core/safetensors.py@@ -28,11 +28,11 @@ from __future__ import annotationsimport jsonimport mmapimport os-from typing import Any, NamedTuple+from typing import Any, BinaryIO, NamedTupleimport torch-__all__ = ["load_safetensors"]+__all__ = ["check_safetensors", "load_safetensors"]class _TensorEntry(NamedTuple):@@ -190,6 +190,65 @@ def _check_the_buffer_is_covered_once(path: str, parsed: dict[str, _TensorEntry])+def check_safetensors(path: str | os.PathLike[str]) -> None:+ """Check that *path* is a readable safetensors file, without reading tensors.++ The header half of :func:`load_safetensors`: the length prefix, the JSON+ header, every entry's dtype and byte range, and that those ranges cover the+ buffer exactly once. It reads only the header, so it stays cheap on a+ multi-gigabyte checkpoint.++ Written for :func:`kornia.core.download_file_from_url`'s ``validate``+ argument, where it turns a truncated cache entry into a re-download instead+ of a permanent failure. Every truncation the download path can produce is+ visible here: a file cut short after a 2xx leaves the declared header length+ or the entries' ``data_offsets`` pointing past the end.++ Args:+ path: the checkpoint to check.++ Raises:+ ValueError: if the file is not a readable safetensors checkpoint. The+ message names *path*, as :func:`load_safetensors` does.+ OSError: if the file cannot be opened.+ """+ path = os.fspath(path)+ with open(path, "rb") as f:+ _read_and_check_header(path, f)+++def _read_and_check_header(path: str, f: BinaryIO) -> tuple[dict[str, _TensorEntry], int]:+ """Validate the header of an open safetensors file, leaving nothing mapped.++ Returns:+ The parsed entries, and the offset the byte buffer starts at.+ """+ size = os.fstat(f.fileno()).st_size+ if size < _HEADER_LEN_BYTES:+ raise ValueError(f"{path}: {size} bytes is too short to be a safetensors file.")+ header_len = int.from_bytes(f.read(_HEADER_LEN_BYTES), "little", signed=False)+ if header_len > _MAX_HEADER_BYTES:+ raise ValueError(f"{path}: the header declares {header_len} bytes, more than the {_MAX_HEADER_BYTES} cap.")+ data_start = _HEADER_LEN_BYTES + header_len+ if data_start > size:+ raise ValueError(+ f"{path}: the header declares {header_len} bytes but the file holds "+ f"{size - _HEADER_LEN_BYTES} after the length prefix."+ )+ try:+ header = json.loads(f.read(header_len))+ except (UnicodeDecodeError, json.JSONDecodeError) as e:+ raise ValueError(f"{path}: the header is not valid JSON: {e}") from e+ if not isinstance(header, dict):+ raise ValueError(f"{path}: the header is a JSON {type(header).__name__}, expected an object.")++ entries = {name: entry for name, entry in header.items() if name != "__metadata__"}+ data_len = size - data_start+ parsed = {name: _parse_entry(path, name, entry, data_len) for name, entry in entries.items()}+ _check_the_buffer_is_covered_once(path, parsed, data_len)+ return parsed, data_start++def load_safetensors(path: str | os.PathLike[str], device: str | torch.device = "cpu") -> dict[str, torch.Tensor]:"""Load a ``.safetensors`` checkpoint into a state dict.@@ -228,29 +287,7 @@ def load_safetensors(path: str | os.PathLike[str], device: str | torch.device ="""path = os.fspath(path)with open(path, "rb") as f:- size = os.fstat(f.fileno()).st_size- if size < _HEADER_LEN_BYTES:- raise ValueError(f"{path}: {size} bytes is too short to be a safetensors file.")- header_len = int.from_bytes(f.read(_HEADER_LEN_BYTES), "little", signed=False)- if header_len > _MAX_HEADER_BYTES:- raise ValueError(f"{path}: the header declares {header_len} bytes, more than the {_MAX_HEADER_BYTES} cap.")- data_start = _HEADER_LEN_BYTES + header_len- if data_start > size:- raise ValueError(- f"{path}: the header declares {header_len} bytes but the file holds "- f"{size - _HEADER_LEN_BYTES} after the length prefix."- )- try:- header = json.loads(f.read(header_len))- except (UnicodeDecodeError, json.JSONDecodeError) as e:- raise ValueError(f"{path}: the header is not valid JSON: {e}") from e- if not isinstance(header, dict):- raise ValueError(f"{path}: the header is a JSON {type(header).__name__}, expected an object.")-- entries = {name: entry for name, entry in header.items() if name != "__metadata__"}- data_len = size - data_start- parsed = {name: _parse_entry(path, name, entry, data_len) for name, entry in entries.items()}- _check_the_buffer_is_covered_once(path, parsed, data_len)+ parsed, data_start = _read_and_check_header(path, f)state_dict: dict[str, torch.Tensor] = {}# ``ACCESS_COPY`` maps the whole file, so the offsets below are filediff --git a/kornia/models/kimi_vl/builder.py b/kornia/models/kimi_vl/builder.pyindex d94cc3fca..6e76c1aaf 100644--- a/kornia/models/kimi_vl/builder.py+++ b/kornia/models/kimi_vl/builder.py@@ -24,7 +24,7 @@ from typing import Optionalimport torchfrom kornia.core.download import download_hf_file-from kornia.core.safetensors import load_safetensors+from kornia.core.safetensors import check_safetensors, load_safetensorsfrom .config import KimiVLConfig, _kimi_vl_a3b_instruct_configfrom .model import KimiVLModel@@ -47,7 +47,11 @@ def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, toReturns:The checkpoint's state dict, on the CPU."""- return load_safetensors(download_hf_file(model_name, _WEIGHTS_FILE, model_dir=cache_dir))+ # validate=: a transfer cut short after a 2xx leaves a truncated file in the+ # cache, which is returned as a hit forever after. Checking the header here+ # makes the download path re-fetch it once instead.+ path = download_hf_file(model_name, _WEIGHTS_FILE, model_dir=cache_dir, validate=check_safetensors)+ return load_safetensors(path)class KimiVLBuilder:diff --git a/kornia/models/siglip2/builder.py b/kornia/models/siglip2/builder.pyindex 59625538f..fe2565671 100644--- a/kornia/models/siglip2/builder.py+++ b/kornia/models/siglip2/builder.py@@ -25,7 +25,7 @@ from typing import Optionalimport torchfrom kornia.core.download import download_hf_file-from kornia.core.safetensors import load_safetensors+from kornia.core.safetensors import check_safetensors, load_safetensorsfrom .config import SigLip2Configfrom .model import SigLip2Model@@ -53,7 +53,9 @@ def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, toread.RuntimeError: if the checkpoint cannot be downloaded."""- path = download_hf_file(model_name, _WEIGHTS_FILE, model_dir=cache_dir)+ # validate=: see KimiVL's builder -- a truncated cache entry is re-fetched+ # once rather than returned as a hit on every later call.+ path = download_hf_file(model_name, _WEIGHTS_FILE, model_dir=cache_dir, validate=check_safetensors)try:return load_safetensors(path)except FileNotFoundError as e:diff --git a/tests/core/test_download.py b/tests/core/test_download.pyindex e8659c204..6a7ff784a 100644--- a/tests/core/test_download.py+++ b/tests/core/test_download.py@@ -1384,3 +1384,137 @@ class TestDownloadHfFile:assert paths[0] != paths[1]assert Path(paths[0]).read_bytes() == b"kornia"assert Path(paths[1]).read_bytes() == b"google"+++class TestDownloadValidate:+ """``validate=`` gives a download-only call the quarantine a load gets.++ Without it a transfer cut short after a 2xx leaves a truncated file in the+ cache, and every later call returns it as a hit -- the caller fails on it+ forever, until someone deletes the file by hand.+ """++ @staticmethod+ def _serve(tmp_path, payload: bytes) -> str:+ source = tmp_path / "remote" / "model.safetensors"+ source.parent.mkdir(parents=True, exist_ok=True)+ source.write_bytes(payload)+ return source.as_uri()++ @staticmethod+ def _reject_truncated(expected_size: int):+ """A stand-in for a header parse: rejects anything short."""++ def validate(path: str) -> None:+ if os.path.getsize(path) != expected_size:+ raise ValueError(f"{path}: truncated")++ return validate++ def test_a_poisoned_cache_entry_is_refetched(self, tmp_path) -> None:+ payload = b"the-whole-file"+ url = self._serve(tmp_path, payload)+ model_dir = tmp_path / "cache"+ model_dir.mkdir()+ (model_dir / "model.safetensors").write_bytes(payload[:4])++ path = download_file_from_url(+ url,+ model_dir=str(model_dir),+ progress=False,+ validate=self._reject_truncated(len(payload)),+ )++ assert Path(path).read_bytes() == payload++ def test_without_validate_the_poisoned_entry_is_returned(self, tmp_path) -> None:+ """The behaviour ``validate`` opts out of, pinned so it stays a choice."""+ payload = b"the-whole-file"+ url = self._serve(tmp_path, payload)+ model_dir = tmp_path / "cache"+ model_dir.mkdir()+ (model_dir / "model.safetensors").write_bytes(payload[:4])++ path = download_file_from_url(url, model_dir=str(model_dir), progress=False)++ assert Path(path).read_bytes() == payload[:4]++ def test_a_good_cache_entry_is_not_refetched(self, monkeypatch, tmp_path) -> None:+ """``validate`` runs on hits, so it must not cost a transfer when it passes."""+ payload = b"the-whole-file"+ url = self._serve(tmp_path, payload)+ model_dir = tmp_path / "cache"+ transfers: list[str] = []+ real = torch.hub.download_url_to_file++ def counted(url_, dst, *args, **kwargs):+ transfers.append(url_)+ return real(url_, dst, *args, **kwargs)++ monkeypatch.setattr(torch.hub, "download_url_to_file", counted)+ validate = self._reject_truncated(len(payload))++ first = download_file_from_url(url, model_dir=str(model_dir), progress=False, validate=validate)+ second = download_file_from_url(url, model_dir=str(model_dir), progress=False, validate=validate)++ assert second == first+ assert transfers == [url], "a valid cache entry was fetched again"++ def test_a_source_that_serves_a_bad_file_falls_through_to_the_next(self, tmp_path) -> None:+ payload = b"the-whole-file"+ bad = tmp_path / "remote" / "bad.safetensors"+ bad.parent.mkdir(parents=True, exist_ok=True)+ bad.write_bytes(payload[:4])+ good_url = self._serve(tmp_path, payload)++ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ path = download_file_from_url(+ [bad.as_uri(), good_url],+ file_name="model.safetensors",+ model_dir=str(tmp_path / "cache"),+ progress=False,+ validate=self._reject_truncated(len(payload)),+ )++ assert Path(path).read_bytes() == payload++ def test_a_file_that_never_validates_raises_and_keeps_the_original(self, tmp_path) -> None:+ """Nothing on disk is known-good, so the pre-call entry is put back.++ Deleting instead would destroy a multi-gigabyte checkpoint over a+ validator that was wrong, which is why the quarantine renames.+ """+ payload = b"the-whole-file"+ url = self._serve(tmp_path, payload)+ model_dir = tmp_path / "cache"+ model_dir.mkdir()+ (model_dir / "model.safetensors").write_bytes(b"original")++ def always_reject(path: str) -> None:+ raise ValueError("never valid")++ with pytest.raises(RuntimeError, match="Failed to download the file"):+ download_file_from_url(url, model_dir=str(model_dir), progress=False, validate=always_reject)++ assert (model_dir / "model.safetensors").read_bytes() == b"original"++ def test_check_safetensors_rejects_a_truncated_checkpoint(self, tmp_path) -> None:+ """The validator the builders actually pass."""+ import json+ import struct++ from kornia.core.safetensors import check_safetensors++ data = torch.arange(8, dtype=torch.float32).numpy().tobytes()+ header = json.dumps({"a": {"dtype": "F32", "shape": [8], "data_offsets": [0, len(data)]}}).encode()+ whole = struct.pack("<Q", len(header)) + header + data++ good = tmp_path / "good.safetensors"+ good.write_bytes(whole)+ check_safetensors(good) # must not raise++ truncated = tmp_path / "bad.safetensors"+ truncated.write_bytes(whole[:-4])+ with pytest.raises(ValueError):+ check_safetensors(truncated)diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.pyindex 3e4bf3a68..6afa38094 100644--- a/tests/models/test_kimi_vl.py+++ b/tests/models/test_kimi_vl.py@@ -83,7 +83,10 @@ class TestKimiVLBuilder(BaseTester):assert state_dict is expectedread.assert_called_once_with("cached.safetensors")download.assert_called_once_with(- "kornia/kimi-vl-a3b-instruct-vision", "model.safetensors", model_dir=str(tmp_path)+ "kornia/kimi-vl-a3b-instruct-vision",+ "model.safetensors",+ model_dir=str(tmp_path),+ validate=kimi_vl_builder.check_safetensors,)def test_pretrained_config_matches_checkpoint_grid(self):diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.pyindex 8cead341b..c8a491304 100644--- a/tests/models/test_siglip2.py+++ b/tests/models/test_siglip2.py@@ -85,7 +85,10 @@ class TestSigLip2Builder:# The repository reaches the downloader whole, so its cache name carries# the owner; every HF repo publishes a ``model.safetensors``.download.assert_called_once_with(- "google/siglip2-base-patch16-224", "model.safetensors", model_dir=str(tmp_path)+ "google/siglip2-base-patch16-224",+ "model.safetensors",+ model_dir=str(tmp_path),+ validate=siglip2_builder.check_safetensors,)def test_the_variant_reaches_the_downloader(self, tmp_path):