Add a codec, an assigner, a state schema, or a file format

You can add a codec, an assigner, a state schema, or a checkpoint file format without changing the rest of Jabara. Each is a subclass of an abstract base class. The four examples of a codec, an assigner, and a state schema are complete scripts in examples/extend/ in the clone. Each defines its class, writes an archive in a temporary directory, and checks what it reads back. The repository's tests run all four. A file format is shown with a built-in one and its test.

Add a codec

A codec turns one chunk of one tensor into bytes and back. Subclass Codec, set id and lossless, implement encode and decode, and register the class with @register_codec. This codec splits each chunk into byte planes and compresses each plane with lzma from the standard library:

"""A codec: split each tensor into byte planes and compress every plane with lzma from the standard library."""

import lzma
import struct
import tempfile
from pathlib import Path

import numpy as np

from jabara.assign import CodecChoice, UniformAssigner
from jabara.codecs import Codec, register_codec
from jabara.container import Archive, write_archive
from jabara.types import TensorMeta, TensorRecord


@register_codec
class ByteGroupLzma(Codec):
    id = "bytegroup-lzma/1"
    lossless = True

    def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
        planes = np.frombuffer(data, dtype=np.uint8).reshape(-1, meta.itemsize).T
        packed = [lzma.compress(plane.tobytes()) for plane in planes]
        return struct.pack(f"<{len(packed)}Q", *map(len, packed)) + b"".join(packed)

    def decode(self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) -> bytes:
        size = meta.itemsize
        lengths = struct.unpack(f"<{size}Q", payload[: 8 * size])
        out, pos = np.empty((size, raw_length // size), dtype=np.uint8), 8 * size
        for i, n in enumerate(lengths):
            out[i] = np.frombuffer(lzma.decompress(payload[pos : pos + n]), dtype=np.uint8)
            pos += n
        return np.transpose(out).tobytes()


weights = np.random.default_rng(0).standard_normal((64, 64)).astype("<f4")
record = TensorRecord(TensorMeta(name="w", dtype="float32", shape=weights.shape), weights)
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "checkpoint.jbr"
    write_archive(path, [record], assign=UniformAssigner(CodecChoice(codec_id=ByteGroupLzma.id)))
    with Archive.open(path) as archive:
        assert archive.read("w") == weights.tobytes()
  • id is <name>/<version>. The archive stores it, and a reader looks up the codec by it. Change the version when the payload format changes. register_codec raises ValueError for an id that is already registered, so import a module that registers a codec only once.

  • meta gives the tensor's dtype, shape, and role, so the codec can choose a strategy from them. data and payload are memoryview objects, and encode returns bytes.

  • decode returns bytes, a new bytearray, or a memoryview of unsigned bytes (format B, one contiguous dimension) over a new buffer, which the caller then owns. Any other type raises TypeError that names the codec, and so does a memoryview that is not one-dimensional, of format B, and contiguous, such as arr.data of a float32 array or a strided view.

  • A codec that builds its output in a bytearray or a NumPy array can return it without a copy. This matters on the thread pool, because a copy of a whole chunk holds the GIL, and the pool's threads then copy one chunk at a time.

  • For a lossless codec, decode(encode(x)) must return the same bytes as x for every chunk whose length is a multiple of meta.itemsize, including a chunk of length zero. decode receives raw_length, the length of the bytes that it must return.

  • Jabara codes chunks on a thread pool, the chunks of different tensors at the same time, and several threads can call one codec instance at the same time. Keep no per-call state on self.

  • A lossy codec sets lossless = False and must be deterministic: the same payload always decodes to the same bytes. The writer then needs allow_lossy=True (see Opt in to a lossy codec and read the recorded error).

  • A delta codec sets needs_ref = True and receives the same chunk of the base tensor as ref (see Store a checkpoint as a difference against a base).

The jabara command knows only the built-in codecs. A codec that your module registers works in Python code that imports the module, with write_archive, save_state, and jabara.bench.compare.

Add a codec with parameters

A codec declares its settings as a nested Params model, a pydantic BaseModel with frozen=True and extra="forbid", and reads them from self.params. This codec compresses each chunk with zlib from the standard library and takes the compression level as a parameter:

"""A codec with a validated parameter: zlib from the standard library, with its compression level as a `Params`."""

import tempfile
import zlib
from pathlib import Path

import numpy as np
from pydantic import BaseModel, JsonValue, ValidationError

from jabara.assign import CodecChoice, UniformAssigner
from jabara.codecs import Codec, register_codec
from jabara.container import Archive, write_archive
from jabara.types import TensorMeta, TensorRecord


@register_codec
class ZlibCodec(Codec):
    id = "zlib/1"
    lossless = True

    class Params(BaseModel, frozen=True, extra="forbid"):
        level: int = 6

    params: Params

    def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes:
        return zlib.compress(data, self.params.level)

    def decode(self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) -> bytes:
        return zlib.decompress(payload)


weights = np.random.default_rng(0).standard_normal((64, 64)).astype("<f4")
record = TensorRecord(TensorMeta(name="w", dtype="float32", shape=weights.shape), weights)
assign = UniformAssigner(CodecChoice(codec_id="zlib/1", params={"level": 9}))
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "checkpoint.jbr"
    write_archive(path, [record], assign=assign)
    with Archive.open(path) as archive:
        assert archive.read("w") == weights.tobytes()
        # The index records the parameters, so a reader decodes without being told them.
        assert archive.index_by_name["w"].params == {"level": 9}
    # `Params` refuses an unknown or ill-typed parameter, when write_archive builds the codec for the tensor.
    bad_params: list[dict[str, JsonValue]] = [{"lvl": 9}, {"level": "high"}]
    for bad in bad_params:
        try:
            write_archive(
                Path(tmp) / "bad.jbr", [record], assign=UniformAssigner(CodecChoice(codec_id="zlib/1", params=bad))
            )
        except ValidationError:
            pass
        else:
            raise AssertionError(f"{bad} was accepted")
  • Give every field of Params a default. A CodecChoice that leaves a parameter out gets the default.

  • CodecChoice.params is a JSON object that CodecChoice does not check. write_archive builds the codec of each tensor from the choice, and the Params model checks the object at that point. An unknown name or a value of the wrong type raises pydantic.ValidationError. The script tries both after the round trip.

  • The archive index stores the full parameters of each tensor, with the defaults filled in, so a reader builds the codec from the index alone. The script reads params from archive.index_by_name.

  • params: Params in the class body only tells a type checker the type of self.params.

Add an assigner

An assigner picks a CodecChoice for each tensor. Subclass Assigner and implement choose. This one keeps the weights bit-exact and stores every Adam moment as 8-bit codes:

"""An assigner: keep weights bit-exact and store every Adam moment as 8-bit codes."""

import tempfile
from pathlib import Path

import numpy as np

from jabara.assign import Assigner, CodecChoice
from jabara.container import Archive, write_archive
from jabara.types import TensorMeta, TensorRecord


class MomentsLossy(Assigner):
    def choose(self, meta: TensorMeta) -> CodecChoice:
        if meta.role.startswith("adam_"):
            return CodecChoice(codec_id="quant8-linear/1")  # lossy: write_archive needs allow_lossy=True
        return CodecChoice(codec_id="bytegroup-zstd/1")


rng = np.random.default_rng(0)
arrays = {
    role: (rng.standard_normal(4096) * scale).astype("<f4") for role, scale in [("weight", 0.02), ("adam_m", 1e-3)]
}
records = [TensorRecord(TensorMeta(name=r, dtype="float32", shape=a.shape, role=r), a) for r, a in arrays.items()]
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "checkpoint.jbr"
    write_archive(path, records, assign=MomentsLossy(), allow_lossy=True)
    with Archive.open(path) as archive:
        assert archive.read("weight") == arrays["weight"].tobytes()
        moment = np.frombuffer(archive.read("adam_m"), dtype="<f4")
        step = (arrays["adam_m"].max() - arrays["adam_m"].min()) / 255
        assert 0 < np.abs(moment - arrays["adam_m"]).max() <= step  # close, not bit-exact

choose runs for every tensor and sees its TensorMeta: the name, dtype, shape, and role. A choice of a lossy codec needs allow_lossy=True where you use the assigner. Pass an instance as assign=, as the script does, or to compress_file, save_state, or jabara.hf.attach. JabaraCheckpointIO also takes assign=, but it never writes a lossy tensor, so it raises LossyNotAllowedError for this assigner. To choose by role alone, use RoleAssigner without a class of your own (see Choose codecs per role).

Add a state schema

A schema sets the role of each tensor from its path in the nested state. Subclass StateSchema and implement role. This one names the roles of an Adafactor state, whose keys differ from Adam's:

"""A state schema: set the roles of an Adafactor state, whose keys differ from Adam's, and keep them in the archive."""

import tempfile
from pathlib import Path

import numpy as np

from jabara.container import Archive, write_archive
from jabara.schemas import StateSchema
from jabara.skeleton import flatten
from jabara.types import TensorMeta, TensorRecord

ROLES = {"exp_avg_sq_row": "adafactor_row", "exp_avg_sq_col": "adafactor_col", "step": "step"}


class AdafactorSchema(StateSchema):
    def role(self, path: tuple[object, ...]) -> str:
        return ROLES.get(str(path[-1]), "other") if path else "other"


state = {
    "state": {
        0: {"step": np.array([10], "<i8"), "exp_avg_sq_row": np.ones(8, "<f4"), "exp_avg_sq_col": np.ones(4, "<f4")}
    }
}
skeleton, leaves = flatten(state, lambda x: isinstance(x, np.ndarray))
schema = AdafactorSchema()
records = []
for name, leaf in leaves:
    array = np.asarray(leaf)
    meta = TensorMeta(name=name, dtype=str(array.dtype), shape=array.shape, role=schema.role(tuple(name.split("/"))))
    records.append(TensorRecord(meta, array))
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "checkpoint.jbr"
    write_archive(path, records, skeleton=skeleton)
    with Archive.open(path) as archive:
        roles = {name: archive.meta(name).role for name in archive.names()}
assert roles == {
    "state/0/step": "step",
    "state/0/exp_avg_sq_row": "adafactor_row",
    "state/0/exp_avg_sq_col": "adafactor_col",
}

path is the tuple of keys and indices that lead to the tensor, so path[-1] is the tensor's own key. The script flattens a nested state of NumPy arrays and writes the archive with write_archive. For a PyTorch state, pass an instance of the schema as schema= to save_state, as in Save and load state in a plain PyTorch loop. A role is any string, so a schema can add roles such as adafactor_row, and a RoleAssigner can then choose codecs for them.

Add a checkpoint file format

A format takes a checkpoint file apart into tensors and puts it back together, so that compress_file, decompress_file, and load_records take the file. Subclass CheckpointFormat, set kind, names, in_directory, and frameworks, implement split and join, and register the class with @register_format. The built-in format for NumPy's .npy files is the whole of one entry. A .npy file holds a text header and then the bytes of one array. The Npy class is 17 non-blank lines, and the two functions it calls to read the header are 33 more (a test checks both counts):

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


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)


@register_format
class Npy(CheckpointFormat):
    """A NumPy `.npy` file: one array."""

    kind = "npy"
    names = ("*.npy",)
    in_directory = ()
    frameworks = (("NumPy", "*.npy"),)

    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]))

    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)

