π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Load safetensors checkpoints with pure torch and kornia's own downloader (#4293)
Dmytro Mishkin14ce0f3331ea
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex acf62c863..63cca7504 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+* KimiVL and SigLIP2 builders load their safetensors checkpoints with kornia's own downloader+ (`kornia.core.download_hf_file`/`download_file_from_url`, which share the retrying, rate-limit-aware+ cache every other checkpoint uses) and a pure-torch reader (`kornia.core.load_safetensors`);+ `huggingface_hub` and `safetensors` are no longer needed. Both were imported without ever being+ declared as dependencies, so `KimiVLBuilder.from_pretrained_hf()` and+ `SigLip2Builder.from_pretrained_hf()` used to raise `ImportError` on a plain `pip install kornia`.+ The checkpoints move to torch's hub cache as a result; see *Breaking changes*. (#4293)* `kornia.models.RRDBNet`, a vendored Real-ESRGAN generator; `RRDBNetBuilder` no longer needs `basicsr`. (#4292)* Repeatable Oxford affine local-feature benchmarks for SIFT, SIFT-AffNet-HardNet, and@@ -121,6 +128,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Breaking changes+* `KimiVLBuilder.from_pretrained_hf()` and `SigLip2Builder.from_pretrained_hf()` cache their+ checkpoint where every other kornia checkpoint lives. `cache_dir=None` used to mean the HuggingFace+ cache (`~/.cache/huggingface/hub/models--<owner>--<name>/snapshots/<sha>/model.safetensors`) and now+ means torch's hub directory (`<torch hub dir>/checkpoints/<owner>--<name>--model.safetensors`); an+ explicit `cache_dir` used to hold the same `models--<owner>--<name>/β¦` tree and now holds the flat+ `<owner>--<name>--model.safetensors` file. Either way the first `from_pretrained_hf()` call after+ upgrading re-downloads the checkpoint (854 MB for KimiVL, ~1.5 GB for SigLIP2) even for users who+ already had it. (#4293)+* Non-maxima suppression applies one border rule at every window size. `NonMaximaSuppression2d` /`nms2d` with a window larger than `(7, 7)`, and `NonMaximaSuppression3d` / `nms3d`, no longer reportmaxima inside the `(k - 1) // 2` border strip. Previously the general path replicate-padded its input,diff --git a/docs/source/core.rst b/docs/source/core.rstindex 0fb0d5188..b907ea1f2 100644--- a/docs/source/core.rst+++ b/docs/source/core.rst@@ -11,3 +11,22 @@ kornia.core:undoc-members:.. autofunction:: kornia.core.utils.batched_forward++Weights+-------++Helpers for fetching and reading pretrained weights. :func:`load_state_dict_from_url`+is 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.++.. autofunction:: hf_url++.. autofunction:: load_state_dict_from_url++.. autofunction:: download_file_from_url++.. autofunction:: download_hf_file++.. autofunction:: load_safetensorsdiff --git a/kornia/core/__init__.py b/kornia/core/__init__.pyindex 65af84318..0f68e5a87 100644--- a/kornia/core/__init__.py+++ b/kornia/core/__init__.py@@ -21,7 +21,7 @@ This subpackage provides core functionality, device management, and backend supp"""from . import external-from .download import hf_url, load_state_dict_from_url+from .download import download_file_from_url, download_hf_file, hf_url, load_state_dict_from_urlfrom .mixin import (ImageModuleMixIn,ONNXExportMixin,@@ -29,6 +29,7 @@ from .mixin import (ONNXRuntimeMixin,)from .module import ImageModule, ImageSequential+from .safetensors import load_safetensorsfrom .tensor_wrapper import TensorWrapper__all__ = [@@ -39,9 +40,12 @@ __all__ = ["ONNXMixin","ONNXRuntimeMixin","TensorWrapper",+ "download_file_from_url",+ "download_hf_file","external","eye_like","hf_url",+ "load_safetensors","load_state_dict_from_url","vec_like",]diff --git a/kornia/core/download.py b/kornia/core/download.pyindex 216c374d3..985478fbe 100644--- a/kornia/core/download.py+++ b/kornia/core/download.py@@ -32,25 +32,78 @@ from urllib.parse import urlparseimport torch-_HF_KORNIA_BASE = "https://huggingface.co/kornia"+_HF_BASE = "https://huggingface.co"++_HF_KORNIA_ORG = "kornia"+++def _hf_repo_id(repo: str) -> str:+ """Return the full ``owner/name`` id *repo* names.++ A repository *name* cannot contain a ``/``, so one marks a spelling that+ already carries its owner; anything else is a repository in the ``kornia``+ org. Both spellings of the same kornia repo must resolve identically, or the+ URL and the cache name derived from them could disagree.++ Example:+ >>> _hf_repo_id("hardnet"), _hf_repo_id("kornia/hardnet")+ ('kornia/hardnet', 'kornia/hardnet')+ """+ return repo if "/" in repo else f"{_HF_KORNIA_ORG}/{repo}"def hf_url(repo: str, filename: str) -> str:- """Return the HuggingFace URL for a file in a kornia model repo.+ """Return the HuggingFace URL for a file in a model repo.Args:- repo: repository name under the ``kornia`` HF org (e.g. ``"hardnet"``).+ repo: repository name under the ``kornia`` HF org (e.g. ``"hardnet"``),+ or a full ``owner/name`` repository id for a repo owned by anyone+ else (e.g. ``"google/siglip2-base-patch16-224"``). The two are told+ apart by the ``/``, which a repository *name* cannot contain.filename: file at the root of that repo (e.g. ``"HardNetPP.pth"``).Returns:A ``resolve/main`` URL that can be passed directly to- :func:`load_state_dict_from_url`.+ :func:`load_state_dict_from_url` or :func:`download_file_from_url`.Example:>>> hf_url("hardnet", "HardNetPP.pth")'https://huggingface.co/kornia/hardnet/resolve/main/HardNetPP.pth'+ >>> hf_url("google/siglip2-base-patch16-224", "model.safetensors")+ 'https://huggingface.co/google/siglip2-base-patch16-224/resolve/main/model.safetensors'"""- return f"{_HF_KORNIA_BASE}/{repo}/resolve/main/{filename}"+ return f"{_HF_BASE}/{_hf_repo_id(repo)}/resolve/main/{filename}"+++def _hf_cache_file_name(repo: str, filename: str) -> str:+ """Return a cache filename that cannot collide with another repo's.++ The download cache is one flat directory keyed by filename, which is fine+ while every checkpoint has a name of its own -- and wrong the moment two+ repositories publish the same one. Every safetensors repository on the Hub+ calls its single-shard checkpoint ``model.safetensors``, so caching by the+ URL basename would hand the second model whichever one was fetched first,+ silently and forever.++ The repository id is folded into the name with ``--`` for the same reason+ the Hub's own cache layout does: it is not a path separator, so the result+ stays one filename in one directory.++ Args:+ repo: the repository, in either spelling :func:`hf_url` accepts. Both+ resolve to the same cache name, because they resolve to the same URL.+ filename: the file's name within that repository.++ Returns:+ The cache filename to pass as ``file_name``.++ Example:+ >>> _hf_cache_file_name("kornia/kimi-vl-a3b-instruct-vision", "model.safetensors")+ 'kornia--kimi-vl-a3b-instruct-vision--model.safetensors'+ >>> _hf_cache_file_name("hardnet", "HardNetPP.pth")+ 'kornia--hardnet--HardNetPP.pth'+ """+ return f"{_hf_repo_id(repo).replace('/', '--')}--{filename}"_TRANSIENT_HTTP_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})@@ -725,3 +778,139 @@ def load_state_dict_from_url(url: str | list[str], **kwargs: Any) -> dict[str, A# ``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_exc+++def download_file_from_url(+ url: str | list[str],+ *,+ file_name: str | None = None,+ model_dir: str | None = None,+ progress: bool = True,+) -> str:+ """Download a file into the torch hub cache and return its path, without loading it.++ The sibling of :func:`load_state_dict_from_url` for a checkpoint torch+ cannot unpickle -- a ``.safetensors`` file, read afterwards with+ :func:`kornia.core.load_safetensors`. It shares that function's cache, its+ fallback-URL handling, its retry-with-backoff on transient failures and rate+ limits (see :data:`_MAX_ATTEMPTS` and :func:`_retry_delay`), and its habit of+ announcing a transfer on :data:`sys.stderr` rather than stdout. A file+ already 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.++ Args:+ url: a URL string, or a list of URL strings tried left-to-right.+ file_name: name to cache the file under. Defaults to the basename of the+ URL -- of the *first* URL when several are given, so that every+ source shares one cache slot. Pass it explicitly whenever that+ basename is not unique to this file: two repositories publishing a+ ``model.safetensors`` each would otherwise share one cache entry, and+ the second model would silently load the first one's weights (see+ :func:`_hf_cache_file_name`). Must be a bare filename: the cache is+ one flat directory, so a value carrying a path separator or naming+ ``.``/``..`` would write outside it.+ 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.++ Returns:+ The path of the cached file.++ Raises:+ ValueError: if ``file_name`` is not a single path component.+ RuntimeError: if every URL fails. The message carries the last failure's+ type and text, the source it came from and the cache path in play,+ and the exception itself is chained.++ Example:+ >>> path = download_file_from_url( # doctest: +SKIP+ ... hf_url("kimi-vl-a3b-instruct-vision", "model.safetensors"),+ ... file_name="kornia--kimi-vl-a3b-instruct-vision--model.safetensors",+ ... )+ """+ if file_name is not None and (file_name in {"", ".", ".."} or os.path.basename(file_name) != file_name):+ raise ValueError(f"file_name must be a bare filename inside the cache directory, got {file_name!r}.")+ urls = [url] if isinstance(url, str) else list(url)++ # Pin the cache filename to the primary URL's basename so that all attempts+ # share one cache slot, exactly as :func:`load_state_dict_from_url` does.+ if len(urls) > 1 and file_name is None:+ file_name = Path(urlparse(urls[0]).path).name+ kwargs: dict[str, Any] = {"model_dir": model_dir, "file_name": file_name, "progress": progress}++ cache_path = _cached_file_path(urls[0], kwargs)+ budget = _SleepBudget(_MAX_CALL_SLEEP_SECONDS)+ last_exc: Exception | None = None+ last_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++ raise RuntimeError(+ f"Failed to download the file from all {len(urls)} source(s). "+ f"Last URL tried: {last_url!r}. "+ f"Last error: {type(last_exc).__name__}: {last_exc}. "+ # 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_exc+++def download_hf_file(repo: str, filename: str, *, model_dir: str | None = None, progress: bool = True) -> 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+ already made: the ``resolve/main`` URL, and a cache name that carries the+ repository id. The second one is not optional -- every repository publishing+ a single-shard checkpoint calls it ``model.safetensors``, and the cache is+ one flat directory, so caching under the URL basename would serve one+ repository's weights for another's, silently and on every later call.++ Args:+ repo: repository name under the ``kornia`` HF org, or a full+ ``owner/name`` id; see :func:`hf_url`.+ filename: file at the root of that repo.+ 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.++ Returns:+ The path of the cached file. Read a ``.safetensors`` one with+ :func:`kornia.core.load_safetensors`.++ Raises:+ ValueError: if ``filename`` carries a path separator; only files at the+ repository root are supported, because the cache is one flat directory.+ RuntimeError: if the download fails; see :func:`download_file_from_url`.++ Example:+ >>> path = download_hf_file( # doctest: +SKIP+ ... "kimi-vl-a3b-instruct-vision", "model.safetensors"+ ... )+ """+ return download_file_from_url(+ hf_url(repo, filename),+ file_name=_hf_cache_file_name(repo, filename),+ model_dir=model_dir,+ progress=progress,+ )diff --git a/kornia/core/safetensors.py b/kornia/core/safetensors.pynew file mode 100644index 000000000..5507a513f--- /dev/null+++ b/kornia/core/safetensors.py@@ -0,0 +1,269 @@+# 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.+#++"""Read ``.safetensors`` checkpoints with nothing but :mod:`torch`.++The format is small enough to read directly -- an 8-byte little-endian length,+a JSON header of that length, then one contiguous byte buffer the header indexes+into -- so a checkpoint published in it costs kornia no dependency. See+https://github.com/huggingface/safetensors#format for the specification.+"""++from __future__ import annotations++import json+import mmap+import os+from typing import Any, NamedTuple++import torch++__all__ = ["load_safetensors"]+++class _TensorEntry(NamedTuple):+ """One header entry, validated: what to read, from where, and how much."""++ dtype: torch.dtype+ shape: list[int]+ start: int+ end: int+ numel: int+++_DTYPES: dict[str, torch.dtype] = {+ "F64": torch.float64,+ "F32": torch.float32,+ "F16": torch.float16,+ "BF16": torch.bfloat16,+ "I64": torch.int64,+ "I32": torch.int32,+ "I16": torch.int16,+ "I8": torch.int8,+ "U8": torch.uint8,+ "BOOL": torch.bool,+}+"""The dtype names this reader accepts, mapped to their torch equivalents.++The format also defines the unsigned widths above 8 bits and two 8-bit float+encodings. They are left out rather than guessed at: torch's ``uint16``/``uint32``+/``uint64`` support only a fraction of the operator surface, and the ``F8``+encodings need a scale that the format does not carry. A checkpoint using one is+rejected by name instead of being read as something else.+"""++_ITEMSIZES: dict[str, int] = {name: torch.empty(0, dtype=dtype).element_size() for name, dtype in _DTYPES.items()}+"""Bytes per element for each accepted dtype, taken from torch rather than written down."""++_HEADER_LEN_BYTES = 8+"""Width of the little-endian unsigned integer the file opens with."""++_MAX_HEADER_BYTES = 100_000_000+"""Ceiling on the declared header length, matching the reference implementation.++The length is read before anything is validated, so a corrupt or hostile file can+name a header of any size a 64-bit integer can hold. Without a bound, the read+below would be asked for that many bytes.+"""+++def _parse_entry(path: str, name: str, entry: Any, data_len: int) -> _TensorEntry:+ """Validate one header entry and return what is needed to read it.++ Args:+ path: the file the entry came from, named in every error message so the+ caller has something to delete or re-download.+ name: the tensor's key in the header.+ entry: the header value for *name*, which a valid file states as a dict+ with ``dtype``, ``shape`` and ``data_offsets``.+ data_len: the size of the byte buffer the offsets index into.++ Returns:+ The entry's dtype, shape, byte range relative to the start of the byte+ buffer, and number of elements.++ Raises:+ ValueError: if the entry is malformed, names a dtype this reader does not+ accept, or describes a byte range that is outside the buffer or the+ wrong size for its shape and dtype.+ """+ if not isinstance(entry, dict):+ raise ValueError(f"{path}: header entry {name!r} is {type(entry).__name__}, expected an object.")+ missing = [key for key in ("dtype", "shape", "data_offsets") if key not in entry]+ if missing:+ raise ValueError(f"{path}: header entry {name!r} is missing {', '.join(missing)}.")++ dtype_name = entry["dtype"]+ if dtype_name not in _DTYPES:+ raise ValueError(+ f"{path}: tensor {name!r} has dtype {dtype_name!r}, which this reader does not support. "+ f"Supported dtypes: {', '.join(sorted(_DTYPES))}."+ )+ dtype = _DTYPES[dtype_name]++ shape = entry["shape"]+ # ``bool`` is an ``int`` subclass and would pass a bare isinstance check, so+ # a shape of ``[True]`` must not read as ``[1]``.+ if not isinstance(shape, list) or any(not isinstance(d, int) or isinstance(d, bool) or d < 0 for d in shape):+ raise ValueError(f"{path}: tensor {name!r} has shape {shape!r}, expected a list of non-negative integers.")++ offsets = entry["data_offsets"]+ if (+ not isinstance(offsets, list)+ or len(offsets) != 2+ or any(not isinstance(o, int) or isinstance(o, bool) or o < 0 for o in offsets)+ ):+ raise ValueError(f"{path}: tensor {name!r} has data_offsets {offsets!r}, expected two non-negative integers.")+ start, end = offsets+ if start > end or end > data_len:+ raise ValueError(+ f"{path}: tensor {name!r} claims bytes [{start}, {end}) of a {data_len}-byte buffer, "+ f"which is not a range inside it."+ )++ numel = 1+ for dim in shape:+ numel *= dim+ expected = numel * _ITEMSIZES[dtype_name]+ if end - start != expected:+ raise ValueError(+ f"{path}: tensor {name!r} is {dtype_name}{shape}, which is {expected} bytes, "+ f"but its data_offsets span {end - start}."+ )+ return _TensorEntry(dtype, shape, start, end, numel)+++def _check_the_buffer_is_covered_once(path: str, parsed: dict[str, _TensorEntry], data_len: int) -> None:+ """Reject a byte buffer the entries do not tile exactly.++ The format requires the buffer to be entirely indexed and free of holes,+ which the per-entry checks do not give: each one only asks whether its own+ range fits. Two entries claiming ``[0, 8]`` and ``[4, 8]`` both fit, and+ would be read as two tensors sharing four bytes -- a file that no writer+ produces and that no reader should quietly accept, since the values one of+ them returns are not the values it was given. A gap is the same defect seen+ from the other side: bytes nothing accounts for mean the header does not+ describe this file.++ Entries are ordered by ``(start, end)`` rather than by name, so an empty+ tensor -- zero bytes at the position the next one starts at -- sorts before+ its neighbour instead of appearing to overlap it.++ Args:+ path: the file being read, named in the error.+ parsed: the validated entries, keyed by tensor name.+ data_len: the size of the byte buffer they must cover.++ Raises:+ ValueError: if the ranges overlap, leave a gap, or stop short of the end+ of the buffer.+ """+ offset = 0+ for name, entry in sorted(parsed.items(), key=lambda item: (item[1].start, item[1].end)):+ if entry.start != offset:+ problem = (+ "overlaps the entry before it" if entry.start < offset else "leaves a gap after the entry before it"+ )+ raise ValueError(+ f"{path}: tensor {name!r} starts at byte {entry.start} where the buffer is covered "+ f"up to {offset}, so it {problem}."+ )+ offset = entry.end+ if offset != data_len:+ raise ValueError(+ f"{path}: the entries cover {offset} bytes of a {data_len}-byte buffer, "+ f"so {data_len - offset} bytes belong to no tensor."+ )+++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.++ A pure-torch reader for the format described at+ https://github.com/huggingface/safetensors#format: eight bytes of+ little-endian header length, a JSON header of that length naming each+ tensor's dtype, shape and byte range, and one contiguous byte buffer those+ ranges index into. The optional ``__metadata__`` key is ignored.++ The file is memory-mapped rather than read whole, so a multi-gigabyte+ checkpoint is not held in memory twice. The mapping is private+ (:data:`mmap.ACCESS_COPY`) rather than read-only: :func:`torch.frombuffer`+ warns on a buffer it cannot write to, and a private mapping is writable+ without touching the file -- nothing here writes to it, so no page is ever+ copied. Every tensor is copied out of the mapping before it is returned, so+ the returned state dict owns its storage and the file is closed by the time+ this function returns.++ Args:+ path: the checkpoint to read.+ device: the device the returned tensors are placed on.++ Returns:+ The state dict, in the order the header lists it.++ Raises:+ ValueError: if the file is not a readable safetensors checkpoint --+ truncated, a header that is not JSON, an entry naming a dtype this+ reader does not accept, a byte range that does not match the tensor+ it belongs to, or entries that overlap or leave part of the buffer+ unaccounted for. Every message names the file.+ OSError: if the file cannot be opened or mapped.++ Example:+ >>> state_dict = load_safetensors("model.safetensors") # doctest: +SKIP+ """+ 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)++ state_dict: dict[str, torch.Tensor] = {}+ # ``ACCESS_COPY`` maps the whole file, so the offsets below are file+ # offsets: the byte buffer starts at ``data_start``.+ with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_COPY) as buf:+ for name, (dtype, shape, start, _, numel) in parsed.items():+ if numel == 0:+ # ``torch.frombuffer`` rejects a count of 0, and an empty+ # tensor stores no bytes to point at anyway.+ state_dict[name] = torch.empty(shape, dtype=dtype, device=device)+ continue+ flat = torch.frombuffer(buf, dtype=dtype, count=numel, offset=data_start + start)+ # ``copy=True`` is what detaches the result from the mapping; the+ # tensor ``frombuffer`` returns is a view of it.+ state_dict[name] = flat.reshape(shape).to(device, copy=True)+ return state_dictdiff --git a/kornia/models/kimi_vl/builder.py b/kornia/models/kimi_vl/builder.pyindex 7008fe350..d94cc3fca 100644--- a/kornia/models/kimi_vl/builder.py+++ b/kornia/models/kimi_vl/builder.py@@ -19,40 +19,35 @@from __future__ import annotations-import loggingfrom typing import Optionalimport torch+from kornia.core.download import download_hf_file+from kornia.core.safetensors import load_safetensors+from .config import KimiVLConfig, _kimi_vl_a3b_instruct_configfrom .model import KimiVLModel-_logger = logging.getLogger(__name__)-__all__ = ["KimiVLBuilder"]_KIMI_VL_A3B_INSTRUCT_REPO_ID = "kornia/kimi-vl-a3b-instruct-vision"+_WEIGHTS_FILE = "model.safetensors"+def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, torch.Tensor]:- """Download model weights from HuggingFace Hub."""- try:- from huggingface_hub import hf_hub_download- from safetensors import safe_open- except ImportError as e:- error_msg = (- "huggingface_hub and safetensors are required for loading model weights. "- "Install them with: pip install huggingface_hub safetensors"- )- _logger.error(error_msg)- raise ImportError(error_msg) from e-- weights_path = hf_hub_download(repo_id=model_name, filename="model.safetensors", cache_dir=cache_dir)- state_dict = {}- with safe_open(weights_path, framework="pt", device="cpu") as f:- for key in f.keys():- state_dict[key] = f.get_tensor(key)- return state_dict+ """Download the checkpoint of a HuggingFace repo and read it into a state dict.++ Args:+ model_name: full ``owner/name`` repository id on the HuggingFace Hub.+ cache_dir: directory to cache the checkpoint in, or ``None`` for torch's+ hub cache -- the same cache every other kornia checkpoint uses.++ Returns:+ The checkpoint's state dict, on the CPU.+ """+ return load_safetensors(download_hf_file(model_name, _WEIGHTS_FILE, model_dir=cache_dir))class KimiVLBuilder:@@ -86,15 +81,15 @@ class KimiVLBuilder:model interpolates at runtime for other input resolutions.Args:- cache_dir: Optional cache directory for downloaded files.+ cache_dir: Optional cache directory for downloaded files. Defaults+ to torch's hub cache, which is where every other kornia+ checkpoint is cached.Returns:KimiVLModel instance with pretrained weights... note::- Only Kimi-VL-A3B-Instruct is currently supported. This method- requires the `huggingface_hub` and `safetensors` libraries:- ``pip install huggingface_hub safetensors``+ Only Kimi-VL-A3B-Instruct is currently supported."""state_dict = _download_weights(_KIMI_VL_A3B_INSTRUCT_REPO_ID, cache_dir)model = KimiVLBuilder.from_config(_kimi_vl_a3b_instruct_config())diff --git a/kornia/models/siglip2/builder.py b/kornia/models/siglip2/builder.pyindex f06476a33..59625538f 100644--- a/kornia/models/siglip2/builder.py+++ b/kornia/models/siglip2/builder.py@@ -24,6 +24,9 @@ from typing import Optionalimport torch+from kornia.core.download import download_hf_file+from kornia.core.safetensors import load_safetensors+from .config import SigLip2Configfrom .model import SigLip2Model@@ -31,29 +34,32 @@ _logger = logging.getLogger(__name__)__all__ = ["SigLip2Builder"]+_WEIGHTS_FILE = "model.safetensors"+def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, torch.Tensor]:- """Download model weights from HuggingFace Hub."""- try:- from huggingface_hub import hf_hub_download- from safetensors import safe_open- except ImportError as e:- error_msg = (- "safetensors library is required for loading model weights. Install it with: pip install safetensors"- )- _logger.error(error_msg)- raise ImportError(error_msg) from e+ """Download the checkpoint of a HuggingFace repo and read it into a state dict.++ Args:+ model_name: full ``owner/name`` repository id on the HuggingFace Hub.+ cache_dir: directory to cache the checkpoint in, or ``None`` for torch's+ hub cache -- the same cache every other kornia checkpoint uses.++ Returns:+ The checkpoint's state dict, on the CPU.+ Raises:+ FileNotFoundError: if the downloaded checkpoint is gone by the time it is+ read.+ RuntimeError: if the checkpoint cannot be downloaded.+ """+ path = download_hf_file(model_name, _WEIGHTS_FILE, model_dir=cache_dir)try:- weights_path = hf_hub_download(repo_id=model_name, filename="model.safetensors", cache_dir=cache_dir)- state_dict = {}- with safe_open(weights_path, framework="pt", device="cpu") as f:- for key in f.keys():- state_dict[key] = f.get_tensor(key)- return state_dict+ return load_safetensors(path)except FileNotFoundError as e:error_msg = (- f"Could not find model.safetensors for {model_name}. The model must be available in safetensors format."+ f"Could not find model.safetensors for {model_name} at {path}: the cached checkpoint disappeared "+ "between the download and the read. Delete that cache entry and retry.")_logger.error(error_msg)raise FileNotFoundError(error_msg) from e@@ -125,25 +131,17 @@ class SigLip2Builder:Args:model_name: HuggingFace model identifier. Default: "google/siglip2-base-patch16-224".- cache_dir: Optional cache directory for model files.+ cache_dir: Optional cache directory for model files. Defaults to+ torch's hub cache, which is where every other kornia checkpoint+ is cached.Returns:SigLip2Model instance with pretrained weights... note::- This method requires the `huggingface_hub` library to download files.- Install it with: ``pip install huggingface_hub``- For safetensors files, also install: ``pip install safetensors``+ The repository must publish its weights as a single+ ``model.safetensors`` file at its root."""- # check for huggingface_hub dependency- try:- import huggingface_hub # noqa: F401- except ImportError as e:- raise ImportError(- "huggingface_hub library is required for downloading pretrained models. "- "Install it with: pip install huggingface_hub"- ) from e-# create config from model nameconfig = SigLip2Config.from_name(model_name)diff --git a/tests/api_surface.json b/tests/api_surface.jsonindex 33e777e76..b27c75f82 100644--- a/tests/api_surface.json+++ b/tests/api_surface.json@@ -179,8 +179,13 @@"ONNXMixin","ONNXRuntimeMixin","TensorWrapper",+ "download_file_from_url",+ "download_hf_file","external","eye_like",+ "hf_url",+ "load_safetensors",+ "load_state_dict_from_url","vec_like"],"kornia.enhance": [diff --git a/tests/core/test_download.py b/tests/core/test_download.pyindex e61f66fcb..e8659c204 100644--- a/tests/core/test_download.py+++ b/tests/core/test_download.py@@ -25,6 +25,7 @@ import timeimport warningsfrom email.message import Messagefrom email.utils import formatdate+from pathlib import Pathfrom unittest.mock import call, patchfrom urllib.error import HTTPError, URLError@@ -32,7 +33,13 @@ import pytestimport torchfrom kornia.core import download as download_mod-from kornia.core.download import hf_url, load_state_dict_from_url+from kornia.core.download import (+ _hf_cache_file_name,+ download_file_from_url,+ download_hf_file,+ hf_url,+ load_state_dict_from_url,+)@pytest.fixture(autouse=True)@@ -53,6 +60,35 @@ class TestHfUrl:url = hf_url("loftr", "loftr_outdoor.ckpt")assert url.startswith("https://huggingface.co/kornia/loftr/resolve/main/")+ def test_a_full_repo_id_keeps_its_owner(self) -> None:+ """A repo name cannot contain a ``/``, so one marks an ``owner/name`` id."""+ assert hf_url("google/siglip2-base-patch16-224", "model.safetensors") == (+ "https://huggingface.co/google/siglip2-base-patch16-224/resolve/main/model.safetensors"+ )+++class TestHfCacheFileName:+ """The cache is one flat directory, and every HF repo names its checkpoint alike."""++ def test_repo_id_is_folded_into_the_name(self) -> None:+ assert _hf_cache_file_name("kornia/kimi-vl-a3b-instruct-vision", "model.safetensors") == (+ "kornia--kimi-vl-a3b-instruct-vision--model.safetensors"+ )++ def test_both_spellings_of_a_kornia_repo_agree(self) -> None:+ """They resolve to one URL, so they must resolve to one cache entry."""+ assert _hf_cache_file_name("hardnet", "HardNetPP.pth") == _hf_cache_file_name("kornia/hardnet", "HardNetPP.pth")+ assert _hf_cache_file_name("hardnet", "HardNetPP.pth") == "kornia--hardnet--HardNetPP.pth"++ def test_two_repos_do_not_collide(self) -> None:+ first = _hf_cache_file_name("google/siglip2-base-patch16-224", "model.safetensors")+ second = _hf_cache_file_name("google/siglip2-base-patch16-256", "model.safetensors")+ assert first != second++ def test_the_result_is_one_path_component(self) -> None:+ name = _hf_cache_file_name("google/siglip2-base-patch16-224", "model.safetensors")+ assert os.sep not in name and "/" not in name+class TestLoadStateDictFromUrl:_SD = {"weight": 1}@@ -1120,3 +1156,231 @@ class TestFailureMessageCarriesCause: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)+++class TestDownloadFileFromUrl:+ """The path for checkpoints torch cannot unpickle -- a ``.safetensors`` file.++ The transfers here are real: a ``file://`` URL goes through the same+ ``torch.hub.download_url_to_file`` a remote one does, so the cache path, the+ bytes on disk and the cache hit are all exercised end to end without a+ network or a stub standing in for the transfer.+ """++ @staticmethod+ def _serve(tmp_path, name: str = "model.safetensors", payload: bytes = b"weights") -> tuple[str, bytes]:+ """Write a file and return the ``file://`` URL that serves it."""+ source = tmp_path / "remote" / name+ source.parent.mkdir(parents=True, exist_ok=True)+ source.write_bytes(payload)+ return source.as_uri(), payload++ def test_downloads_into_model_dir(self, tmp_path) -> None:+ url, payload = self._serve(tmp_path)+ model_dir = tmp_path / "cache"++ path = download_file_from_url(url, model_dir=str(model_dir), progress=False)++ assert path == str(model_dir / "model.safetensors")+ assert Path(path).read_bytes() == payload++ def test_second_call_is_a_cache_hit(self, monkeypatch, tmp_path) -> None:+ url, _ = self._serve(tmp_path)+ 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)++ first = download_file_from_url(url, model_dir=str(model_dir), progress=False)+ second = download_file_from_url(url, model_dir=str(model_dir), progress=False)++ assert second == first+ assert transfers == [url], "the cached file was fetched again"++ def test_defaults_to_the_torch_hub_cache(self, monkeypatch, tmp_path) -> None:+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path / "hub"))+ url, _ = self._serve(tmp_path)++ path = download_file_from_url(url, progress=False)++ assert path == str(tmp_path / "hub" / "checkpoints" / "model.safetensors")++ def test_file_name_overrides_the_basename(self, tmp_path) -> None:+ """Two repositories publish a ``model.safetensors`` each; one cache slot is not enough."""+ first_url, first_payload = self._serve(tmp_path / "a", payload=b"first")+ second_url, second_payload = self._serve(tmp_path / "b", payload=b"second")+ model_dir = tmp_path / "cache"++ first = download_file_from_url(first_url, file_name="a--model.safetensors", model_dir=str(model_dir))+ second = download_file_from_url(second_url, file_name="b--model.safetensors", model_dir=str(model_dir))++ assert first != second+ assert Path(first).read_bytes() == first_payload+ assert Path(second).read_bytes() == second_payload++ def test_fallback_source_is_tried(self, monkeypatch, tmp_path) -> None:+ url, payload = self._serve(tmp_path)+ model_dir = tmp_path / "cache"+ dead = (tmp_path / "remote" / "missing.safetensors").as_uri()+ # A missing file:// URL raises URLError, which is transient, so the dead+ # source is retried before the fallback is reached; the waits are faked.+ monkeypatch.setattr(download_mod, "time", _FakeTime())++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ path = download_file_from_url([dead, url], model_dir=str(model_dir), progress=False)++ # The cache name is pinned to the *first* URL, as in load_state_dict_from_url.+ assert path == str(model_dir / "missing.safetensors")+ assert Path(path).read_bytes() == payload+ assert any("Trying next source" in str(warning.message) for warning in caught)++ def test_all_sources_failing_names_the_cause_and_the_path(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, 404)),+ )++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ with pytest.raises(RuntimeError) as excinfo:+ download_file_from_url(["http://a.example.com/m.safetensors", "http://b.example.com/m.safetensors"])++ message = str(excinfo.value)+ assert "Failed to download the file from all 2 source" in message+ assert "HTTPError" in message and "404" in message+ assert os.path.join(str(tmp_path), "checkpoints", "m.safetensors") in message+ assert isinstance(excinfo.value.__cause__, HTTPError)++ def test_a_transient_failure_is_retried(self, monkeypatch, tmp_path) -> None:+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))+ monkeypatch.setattr(download_mod, "time", _FakeTime())+ attempts: list[str] = []++ def flaky(url, dst, *args, **kwargs):+ attempts.append(url)+ if len(attempts) < 3:+ raise _http_error(url, 429)+ Path(dst).write_bytes(b"weights")++ monkeypatch.setattr(torch.hub, "download_url_to_file", flaky)++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ path = download_file_from_url("http://example.com/m.safetensors", progress=False)++ assert len(attempts) == 3+ assert Path(path).read_bytes() == b"weights"++ def test_a_partial_transfer_does_not_block_the_next_source(self, monkeypatch, tmp_path) -> None:+ """A source that writes and then fails must not be handed to the next one as a cache hit."""+ monkeypatch.setattr(torch.hub, "get_dir", lambda: str(tmp_path))++ def half_written(url, dst, *args, **kwargs):+ if "primary" in url:+ Path(dst).write_bytes(b"truncated")+ raise OSError("connection reset")+ Path(dst).write_bytes(b"complete")++ monkeypatch.setattr(torch.hub, "download_url_to_file", half_written)++ with warnings.catch_warnings(record=True):+ warnings.simplefilter("always")+ path = download_file_from_url(+ ["http://primary.example.com/m.safetensors", "http://mirror.example.com/m.safetensors"],+ progress=False,+ )++ # ``b"truncated"`` here would mean the mirror was skipped: the two share+ # one cache path, so the primary's leftovers would have read as a hit.+ assert Path(path).read_bytes() == b"complete"++ def test_transfer_is_announced_on_stderr_only(self, capsys, tmp_path) -> None:+ url, _ = self._serve(tmp_path)++ download_file_from_url(url, model_dir=str(tmp_path / "cache"), progress=False)++ captured = capsys.readouterr()+ assert captured.out == ""+ assert f'Downloading: "{url}"' in captured.err++ @pytest.mark.parametrize("file_name", ["../escaped.safetensors", "sub/model.safetensors", "", ".", ".."])+ def test_file_name_must_be_a_bare_filename(self, tmp_path, file_name) -> None:+ """The cache is one flat directory; a name with a path in it would write outside it."""+ url, _ = self._serve(tmp_path)+ model_dir = tmp_path / "cache"++ with pytest.raises(ValueError, match="bare filename"):+ download_file_from_url(url, file_name=file_name, model_dir=str(model_dir), progress=False)++ assert not (tmp_path / "escaped.safetensors").exists()+ assert not model_dir.exists(), "nothing was transferred"++ def test_an_absolute_file_name_is_rejected(self, tmp_path) -> None:+ url, _ = self._serve(tmp_path)++ with pytest.raises(ValueError, match="bare filename"):+ download_file_from_url(url, file_name=str(tmp_path / "abs.safetensors"), model_dir=str(tmp_path / "cache"))++ assert not (tmp_path / "abs.safetensors").exists()+++class TestDownloadHfFile:+ """The Hub wrapper: the ``resolve/main`` URL and the collision-free cache name in one call."""++ @staticmethod+ def _capture(monkeypatch) -> list[tuple]:+ """Record what reaches ``download_file_from_url`` instead of downloading."""+ calls: list[tuple] = []++ def fake(url, **kwargs):+ calls.append((url, kwargs))+ return "cached"++ monkeypatch.setattr(download_mod, "download_file_from_url", fake)+ return calls++ def test_full_repo_id(self, monkeypatch) -> None:+ calls = self._capture(monkeypatch)++ assert download_hf_file("google/siglip2-base-patch16-224", "model.safetensors") == "cached"++ url, kwargs = calls[0]+ assert url == "https://huggingface.co/google/siglip2-base-patch16-224/resolve/main/model.safetensors"+ assert kwargs["file_name"] == "google--siglip2-base-patch16-224--model.safetensors"+ assert kwargs["model_dir"] is None++ def test_bare_repo_name_resolves_under_the_kornia_org(self, monkeypatch, tmp_path) -> None:+ calls = self._capture(monkeypatch)++ download_hf_file("kimi-vl-a3b-instruct-vision", "model.safetensors", model_dir=str(tmp_path), progress=False)++ url, kwargs = calls[0]+ assert url == "https://huggingface.co/kornia/kimi-vl-a3b-instruct-vision/resolve/main/model.safetensors"+ # The org is in the cache name too, so the bare and full spellings of the+ # same repo cannot end up in two cache entries.+ assert kwargs["file_name"] == "kornia--kimi-vl-a3b-instruct-vision--model.safetensors"+ assert kwargs["model_dir"] == str(tmp_path)+ assert kwargs["progress"] is False++ def test_two_repos_publishing_the_same_filename_do_not_collide(self, tmp_path) -> None:+ """End to end, through a real transfer: one cache directory, two entries."""+ model_dir = tmp_path / "cache"+ paths = []+ for owner in ("kornia", "google"):+ source = tmp_path / owner / "model.safetensors"+ source.parent.mkdir(parents=True, exist_ok=True)+ source.write_bytes(owner.encode())+ with patch.object(download_mod, "hf_url", return_value=source.as_uri()):+ paths.append(download_hf_file(f"{owner}/a-model", "model.safetensors", model_dir=str(model_dir)))++ assert paths[0] != paths[1]+ assert Path(paths[0]).read_bytes() == b"kornia"+ assert Path(paths[1]).read_bytes() == b"google"diff --git a/tests/core/test_safetensors.py b/tests/core/test_safetensors.pynew file mode 100644index 000000000..847157856--- /dev/null+++ b/tests/core/test_safetensors.py@@ -0,0 +1,314 @@+# 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.+#++"""Tests for the pure-torch ``.safetensors`` reader.++Every file here is written **by hand** from the format specification+(https://github.com/huggingface/safetensors#format) rather than by the+``safetensors`` package. That package is a transitive dependency of the dev+environment, so a test that used it to produce the fixtures would pass locally+and prove nothing about the install kornia actually declares -- and a test that+used it to produce the *expectations* would only be comparing two readers.+"""++from __future__ import annotations++import json+import re+import struct+import warnings+from pathlib import Path+from typing import Any++import pytest+import torch++from kornia.core.safetensors import load_safetensors++# Names the format gives the dtypes this reader accepts, for the fixtures below.+_NAMES: dict[torch.dtype, str] = {+ torch.float64: "F64",+ torch.float32: "F32",+ torch.float16: "F16",+ torch.bfloat16: "BF16",+ torch.int64: "I64",+ torch.int32: "I32",+ torch.int16: "I16",+ torch.int8: "I8",+ torch.uint8: "U8",+ torch.bool: "BOOL",+}+++def _raw(tensor: torch.Tensor) -> bytes:+ """Return a tensor's little-endian row-major bytes.++ ``view(torch.uint8)`` reinterprets the storage without touching it, so this+ is the tensor's own bytes rather than a re-encoding of its values -- which is+ what makes the round-trip assertions below exact.+ """+ if tensor.numel() == 0:+ return b""+ return tensor.contiguous().view(torch.uint8).numpy().tobytes()+++def _build(tensors: dict[str, torch.Tensor], metadata: dict[str, str] | None = None) -> bytes:+ """Serialise *tensors* into safetensors bytes, straight from the spec."""+ header: dict[str, Any] = {}+ blob = b""+ for name, tensor in tensors.items():+ payload = _raw(tensor)+ header[name] = {+ "dtype": _NAMES[tensor.dtype],+ "shape": list(tensor.shape),+ "data_offsets": [len(blob), len(blob) + len(payload)],+ }+ blob += payload+ if metadata is not None:+ header["__metadata__"] = metadata+ return _pack(header, blob)+++def _pack(header: Any, blob: bytes) -> bytes:+ """Assemble a file from a header object and a byte buffer, valid or not."""+ encoded = json.dumps(header).encode("utf-8")+ return struct.pack("<Q", len(encoded)) + encoded + blob+++def _write(tmp_path: Path, payload: bytes) -> Path:+ path = tmp_path / "model.safetensors"+ path.write_bytes(payload)+ return path+++def tensors() -> dict[str, torch.Tensor]:+ """One tensor per interesting case: a float grid, bf16, int64 and an empty one."""+ return {+ "weight": torch.randn(3, 4),+ # bfloat16 has no numpy equivalent, so a reader that goes through numpy+ # cannot serve it at all -- and its 16-bit values are easy to read as+ # float16 by mistake, which would be silently wrong rather than an error.+ "scale": torch.tensor([1.5, -2.0, 0.25], dtype=torch.bfloat16),+ "index": torch.arange(6, dtype=torch.int64).reshape(2, 3),+ # A dimension of 0 stores no bytes but keeps its shape in the header.+ "empty": torch.zeros(0, 5),+ }+++class TestLoadSafetensors:+ def test_round_trip(self, tmp_path, tensors) -> None:+ path = _write(tmp_path, _build(tensors, {"format": "pt"}))++ loaded = load_safetensors(path)++ assert list(loaded) == list(tensors), "the header order is the state dict order"+ for name, expected in tensors.items():+ assert loaded[name].dtype == expected.dtype, name+ assert loaded[name].shape == expected.shape, name+ assert torch.equal(loaded[name], expected), name++ def test_metadata_is_not_a_tensor(self, tmp_path, tensors) -> None:+ path = _write(tmp_path, _build(tensors, {"format": "pt"}))++ assert "__metadata__" not in load_safetensors(path)++ def test_reads_a_path_object(self, tmp_path, tensors) -> None:+ path = _write(tmp_path, _build(tensors))++ assert torch.equal(load_safetensors(Path(path))["weight"], tensors["weight"])++ def test_emits_no_warning(self, tmp_path, tensors) -> None:+ """``torch.frombuffer`` warns on a read-only buffer; the mapping must not be one."""+ path = _write(tmp_path, _build(tensors))++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ load_safetensors(path)++ assert not caught, f"load_safetensors warned: {[str(record.message) for record in caught]}"++ def test_tensors_do_not_share_the_file_buffer(self, tmp_path, tensors) -> None:+ """A returned tensor must own its storage, not view a mapping that is closed.++ Writing through a view of the closed mapping is what would crash, and a+ view of a mapping that is *not* closed would keep the file open for as+ long as the model lives.+ """+ path = _write(tmp_path, _build(tensors))++ loaded = load_safetensors(path)+ loaded["weight"] += 1.0+ loaded["index"][0, 0] = 42++ assert loaded["weight"][0, 0] == tensors["weight"][0, 0] + 1.0+ assert loaded["index"][0, 0] == 42+ # The file is untouched: a copy-on-write mapping never reaches the disk,+ # and re-reading it returns what was written.+ assert torch.equal(load_safetensors(path)["index"], tensors["index"])++ @pytest.mark.parametrize("dtype", sorted(_NAMES, key=lambda d: _NAMES[d]), ids=lambda d: _NAMES[d])+ def test_every_supported_dtype_round_trips(self, tmp_path, dtype) -> None:+ expected = torch.tensor([1, 0, 1, 1], dtype=dtype).reshape(2, 2)+ path = _write(tmp_path, _build({"t": expected}))++ loaded = load_safetensors(path)["t"]++ assert loaded.dtype == dtype+ assert torch.equal(loaded, expected)++ def test_device_is_honoured(self, tmp_path, device, tensors) -> None:+ path = _write(tmp_path, _build(tensors))++ loaded = load_safetensors(path, device=device)++ assert loaded["weight"].device.type == torch.device(device).type+ # The empty tensor takes a different branch and must land on the same device.+ assert loaded["empty"].device.type == torch.device(device).type+ assert torch.equal(loaded["weight"].cpu(), tensors["weight"])+++class TestRejectsCorruptFiles:+ """Every rejection names the file, so the caller knows what to delete."""++ def test_corrupt_data_offsets(self, tmp_path, tensors) -> None:+ header = {+ "weight": {"dtype": "F32", "shape": [3, 4], "data_offsets": [0, 40]}, # 3x4 F32 is 48 bytes+ }+ path = _write(tmp_path, _pack(header, _raw(tensors["weight"])))++ with pytest.raises(ValueError, match="48 bytes, but its data_offsets span 40"):+ load_safetensors(path)++ def test_offsets_outside_the_buffer(self, tmp_path, tensors) -> None:+ header = {"weight": {"dtype": "F32", "shape": [3, 4], "data_offsets": [16, 64]}}+ path = _write(tmp_path, _pack(header, _raw(tensors["weight"])))++ with pytest.raises(ValueError, match="not a range inside it"):+ load_safetensors(path)++ def test_reversed_offsets(self, tmp_path, tensors) -> None:+ header = {"weight": {"dtype": "F32", "shape": [3, 4], "data_offsets": [48, 0]}}+ path = _write(tmp_path, _pack(header, _raw(tensors["weight"])))++ with pytest.raises(ValueError, match="not a range inside it"):+ load_safetensors(path)++ def test_overlapping_ranges(self, tmp_path) -> None:+ """Two tensors sharing bytes: both ranges fit, and the file is still nonsense."""+ header = {+ "a": {"dtype": "F32", "shape": [2], "data_offsets": [0, 8]},+ "b": {"dtype": "F32", "shape": [2], "data_offsets": [4, 12]},+ }+ path = _write(tmp_path, _pack(header, b"\x00" * 12))++ with pytest.raises(ValueError, match="overlaps the entry before it"):+ load_safetensors(path)++ def test_a_gap_between_ranges(self, tmp_path) -> None:+ """The spec forbids holes: bytes nothing indexes mean the header is not this file's."""+ header = {+ "a": {"dtype": "F32", "shape": [2], "data_offsets": [0, 8]},+ "b": {"dtype": "F32", "shape": [2], "data_offsets": [12, 20]},+ }+ path = _write(tmp_path, _pack(header, b"\x00" * 20))++ with pytest.raises(ValueError, match="leaves a gap after the entry before it"):+ load_safetensors(path)++ def test_trailing_bytes_belong_to_no_tensor(self, tmp_path, tensors) -> None:+ path = _write(tmp_path, _build(tensors) + b"\x00" * 16)++ with pytest.raises(ValueError, match="belong to no tensor"):+ load_safetensors(path)++ def test_unknown_dtype(self, tmp_path) -> None:+ header = {"weight": {"dtype": "F8_E4M3", "shape": [2], "data_offsets": [0, 2]}}+ path = _write(tmp_path, _pack(header, b"\x00\x00"))++ with pytest.raises(ValueError, match="dtype 'F8_E4M3', which this reader does not support"):+ load_safetensors(path)++ def test_missing_field(self, tmp_path) -> None:+ header = {"weight": {"dtype": "F32", "shape": [1]}}+ path = _write(tmp_path, _pack(header, b"\x00" * 4))++ with pytest.raises(ValueError, match="missing data_offsets"):+ load_safetensors(path)++ def test_entry_is_not_an_object(self, tmp_path) -> None:+ path = _write(tmp_path, _pack({"weight": [1, 2, 3]}, b""))++ with pytest.raises(ValueError, match="header entry 'weight' is list"):+ load_safetensors(path)++ @pytest.mark.parametrize("shape", [[-1], "4", [1.5], [True]])+ def test_invalid_shape(self, tmp_path, shape) -> None:+ header = {"weight": {"dtype": "U8", "shape": shape, "data_offsets": [0, 1]}}+ path = _write(tmp_path, _pack(header, b"\x00"))++ with pytest.raises(ValueError, match="expected a list of non-negative integers"):+ load_safetensors(path)++ @pytest.mark.parametrize("offsets", [[0], [0, 1, 2], [-1, 1], "0,1", [False, True]])+ def test_invalid_offsets(self, tmp_path, offsets) -> None:+ """``[False, True]`` is the offsets twin of the ``[True]`` shape: a bool is an ``int``."""+ header = {"weight": {"dtype": "U8", "shape": [1], "data_offsets": offsets}}+ path = _write(tmp_path, _pack(header, b"\x00"))++ with pytest.raises(ValueError, match="expected two non-negative integers"):+ load_safetensors(path)++ def test_header_is_not_json(self, tmp_path) -> None:+ payload = struct.pack("<Q", 4) + b"nope"+ path = _write(tmp_path, payload)++ with pytest.raises(ValueError, match="the header is not valid JSON"):+ load_safetensors(path)++ def test_header_is_not_an_object(self, tmp_path) -> None:+ path = _write(tmp_path, _pack([1, 2], b""))++ with pytest.raises(ValueError, match="the header is a JSON list"):+ load_safetensors(path)++ def test_truncated_header(self, tmp_path, tensors) -> None:+ payload = _build(tensors)+ path = _write(tmp_path, payload[: 8 + 4])++ with pytest.raises(ValueError, match="but the file holds"):+ load_safetensors(path)++ def test_file_shorter_than_the_length_prefix(self, tmp_path) -> None:+ path = _write(tmp_path, b"\x00\x00\x00")++ with pytest.raises(ValueError, match="too short to be a safetensors file"):+ load_safetensors(path)++ def test_absurd_header_length_is_not_read(self, tmp_path) -> None:+ """A 64-bit length is read before anything is validated; it must be bounded."""+ path = _write(tmp_path, struct.pack("<Q", 2**63) + b"{}")++ with pytest.raises(ValueError, match="more than the"):+ load_safetensors(path)++ def test_the_message_names_the_file(self, tmp_path) -> None:+ header = {"weight": {"dtype": "F32", "shape": [3, 4], "data_offsets": [0, 40]}}+ path = _write(tmp_path, _pack(header, b"\x00" * 48))++ with pytest.raises(ValueError, match=re.escape(str(path))):+ load_safetensors(path)diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.pyindex fdcea9033..d18e94d15 100644--- a/tests/core/test_weights_prefetch.py+++ b/tests/core/test_weights_prefetch.py@@ -31,14 +31,24 @@ 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+invisible to the prefetch list -- its sibling+:func:`kornia.core.download.download_file_from_url`, which the vision-language+builders (``kornia/models/{kimi_vl,siglip2}/builder.py``) fetch a+``model.safetensors`` with, and ``CachedDownloader`` into``.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 matrixdownloads through either today; a test that did would fetch live from everymatrix cell with this file still green.+``download_file_from_url`` does share the ``weights/`` cache, so its callers+could in principle be prefetched -- they are not, for a reason the checkpoints+above do not have: SigLIP2 takes the repository as an *argument*, so there is no+fixed set of variants to enumerate, and the two checkpoints in play are hundreds+of megabytes for a pair of integration tests. The call-site scan below covers+both functions, so a model that starts downloading through either is caught here+either way.+``docs/generate_examples.py`` also fetches one non-checkpoint tensor(``knchurch_disk.pt``, the image pair the matching examples are drawn on)straight through ``torch.hub.load_state_dict_from_url``. It lands in the same@@ -170,10 +180,15 @@ _ENUMERATED_MODULES = (# 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/core/__init__.py`` is deliberately absent: it re-exports the+ # names without ever calling one, so the scan below never matches it and an+ # entry for it would be exactly the dead exemption+ # ``test_no_allowlisted_module_has_stopped_downloading`` exists to catch.+ "kornia/core/download.py": "defines the functions","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",+ "kornia/models/kimi_vl/builder.py": "one safetensors checkpoint, hundreds of MB, integration tests only",+ "kornia/models/siglip2/builder.py": "safetensors checkpoint of a caller-named repo; no fixed variant list",}# Checkpoints deliberately left out of the CI cache, with the reason. A variant@@ -266,6 +281,22 @@ NOT_PREFETCHED: dict[str, str] = {}+# ``download_file_from_url`` and its Hub wrapper ``download_hf_file`` fetch into+# the same cache without loading what they fetched, so a checkpoint pulled+# through either is as invisible to the prefetch list as one pulled through+# ``load_state_dict_from_url``.+_DOWNLOAD_CALL = re.compile(r"\b(?:load_state_dict_from_url|download_file_from_url|download_hf_file)\s*\(")+++def _download_call_sites() -> set[str]:+ """Return the repository-relative modules in ``kornia/`` that call a download function."""+ return {+ path.relative_to(_REPO_ROOT).as_posix()+ for path in sorted((_REPO_ROOT / "kornia").rglob("*.py"))+ if _DOWNLOAD_CALL.search(path.read_text(encoding="utf-8"))+ }++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)@@ -411,6 +442,22 @@ class TestWeightsPrefetchCoverage:f"weight source to WEIGHT_REGISTRIES so the entry is guarded in both directions.")+ def test_no_allowlisted_module_has_stopped_downloading(self) -> None:+ """A dead allowlist entry reads as coverage for a module that no longer downloads.++ The scan below subtracts this allowlist, so an entry that matches nothing+ is invisible: rename or delete a builder and its exemption survives,+ ready to excuse a *new* module that lands under the old path. The+ stale-exemption check :data:`NOT_PREFETCHED` gets is this one.+ """+ if not _KORNIA_IS_THE_CHECKOUT:+ pytest.skip("kornia is imported from outside this checkout; the call-site scan cannot match it")+ stale = sorted(set(_DOWNLOAD_CALL_ALLOWLIST) - _download_call_sites())+ assert not stale, (+ f"_DOWNLOAD_CALL_ALLOWLIST exempts modules that no longer call a download "+ f"function: {stale}. Drop the entry, or fix the path it was renamed to."+ )+def test_every_download_call_site_is_enumerated(self) -> None:"""Nothing else holds :data:`WEIGHT_REGISTRIES` to "every weight source in the library".@@ -424,13 +471,7 @@ class TestWeightsPrefetchCoverage:"""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))+ unaccounted = sorted(_download_call_sites() - _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: "diff --git a/tests/integration/models/test_kimi_vl.py b/tests/integration/models/test_kimi_vl.pyindex 0fc62a2d1..5be1a9b6c 100644--- a/tests/integration/models/test_kimi_vl.py+++ b/tests/integration/models/test_kimi_vl.py@@ -29,6 +29,7 @@ import pytestimport torchimport torch.nn.functional as F+from kornia.core import load_safetensorsfrom kornia.models.kimi_vl import KimiVLConfig, KimiVLModelfrom kornia.models.kimi_vl.config import KimiVLProjectorConfig, MoonViTConfig@@ -45,9 +46,6 @@ def test_kimi_vl_official_weights():if not weights_dir:pytest.skip("KIMI_VL_WEIGHTS_DIR is not set; skipping test_kimi_vl_official_weights")- safetensors_torch = pytest.importorskip("safetensors.torch")- load_file = safetensors_torch.load_file-index_path = os.path.join(weights_dir, "model.safetensors.index.json")if not os.path.exists(index_path):@@ -62,7 +60,7 @@ def test_kimi_vl_official_weights():state_dict = {}for shard in shards:shard_path = os.path.join(weights_dir, shard)- shard_weights = load_file(shard_path)+ shard_weights = load_safetensors(shard_path)for k in vision_keys:if k in shard_weights:state_dict[k] = shard_weights[k]diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.pyindex 322d72531..3e4bf3a68 100644--- a/tests/models/test_kimi_vl.py+++ b/tests/models/test_kimi_vl.py@@ -71,6 +71,21 @@ class TestKimiVLBuilder(BaseTester):assert actual.config is configmock_download.assert_called_once_with(kimi_vl_builder._KIMI_VL_A3B_INSTRUCT_REPO_ID, "cache")+ def test_download_weights_uses_kornias_downloader(self, tmp_path):+ """No optional package: kornia's own downloader, then its own safetensors reader."""+ expected = {"weight": torch.zeros(1)}+ with (+ patch.object(kimi_vl_builder, "download_hf_file", return_value="cached.safetensors") as download,+ patch.object(kimi_vl_builder, "load_safetensors", return_value=expected) as read,+ ):+ state_dict = kimi_vl_builder._download_weights(kimi_vl_builder._KIMI_VL_A3B_INSTRUCT_REPO_ID, str(tmp_path))++ assert state_dict is expected+ read.assert_called_once_with("cached.safetensors")+ download.assert_called_once_with(+ "kornia/kimi-vl-a3b-instruct-vision", "model.safetensors", model_dir=str(tmp_path)+ )+def test_pretrained_config_matches_checkpoint_grid(self):config = kimi_vl_builder._kimi_vl_a3b_instruct_config()# The published checkpoint stores the original 64x64 pos-embed grid.diff --git a/tests/models/test_siglip2.py b/tests/models/test_siglip2.pyindex 3e10b8c76..8cead341b 100644--- a/tests/models/test_siglip2.py+++ b/tests/models/test_siglip2.py@@ -18,10 +18,12 @@"""Tests for SigLip2 model."""from dataclasses import replace+from unittest.mock import patchimport pytestimport torch+import kornia.models.siglip2.builder as siglip2_builderfrom kornia.models.siglip2 import SigLip2Config, SigLip2Model, SigLip2Resultfrom kornia.models.siglip2.attention import SigLip2Attentionfrom kornia.models.siglip2.config import SigLip2TextConfig, SigLip2VisionConfig@@ -67,6 +69,47 @@ def _create_input_ids(batch_size, seq_len, config, device):return torch.randint(0, min(100, config.text_config.vocab_size), (batch_size, seq_len), device=device)+class TestSigLip2Builder:+ """The download path: kornia's own downloader and safetensors reader, no optional package."""++ def test_download_weights_uses_kornias_downloader(self, tmp_path):+ expected = {"weight": torch.zeros(1)}+ with (+ patch.object(siglip2_builder, "download_hf_file", return_value="cached.safetensors") as download,+ patch.object(siglip2_builder, "load_safetensors", return_value=expected) as read,+ ):+ state_dict = siglip2_builder._download_weights("google/siglip2-base-patch16-224", str(tmp_path))++ assert state_dict is expected+ read.assert_called_once_with("cached.safetensors")+ # 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)+ )++ def test_the_variant_reaches_the_downloader(self, tmp_path):+ """Two variants must not resolve to one download, and so to one cache entry."""+ repos = []+ with (+ patch.object(siglip2_builder, "download_hf_file", return_value="cached.safetensors") as download,+ patch.object(siglip2_builder, "load_safetensors", return_value={}),+ ):+ for model_name in ("google/siglip2-base-patch16-224", "google/siglip2-base-patch16-256"):+ siglip2_builder._download_weights(model_name, None)+ repos.append(download.call_args.args[0])++ assert repos == ["google/siglip2-base-patch16-224", "google/siglip2-base-patch16-256"]++ def test_a_missing_checkpoint_is_reported_with_the_model_name(self, tmp_path):+ with (+ patch.object(siglip2_builder, "download_hf_file", return_value="cached.safetensors"),+ patch.object(siglip2_builder, "load_safetensors", side_effect=FileNotFoundError("gone")),+ ):+ with pytest.raises(FileNotFoundError, match=r"Could not find model\.safetensors for google/nope"):+ siglip2_builder._download_weights("google/nope", None)++class TestSigLip2Model(BaseTester):"""Test suite for SigLip2 model."""