jabara.container のソースコード

"""The .jbr archive: writer and reader. See DESIGN.md, "Archive format, version 1"."""

from __future__ import annotations

import math
import os
import struct
import threading
import time
import zlib
from collections import deque
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from types import TracebackType
from typing import TYPE_CHECKING, Annotated, Any, BinaryIO, Generic, Literal, TypeVar

import numpy as np
from pydantic import BaseModel, Field, JsonValue, NonNegativeInt, ValidationError, model_validator

from jabara import __version__, _durable
from jabara.assign import Assigner, CodecChoice, DefaultAssigner
from jabara.codecs import Codec, get_codec
from jabara.codecs.quant import to_float64
from jabara.errors import (
    ArchiveFormatError,
    BaseMismatchError,
    ChecksumError,
    LossyNotAllowedError,
    MissingBaseError,
)
from jabara.types import TensorMeta, TensorRecord, as_memoryview

#: The first 8 bytes of every archive.
MAGIC = b"JABARA\x00\x01"
#: The last 8 bytes of every archive.
MAGIC_END = b"\x01\x00ARABAJ"
FORMAT: Literal[1] = 1
#: The format of an archive whose delta tensors refer to more than one base archive.
FORMAT_BASES: Literal[2] = 2
_TRAILER = 8 + 4 + len(MAGIC_END)  # index length, index crc, end magic
#: The default `chunk_size` of `write_archive`, in bytes (16 MiB).
CHUNK_SIZE = 16 << 20
#: The largest raw chunk the format allows, in bytes (256 MiB).
MAX_CHUNK_SIZE = 256 << 20

if TYPE_CHECKING:
    from typing_extensions import Self

T = TypeVar("T")
R = TypeVar("R")
K = TypeVar("K")
_DecodeItem = tuple[int, tuple[int, int], tuple[bytes, int, int]]  # chunk number, span, (payload, length, crc32)
_Decoded = bytes | bytearray | memoryview
_Seal = tuple[int, float]  # the CRC-32 a reader must produce, the largest absolute error


