jabara.formats.safetensors のソースコード

"""Parse and rebuild safetensors files without the safetensors package. See DESIGN.md."""

from __future__ import annotations

import json
import mmap
import os
import struct
from collections.abc import Iterable
from pathlib import Path
from typing import Annotated

from pydantic import BaseModel, JsonValue, NonNegativeInt, Strict, ValidationError

from jabara import _durable
from jabara.errors import ArchiveFormatError
from jabara.formats.base import CheckpointFormat, Split
from jabara.formats.registry import register_format
from jabara.types import TensorMeta, TensorRecord

# The header length that starts the file: a little-endian uint64.
_LENGTH_BYTES = 8
_DTYPES = {
    "BOOL": "bool",
    "U8": "uint8",
    "I8": "int8",
    "U16": "uint16",
    "I16": "int16",
    "F16": "float16",
    "BF16": "bfloat16",
    "U32": "uint32",
    "I32": "int32",
    "F32": "float32",
    "U64": "uint64",
    "I64": "int64",
    "F64": "float64",
    "C64": "complex64",
}

# Strict ints: JSON floats and booleans are not sizes, as in the reference parser.
_Size = Annotated[NonNegativeInt, Strict()]


class _Entry(BaseModel, frozen=True):
    """One tensor's entry in the header, as the format defines it."""

    dtype: str
    shape: tuple[_Size, ...]
    data_offsets: tuple[_Size, _Size]


[ドキュメント] def read_safetensors(path: str | os.PathLike[str]) -> tuple[bytes, list[TensorRecord]]: """Return the header bytes of a safetensors file and its tensors in file order, backed by a memory map. Raises `ArchiveFormatError` if the file is not a valid safetensors file or holds a dtype that Jabara does not know. """ def bad(msg: str) -> ArchiveFormatError: return ArchiveFormatError(f"{path}: not a valid safetensors file: {msg}") with Path(path).open("rb") as f: size = os.fstat(f.fileno()).st_size if size < _LENGTH_BYTES: raise bad("shorter than the 8-byte header length") (n,) = struct.unpack("<Q", f.read(_LENGTH_BYTES)) if _LENGTH_BYTES + n > size: raise bad("header length exceeds the file size") header = f.read(n) mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) try: parsed = json.loads(header) except (ValueError, RecursionError) as e: raise bad(f"header is not JSON ({e!r})") from e if not isinstance(parsed, dict): raise bad("header is not a JSON object") data_start = 8 + n entries = [] for name, info in parsed.items(): if name == "__metadata__": if not isinstance(info, dict) or not all(type(v) is str for v in info.values()): raise bad("__metadata__ is not an object of strings") continue try: entry = _Entry.model_validate(info) except ValidationError as e: raise bad(f"tensor {name!r} has a malformed entry ({e})") from e if entry.dtype not in _DTYPES: raise bad(f"tensor {name!r} has the unsupported dtype {entry.dtype!r}") meta = TensorMeta(name=name, dtype=_DTYPES[entry.dtype], shape=entry.shape, role="weight") begin, end = entry.data_offsets if end - begin != meta.nbytes: raise bad(f"tensor {name!r}: data_offsets do not match dtype and shape") entries.append((begin, end, meta)) # An empty tensor can share its start with a non-empty one; it must come first for the data to be contiguous. entries.sort(key=lambda e: (e[0], e[1])) view = memoryview(mm) records = [] expected = 0 for begin, end, meta in entries: if begin != expected: raise bad(f"tensor {meta.name!r} leaves a gap or overlap in the data section") expected = end records.append(TensorRecord(meta, view[data_start + begin : data_start + end])) if data_start + expected != size: raise bad("data section size does not match the header") return header, records
[ドキュメント] def write_safetensors(path: str | os.PathLike[str], header: bytes, tensors: Iterable[bytes]) -> None: """Write a safetensors file from its header bytes and the tensor bytes in order. The file is written to a new temporary file next to `path`, synced to stable storage, and renamed at the end. Raises `ValueError` if the tensor bytes do not add up to the header's offsets. """ expected = 0 for info in json.loads(header).values(): if "data_offsets" in info: expected = max(expected, info["data_offsets"][1]) with _durable.writing(path) as tmp, tmp.open("wb") as f: f.write(struct.pack("<Q", len(header))) f.write(header) written = 0 for chunk in tensors: f.write(chunk) written += len(chunk) if written != expected: raise ValueError(f"tensor bytes ({written}) do not match the header ({expected})")
[ドキュメント] @register_format class Safetensors(CheckpointFormat): """A safetensors file: a JSON header, then the bytes of every tensor. The header is kept as text.""" kind = "safetensors" names = ("*.safetensors",) in_directory = ("*.safetensors",) frameworks = (("Hugging Face Transformers, Accelerate, PEFT, Diffusers, MLX", "*.safetensors"),)
[ドキュメント] def split(self, path: Path) -> Split: header, records = read_safetensors(path) return Split(records, {"header": header.decode("utf-8")})
[ドキュメント] def join( self, source: dict[str, JsonValue], remainder: bytes, # noqa: ARG002 - CheckpointFormat.join's signature; the header is the whole remainder tensors: Iterable[bytes], out: Path, *, exact: bool, # noqa: ARG002 - CheckpointFormat.join's signature; the header holds no checksum ) -> None: header = source.get("header") if not isinstance(header, str): raise ArchiveFormatError(f"{out}: safetensors source has no header text") try: write_safetensors(out, header.encode("utf-8"), tensors) except (ValueError, TypeError, KeyError, IndexError, AttributeError) as e: raise ArchiveFormatError(f"{out}: stored safetensors header does not fit its tensors ({e})") from e