Its test writes a file with np.save, compresses and restores it, and compares the bytes:

@pytest.mark.parametrize(
    "array",
    [
        rng.standard_normal((16, 8)).astype("<f4"),
        np.arange(12, dtype="<i8").reshape(3, 4),
        np.asfortranarray(rng.standard_normal((4, 6))),
        np.float16(1.5) * np.ones(()),
        np.arange(5, dtype=">f4"),  # big-endian: kept as bytes
        np.zeros(0, dtype="<f4"),
    ],
    ids=["float32", "int64", "fortran", "scalar", "big-endian", "empty"],
)
def test_a_npy_file_comes_back_byte_for_byte(array: NDArray[Any], tmp_path: Path) -> None:
    path = tmp_path / "array.npy"
    np.save(path, array)
    ((dtype, shape, role),) = round_trip(path).values()
    if array.dtype.byteorder == ">":
        assert (dtype, role) == ("uint8", "other")
    else:
        fortran = array.ndim > 1 and array.flags.f_contiguous and not array.flags.c_contiguous
        assert (shape, role) == (array.shape, "weight" if array.dtype.kind == "f" and not fortran else "other")
  • kind is stored in the archive index, and decompress_file finds the format by it, so never change it. register_format raises ValueError for a kind or a name pattern that is already registered.

  • names are the fnmatch patterns of a file that is named on its own. in_directory are the patterns of the files that compress_dir and jabara compress DIR take from a checkpoint directory; leave out files that a checkpoint keeps beside its tensors, such as a scheduler state. Npy takes none, because a directory may hold .npy files that are data, not a checkpoint.

  • split finds where each tensor sits in the file as a Span and hands the spans to jabara.formats.splice.cut, which returns the records, the source that the archive index stores, and every other byte of the file as the remainder. Jabara stores the remainder as one more tensor, (remainder), always losslessly. join hands them to splice.join, which writes the file back. A format can also build a Split itself.

  • split must not run code that the file holds. Npy reads the header, a Python literal, 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.

  • join(split(f)) must rebuild f byte for byte when the tensors come back bit for bit. exact tells join whether they did: it is false when a lossy codec stored some tensor. A file with checksums of its own, such as a zip, passes where it records them to cut (Span.crc_at, Checksum), and splice.join rewrites them after a lossy restore.

  • The jabara command knows only the built-in formats, which Checkpoint file formats lists with the size of each entry. A format that your module registers works in Python code that imports the module, with compress_file, decompress_file, compress_dir, and load_records.