"""NumPy's `.npy` and `.npz` files, which MLX writes too. See DESIGN.md.
A `.npy` file is a magic string, a header that is a Python literal (dtype, order, shape), and the bytes of one array.
A `.npz` file is a zip of `.npy` members. The header is read with `ast.literal_eval`, which runs no code. An array of
Python objects is a pickle; its bytes are kept as `uint8` and never read as objects.
"""
from __future__ import annotations
import ast
import mmap
from collections.abc import Callable, Iterable
from pathlib import Path
import numpy as np
from pydantic import JsonValue
from jabara.errors import ArchiveFormatError
from jabara.formats import splice
from jabara.formats._zip import stored_members
from jabara.formats.base import CheckpointFormat, Split
from jabara.formats.registry import register_format
from jabara.formats.splice import Checksum, Span
from jabara.types import DTYPE_ITEMSIZE, FLOAT_DTYPES, TensorMeta
_MAGIC = b"\x93NUMPY"
_VERSIONS = {1, 2, 3}
[docs]
def dtype_name(dtype: np.dtype[np.generic]) -> str | None:
"""The Jabara dtype name of a little-endian (or single-byte) NumPy dtype, or None for any other dtype."""
if dtype.byteorder == ">" or dtype.hasobject or dtype.fields is not None or dtype.subdtype is not None:
return None
name = dtype.name
return name if name in DTYPE_ITEMSIZE and np.dtype(name).itemsize == dtype.itemsize else None
[docs]
def array_span(raw: mmap.mmap, start: int, end: int, name: str, bad: Callable[[str], ArchiveFormatError]) -> Span:
"""The array of the `.npy` bytes `raw[start:end]`, named `name`: role `weight` for a float array, and `uint8`
with role `other` for a dtype Jabara does not carry (its bytes are kept as they are)."""
if raw[start : start + 6] != _MAGIC or end - start < 10: # noqa: PLR2004 - the magic, version, and length
raise bad(f"{name} is not a .npy array")
version = raw[start + 6]
if version not in _VERSIONS:
raise bad(f"{name} is a .npy array of version {version}, which Jabara does not know")
size = 2 if version == 1 else 4 # the header length is a uint16 in version 1, a uint32 later
begin = start + 8 + size + int.from_bytes(raw[start + 8 : start + 8 + size], "little")
if begin > end:
raise bad(f"{name} has a .npy header longer than the array")
try:
header = ast.literal_eval(raw[start + 8 + size : begin].decode("latin1"))
dtype, shape = np.dtype(header["descr"]), tuple(int(n) for n in header["shape"])
fortran = bool(header.get("fortran_order"))
except (ValueError, TypeError, KeyError, SyntaxError, MemoryError, RecursionError, OverflowError) as e:
raise bad(f"{name} has a .npy header that does not parse ({type(e).__name__})") from e
known = dtype_name(dtype)
if known is None or any(n < 0 for n in shape) or int(np.prod(shape)) * dtype.itemsize != end - begin:
meta = TensorMeta(name=name, dtype="uint8", shape=(end - begin,), role="other")
else:
# A Fortran-order array is recorded with its shape but its bytes in column order: no role invites a lossy
# codec that would read them in row order.
role = "weight" if known in FLOAT_DTYPES and not fortran else "other"
meta = TensorMeta(name=name, dtype=known, shape=shape, role=role)
return Span(begin, end, meta)
[docs]
@register_format
class Npy(CheckpointFormat):
"""A NumPy `.npy` file: one array."""
kind = "npy"
names = ("*.npy",)
in_directory = ()
frameworks = (("NumPy", "*.npy"),)
[docs]
def split(self, path: Path) -> Split:
raw = splice.open_map(path, "a .npy file")
def bad(msg: str) -> ArchiveFormatError:
return ArchiveFormatError(f"{path}: {msg}")
span = array_span(raw, 0, len(raw), "array", bad)
return Split(*splice.cut(path, raw, [span]))
[docs]
def join(
self, source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool
) -> None:
splice.join(source, remainder, tensors, out, exact=exact)
[docs]
@register_format
class Npz(CheckpointFormat):
"""A NumPy `.npz` file from `np.savez`: a zip of `.npy` members, each stored as it is. A compressed `.npz`
(`np.savez_compressed`) is refused: deflating a member again gives the same bytes only with the same zlib build,
so its restore could not promise the original bytes."""
kind = "npz"
names = ("*.npz",)
in_directory = ()
frameworks = (("NumPy (np.savez), MLX (mx.savez)", "*.npz"),)
[docs]
def split(self, path: Path) -> Split:
raw = splice.open_map(path, "a .npz file")
def bad(msg: str) -> ArchiveFormatError:
return ArchiveFormatError(f"{path}: not a .npz file written by np.savez: {msg}")
members = stored_members(
path, raw, bad, "np.savez_compressed deflates its members, and Jabara can restore only np.savez files"
)
spans = [array_span(raw, m.start, m.end, name.removesuffix(".npy"), bad) for name, m in members.items()]
checksums = [Checksum(m.start, m.end, m.crc_at) for m in members.values()]
return Split(*splice.cut(path, raw, spans, checksums))
[docs]
def join(
self, source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool
) -> None:
splice.join(source, remainder, tensors, out, exact=exact)