Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): raise ValueError for malformed safetensors headers; check_safetensors rejects empty shapes torch cannot build (#5248)

Dmytro Mishkine0102e4a040c
diff --git a/changelog.d/5248.fixed.md b/changelog.d/5248.fixed.md
new file mode 100644
index 000000000..94495bc89
--- /dev/null
+++ b/changelog.d/5248.fixed.md
@@ -0,0 +1 @@
+`check_safetensors` and `load_safetensors` now raise the documented `ValueError`, naming the file, for several malformed headers that used to escape it. Previously a `dtype` given as a JSON list or object raised `TypeError`, a deeply nested header raised `RecursionError`, and an integer too long for Python to decode, or a shape whose byte size was too large to print, raised a `ValueError` that did not name the file. A shape of many large dimensions is now rejected in linear time, where multiplying it out took about a minute for 100 000 dimensions, and error messages quote header values in shortened form. `check_safetensors` now also rejects any empty tensor shape that torch cannot build, such as `[2**63, 0]` or `[0, 2**62, 2**62]`, so `load_safetensors` can load, on the CPU, every file the check accepts. The header is still not validated beyond what the reader uses: the optional `__metadata__` entry is ignored whatever it holds, and when a key appears twice the last one wins.
diff --git a/kornia/core/safetensors.py b/kornia/core/safetensors.py
index ca0d3f12d..f39ddf6d5 100644
--- a/kornia/core/safetensors.py
+++ b/kornia/core/safetensors.py
@@ -28,6 +28,8 @@ from __future__ import annotations
import json
import mmap
import os
+import reprlib
+from collections.abc import Iterable
from typing import Any, BinaryIO, NamedTuple
import torch
@@ -72,6 +74,9 @@ _ITEMSIZES: dict[str, int] = {name: torch.empty(0, dtype=dtype).element_size() f
_HEADER_LEN_BYTES = 8
"""Width of the little-endian unsigned integer the file opens with."""
+_MAX_DIM = torch.iinfo(torch.int64).max
+"""The largest dimension a torch tensor can have: its sizes are 64-bit signed."""
+
_MAX_HEADER_BYTES = 100_000_000
"""Ceiling on the declared header length, matching the reference implementation.
@@ -80,6 +85,59 @@ 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.
"""
+_REPR = reprlib.Repr()
+_REPR.maxlevel = 3
+_REPR.maxlist = 8
+_REPR.maxdict = 8
+_REPR.maxstring = 200
+_REPR.maxlong = 40
+_REPR.maxother = 80
+
+
+def _short(value: Any) -> str:
+ """Return ``repr(value)``, cut short.
+
+ Every value an error message quotes comes from the header, and the file
+ decides how large it is: under the header cap, a ``dtype`` can be a list of
+ ten million numbers, which quoted whole is a 30 MB message.
+ """
+ return _REPR.repr(value)
+
+
+def _clip(text: str, limit: int = 200) -> str:
+ """Cut *text* to *limit* characters; torch quotes every size in some errors."""
+ return text if len(text) <= limit else text[:limit] + " ..."
+
+
+def _bounded_product(factors: Iterable[int], limit: int) -> int | None:
+ """Multiply positive *factors*, giving up once the product passes *limit*.
+
+ Multiplying a long list of large factors all the way out is quadratic in
+ their number, since every factor adds a word to the product: a header of
+ 100 000 dimensions of ``2**62`` takes about a minute. Here every
+ multiplication starts from at most *limit*, so the cost is linear.
+
+ Returns:
+ The exact product when every factor was used, which can exceed *limit*
+ by the last one; ``None`` when a partial product passed *limit* first.
+ """
+ product = 1
+ for factor in factors:
+ if product > limit:
+ return None
+ product *= factor
+ return product
+
+
+def _above_one(shape: list[int]) -> Iterable[int]:
+ """The dimensions of *shape* above 1, the only ones that change a product, found at C speed.
+
+ Every one of them at least doubles the product, so a product bounded below
+ ``2**63`` multiplies at most 64 of them before it stops, however many
+ dimensions the header lists.
+ """
+ return filter((1).__lt__, shape)
+
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.
@@ -98,19 +156,21 @@ def _parse_entry(path: str, name: str, entry: Any, data_len: int) -> _TensorEntr
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.
+ accept, has a shape torch cannot build, 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.")
+ raise ValueError(f"{path}: header entry {_short(name)} 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)}.")
+ raise ValueError(f"{path}: header entry {_short(name)} is missing {', '.join(missing)}.")
dtype_name = entry["dtype"]
- if dtype_name not in _DTYPES:
+ # A JSON list or object is unhashable, so the membership test alone would
+ # raise ``TypeError`` rather than reject it.
+ if not isinstance(dtype_name, str) or dtype_name not in _DTYPES:
raise ValueError(
- f"{path}: tensor {name!r} has dtype {dtype_name!r}, which this reader does not support. "
+ f"{path}: tensor {_short(name)} has dtype {_short(dtype_name)}, which this reader does not support. "
f"Supported dtypes: {', '.join(sorted(_DTYPES))}."
)
dtype = _DTYPES[dtype_name]
@@ -119,7 +179,14 @@ def _parse_entry(path: str, name: str, entry: Any, data_len: int) -> _TensorEntr
# ``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.")
+ raise ValueError(
+ f"{path}: tensor {_short(name)} has shape {_short(shape)}, expected a list of non-negative integers."
+ )
+ if max(shape, default=0) > _MAX_DIM:
+ raise ValueError(
+ f"{path}: tensor {_short(name)} has shape {_short(shape)}, whose dimensions must be at most 2**63 - 1, "
+ f"the largest size a torch tensor can have."
+ )
offsets = entry["data_offsets"]
if (
@@ -127,23 +194,47 @@ def _parse_entry(path: str, name: str, entry: Any, data_len: int) -> _TensorEntr
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.")
+ raise ValueError(
+ f"{path}: tensor {_short(name)} has data_offsets {_short(offsets)}, 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"{path}: tensor {_short(name)} claims bytes [{_short(start)}, {_short(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:
+ itemsize = _ITEMSIZES[dtype_name]
+ # A count past what the buffer holds cannot match any range inside it, so
+ # the product stops there instead of multiplying every dimension out.
+ numel = 0 if 0 in shape else _bounded_product(_above_one(shape), data_len // itemsize)
+ if numel is None or numel * itemsize != end - start:
+ size = f"more than the {data_len}-byte buffer holds" if numel is None else f"{numel * itemsize} bytes"
raise ValueError(
- f"{path}: tensor {name!r} is {dtype_name}{shape}, which is {expected} bytes, "
+ f"{path}: tensor {_short(name)} is {dtype_name}{_short(shape)}, which is {size}, "
f"but its data_offsets span {end - start}."
)
+ if numel == 0:
+ # An empty tensor spans no bytes, so the check above bounds none of its
+ # other dimensions, and torch still derives contiguous strides and a
+ # storage size from them in 64-bit arithmetic that can overflow. While
+ # the product of ``max(d, 1)`` stays below 2**63, neither can: every
+ # stride is a product of a suffix of those factors, and every partial
+ # product of the sizes is at most their product, or 0 from the first 0.
+ # Factors of 0 and 1 contribute 1, so only the larger ones are multiplied.
+ # Past that bound, building the tensor on the meta device runs the same
+ # checks as the ``torch.empty`` in :func:`load_safetensors` does on the
+ # CPU, without allocating its storage, so a shape accepted here is one
+ # the load can build there.
+ extent = _bounded_product(_above_one(shape), _MAX_DIM)
+ if extent is None or extent > _MAX_DIM:
+ try:
+ torch.empty(shape, dtype=dtype, device="meta")
+ except RuntimeError as e:
+ raise ValueError(
+ f"{path}: tensor {_short(name)} has shape {_short(shape)}, which torch cannot build: "
+ f"{_clip(str(e))}"
+ ) from e
return _TensorEntry(dtype, shape, start, end, numel)
@@ -179,7 +270,7 @@ def _check_the_buffer_is_covered_once(path: str, parsed: dict[str, _TensorEntry]
"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"{path}: tensor {_short(name)} starts at byte {entry.start} where the buffer is covered "
f"up to {offset}, so it {problem}."
)
offset = entry.end
@@ -194,9 +285,11 @@ 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.
+ header, every entry's dtype, shape and byte range, and that those ranges
+ cover the buffer exactly once. A file this accepts is one
+ :func:`load_safetensors` can build on the CPU, including an empty tensor's
+ shape, which no byte range bounds; another device can add limits of its own.
+ 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
@@ -235,10 +328,20 @@ def _read_and_check_header(path: str, f: BinaryIO) -> tuple[dict[str, _TensorEnt
f"{path}: the header declares {header_len} bytes but the file holds "
f"{size - _HEADER_LEN_BYTES} after the length prefix."
)
+ raw = f.read(header_len)
try:
- header = json.loads(f.read(header_len))
+ header = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as e:
raise ValueError(f"{path}: the header is not valid JSON: {e}") from e
+ except ValueError as e:
+ # Valid JSON that ``json`` still refuses: an integer with more digits than
+ # ``sys.get_int_max_str_digits()`` allows. Its message names no file.
+ raise ValueError(f"{path}: the header cannot be decoded: {e}") from e
+ except RecursionError as e:
+ # The decoder recurses once per nesting level, so about a thousand ``[``
+ # -- a kilobyte, far under the header cap -- exhaust the interpreter's
+ # recursion limit. A safetensors header nests three levels deep.
+ raise ValueError(f"{path}: the header is nested too deeply to decode: {e}") from e
if not isinstance(header, dict):
raise ValueError(f"{path}: the header is a JSON {type(header).__name__}, expected an object.")
@@ -276,10 +379,11 @@ def load_safetensors(path: str | os.PathLike[str], device: str | torch.device =
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.
+ truncated, a header that is not JSON or nests too deeply to decode,
+ an entry naming a dtype this reader does not accept, a shape torch
+ cannot build, 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:
diff --git a/tests/core/test_safetensors.py b/tests/core/test_safetensors.py
index 847157856..1e8b9ad27 100644
--- a/tests/core/test_safetensors.py
+++ b/tests/core/test_safetensors.py
@@ -30,6 +30,7 @@ from __future__ import annotations
import json
import re
import struct
+import time
import warnings
from pathlib import Path
from typing import Any
@@ -37,7 +38,7 @@ from typing import Any
import pytest
import torch
-from kornia.core.safetensors import load_safetensors
+from kornia.core.safetensors import check_safetensors, load_safetensors
# Names the format gives the dtypes this reader accepts, for the fixtures below.
_NAMES: dict[torch.dtype, str] = {
@@ -84,8 +85,12 @@ def _build(tensors: dict[str, torch.Tensor], metadata: dict[str, str] | None = N
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")
+ """Assemble a file from a header and a byte buffer, valid or not.
+
+ The header is an object to serialise, or raw bytes for a header that no
+ ``json.dumps`` call would produce.
+ """
+ encoded = header if isinstance(header, bytes) else json.dumps(header).encode("utf-8")
return struct.pack("<Q", len(encoded)) + encoded + blob
@@ -95,6 +100,12 @@ def _write(tmp_path: Path, payload: bytes) -> Path:
return path
+# ``check_safetensors`` is the header half of ``load_safetensors``: a header one
+# of them accepts and the other cannot read is a disagreement, so a header case
+# runs through both.
+_BOTH_READERS = pytest.mark.parametrize("reader", [check_safetensors, load_safetensors], ids=["check", "load"])
+
+
@pytest.fixture
def tensors() -> dict[str, torch.Tensor]:
"""One tensor per interesting case: a float grid, bf16, int64 and an empty one."""
@@ -256,22 +267,65 @@ class TestRejectsCorruptFiles:
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:
+ @_BOTH_READERS
+ @pytest.mark.parametrize("shape", [[-1], "4", [1.5], [True], None, {"0": 1}, [[1]], ["1"]])
+ def test_invalid_shape(self, tmp_path, reader, 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)
+ reader(path)
- @pytest.mark.parametrize("offsets", [[0], [0, 1, 2], [-1, 1], "0,1", [False, True]])
- def test_invalid_offsets(self, tmp_path, offsets) -> None:
+ @_BOTH_READERS
+ @pytest.mark.parametrize(
+ "offsets", [[0], [0, 1, 2], [-1, 1], "0,1", [False, True], None, [0.0, 1.0], [0, "1"], {"0": 0, "1": 1}]
+ )
+ def test_invalid_offsets(self, tmp_path, reader, 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)
+ reader(path)
+
+ @_BOTH_READERS
+ @pytest.mark.parametrize(
+ "dtype", [["F32"], {"F32": 1}, None, 32, True], ids=["list", "object", "null", "number", "bool"]
+ )
+ def test_dtype_that_is_not_a_string(self, tmp_path, reader, dtype) -> None:
+ """A list or an object is unhashable, so a bare ``in _DTYPES`` raised ``TypeError`` (#5218)."""
+ header = {"weight": {"dtype": dtype, "shape": [2], "data_offsets": [0, 8]}}
+ path = _write(tmp_path, _pack(header, b"\x00" * 8))
+
+ expected = f"{path}: tensor 'weight' has dtype {dtype!r}, which this reader does not support"
+ with pytest.raises(ValueError, match=re.escape(expected)):
+ reader(path)
+
+ @_BOTH_READERS
+ @pytest.mark.parametrize("where", ["header", "entry"])
+ def test_deeply_nested_header(self, tmp_path, reader, where) -> None:
+ """200 000 levels is a 400 kB header, far under the cap, and deeper than ``json`` recurses (#5218)."""
+ nested = b"[" * 200_000 + b"]" * 200_000
+ if where == "entry":
+ nested = b'{"weight": {"dtype": ' + nested + b', "shape": [1], "data_offsets": [0, 1]}}'
+ path = _write(tmp_path, _pack(nested, b"\x00"))
+
+ with pytest.raises(ValueError, match=re.escape(f"{path}: the header is nested too deeply to decode")):
+ reader(path)
+
+ @_BOTH_READERS
+ def test_an_integer_too_long_to_decode(self, tmp_path, reader) -> None:
+ """Valid JSON that ``json`` still refuses: more digits than ``sys.get_int_max_str_digits()``.
+
+ The ``ValueError`` ``json`` raises for it carries no path, so only the
+ path is matched: under a raised digit limit the integer decodes and the
+ shape check rejects it instead, with the same prefix.
+ """
+ header = b'{"weight": {"dtype": "U8", "shape": [' + b"1" * 5000 + b'], "data_offsets": [0, 1]}}'
+ path = _write(tmp_path, _pack(header, b"\x00"))
+
+ with pytest.raises(ValueError, match=re.escape(f"{path}: ")):
+ reader(path)
def test_header_is_not_json(self, tmp_path) -> None:
payload = struct.pack("<Q", 4) + b"nope"
@@ -312,3 +366,149 @@ class TestRejectsCorruptFiles:
with pytest.raises(ValueError, match=re.escape(str(path))):
load_safetensors(path)
+
+
+class TestShapesTorchCannotBuild:
+ """``check_safetensors`` accepts exactly the shapes ``load_safetensors`` can build on the CPU (#5218).
+
+ An empty tensor stores no bytes, so the byte-size check says nothing about
+ its other dimensions. The format allows empty tensors because they are
+ valid in the tensor libraries, and a torch tensor's sizes and contiguous
+ strides are 64-bit signed integers: a shape outside that is not a torch
+ tensor. Both readers reject it in the header check, with a message naming
+ the file, instead of the load failing inside ``torch.empty``.
+ """
+
+ @_BOTH_READERS
+ @pytest.mark.parametrize("shape", [[2**63, 0], [0, 2**63], [2**64 - 1, 0]])
+ def test_a_dimension_beyond_int64(self, tmp_path, reader, shape) -> None:
+ header = {"weight": {"dtype": "F32", "shape": shape, "data_offsets": [0, 0]}}
+ path = _write(tmp_path, _pack(header, b""))
+
+ with pytest.raises(ValueError, match=re.escape(f"{path}: tensor 'weight' has shape {shape}, whose dimensions")):
+ reader(path)
+
+ @_BOTH_READERS
+ @pytest.mark.parametrize("shape", [[0, 2**62, 2**62], [0, 3, 2**62]])
+ def test_an_empty_shape_whose_strides_overflow(self, tmp_path, reader, shape) -> None:
+ """Every dimension fits in 64 bits; the contiguous strides torch derives from them do not."""
+ header = {"weight": {"dtype": "F32", "shape": shape, "data_offsets": [0, 0]}}
+ path = _write(tmp_path, _pack(header, b""))
+
+ with pytest.raises(ValueError, match=re.escape(f"{path}: tensor 'weight' has shape {shape}, which torch")):
+ reader(path)
+
+ @_BOTH_READERS
+ @pytest.mark.parametrize("shape", [[2**62, 2**62, 0], [2**62, 4, 0]])
+ def test_an_empty_shape_whose_storage_size_may_overflow(self, tmp_path, reader, shape) -> None:
+ """The readers accept these exactly when ``torch.empty`` builds them on the CPU.
+
+ Whether it does depends on how c10 was compiled. Its storage-size check
+ (``safe_multiplies_u64`` in ``c10/util/safe_numerics.h``) multiplies the
+ sizes in order in unsigned 64 bits where the compiler provides a checked
+ multiply, which rejects both shapes on the macOS build this was written
+ on; the header's MSVC branch counts any zero size as no overflow. The
+ test pins agreement with the running build rather than either answer.
+ """
+ try:
+ torch.empty(shape, dtype=torch.float32)
+ except RuntimeError:
+ torch_builds_it = False
+ else:
+ torch_builds_it = True
+ header = {"weight": {"dtype": "F32", "shape": shape, "data_offsets": [0, 0]}}
+ path = _write(tmp_path, _pack(header, b""))
+
+ if torch_builds_it:
+ reader(path)
+ else:
+ with pytest.raises(ValueError, match=re.escape(f"{path}: tensor 'weight' has shape {shape}, which torch")):
+ reader(path)
+
+ @pytest.mark.parametrize("shape", [[2**63 - 1, 0], [0, 2**63 - 1], [2**62, 3, 0]])
+ def test_an_empty_tensor_keeps_a_huge_nominal_shape(self, tmp_path, device, shape) -> None:
+ """The other side of the boundary: what torch can build, both readers accept.
+
+ ``[2**62, 3, 0]`` builds under either branch of c10's storage-size check,
+ while ``[2**62, 4, 0]`` depends on the branch (see the test above). That
+ is why the check asks torch rather than restating its arithmetic.
+ """
+ header = {"weight": {"dtype": "F32", "shape": shape, "data_offsets": [0, 0]}}
+ path = _write(tmp_path, _pack(header, b""))
+
+ check_safetensors(path)
+ loaded = load_safetensors(path, device=device)["weight"]
+
+ assert list(loaded.shape) == shape
+ assert loaded.device.type == torch.device(device).type
+
+ @_BOTH_READERS
+ @pytest.mark.parametrize("empty", [False, True], ids=["nonempty", "empty"])
+ def test_many_large_dimensions_are_rejected_in_linear_time(self, tmp_path, reader, empty) -> None:
+ """100 000 dimensions of ``2**62``, a 2 MB header, are rejected without multiplying them all out.
+
+ Multiplying all of them out is quadratic in their count -- close to a
+ minute at this size -- and reaches more digits than ``str`` converts.
+ The product has to stop once it passes what the buffer holds, which the
+ message says, or, for the empty shape whose ``0`` comes last, once it
+ passes what a 64-bit stride can hold. The time bound is loose: the
+ rejection takes a few hundredths of a second, the quadratic product
+ about fifty.
+ """
+ shape = [2**62] * 100_000 + ([0] if empty else [])
+ header = {"weight": {"dtype": "U8", "shape": shape, "data_offsets": [0, 0 if empty else 1]}}
+ path = _write(tmp_path, _pack(header, b"" if empty else b"\x00"))
+ problem = "which torch cannot build" if empty else "which is more than the 1-byte buffer holds, but its"
+
+ start = time.perf_counter()
+ with pytest.raises(ValueError, match=re.escape(f"{path}: tensor 'weight' ")) as caught:
+ reader(path)
+ elapsed = time.perf_counter() - start
+
+ assert problem in str(caught.value)
+ assert len(str(caught.value)) < 2000
+ assert elapsed < 10.0, f"rejecting the header took {elapsed:.1f} s"
+
+
+class TestMessagesStayShort:
+ """The file decides how large a header value is; the message quoting it stays a few lines."""
+
+ @_BOTH_READERS
+ @pytest.mark.parametrize("field", ["dtype", "shape", "data_offsets", "name"])
+ def test_a_huge_value_is_shortened(self, tmp_path, reader, field) -> None:
+ """A 10M-element ``dtype`` list is a 20 MB header, under the cap; quoted whole, it was a 30 MB message."""
+ entry = {"dtype": b'"U8"', "shape": b"[1]", "data_offsets": b"[0, 1]"}
+ name = b"weight"
+ if field == "dtype":
+ entry["dtype"] = b"[" + b"0," * (10**7 - 1) + b"0]"
+ elif field == "shape":
+ entry["shape"] = b"[" + b"-1," * (10**6 - 1) + b"-1]"
+ elif field == "data_offsets":
+ entry["data_offsets"] = b"[" + b"0," * (10**6 - 1) + b"0]"
+ else:
+ name = b"w" * 10**6
+ entry["dtype"] = b'"XYZ"'
+ fields = b", ".join(b'"' + key.encode() + b'": ' + value for key, value in entry.items())
+ path = _write(tmp_path, _pack(b'{"' + name + b'": {' + fields + b"}}", b"\x00"))
+
+ with pytest.raises(ValueError, match=re.escape(f"{path}: tensor ")) as caught:
+ reader(path)
+
+ assert len(str(caught.value)) < 2000, f"a {len(str(caught.value))}-character message"
+
+ def test_a_size_mismatch_states_the_exact_byte_count(self, tmp_path) -> None:
+ """The product is exact when it completes, even if its last factor takes it past the buffer."""
+ header = {"weight": {"dtype": "F32", "shape": [3], "data_offsets": [0, 8]}}
+ path = _write(tmp_path, _pack(header, b"\x00" * 8))
+
+ with pytest.raises(ValueError, match=re.escape("is F32[3], which is 12 bytes, but its data_offsets span 8.")):
+ load_safetensors(path)
+
+ def test_a_shape_larger_than_the_buffer_says_so(self, tmp_path) -> None:
+ """The product stops once it passes the buffer, so the count is a bound, not a number."""
+ header = {"weight": {"dtype": "F32", "shape": [2**40, 2**40], "data_offsets": [0, 8]}}
+ path = _write(tmp_path, _pack(header, b"\x00" * 8))
+
+ expected = f"is F32{[2**40, 2**40]}, which is more than the 8-byte buffer holds, but its data_offsets span 8."
+ with pytest.raises(ValueError, match=re.escape(expected)):
+ load_safetensors(path)