Jabara
Theme

Compress training checkpoints behind one codec interface

Jabara compresses the model weights and the optimizer state of a training run, and restores them bit for bit by default.

Install

Jabara is not on PyPI yet. Install it from source:

Shell
git clone https://github.com/iamtatsuki05/jabara
cd jabara
pip install .

Python 3.10 or newer. An integration needs its extra, for example pip install ".[torch]"; the extras are torch, hf, lightning, and zipnn.

Built-in codecs

Lossless compression, deltas against an earlier checkpoint, and quantization all sit behind one codec interface, so you use, compare, and add codecs in the same way. The table is generated from the codec registry. Its last column names the library a codec wraps, the work that describes that library's method or format, and related work for the codecs that are this project's own and do not reproduce a published method.

A codec that needs a base codes a tensor as its difference from the same tensor of an earlier checkpoint. zipnn/1 needs the zipnn extra and raises MissingDependencyError without it. To write an archive with a lossy codec, pass allow_lossy=True. Without it, write_archive raises LossyNotAllowedError. jabara.bench.compare runs lossy candidates too and reports the error of each, so the results viewer has lossy rows for which no archive was written.

Built-in codecs
CodecTypeNeeds a baseBuilds on
bytegroup-zstd/1losslessnorelated Hershcovitch et al. 2025
related Waddington and Constantinescu 2025
wraps python-zstandard
quant8-linear/1lossynorelated Peng et al. 2025
wraps python-zstandard
quant8-log/1lossynorelated Dettmers et al. 2021
wraps python-zstandard
raw/1losslessnonone
sub-delta/1losslessyesrelated Ashok 2026
xor-delta/1losslessyesrelated Hershcovitch et al. 2025
related Waddington and Constantinescu 2025
zipnn/1losslessnowraps ZipNN: A Lossless Compression Library for AI pipelines
describes Hershcovitch et al. 2025
zstd/1losslessnowraps python-zstandard
wraps Zstandard - Fast real-time compression algorithm
describes Collet and Kucherawy 2021

Three extension points

Each is an abstract base class, and you extend Jabara by subclassing one. Each sample below is a complete script that defines one extension, uses it through write_archive and Archive, and checks the round trip. A test runs all three.

Codec

Turns one chunk of one tensor into bytes and back. It sets id and lossless, sets needs_ref when it reads the same chunk of its base, and is registered with register_codec.

Python
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()

A codec: split each tensor into byte planes and compress every plane with lzma from the standard library. From examples/extend/custom_codec.py.

Assigner

Chooses the codec for each tensor. It returns a CodecChoice: a codec id, its parameters, and an optional fallback for a delta codec whose base has no matching tensor. The library ships DefaultAssigner, UniformAssigner, and RoleAssigner.

Python
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

An assigner: keep weights bit-exact and store every Adam moment as 8-bit codes. From examples/extend/custom_assigner.py.

State schema

Names the role of each tensor from its path in the nested state, so that an assigner can treat weights, first moments, and second moments differently. The library ships OptimizerSchema, MuonSchema, and WeightsSchema.

Python
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",
}

A state schema: set the roles of an Adafactor state, whose keys differ from Adam's, and keep them in the archive. From examples/extend/custom_schema.py.