[ドキュメント] class ArchiveInfo(BaseModel, frozen=True, extra="forbid"): """What `write_archive` returns: the path, the raw and stored byte totals, and the elapsed seconds.""" #: The path of the archive. path: str #: The tensor bytes before coding. raw_bytes: int #: The bytes of the encoded chunks, without the index. stored_bytes: int #: The wall-clock seconds the write took. elapsed_seconds: float
[ドキュメント] class TensorStats(BaseModel, frozen=True, extra="forbid"): """The codec and sizes of one tensor, read from the index. `max_abs_err` is None for a lossless tensor.""" #: The tensor's name, dtype, shape, and role. meta: TensorMeta #: The id of the codec that coded the tensor. codec: str #: Whether the codec restores the tensor bit for bit. lossless: bool #: The largest absolute error a lossy codec recorded; `None` for a lossless tensor. max_abs_err: float | None #: The tensor bytes before coding. raw_bytes: int #: The bytes of the tensor's encoded chunks. stored_bytes: int
[ドキュメント] class ChunkEntry(BaseModel, frozen=True, extra="forbid"): """The index entry of one chunk: its offset, its stored length, its raw length (1 to `MAX_CHUNK_SIZE` bytes), and the CRC-32 of the bytes a reader must produce. """ #: Where the chunk's stored bytes start in the file. offset: NonNegativeInt #: The number of stored bytes. length: NonNegativeInt #: The number of bytes the chunk restores to. raw_length: Annotated[int, Field(ge=1, le=MAX_CHUNK_SIZE)] #: The CRC-32 of the bytes a reader must produce. crc32: Annotated[int, Field(ge=0, le=0xFFFFFFFF)]
[ドキュメント] class TensorEntry(TensorMeta, frozen=True, extra="forbid"): """The index entry of one tensor: its metadata, the codec id and parameters, `lossless`, `max_abs_err`, and its chunks. Each chunk's raw length is a multiple of the item size, and together they are `nbytes`. """ #: The id of the codec that coded the tensor. codec: str #: The codec's full parameters, defaults filled in. params: dict[str, JsonValue] #: Whether the codec restores the tensor bit for bit. lossless: bool #: The largest absolute error a lossy codec recorded; `None` for a lossless tensor. max_abs_err: float | None #: The tensor's chunks, in order. chunks: list[ChunkEntry] @model_validator(mode="after") def _chunks_cover_the_tensor(self) -> TensorEntry: if any(c.raw_length % self.itemsize for c in self.chunks): raise ValueError(f"tensor {self.name!r}: a chunk is not a whole number of {self.dtype} items") total = sum(c.raw_length for c in self.chunks) if total != self.nbytes: raise ValueError(f"tensor {self.name!r}: chunks hold {total} bytes, dtype and shape need {self.nbytes}") return self
[ドキュメント] class BaseRef(BaseModel, frozen=True, extra="forbid"): """Names the base archive of a delta archive by file name and index CRC-32.""" #: The file name of the base archive. name: str #: The CRC-32 of the base archive's index. index_crc: int
[ドキュメント] class ArchiveIndex(BaseModel, frozen=True, extra="forbid", ser_json_inf_nan="constants"): """The JSON index at the end of an archive. `model_json_schema()` is the schema of the format.""" #: The format version: 2 when `base` lists several base archives, 1 otherwise. format: Literal[1, 2] #: The name and version of the library that wrote the archive. writer: str #: One entry per tensor. tensors: list[TensorEntry] #: The nested structure that `save_state` saved; JSON the container does not read. skeleton: JsonValue #: Where the tensors came from, as an object with a `kind`; JSON the container does not read. source: JsonValue #: The base archive that delta-coded tensors refer to, a list of two or more in format 2; `None` when no tensor is #: delta-coded. base: BaseRef | list[BaseRef] | None @model_validator(mode="after") def _base_fits_the_format(self) -> ArchiveIndex: if self.format == FORMAT_BASES and not (isinstance(self.base, list) and len(self.base) > 1): raise ValueError("format 2 needs a list of two or more base archives") if self.format == FORMAT and isinstance(self.base, list): raise ValueError("format 1 names one base archive; a list of them needs format 2") return self
[ドキュメント] def base_refs(self) -> list[BaseRef]: """The base archives, in the order the delta tensors look them up; empty when there is none.""" if self.base is None: return [] return self.base if isinstance(self.base, list) else [self.base]
@model_validator(mode="after") def _names_are_unique(self) -> ArchiveIndex: seen: set[str] = set() for t in self.tensors: if t.name in seen: raise ValueError(f"duplicate tensor name {t.name!r}") seen.add(t.name) return self
def _check_threads(threads: int | None) -> None: if threads is not None and threads < 1: raise ValueError(f"threads must be at least 1, got {threads}") def _thread_count(threads: int | None) -> int: _check_threads(threads) return min(8, os.cpu_count() or 1) if threads is None else threads # A pool pays off from two items up: one item runs on the calling thread. _POOLED = 2 def _map(fn: Callable[[T], R], items: Sequence[T], pool: ThreadPoolExecutor | None) -> list[R]: if pool is None or len(items) < _POOLED: return [fn(item) for item in items] return list(pool.map(fn, items)) def _threaded_copy(codec: Codec, threads: int) -> Codec | None: """The copy `codec.with_threads(threads)` returns, checked, or None for a codec without threads of its own.""" threaded = codec.with_threads(threads) if threaded is None: return None # The index records the original's id and params, and a reader at threads=1 decodes with the original. if type(threaded) is not type(codec) or threaded.id != codec.id or threaded.params != codec.params: raise TypeError( f"codec {codec.id}: with_threads must return a copy of the same class with the same id and params, " f"got {type(threaded).__qualname__} {threaded.id} with params {threaded.params!r}" ) return threaded def _threads_inside(codec: Codec, pool: ThreadPoolExecutor | None) -> tuple[Codec, ThreadPoolExecutor | None]: """A codec with threads of its own gets the pool's thread budget and codes the chunks one after another.""" threaded = _threaded_copy(codec, pool._max_workers) if pool is not None else None # noqa: SLF001 - ThreadPoolExecutor gives its size only as _max_workers return (codec, pool) if threaded is None else (threaded, None) @dataclass(frozen=True) class _Task(Generic[K, R]): """One step of `_Workers.ordered`: `run` returns the results of one or more chunks of the tensor `key` names. `run` None is a marker: it runs nothing and marks a point in the order (the end of a tensor), or, `alone`, a barrier. An `alone` task codes a whole tensor with a codec that has threads of its own, on the calling thread, while no pool thread works. """ key: K run: Callable[[], list[R]] | None alone: bool = False class _Workers: """The thread budget of one call: a pool of `threads` threads, or, with `threads=1`, the calling thread alone. `ordered` runs the chunks of every tensor of the call on the pool, so chunks of different tensors are coded together, and hands back the results in task order, so nothing a caller writes or raises depends on which chunk finishes first. At most `window` tasks are in flight: submitted, or done and waiting for an earlier one. A delta tensor's base is decoded with these same workers behind a barrier, so the base's chunks start when no earlier chunk is in flight and the window holds for them too. """ def __init__(self, threads: int) -> None: self.threads = threads self.pool = ThreadPoolExecutor(threads) if threads > 1 else None self.window = 2 * threads if self.pool is not None else 1 def __enter__(self) -> Self: return self def __exit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None ) -> None: if self.pool is not None: self.pool.shutdown(cancel_futures=True) # waits for the tasks already running def threaded(self, codec: Codec) -> Codec | None: """The copy of `codec` with this budget's threads inside, or None to code its chunks on the pool.""" return _threaded_copy(codec, self.threads) if self.pool is not None else None def ordered(self, tasks: Iterable[_Task[K, R]]) -> Iterator[tuple[K, list[R] | None]]: """Yield `(task.key, task.run())` for each task, in task order; None for a marker, a task that runs nothing. A task's exception is raised where its result would be yielded, after every earlier result. An `Exception` from `tasks` itself (the caller refusing the next tensor) is raised after every result of the tasks taken before it, as when each tensor ran to the end before the next was looked at. An `alone` task, and an `alone` marker (a barrier, which yields nothing), wait until every earlier result is out, so no pool thread works while it runs and no earlier chunk is held while it goes on. """ pending: deque[tuple[K, Future[list[R]] | None]] = deque() on_pool = 0 # the entries of `pending` that are not markers; counted here, since markers can pile up def take(keep: int) -> Iterator[tuple[K, list[R] | None]]: """Yield from the front of `pending` until at most `keep` of its tasks are on the pool. Markers take no room in the window, and one at the front is yielded at once. """ nonlocal on_pool while pending and (pending[0][1] is None or on_pool > keep): key, future = pending.popleft() if future is None: yield key, None else: on_pool -= 1 yield key, future.result() source = iter(tasks) refusal: Exception | None = None try: while True: try: task = next(source) except StopIteration: break except Exception as e: # noqa: BLE001 - raised below, once the results of the earlier tasks are out refusal = e break run, pool = task.run, self.pool if run is None and not task.alone: pending.append((task.key, None)) elif run is None or task.alone or pool is None: if pending: yield from take(0) if run is not None: yield task.key, run() continue else: pending.append((task.key, pool.submit(run))) on_pool += 1 yield from take(self.window - 1) yield from take(0) if refusal is not None: raise refusal finally: for _, future in pending: if future is not None: future.cancel() def _chunk_lengths(nbytes: int, chunk_size: int, itemsize: int) -> list[int]: step = max(itemsize, chunk_size // itemsize * itemsize) return [min(step, nbytes - start) for start in range(0, nbytes, step)] def _checked_result(codec: Codec, out: object, where: str) -> bytes | bytearray | memoryview: """`out` if it is a decode result the container can take: `bytes`, a `bytearray`, or a memoryview that is one-dimensional, of format `B`, and contiguous. Anything else raises `TypeError` naming the codec: `len` of another view counts items, not bytes, and a strided view cannot be checksummed, so the length and CRC-32 checks would blame the archive for the codec's mistake. Nothing is copied. """ if isinstance(out, (bytes, bytearray)): return out if isinstance(out, memoryview): if out.format == "B" and out.ndim == 1 and out.c_contiguous: return out shape = "contiguous" if out.c_contiguous else "not contiguous" problem = f"a memoryview of format {out.format!r} with {out.ndim} dimension(s), {shape}" else: problem = f"a {type(out).__qualname__}" raise TypeError( f"{where}: codec {codec.id} decode returned {problem}; it must return bytes, a bytearray, or a one-dimensional " "contiguous memoryview of format 'B'" ) def _max_abs_diff(a: memoryview, b: bytes | bytearray | memoryview, dtype: str) -> float: """The largest absolute difference. Equal items, and NaN against NaN, count 0; NaN against a number counts inf.""" x, y = to_float64(a, dtype), to_float64(b, dtype) with np.errstate(invalid="ignore"): diff = np.abs(x - y) diff = np.where((x == y) | (np.isnan(x) & np.isnan(y)), 0.0, np.where(np.isnan(diff), np.inf, diff)) return float(diff.max()) if diff.size else 0.0 def _spans(lengths: Sequence[int]) -> list[tuple[int, int]]: spans, pos = [], 0 for n in lengths: spans.append((pos, n)) pos += n return spans def _ref(ref_all: memoryview | None, lo: int, n: int) -> memoryview | None: return ref_all[lo : lo + n] if ref_all is not None else None def _encode_one( codec: Codec, meta: TensorMeta, data: memoryview, ref_all: memoryview | None, span: tuple[int, int] ) -> bytes: lo, n = span return codec.encode(data[lo : lo + n], meta, _ref(ref_all, lo, n)) def _seal_one( codec: Codec, meta: TensorMeta, data: memoryview, ref_all: memoryview | None, item: tuple[int, tuple[int, int], bytes], ) -> _Seal: i, (lo, n), payload = item chunk = data[lo : lo + n] if codec.lossless: return zlib.crc32(chunk), 0.0 decoded = _checked_result( codec, codec.decode(memoryview(payload), meta, n, _ref(ref_all, lo, n)), f"tensor {meta.name!r} chunk {i}" ) if len(decoded) != n: raise ValueError( f"tensor {meta.name!r} chunk {i}: codec {codec.id} decoded {len(decoded)} bytes, expected {n}" ) return zlib.crc32(decoded), _max_abs_diff(chunk, decoded, meta.dtype) def _decode_one(codec: Codec, meta: TensorMeta, ref_all: memoryview | None, where: str, item: _DecodeItem) -> _Decoded: i, (lo, n), (payload, _, _) = item try: out = codec.decode(memoryview(payload), meta, n, _ref(ref_all, lo, n)) except MissingBaseError: raise except Exception as e: raise ChecksumError(f"{where} chunk {i}: decode failed ({e})") from e return _checked_result(codec, out, f"{where} chunk {i}") # outside the try: a codec bug is not corruption def _check_one(where: str, item: _DecodeItem, out: _Decoded) -> _Decoded: i, (_, n), (_, _, crc) = item if len(out) != n or zlib.crc32(out) != crc: raise ChecksumError(f"{where} chunk {i}: checksum mismatch") return out
[ドキュメント] def encode_chunks( codec: Codec, meta: TensorMeta, data: memoryview, lengths: Sequence[int], ref_all: memoryview | None, pool: ThreadPoolExecutor | None, ) -> list[bytes]: """Encode each chunk of one tensor with `codec`; `ref_all` is the whole base tensor, if the codec needs one.""" codec, pool = _threads_inside(codec, pool) return _map(partial(_encode_one, codec, meta, data, ref_all), _spans(lengths), pool)
[ドキュメント] def seal_chunks( codec: Codec, meta: TensorMeta, data: memoryview, lengths: Sequence[int], payloads: Sequence[bytes], ref_all: memoryview | None, pool: ThreadPoolExecutor | None, ) -> list[_Seal]: """Per chunk, the CRC-32 of the bytes a reader must produce and the largest absolute error (0.0 if lossless).""" items = list(zip(range(len(lengths)), _spans(lengths), payloads, strict=True)) return _map(partial(_seal_one, codec, meta, data, ref_all), items, pool)
[ドキュメント] def decode_chunks( codec: Codec, meta: TensorMeta, chunks: Sequence[tuple[bytes, int, int]], ref_all: memoryview | None, pool: ThreadPoolExecutor | None, where: str, ) -> list[_Decoded]: """Decode `(payload, raw_length, crc32)` chunks and check each length and checksum. A codec with threads of its own decodes every chunk before the checks run on the pool, so the two never hold threads at the same time. """ threaded, decode_pool = _threads_inside(codec, pool) if decode_pool is pool: # no copy: each pool thread decodes and checks its own chunks return _map(partial(_decode_and_check, codec, meta, ref_all, where), _decode_items(chunks), pool) return _decode_threaded(threaded, meta, chunks, ref_all, pool, where)
def _decode_items(chunks: Sequence[tuple[bytes, int, int]]) -> list[_DecodeItem]: return list(zip(range(len(chunks)), _spans([n for _, n, _ in chunks]), chunks, strict=True)) def _decode_threaded( threaded: Codec, meta: TensorMeta, chunks: Sequence[tuple[bytes, int, int]], ref_all: memoryview | None, pool: ThreadPoolExecutor | None, where: str, ) -> list[_Decoded]: """Decode every chunk with the copy that has threads of its own, then check them all on the pool.""" items = _decode_items(chunks) decoded = [_decode_one(threaded, meta, ref_all, where, item) for item in items] return _map(lambda pair: _check_one(where, *pair), list(zip(items, decoded, strict=True)), pool) def _decode_and_check( codec: Codec, meta: TensorMeta, ref_all: memoryview | None, where: str, item: _DecodeItem ) -> _Decoded: return _check_one(where, item, _decode_one(codec, meta, ref_all, where, item)) def _encode_and_seal( codec: Codec, meta: TensorMeta, data: memoryview, ref_all: memoryview | None, i: int, span: tuple[int, int] ) -> list[tuple[bytes, _Seal | Exception]]: payload = _encode_one(codec, meta, data, ref_all, span) try: return [(payload, _seal_one(codec, meta, data, ref_all, (i, span, payload)))] except Exception as e: # noqa: BLE001 - raised once every chunk of the tensor is encoded, as by seal_chunks return [(payload, e)] def _encode_tasks( key: K, codec: Codec, meta: TensorMeta, data: memoryview, lengths: Sequence[int], ref_all: memoryview | None, workers: _Workers, *, seal: bool, ) -> Iterator[_Task[K, Any]]: """The tasks that encode the chunks of one tensor, one per chunk on the pool, or one `alone` task for a codec with threads of its own (`encode_chunks`). Each yields `bytes` per chunk, or with `seal` a `(payload, seal)` pair whose seal is the chunk's CRC-32 and error from `seal_chunks`, or the exception that check raised. """ threaded = workers.threaded(codec) if threaded is not None: if lengths: run = partial(_encode_threaded, codec, threaded, meta, data, lengths, ref_all, workers.pool, seal=seal) yield _Task(key, run, alone=True) return for i, span in enumerate(_spans(lengths)): if seal: yield _Task(key, partial(_encode_and_seal, codec, meta, data, ref_all, i, span)) else: yield _Task(key, partial(_encode_chunk, codec, meta, data, ref_all, span)) def _encode_chunk( codec: Codec, meta: TensorMeta, data: memoryview, ref_all: memoryview | None, span: tuple[int, int] ) -> list[bytes]: return [_encode_one(codec, meta, data, ref_all, span)] def _encode_threaded( codec: Codec, threaded: Codec, meta: TensorMeta, data: memoryview, lengths: Sequence[int], ref_all: memoryview | None, pool: ThreadPoolExecutor | None, *, seal: bool, ) -> list[Any]: """`encode_chunks` and, with `seal`, `seal_chunks` of one tensor, given the copy `threaded` of `codec`.""" payloads = [_encode_one(threaded, meta, data, ref_all, span) for span in _spans(lengths)] if not seal: return payloads return list(zip(payloads, seal_chunks(codec, meta, data, lengths, payloads, ref_all, pool), strict=True)) def _decode_tasks( key: K, codec: Codec, meta: TensorMeta, chunks: Iterable[tuple[bytes, int, int]], ref_all: memoryview | None, workers: _Workers, where: str, *, alone: bool = False, ) -> Iterator[_Task[K, _Decoded]]: """The tasks that decode and check the `(payload, raw_length, crc32)` chunks of one tensor: one per chunk on the pool, taking each chunk from `chunks` only when its task is made, or one `alone` task for a codec with threads of its own (`decode_chunks`). With `alone`, every task is `alone`: the chunks are decoded on the calling thread. """ threaded = workers.threaded(codec) if threaded is not None: jobs = list(chunks) if jobs: yield _Task(key, partial(_decode_threaded, threaded, meta, jobs, ref_all, workers.pool, where), alone=True) return lo = 0 for i, chunk in enumerate(chunks): n = chunk[1] yield _Task(key, partial(_decode_chunk, codec, meta, ref_all, where, (i, (lo, n), chunk)), alone=alone) lo += n def _decode_chunk( codec: Codec, meta: TensorMeta, ref_all: memoryview | None, where: str, item: _DecodeItem ) -> list[_Decoded]: return [_decode_and_check(codec, meta, ref_all, where, item)]
[ドキュメント] def is_reference(base: TensorMeta, meta: TensorMeta) -> bool: """Whether the base tensor `base` is the delta reference of `meta`: same name, dtype, and shape. The role is a label for assigners and analysis, not part of the bytes, so it takes no part. The writer, the reader, and `jabara.bench` all match with this rule. """ return base.name == meta.name and base.dtype == meta.dtype and base.shape == meta.shape
def _reference(bases: Sequence[Archive], meta: TensorMeta) -> Archive | None: """The first of `bases` that holds the reference of `meta`. The writer and the reader both look it up this way, in the order of the base archives the index lists, so they agree on the reference when two base archives hold one.""" for base in bases: if meta.name in base.index_by_name and is_reference(base.meta(meta.name), meta): return base return None def _bases(base: Archive | Sequence[Archive] | None) -> list[Archive]: if base is None: return [] return [base] if isinstance(base, Archive) else list(base) def _resolve(meta: TensorMeta, choice: CodecChoice, *, has_base: bool) -> tuple[CodecChoice, Codec]: """The codec for `meta`; `has_base` says whether the base holds a tensor with the same name, dtype, and shape.""" codec = get_codec(choice.codec_id, choice.params) if codec.needs_ref and not has_base: if choice.fallback is None: raise MissingBaseError(f"tensor {meta.name!r}: codec {choice.codec_id} needs a matching base tensor") choice = choice.fallback codec = get_codec(choice.codec_id, choice.params) if codec.needs_ref: raise ValueError(f"tensor {meta.name!r}: fallback codec {choice.codec_id} must not need a ref") return choice, codec def _check_reads_back(skeleton: JsonValue, source: JsonValue) -> None: """Raise `ValueError` unless an index holding `skeleton` and `source` serializes and parses back. The reader's JSON parser limits nesting depth, so JSON nested deeper than that would make an archive no reader can open. """ try: probe = ArchiveIndex(format=FORMAT, writer="", tensors=[], skeleton=skeleton, source=source, base=None) ArchiveIndex.model_validate_json(probe.model_dump_json()) except ValueError as e: reason = e.errors()[0]["msg"] if isinstance(e, ValidationError) else str(e) raise ValueError(f"skeleton or source cannot be stored in an archive that reads back: {reason}") from e
[ドキュメント] def write_archive( path: str | os.PathLike[str], tensors: Iterable[TensorRecord], *, skeleton: JsonValue = None, source: JsonValue = None, assign: Assigner | None = None, threads: int | None = None, chunk_size: int = CHUNK_SIZE, base: Archive | Sequence[Archive] | None = None, allow_lossy: bool = False, ) -> ArchiveInfo: """Write `tensors` to an archive at `path` and return its sizes. Each tensor is coded chunk by chunk with the codec that `assign` picks, `DefaultAssigner` if None. `tensors` may be lazy: with `threads` above 1 the next record is taken while chunks of earlier ones are still being coded, from the caller's buffers and without a copy, so the bytes of a record must not change until the call returns. A source that refills one buffer for every record writes an archive with wrong contents, and no error is raised. The file is written to a new temporary file next to `path`, synced to stable storage, and renamed at the end. Raises `LossyNotAllowedError` for a lossy codec unless `allow_lossy`, `MissingBaseError` for a delta tensor with no base match and no fallback, `BaseMismatchError` if a base is a delta archive opened without its own base, and `ValueError` for a `path` that is a base archive itself, a duplicate tensor name, a wrong data length, a lossy decode of the wrong length, a `max_abs_err` that is not finite, a `skeleton` or `source` that would not read back, `threads` below 1, or `chunk_size` above `MAX_CHUNK_SIZE`. """ start = time.perf_counter() if chunk_size > MAX_CHUNK_SIZE: raise ValueError(f"chunk_size {chunk_size} exceeds the format limit MAX_CHUNK_SIZE ({MAX_CHUNK_SIZE})") _check_reads_back(skeleton, source) assign = assign or DefaultAssigner() final = os.fspath(path) n_threads = _thread_count(threads) bases = _bases(base) for b in bases: if b.index.base is not None and not b._bases: # noqa: SLF001 - Archive and write_archive share this module raise BaseMismatchError( f"{b.path}: a delta archive is a base only when it was opened with its own base, which decoding it needs" ) # Compared by inode, not by name, so neither a symlink nor another spelling of the path gets past it. if os.path.exists(final) and os.path.samestat(Path(final).stat(), os.fstat(b._f.fileno())): # noqa: SLF001 - Archive and write_archive share this module raise ValueError(f"{final}: is the base archive {b.path}; the new archive would replace the base it needs") entries: list[TensorEntry] = [] with _Workers(n_threads) as workers, _durable.writing(final) as tmp, tmp.open("wb") as f: f.write(MAGIC) tasks = _write_tasks(tensors, assign, bases, chunk_size, workers, allow_lossy=allow_lossy) # Payloads arrive in tensor and chunk order, whichever chunk finished first, so the layout is fixed. used: set[int] = set() for state, results in workers.ordered(tasks): if results is None: entries.append(state.entry()) if state.base is not None: used.add(id(state.base)) else: state.write(f, results) index = _index(entries, skeleton, source, [b for b in bases if id(b) in used]) blob = index.model_dump_json().encode("utf-8") f.write(blob + struct.pack("<QI", len(blob), zlib.crc32(blob)) + MAGIC_END) return ArchiveInfo( path=final, raw_bytes=sum(e.nbytes for e in entries), stored_bytes=sum(c.length for e in entries for c in e.chunks), elapsed_seconds=time.perf_counter() - start, )
def _index(entries: list[TensorEntry], skeleton: JsonValue, source: JsonValue, used: list[Archive]) -> ArchiveIndex: """`used` holds the base archives that some tensor refers to, in the order the writer was given them. One of them is written as format 1, which 0.1.0 reads; several need format 2.""" refs = [BaseRef(name=Path(b.path).name, index_crc=b.index_crc) for b in used] return ArchiveIndex( format=FORMAT_BASES if len(refs) > 1 else FORMAT, writer=f"jabara {__version__}", tensors=entries, skeleton=skeleton, source=source if source is not None else {"kind": "tensors"}, base=refs if len(refs) > 1 else (refs[0] if refs else None), ) @dataclass class _Writing: """One tensor while its chunks are written: what its index entry needs, and the first failed check of a chunk, which is raised once every chunk of the tensor is encoded, as `seal_chunks` after `encode_chunks`. """ meta: TensorMeta choice: CodecChoice codec: Codec lengths: list[int] #: The base archive whose tensor this delta tensor refers to; None for a tensor coded on its own. base: Archive | None = None chunks: list[ChunkEntry] = field(default_factory=list) max_err: float = 0.0 failed: Exception | None = None def write(self, f: BinaryIO, results: list[tuple[bytes, _Seal | Exception]]) -> None: for payload, seal in results: if self.failed is not None: continue if isinstance(seal, Exception): self.failed = seal continue crc, err = seal n = self.lengths[len(self.chunks)] self.chunks.append(ChunkEntry(offset=f.tell(), length=len(payload), raw_length=n, crc32=crc)) f.write(payload) self.max_err = max(self.max_err, err) def entry(self) -> TensorEntry: if self.failed is not None: raise self.failed if not math.isfinite(self.max_err): raise ValueError( f"tensor {self.meta.name!r}: codec {self.choice.codec_id} gives max_abs_err {self.max_err}, " "not a finite number" ) return TensorEntry( **self.meta.model_dump(), codec=self.choice.codec_id, params=self.codec.params.model_dump(mode="json"), lossless=self.codec.lossless, max_abs_err=None if self.codec.lossless else self.max_err, chunks=self.chunks, ) def _write_tasks( tensors: Iterable[TensorRecord], assign: Assigner, bases: Sequence[Archive], chunk_size: int, workers: _Workers, *, allow_lossy: bool, ) -> Iterator[_Task[_Writing, Any]]: """For each tensor, taken from `tensors` only when the window has room: the checks that refuse it, then the tasks that encode and seal its chunks, then a task that marks its end. """ seen: set[str] = set() for record in tensors: meta = record.meta if meta.name in seen: raise ValueError(f"duplicate tensor name {meta.name!r}") seen.add(meta.name) data = as_memoryview(record.data) if len(data) != meta.nbytes: raise ValueError(f"tensor {meta.name!r}: got {len(data)} bytes, expected {meta.nbytes}") base = _reference(bases, meta) choice, codec = _resolve(meta, assign.choose(meta), has_base=base is not None) if not codec.lossless and not allow_lossy: raise LossyNotAllowedError(f"tensor {meta.name!r}: codec {choice.codec_id} is lossy") ref_all: memoryview | None = None if codec.needs_ref: assert base is not None state = _Writing(meta, choice, codec, base.chunk_lengths(meta.name), base) # the base's chunk boundaries # The base is decoded on these threads once the window is empty, so its chunks fit in the window too. yield _Task(state, None, alone=True) ref_all = memoryview(base._read_with(meta.name, workers)) # noqa: SLF001 - Archive and its readers share this module else: state = _Writing(meta, choice, codec, _chunk_lengths(len(data), chunk_size, meta.itemsize)) lengths = state.lengths yield from _encode_tasks(state, codec, meta, data, lengths, ref_all, workers, seal=True) yield _Task(state, None)
[ドキュメント] class Archive: """A reader for one archive, usable as a context manager. Build it with `Archive.open`. `base` is the open full archive that a delta archive was written against, or the several that a format 2 archive names. `path` is the path it was opened with, `index` the validated `ArchiveIndex`, `index_crc` the CRC-32 of the index bytes (what a delta archive records of its base), and `index_by_name` maps each tensor name to its `TensorEntry`. """ def __init__(self, path: str, f: BinaryIO, index: ArchiveIndex, index_crc: int, bases: list[Archive]) -> None: self.path = path self.index = index self.index_crc = index_crc self._f = f self._lock = threading.Lock() self._bases = bases self.index_by_name: dict[str, TensorEntry] = {t.name: t for t in index.tensors} self._codecs: dict[str, Codec] = {}
[ドキュメント] @classmethod def open(cls, path: str | os.PathLike[str], *, base: Archive | Sequence[Archive] | None = None) -> Archive: """Open the archive at `path`. Raises `ArchiveFormatError` for a file that is not a readable archive, including an index that contradicts itself or the file (see `ChunkEntry`, `TensorEntry`, and the unique names of `ArchiveIndex`) or a chunk outside the data area or overlapping another, and `BaseMismatchError` when `base` is given and lacks an archive this one was written against, matched by index CRC-32. All of this is checked before any chunk is read. `base` may hold more archives than the index names. """ p = os.fspath(path) f = Path(p).open("rb") # noqa: SIM115 - the handle lives as long as the Archive try: index, crc = cls._parse(p, f) return cls(p, f, index, crc, _matched_bases(p, index.base_refs(), _bases(base))) except BaseException: f.close() raise
@staticmethod def _parse(p: str, f: BinaryIO) -> tuple[ArchiveIndex, int]: size = os.fstat(f.fileno()).st_size if size < len(MAGIC) + _TRAILER: raise ArchiveFormatError(f"{p}: file too short to be a Jabara archive") if f.read(len(MAGIC)) != MAGIC: raise ArchiveFormatError(f"{p}: bad magic, not a Jabara archive") f.seek(size - _TRAILER) tail = f.read(_TRAILER) if tail[12:] != MAGIC_END: raise ArchiveFormatError(f"{p}: bad end magic, file is truncated or not a Jabara archive") n, crc = struct.unpack("<QI", tail[:12]) index_start = size - _TRAILER - n if index_start < len(MAGIC): raise ArchiveFormatError(f"{p}: index length {n} does not fit in the file") f.seek(index_start) blob = f.read(n) if zlib.crc32(blob) != crc: raise ArchiveFormatError(f"{p}: index checksum mismatch") try: index = ArchiveIndex.model_validate_json(blob) except ValidationError as e: raise ArchiveFormatError(f"{p}: malformed index ({e})") from e # The writer puts chunks back to back, so each byte of the data area belongs to at most one chunk. Without # this, chunks pointing at one payload would let a small file decode to any size. end = len(MAGIC) for offset, length, name in sorted((c.offset, c.length, t.name) for t in index.tensors for c in t.chunks): if offset < end or offset + length > index_start: raise ArchiveFormatError( f"{p}: tensor {name!r} has a chunk outside the data area or overlapping another" ) end = offset + length return index, crc def __enter__(self) -> Self: return self def __exit__( self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None ) -> None: self.close()
[ドキュメント] def close(self) -> None: """Close the file.""" self._f.close()
[ドキュメント] def names(self) -> list[str]: """Return the tensor names in archive order.""" return [t.name for t in self.index.tensors]
[ドキュメント] def meta(self, name: str) -> TensorMeta: """Return the `TensorMeta` of `name`. Raises `KeyError` if there is no such tensor.""" t = self._entry(name) return TensorMeta(name=t.name, dtype=t.dtype, shape=t.shape, role=t.role)
[ドキュメント] def chunk_lengths(self, name: str) -> list[int]: """Return the raw length of each chunk of `name`. Raises `KeyError` if there is no such tensor.""" return [c.raw_length for c in self._entry(name).chunks]
def _entry(self, name: str) -> TensorEntry: try: return self.index_by_name[name] except KeyError: raise KeyError(f"{self.path}: no tensor named {name!r}") from None def _codec(self, entry: TensorEntry) -> Codec: if entry.name not in self._codecs: self._codecs[entry.name] = get_codec(entry.codec, entry.params) return self._codecs[entry.name] def _read_at(self, offset: int, length: int) -> bytes: with self._lock: self._f.seek(offset) return self._f.read(length)
[ドキュメント] def read(self, name: str, *, threads: int | None = None) -> bytes: """Return the raw little-endian bytes of `name`, checked against the chunk checksums. Raises `ChecksumError` on a mismatch, `MissingBaseError` for a delta tensor when no base was given, `BaseMismatchError` when the base lacks a tensor of the same name, dtype, and shape, and `KeyError` for an unknown name. """ self._codec(self._entry(name)) with _Workers(_thread_count(threads)) as workers: return self._read_with(name, workers)
[ドキュメント] def verify(self, *, threads: int | None = None) -> None: """Decode every tensor and check every checksum. Raises the first error that `read` would raise.""" with _Workers(_thread_count(threads)) as workers: for _ in self._decoded(self.names(), workers, keep=False): pass
def _read_many( self, names: Sequence[str], *, threads: int | None ) -> Generator[tuple[str, list[_Decoded]], None, None]: """For each of `names` in order, the name and its decoded chunks, checked as by `read`, with the chunks of different tensors decoded together on one budget of `threads`. Raises what `read` raises, at the tensor where `read` would. Close the iterator when stopping early, so that its pool shuts down. """ with _Workers(_thread_count(threads)) as workers: yield from self._decoded(names, workers) def _read_with(self, name: str, workers: _Workers) -> bytes: # A tensor read by itself (a `read`, or a base behind its barrier) has nothing to share the pool with, so one # chunk is decoded on the calling thread: handing it to a pool thread would only add the cost of the handoff. alone = len(self._entry(name).chunks) < _POOLED ((_, parts),) = self._decoded([name], workers, alone=alone) return b"".join(parts) def _decoded( self, names: Iterable[str], workers: _Workers, *, keep: bool = True, alone: bool = False ) -> Iterator[tuple[str, list[_Decoded]]]: for (name, parts), results in workers.ordered(self._read_tasks(names, workers, alone=alone)): if results is None: yield name, parts elif keep: parts.extend(results) def _read_tasks( self, names: Iterable[str], workers: _Workers, *, alone: bool = False ) -> Iterator[_Task[tuple[str, list[_Decoded]], Any]]: """For each tensor: the checks that refuse it, then the tasks that decode its chunks, each chunk read from the file only when its task is made, then a task that marks its end. `alone` is that of `_decode_tasks`. """ for name in names: entry = self._entry(name) meta = self.meta(name) codec = self._codec(entry) key: tuple[str, list[_Decoded]] = (name, []) ref_all: memoryview | None = None if codec.needs_ref: if not self._bases: raise MissingBaseError(f"{self.path}: tensor {name!r} is a delta and needs its base archive") base = _reference(self._bases, meta) if base is None: raise BaseMismatchError(f"{self.path}: base has no tensor {name!r} with the same dtype and shape") # The base is decoded on these threads once the window is empty, so its chunks fit in the window too. yield _Task(key, None, alone=True) ref_all = memoryview(base._read_with(name, workers)) # noqa: SLF001 - Archive and its readers share this module chunks = ((self._read_at(c.offset, c.length), c.raw_length, c.crc32) for c in entry.chunks) where = f"{self.path}: tensor {name!r}" yield from _decode_tasks(key, codec, meta, chunks, ref_all, workers, where, alone=alone) yield _Task(key, None)
[ドキュメント] def stats(self) -> list[TensorStats]: """Return the codec and sizes of every tensor.""" return [ TensorStats( meta=self.meta(t.name), codec=t.codec, lossless=t.lossless, max_abs_err=t.max_abs_err, raw_bytes=sum(c.raw_length for c in t.chunks), stored_bytes=sum(c.length for c in t.chunks), ) for t in self.index.tensors ]
def _matched_bases(path: str, refs: list[BaseRef], given: list[Archive]) -> list[Archive]: """For each base archive the index names, the given archive with its index CRC-32, in the index's order. Empty when nothing was given, so that reading a delta tensor raises `MissingBaseError`.""" if not refs or not given: return [] matched = [] for ref in refs: found = next((b for b in given if b.index_crc == ref.index_crc), None) if found is None: got = ( f"got {given[0].path!r} (index crc {given[0].index_crc})" if len(given) == 1 else f"and none of the {len(given)} given base archives has that index crc" ) raise BaseMismatchError(f"{path}: written against base {ref.name!r} (index crc {ref.index_crc}), {got}") matched.append(found) return matched