"""Cutting tensors out of a file and putting them back: the part every format that keeps a remainder shares.
A format finds where its tensors sit in the file. `cut` turns those spans into records viewed in a memory map and the
remainder, every other byte; `join` writes the remainder with each tensor back at its offset. The file's size and
CRC-32 check a lossless restore. A container with checksums of its own (a zip) lists where it records them, and a
lossy restore rewrites them.
"""
from __future__ import annotations
import mmap
import os
import zlib
from collections.abc import Iterable, Sequence
from pathlib import Path
from typing import NamedTuple
from pydantic import BaseModel, JsonValue, NonNegativeInt, ValidationError
from jabara import _durable
from jabara.container import MAGIC
from jabara.errors import ArchiveFormatError
from jabara.types import TensorMeta, TensorRecord
_U32 = 4
_READ = 1 << 24 # bytes read at a time to checksum a member again
[ドキュメント]
class Span(NamedTuple):
"""Where one tensor's bytes sit in the file, and what it is."""
start: int
end: int
meta: TensorMeta
#: Where the file records the CRC-32 of exactly these bytes (a zip member that holds only the tensor).
crc_at: tuple[int, ...] = ()
[ドキュメント]
class Checksum(NamedTuple):
"""A CRC-32 the file records over a range that holds tensors and other bytes (a zip member with a header)."""
start: int
end: int
crc_at: tuple[int, ...]
[ドキュメント]
class Source(BaseModel, frozen=True, extra="ignore"):
"""What `join` reads from the archive index."""
size: NonNegativeInt
crc32: NonNegativeInt
#: Per tensor in file order: offset, length, and where the file records the tensor's own CRC-32.
storages: list[tuple[NonNegativeInt, NonNegativeInt, list[NonNegativeInt]]]
#: Per range with a CRC-32 of its own: offset, length, and where the file records it.
members: list[tuple[NonNegativeInt, NonNegativeInt, list[NonNegativeInt]]] = []
[ドキュメント]
def open_map(path: Path, what: str) -> mmap.mmap:
"""The file mapped read-only. `ArchiveFormatError` for an empty file or a Jabara archive."""
with path.open("rb") as f:
if os.fstat(f.fileno()).st_size == 0:
raise ArchiveFormatError(f"{path}: an empty file, not {what}")
raw = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if raw[: len(MAGIC)] == MAGIC:
raise ArchiveFormatError(f"{path}: already a Jabara archive, such as a .ckpt that the Lightning plugin writes")
return raw
[ドキュメント]
def cut(
path: Path, raw: mmap.mmap, spans: Sequence[Span], checksums: Sequence[Checksum] = ()
) -> tuple[list[TensorRecord], dict[str, JsonValue], bytes]:
"""The records, the `source`, and the remainder for tensors at `spans`. `ArchiveFormatError` for spans that
overlap or run past the end of the file, or a tensor whose bytes do not match its dtype and shape."""
ordered = sorted(spans, key=lambda s: s.start)
names = [s.meta.name for s in ordered]
if len(set(names)) != len(names):
twice = next(n for n in names if names.count(n) > 1)
raise ArchiveFormatError(f"{path}: two tensors are named {twice!r}")
last = 0
for s in ordered:
if s.start < last or s.end > len(raw) or s.end - s.start != s.meta.nbytes:
raise ArchiveFormatError(f"{path}: tensor {s.meta.name!r} overlaps another or does not fit the file")
last = s.end
view = memoryview(raw)
remainder = bytearray()
last = 0
for s in ordered:
remainder += raw[last : s.start]
last = s.end
remainder += raw[last:]
source = Source(
size=len(raw),
crc32=zlib.crc32(view),
storages=[(s.start, s.end - s.start, list(s.crc_at)) for s in ordered],
members=[(c.start, c.end - c.start, list(c.crc_at)) for c in checksums],
)
records = [TensorRecord(s.meta, view[s.start : s.end]) for s in ordered]
return records, source.model_dump(mode="json"), bytes(remainder)
def _in_order(source: Source) -> bool:
"""Whether the tensors sit in file order without overlap, and every range and CRC position is inside the file;
a lossy restore, which checks no whole-file CRC-32, relies on it."""
last = 0
for start, length, crc_at in source.storages:
if start < last or any(at + _U32 > source.size for at in crc_at):
return False
last = start + length
return last <= source.size and all(
start + length <= source.size and all(at + _U32 <= source.size for at in crc_at)
for start, length, crc_at in source.members
)
[ドキュメント]
def join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) -> None:
"""Write the file at `out` from what `cut` returned. With `exact`, check the whole file's CRC-32; without, write
the new CRC-32 of each tensor and each checksummed range where the file records it."""
try:
parsed = Source.model_validate(source)
except ValidationError as e:
raise ArchiveFormatError(f"{out}: the archive's source is malformed ({e})") from e
if parsed.size != len(remainder) + sum(n for _, n, _ in parsed.storages) or not _in_order(parsed):
raise ArchiveFormatError(f"{out}: the archive's source does not fit the stored bytes")
with _durable.writing(out) as tmp, tmp.open("w+b") as f:
written = taken = running = 0
patches = []
pending = iter(tensors)
for start, length, crc_at in parsed.storages:
head = remainder[taken : taken + start - written]
data = next(pending, None)
if data is None or len(data) != length:
raise ArchiveFormatError(f"{out}: a stored tensor does not fit its place in the file")
for part in (head, data):
f.write(part)
running = zlib.crc32(part, running)
taken, written = taken + len(head), start + length
patches += [(at, zlib.crc32(data)) for at in crc_at]
tail = remainder[taken:]
f.write(tail)
running = zlib.crc32(tail, running)
if next(pending, None) is not None:
raise ArchiveFormatError(f"{out}: the archive holds more tensors than the file has places for")
if exact:
if running != parsed.crc32:
raise ArchiveFormatError(f"{out}: the rebuilt file does not match the CRC-32 of the original")
return
# Lossy tensors changed some bytes; the checksums the file keeps must follow them.
for start, length, crc_at in parsed.members:
f.seek(start)
value = 0
for _ in range(0, length, _READ):
value = zlib.crc32(f.read(min(_READ, start + length - f.tell())), value)
patches += [(at, value) for at in crc_at]
for at, value in patches:
f.seek(at)
f.write(value.to_bytes(_U32, "little"))