Python API

This page is generated from the docstrings and signatures in src/jabara. The modules are listed from the core types up to the adapters.

Types

Core data shapes shared by every layer. See DESIGN.md.

jabara.types.DTYPE_ITEMSIZE: dict[str, int] = {'bfloat16': 2, 'bool': 1, 'complex128': 16, 'complex64': 8, 'float16': 2, 'float32': 4, 'float64': 8, 'int16': 2, 'int32': 4, 'int64': 8, 'int8': 1, 'uint16': 2, 'uint32': 4, 'uint64': 8, 'uint8': 1}

Bytes per element for every dtype name an archive may carry. numpy has no bfloat16, so the core treats tensors as raw bytes and only ever needs the item size.

jabara.types.FLOAT_DTYPES: frozenset[str] = frozenset({'bfloat16', 'float16', 'float32', 'float64'})

The float dtypes: the ones DefaultAssigner sends to bytegroup-zstd/1 and the quantizers accept.

class jabara.types.TensorMeta(*, name: str, dtype: str, shape: tuple[Annotated[int, Ge(ge=0)], ...], role: str = 'other')[source]

Bases: BaseModel

The name, dtype, shape, and role of a tensor. dtype must be a name in DTYPE_ITEMSIZE, and shape holds non-negative sizes.

name: str

The tensor's name, such as state/0/exp_avg.

dtype: str

The dtype name, a key of DTYPE_ITEMSIZE.

shape: tuple[NonNegativeInt, ...]

The size of each dimension.

role: Role

What the tensor is for, such as weight or adam_m; other when no schema names it.

property itemsize: int

Bytes per element.

property nbytes: int

Bytes in the whole tensor.

class jabara.types.TensorRecord(meta: TensorMeta, data: bytes | bytearray | memoryview | NDArray[Any])[source]

Bases: object

A tensor as raw little-endian bytes (data) with its meta. len(data) equals meta.nbytes. data is read in place, without a copy, so it must not change while a call that was given the record runs.

meta: TensorMeta

The name, dtype, shape, and role.

data: bytes | bytearray | memoryview | NDArray[Any]

The tensor's bytes, little-endian.

jabara.types.as_memoryview(data: bytes | bytearray | memoryview | NDArray[Any]) → memoryview[source]

View any supported buffer as flat unsigned bytes without copying.

Codecs

The codec interface. See DESIGN.md, "Codec interface".

class jabara.codecs.base.NoParams[source]

Bases: BaseModel

The parameters of a codec that takes none.

class jabara.codecs.base.Work(*, kind: Literal['paper', 'specification', 'implementation'], title: str, authors: tuple[str, ...], year: int, url: str)[source]

Bases: BaseModel

A paper, a specification, or a library.

kind: Literal['paper', 'specification', 'implementation']
title: str
authors: tuple[str, ...]

As the source lists them, in its order; for a library, its author or owner as its own page names them.

year: int

The year of the publication, or of the release of a library that jabara uses.

url: str
class jabara.codecs.base.Reference(*, relation: Literal['wraps', 'describes', 'related'], work: Work)[source]

Bases: BaseModel

A work a codec builds on, and how. jabara codecs and the codec reference list them.

relation: Literal['wraps', 'describes', 'related']

"wraps": the codec calls this library. "describes": the work describes the method or the format of a library the codec wraps. "related": the work has the same idea; the codec is this project's own and does not reproduce the work's method.

work: Work
class jabara.codecs.base.Codec(params: BaseModel | None = None)[source]

Bases: ABC

Base class of every codec. A subclass sets id and lossless, optionally needs_ref, Params, dtypes, extra and references, and implements encode and decode for one chunk of one tensor. A codec with threads of its own also overrides with_threads. The first sentence of the class docstring is the codec's one-line description in jabara codecs --long.

id: ClassVar[str]

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

lossless: ClassVar[bool]

True when decode(encode(x)) returns x byte for byte for every chunk.

needs_ref: ClassVar[bool] = False

True for a delta codec: encode and decode then receive the same chunk of the base tensor as ref.

Params

The pydantic model of the codec's parameters (frozen, extra="forbid"). NoParams for a codec without any.

alias of NoParams

dtypes: ClassVar[frozenset[str]] = frozenset({'bfloat16', 'bool', 'complex128', 'complex64', 'float16', 'float32', 'float64', 'int16', 'int32', 'int64', 'int8', 'uint16', 'uint32', 'uint64', 'uint8'})

The dtypes the codec encodes; any other raises UnsupportedDtypeError. Every dtype unless a subclass narrows it.

extra: ClassVar[str | None] = None

The jabara extra that installs the package the codec imports on first use, or None. The package's top-level module has the extra's name.

references: ClassVar[tuple[Reference, ...]] = ()

What the codec builds on. Empty for a codec that cites nothing.

abstractmethod encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) → bytes[source]

Return the encoded bytes of one chunk. ref is the same chunk of the base tensor; only a codec with needs_ref reads it.

abstractmethod decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) → bytes | bytearray | memoryview[source]

Return the raw_length bytes that were encoded, as bytes, as a new bytearray, or as a memoryview of unsigned bytes (format B, one contiguous dimension) over a new buffer, which the caller then owns. A codec whose library returns a bytearray, or that builds its output in a NumPy array, needs no copy. The container checks the type where it takes the result and raises TypeError naming the codec for anything else: a view of a float32 array (arr.data), a two-dimensional view, and a strided view are all errors; use .cast("B") on a contiguous view of another format, and .reshape(-1) before .data. A lossless codec returns its input byte for byte. A lossy codec returns the same bytes every time for the same payload.

with_threads(threads: int) → Codec | None[source]

Return a copy of this codec that codes one chunk with at most threads threads of its own, or None for a codec that has none (the default). The container then codes the chunks one after another with the copy instead of on its thread pool. The copy must be the same class with the same id and params (the container raises TypeError otherwise), encode every chunk to the same payload, and decode every payload to the same bytes, so neither an archive's bytes nor whether it reads back depend on threads. Override it for a codec that holds the GIL while it works, because a pool cannot run such a codec in parallel.

The codec registry: it maps a codec id and parameters to a configured codec.

jabara.codecs.registry.register_codec(cls: C) → C[source]

Class decorator that registers a codec under its id. Raises ValueError if the id is already registered.

jabara.codecs.registry.get_codec(codec_id: str, params: Mapping[str, JsonValue] | None = None) → Codec[source]

Return a codec instance for codec_id, configured with params, a JSON object that the codec's Params model checks. Raises UnknownCodecError for an unknown id and pydantic.ValidationError for invalid parameters.

jabara.codecs.registry.codec_ids() → list[str][source]

Return the registered codec ids, sorted.

Built-in lossless codecs: raw/1, zstd/1, and bytegroup-zstd/1.

class jabara.codecs.builtin.RawCodec(params: BaseModel | None = None)[source]

Bases: Codec

Stores the bytes unchanged.

id: ClassVar[str] = 'raw/1'

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

lossless: ClassVar[bool] = True

True when decode(encode(x)) returns x byte for byte for every chunk.

encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) → bytes[source]

Return a copy of the chunk.

decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) → bytes[source]

Return a copy of the payload. Raises ValueError if its length is not raw_length.

class jabara.codecs.builtin.ZstdCodec(params: BaseModel | None = None)[source]

Bases: Codec

Compresses the whole chunk with Zstandard.

id = 'zstd/1'

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

lossless = True

True when decode(encode(x)) returns x byte for byte for every chunk.

references = (Reference(relation='wraps', work=Work(kind='implementation', title='python-zstandard', authors=('Gregory Szorc',), year=2025, url='https://github.com/indygreg/python-zstandard')), Reference(relation='wraps', work=Work(kind='implementation', title='Zstandard - Fast real-time compression algorithm', authors=('Meta Platforms, Inc. and affiliates',), year=2025, url='https://github.com/meta/zstd')), Reference(relation='describes', work=Work(kind='specification', title="Zstandard Compression and the 'application/zstd' Media Type", authors=('Y. Collet', 'M. Kucherawy'), year=2021, url='https://www.rfc-editor.org/info/rfc8878')))

What the codec builds on. Empty for a codec that cites nothing.

class Params(*, level: int = 3)[source]

Bases: BaseModel

level is the Zstandard compression level.

level: int
params: Params
encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) → bytes[source]

Return the chunk compressed with Zstandard.

decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) → bytes[source]

Return the decompressed chunk. Raises ValueError if the frame declares more than raw_length bytes or its size is not raw_length.

class jabara.codecs.builtin.ByteGroupZstdCodec(params: BaseModel | None = None)[source]

Bases: Codec

Splits the chunk into one byte plane per item byte and compresses each plane with Zstandard. For one-byte items it is the same as zstd/1.

id = 'bytegroup-zstd/1'

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

lossless = True

True when decode(encode(x)) returns x byte for byte for every chunk.

references = (Reference(relation='related', work=Work(kind='paper', title='ZipNN: Lossless Compression for AI Models', authors=('Moshik Hershcovitch', 'Andrew Wood', 'Leshem Choshen', 'Guy Girmonsky', 'Roy Leibovitz', 'Or Ozeri', 'Ilias Ennmouri', 'Michal Malka', 'Peter Chin', 'Swaminathan Sundararaman', 'Danny Harnik'), year=2025, url='https://doi.org/10.1109/CLOUD67622.2025.00028')), Reference(relation='related', work=Work(kind='paper', title='Lossless Compression for LLM Tensor Incremental Snapshots', authors=('Daniel Waddington', 'Cornel Constantinescu'), year=2025, url='https://arxiv.org/abs/2505.09810')), Reference(relation='wraps', work=Work(kind='implementation', title='python-zstandard', authors=('Gregory Szorc',), year=2025, url='https://github.com/indygreg/python-zstandard')))

What the codec builds on. Empty for a codec that cites nothing.

class Params(*, level: int = 3)[source]

Bases: BaseModel

level is the Zstandard compression level of every plane.

level: int
params: Params
encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) → bytes[source]

Return the plane lengths followed by the compressed planes. Raises ValueError if the chunk is not a multiple of the item size.

decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) → bytes | memoryview[source]

Rebuild the chunk from its planes, as a memoryview of a new array. Raises ValueError for a malformed payload.

Lossless delta codecs: xor-delta/1 and sub-delta/1.

class jabara.codecs.delta.DeltaParams(*, inner: str = 'bytegroup-zstd/1', inner_params: dict[str, JsonValue] = {})[source]

Bases: BaseModel

inner is the id of the lossless codec that codes the difference, and inner_params are its parameters. The inner codec must not need a base.

inner: str

The id of the lossless codec that codes the difference.

inner_params: dict[str, JsonValue]

The parameters of the inner codec.

class jabara.codecs.delta.XorDeltaCodec(params: BaseModel | None = None)[source]

Bases: _DeltaCodec

Codes the bitwise XOR of the chunk and the same chunk of the base, with the inner codec. Accepts every dtype.

id: ClassVar[str] = 'xor-delta/1'

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

references: ClassVar[tuple[Reference, ...]] = (Reference(relation='related', work=Work(kind='paper', title='ZipNN: Lossless Compression for AI Models', authors=('Moshik Hershcovitch', 'Andrew Wood', 'Leshem Choshen', 'Guy Girmonsky', 'Roy Leibovitz', 'Or Ozeri', 'Ilias Ennmouri', 'Michal Malka', 'Peter Chin', 'Swaminathan Sundararaman', 'Danny Harnik'), year=2025, url='https://doi.org/10.1109/CLOUD67622.2025.00028')), Reference(relation='related', work=Work(kind='paper', title='Lossless Compression for LLM Tensor Incremental Snapshots', authors=('Daniel Waddington', 'Cornel Constantinescu'), year=2025, url='https://arxiv.org/abs/2505.09810')))

What the codec builds on. Empty for a codec that cites nothing.

class jabara.codecs.delta.SubDeltaCodec(params: BaseModel | None = None)[source]

Bases: _DeltaCodec

Codes the wrap-around difference of the chunk and the base chunk, read as unsigned integers of the item size, with the inner codec. complex128 raises UnsupportedDtypeError.

id: ClassVar[str] = 'sub-delta/1'

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

dtypes: ClassVar[frozenset[str]] = frozenset({'bfloat16', 'bool', 'complex64', 'float16', 'float32', 'float64', 'int16', 'int32', 'int64', 'int8', 'uint16', 'uint32', 'uint64', 'uint8'})

The dtypes the codec encodes; any other raises UnsupportedDtypeError. Every dtype unless a subclass narrows it.

references: ClassVar[tuple[Reference, ...]] = (Reference(relation='related', work=Work(kind='paper', title='ULPack: Reference-Conditioned Lossless Compression of Checkpoint Trajectories', authors=('Aniket Srinivasan Ashok',), year=2026, url='https://arxiv.org/abs/2610.14184')),)

What the codec builds on. Empty for a codec that cites nothing.

Lossy 8-bit codecs: quant8-linear/1 and quant8-log/1.

Both work per chunk on the values widened to float64 and store a table of at most 256 reconstruction values in the tensor's own dtype, then the Zstandard-compressed 8-bit codes that index it. Decoding is a table lookup on the stored bytes, with no floating-point arithmetic, so a payload decodes to the same bytes on every machine. NaN, infinities, and a range that overflows float64 raise NonFiniteError; nothing is clamped.

jabara.codecs.quant.to_float64(buf: bytes | bytearray | memoryview, dtype: str) → ndarray[Any, Any][source]

Widen little-endian float bytes to float64; bfloat16 goes through its float32 bit pattern.

class jabara.codecs.quant.QuantParams(*, level: int = 3)[source]

Bases: BaseModel

level is the Zstandard compression level of the 8-bit codes.

level: int

The Zstandard compression level of the 8-bit codes.

class jabara.codecs.quant.Quant8LinearCodec(params: BaseModel | None = None)[source]

Bases: _Quant8

8-bit codes for 255 equal steps from the chunk minimum to its maximum.

Code c stands for lo + c * scale.

Per chunk, scale = (max - min) / 255 (the exact quotient). With tiny the smallest positive subnormal of the dtype, abs(x - x_hat) <= m * scale / 2 + 2**-48 * max(abs(x)) + tiny, where m is 1 for float64 and 2 for float16, bfloat16, and float32. No decoded value leaves [min, max]. A chunk whose items all have the same bits decodes exactly, -0.0 included.

Zeros keep no sign of their own. Entry 0 is lo, the chunk minimum, and no other entry is -0.0. When the minimum is zero, every zero gets code 0 and decodes to -0.0 if the chunk holds a -0.0, else to +0.0, so a chunk that mixes 0.0 and -0.0 decodes all its zeros to -0.0. When the minimum is negative, a zero decodes to +0.0 or to a nonzero value within the bound, so no zero decodes to -0.0.

Payload: the table size in bytes (uint16), the table (entry c is lo + c * scale kept inside [min, max] and rounded to the dtype, for c up to the largest code used), then the Zstandard-compressed codes.

id: ClassVar[str] = 'quant8-linear/1'

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

references: ClassVar[tuple[Reference, ...]] = (Reference(relation='related', work=Work(kind='paper', title='BitSnap: Checkpoint Sparsification and Quantization in LLM Training', authors=('Yanxin Peng', 'Qingping Li', 'Baodong Wu', 'Shigang Li', 'Guohao Dai', 'Shengen Yan', 'Yu Wang'), year=2025, url='https://arxiv.org/abs/2511.12376')), Reference(relation='wraps', work=Work(kind='implementation', title='python-zstandard', authors=('Gregory Szorc',), year=2025, url='https://github.com/indygreg/python-zstandard')))

What the codec builds on. Empty for a codec that cites nothing.

encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) → bytes[source]

Return the table followed by the Zstandard-compressed codes. Raises UnsupportedDtypeError for a dtype that is not a float, and NonFiniteError for NaN, an infinity, or a range that overflows float64.

decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) → memoryview[source]

Return the chunk: the table entry of every code, as a memoryview of the new array that holds them.

class jabara.codecs.quant.Quant8LogCodec(params: BaseModel | None = None)[source]

Bases: _Quant8

Logarithmic steps on the magnitude; the sign of every item is a separate packed bit plane.

Code 0 is the zero code: the item decodes to a signed zero. Codes 1 to 255 are 255 levels of ln(abs(x)) from the chunk's smallest to its largest nonzero magnitude, with step = (ln(max) - ln(min)) / 254; code c stands for exp(ln_min + (c - 1) * step). With step the exact quotient and m and tiny as for the linear codec, abs(x - x_hat) <= m * abs(x) * (exp(step / 2) - 1) + 2**-40 * abs(x) + tiny. No decoded magnitude leaves [min, max] of the nonzero magnitudes. Exact zeros, including -0.0, and every sign are kept exactly. Payload: the table size in bytes (uint16), the table of magnitudes in the dtype (entry 0 is zero), the packed sign plane (ceil(n / 8) bytes), then the Zstandard-compressed codes.

id: ClassVar[str] = 'quant8-log/1'

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

references: ClassVar[tuple[Reference, ...]] = (Reference(relation='related', work=Work(kind='paper', title='8-bit Optimizers via Block-wise Quantization', authors=('Tim Dettmers', 'Mike Lewis', 'Sam Shleifer', 'Luke Zettlemoyer'), year=2021, url='https://arxiv.org/abs/2110.02861')), Reference(relation='wraps', work=Work(kind='implementation', title='python-zstandard', authors=('Gregory Szorc',), year=2025, url='https://github.com/indygreg/python-zstandard')))

What the codec builds on. Empty for a codec that cites nothing.

encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) → bytes[source]

Return the table, the sign plane, and the Zstandard-compressed codes. Raises UnsupportedDtypeError for a dtype that is not a float, and NonFiniteError for NaN, an infinity, or a range that overflows float64.

decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) → memoryview[source]

Return the chunk: the magnitude of every code from the table, with the sign bit from the plane, as a memoryview of the new array that holds them.

zipnn/1: the zipnn package behind the codec interface.

class jabara.codecs.zipnn.ZipNNCodec(params: BaseModel | None = None, *, threads: int = 1)[source]

Bases: Codec

The zipnn package, with Zstandard as its entropy coder.

Lossless. Handles float16, bfloat16, and float32. Any other dtype raises UnsupportedDtypeError.

The third-party zipnn package is imported on first use. It imports torch, so the first call loads torch into the process. This import hides the FutureWarning about torch.jit.script that torch issues.

zipnn holds the GIL for a whole call and runs the call on threads of its own, so the container's thread pool cannot run two chunks at once. with_threads hands it the caller's thread budget instead; the bytes it writes are the same for every thread count. An instance from get_codec uses one thread.

id: ClassVar[str] = 'zipnn/1'

<name>/<version>, the key in the registry and in the archive index. Change the version when the payload format changes.

lossless: ClassVar[bool] = True

True when decode(encode(x)) returns x byte for byte for every chunk.

dtypes: ClassVar[frozenset[str]] = frozenset({'bfloat16', 'float16', 'float32'})

The dtypes the codec encodes; any other raises UnsupportedDtypeError. Every dtype unless a subclass narrows it.

extra: ClassVar[str | None] = 'zipnn'

The jabara extra that installs the package the codec imports on first use, or None. The package's top-level module has the extra's name.

references: ClassVar[tuple[Reference, ...]] = (Reference(relation='wraps', work=Work(kind='implementation', title='ZipNN: A Lossless Compression Library for AI pipelines', authors=('ZipNN Contributors',), year=2026, url='https://github.com/zipnn/zipnn')), Reference(relation='describes', work=Work(kind='paper', title='ZipNN: Lossless Compression for AI Models', authors=('Moshik Hershcovitch', 'Andrew Wood', 'Leshem Choshen', 'Guy Girmonsky', 'Roy Leibovitz', 'Or Ozeri', 'Ilias Ennmouri', 'Michal Malka', 'Peter Chin', 'Swaminathan Sundararaman', 'Danny Harnik'), year=2025, url='https://doi.org/10.1109/CLOUD67622.2025.00028')))

What the codec builds on. Empty for a codec that cites nothing.

with_threads(threads: int) → ZipNNCodec[source]

Return a copy that runs each zipnn call on threads threads.

encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) → bytes[source]

Return the chunk compressed with zipnn. Raises UnsupportedDtypeError for a dtype other than float16, bfloat16, and float32, and MissingDependencyError if the zipnn package is not installed.

decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) → bytes | bytearray[source]

Return the chunk decompressed with zipnn. Raises the same errors as encode.

Assignment

Choosing a codec per tensor. See DESIGN.md, "Assignment".

class jabara.assign.CodecChoice(*, codec_id: str, params: dict[str, JsonValue] = {}, fallback: CodecChoice | None = None)[source]

Bases: BaseModel

A codec id with its parameters. params is checked against the codec's Params model. fallback is used for a delta codec when the base has no matching tensor; it must not need a base.

codec_id: str

The id of the codec, such as bytegroup-zstd/1.

params: dict[str, JsonValue]

The codec's parameters; those left out take the codec's defaults.

fallback: CodecChoice | None

Used when a delta codec is chosen but the base has no matching tensor; it must not need a base.

class jabara.assign.Assigner[source]

Bases: ABC

Picks the codec for each tensor. Subclass it and implement choose.

abstractmethod choose(meta: TensorMeta) → CodecChoice[source]

Return the CodecChoice for the tensor that meta describes.

class jabara.assign.DefaultAssigner[source]

Bases: Assigner

bytegroup-zstd/1 for float dtypes and zstd/1 for everything else.

choose(meta: TensorMeta) → CodecChoice[source]

Return the default choice for the dtype of meta.

class jabara.assign.UniformAssigner(choice: CodecChoice)[source]

Bases: Assigner

Applies one choice to float tensors and the default choice to every other tensor.

choose(meta: TensorMeta) → CodecChoice[source]

Return choice for a float tensor and the default choice otherwise.

class jabara.assign.RoleAssigner(by_role: Mapping[str, CodecChoice], default: Assigner | None = None)[source]

Bases: Assigner

Picks a choice by tensor role. A role that by_role does not list goes to default, which is DefaultAssigner() when omitted.

choose(meta: TensorMeta) → CodecChoice[source]

Return the choice for the role of meta, or the default's choice if the role is not listed.

Roles

State schemas: set the role of each tensor from its path in the nested state. See DESIGN.md.

class jabara.schemas.StateSchema[source]

Bases: ABC

Sets the role of each tensor from its path in the nested state. Subclass it and implement role.

abstractmethod role(path: tuple[object, ...]) → str[source]

Return the role of the tensor at path, a tuple of the keys and indices that lead to it.

class jabara.schemas.OptimizerSchema[source]

Bases: StateSchema

Roles by the last path element: exp_avg is adam_m, exp_avg_sq is adam_v, max_exp_avg_sq is adam_vmax, momentum_buffer is momentum, step is step, and anything else is other.

roles: ClassVar[Mapping[str, str]] = {'exp_avg': 'adam_m', 'exp_avg_sq': 'adam_v', 'max_exp_avg_sq': 'adam_vmax', 'momentum_buffer': 'momentum', 'step': 'step'}
role(path: tuple[object, ...]) → str[source]

Return the role for the last element of path.

class jabara.schemas.MuonSchema[source]

Bases: OptimizerSchema

Like OptimizerSchema, but momentum_buffer is muon_momentum.

roles: ClassVar[Mapping[str, str]] = {'exp_avg': 'adam_m', 'exp_avg_sq': 'adam_v', 'max_exp_avg_sq': 'adam_vmax', 'momentum_buffer': 'muon_momentum', 'step': 'step'}
class jabara.schemas.WeightsSchema[source]

Bases: StateSchema

Gives every tensor the role weight.

role(path: tuple[object, ...]) → str[source]

Return weight.

Archives

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

jabara.container.MAGIC = b'JABARA\x00\x01'

The first 8 bytes of every archive.

jabara.container.MAGIC_END = b'\x01\x00ARABAJ'

The last 8 bytes of every archive.

jabara.container.FORMAT_BASES: Literal[2] = 2

The format of an archive whose delta tensors refer to more than one base archive.

jabara.container.CHUNK_SIZE = 16777216

The default chunk_size of write_archive, in bytes (16 MiB).

jabara.container.MAX_CHUNK_SIZE = 268435456

The largest raw chunk the format allows, in bytes (256 MiB).

class jabara.container.ArchiveInfo(*, path: str, raw_bytes: int, stored_bytes: int, elapsed_seconds: float)[source]

Bases: BaseModel

What write_archive returns: the path, the raw and stored byte totals, and the elapsed seconds.

path: str

The path of the archive.

raw_bytes: int

The tensor bytes before coding.

stored_bytes: int

The bytes of the encoded chunks, without the index.

elapsed_seconds: float

The wall-clock seconds the write took.

class jabara.container.TensorStats(*, meta: TensorMeta, codec: str, lossless: bool, max_abs_err: float | None, raw_bytes: int, stored_bytes: int)[source]

Bases: BaseModel

The codec and sizes of one tensor, read from the index. max_abs_err is None for a lossless tensor.

meta: TensorMeta

The tensor's name, dtype, shape, and role.

codec: str

The id of the codec that coded the tensor.

lossless: bool

Whether the codec restores the tensor bit for bit.

max_abs_err: float | None

The largest absolute error a lossy codec recorded; None for a lossless tensor.

raw_bytes: int

The tensor bytes before coding.

stored_bytes: int

The bytes of the tensor's encoded chunks.

class jabara.container.ChunkEntry(*, offset: Annotated[int, Ge(ge=0)], length: Annotated[int, Ge(ge=0)], raw_length: Annotated[int, Ge(ge=1), Le(le=268435456)], crc32: Annotated[int, Ge(ge=0), Le(le=4294967295)])[source]

Bases: BaseModel

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.

offset: NonNegativeInt

Where the chunk's stored bytes start in the file.

length: NonNegativeInt

The number of stored bytes.

raw_length: Annotated[int, Field(ge=1, le=MAX_CHUNK_SIZE)]

The number of bytes the chunk restores to.

crc32: Annotated[int, Field(ge=0, le=4294967295)]

The CRC-32 of the bytes a reader must produce.

class jabara.container.TensorEntry(*, name: str, dtype: str, shape: tuple[Annotated[int, Ge(ge=0)], ...], role: str = 'other', codec: str, params: dict[str, JsonValue], lossless: bool, max_abs_err: float | None, chunks: list[ChunkEntry])[source]

Bases: TensorMeta

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.

codec: str

The id of the codec that coded the tensor.

params: dict[str, JsonValue]

The codec's full parameters, defaults filled in.

lossless: bool

Whether the codec restores the tensor bit for bit.

max_abs_err: float | None

The largest absolute error a lossy codec recorded; None for a lossless tensor.

chunks: list[ChunkEntry]

The tensor's chunks, in order.

class jabara.container.BaseRef(*, name: str, index_crc: int)[source]

Bases: BaseModel

Names the base archive of a delta archive by file name and index CRC-32.

name: str

The file name of the base archive.

index_crc: int

The CRC-32 of the base archive's index.

class jabara.container.ArchiveIndex(*, format: Literal[1, 2], writer: str, tensors: list[TensorEntry], skeleton: JsonValue, source: JsonValue, base: BaseRef | list[BaseRef] | None)[source]

Bases: BaseModel

The JSON index at the end of an archive. model_json_schema() is the schema of the format.

format: Literal[1, 2]

The format version: 2 when base lists several base archives, 1 otherwise.

writer: str

The name and version of the library that wrote the archive.

tensors: list[TensorEntry]

One entry per tensor.

skeleton: JsonValue

The nested structure that save_state saved; JSON the container does not read.

source: JsonValue

Where the tensors came from, as an object with a kind; JSON the container does not read.

base: BaseRef | list[BaseRef] | None

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_refs() → list[BaseRef][source]

The base archives, in the order the delta tensors look them up; empty when there is none.

jabara.container.encode_chunks(codec: Codec, meta: TensorMeta, data: memoryview, lengths: Sequence[int], ref_all: memoryview | None, pool: ThreadPoolExecutor | None) → list[bytes][source]

Encode each chunk of one tensor with codec; ref_all is the whole base tensor, if the codec needs one.

jabara.container.seal_chunks(codec: Codec, meta: TensorMeta, data: memoryview, lengths: Sequence[int], payloads: Sequence[bytes], ref_all: memoryview | None, pool: ThreadPoolExecutor | None) → list[tuple[int, float]][source]

Per chunk, the CRC-32 of the bytes a reader must produce and the largest absolute error (0.0 if lossless).

jabara.container.decode_chunks(codec: Codec, meta: TensorMeta, chunks: Sequence[tuple[bytes, int, int]], ref_all: memoryview | None, pool: ThreadPoolExecutor | None, where: str) → list[bytes | bytearray | memoryview][source]

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.

jabara.container.is_reference(base: TensorMeta, meta: TensorMeta) → bool[source]

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.

jabara.container.write_archive(path: str | PathLike[str], tensors: Iterable[TensorRecord], *, skeleton: JsonValue = None, source: JsonValue = None, assign: Assigner | None = None, threads: int | None = None, chunk_size: int = 16777216, base: Archive | Sequence[Archive] | None = None, allow_lossy: bool = False) → ArchiveInfo[source]

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.

class jabara.container.Archive(path: str, f: BinaryIO, index: ArchiveIndex, index_crc: int, bases: list[Archive])[source]

Bases: object

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.

index_by_name: dict[str, TensorEntry]
classmethod open(path: str | PathLike[str], *, base: Archive | Sequence[Archive] | None = None) → Archive[source]

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.

close() → None[source]

Close the file.

names() → list[str][source]

Return the tensor names in archive order.

meta(name: str) → TensorMeta[source]

Return the TensorMeta of name. Raises KeyError if there is no such tensor.

chunk_lengths(name: str) → list[int][source]

Return the raw length of each chunk of name. Raises KeyError if there is no such tensor.

read(name: str, *, threads: int | None = None) → bytes[source]

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.

verify(*, threads: int | None = None) → None[source]

Decode every tensor and check every checksum. Raises the first error that read would raise.

stats() → list[TensorStats][source]

Return the codec and sizes of every tensor.

Nested state

Split a nested state into a JSON skeleton and flat tensors, and put it back. See DESIGN.md.

jabara.skeleton.flatten(obj: object, is_tensor: Callable[[object], bool], attrs: Callable[[object], dict[str, Any]] | None = None) → tuple[Any, list[tuple[str, object]]][source]

Split a nested state into a JSON skeleton and its tensors. A leaf for which is_tensor is true becomes {"$t": name}, with the path joined by / as its name, or {"$t": [name, attrs]} when attrs gives it a non-empty dict of JSON attributes (what unflatten's rebuild needs besides the bytes). The _metadata attribute of an OrderedDict (a module state_dict() sets one) is stored beside its items; it holds no tensors. Other attributes are not stored. Returns the skeleton and the (name, tensor) pairs. Raises UnsupportedStateError for an unsupported type, a subclass of a container type, a tensor in _metadata, or two tensors with the same name.

jabara.skeleton.unflatten(skeleton: Any, tensors: Mapping[str, object], rebuild: Callable[[object, dict[str, Any]], object] | None = None) → object[source]

Rebuild the nested state from a skeleton and a mapping of tensors by name. A tensor stored with attributes becomes rebuild(tensor, attrs), and an OrderedDict stored with $metadata gets it back as _metadata. Raises ArchiveFormatError, naming the path in the skeleton, for a malformed skeleton, a tensor missing from tensors or inside $metadata, or attributes with no rebuild.

Torch state

Save a nested torch state to a Jabara archive and load it back.

Imports torch lazily. See DESIGN.md, "Torch layer".

jabara.torch.tensor_records(obj: object, schema: StateSchema | None = None) → list[TensorRecord][source]

The tensor leaves of a nested state as records, named and given roles the way save_state does.

jabara.torch.save_state(obj: object, path: str | PathLike[str], *, schema: StateSchema | None = None, threads: int | None = None, assign: Assigner | None = None, base: Archive | Sequence[Archive] | None = None, allow_lossy: bool = False) → ArchiveInfo[source]

Write a nested state of tensors and plain values to an archive at path, with roles from schema (OptimizerSchema if None). An nn.Parameter leaf and a tensor's requires_grad are kept in the skeleton. Returns the ArchiveInfo. Raises UnsupportedStateError for a value that cannot be stored without pickle (a tensor subclass included) and for a sparse or meta tensor, UnsupportedDtypeError for a dtype that Jabara does not support, and the errors of write_archive.

jabara.torch.load_state(path: str | os.PathLike[str], *, map_location: str | torch.device | None = 'cpu', threads: int | None = None, base: Archive | Sequence[Archive] | None = None) → object[source]

Read an archive that save_state wrote, or that compress_file wrote from a torch file, and return the same nested state, with every tensor on the device map_location names (None is CPU), nn.Parameter leaves as nn.Parameter, requires_grad as saved, and every OrderedDict with the _metadata it had (a module state_dict loads with its module versions). A delta archive needs base, the open archive it was written against. An archive of a torch file is restored to a temporary file and read with torch.load(weights_only=True), which refuses a file that holds other objects than tensors and plain values. Raises ValueError for a map_location that is not None, a str, or a torch.device, or that names the meta device, before the archive is opened, and ArchiveFormatError for an archive of anything else.

Files and directories

Compress and restore checkpoint files and directories. See DESIGN.md.

jabara.files.SUFFIX = '.jbr'

The suffix an archive adds to the name of the file it restores.

jabara.files.REMAINDER = '(remainder)'

The name of the tensor that holds the bytes of a file that are not tensor data (see Split.remainder).

jabara.files.open_bases(base: str | PathLike[str] | Sequence[str | PathLike[str]] | None, *, to_write: bool = False) → Iterator[list[Archive]][source]

The base archives base names, open: none for None, the archive itself for a file, and every *.jbr file of a directory, in name order. A sequence of paths stands for each of them in turn. To write against a directory, it must hold an archive, and every checkpoint file in it must have its archive beside it, so that no tensor silently loses its reference.

A base that is itself a delta archive (a chain, --delta previous) is opened with its own bases, which are the archives with the recorded index CRC-32 among those beside it: in its directory, in the other subdirectories of its parent, and in the parent. BaseMismatchError names the one that is missing.

jabara.files.MAX_CHAIN = 100

The longest chain of bases that is read or written; decoding recurses once per link.

jabara.files.check_source(src: Path) → CheckpointFormat[source]

The format of src, a file compress_file takes. Raises FileNotFoundError or ValueError otherwise.

jabara.files.compress_file(path: str | PathLike[str], *, keep: bool = False, threads: int | None = None, assign: Assigner | None = None, allow_lossy: bool = False, base: str | PathLike[str] | None = None) → ArchiveInfo[source]

Compress one file next to itself. With base, an archive of an earlier checkpoint or a directory of such archives, float tensors are stored as xor-delta/1 against the tensor of the same name, dtype, and shape in them unless assign says otherwise; tensors without one are stored whole.

The archive is written and verified under a temporary name and only then renamed to its own, so an archive under the final name has always been verified.

jabara.files.restore(archive: Archive, out: Path, *, threads: int | None = None) → None[source]

Write the file that archive, an open archive of a file in a registered format, was made from, at out. Raises ArchiveFormatError for an archive of no registered format.

jabara.files.decompress_file(path: str | PathLike[str], *, keep: bool = False, threads: int | None = None, base: str | PathLike[str] | Sequence[str | PathLike[str]] | None = None) → Path[source]

Restore the file an archive was made from. A delta archive needs base, the archive it was written against or a directory that holds the archives it was written against.

jabara.files.checkpoint_files(path: str | PathLike[str]) → list[Path][source]

The files compress_dir takes from the directory path, in name order: the regular files whose names a format takes in a directory (jabara.formats), except a file that already is a Jabara archive, such as a .ckpt that the Lightning plugin writes.

jabara.files.checkpoint_dirs(path: str | PathLike[str]) → list[Path][source]

The checkpoint directories of the parent path: its immediate subdirectories that hold a file compress_dir takes or a *.jbr archive, in natural order of name, then path itself last if it holds such a file. A Hugging Face output_dir keeps the final model beside its checkpoint-* directories, hence the last place.

One level only: a PEFT checkpoint keeps adapter subdirectories that its loader reads by name, so nothing deeper is a checkpoint. A hidden directory (name starts with .) and a symbolic link to a directory are skipped, so the walk never leaves the tree. Raises FileNotFoundError or NotADirectoryError for a path that is no directory.

jabara.files.dependants(directory: Path, archives: Sequence[Path]) → list[Path][source]

The delta archives that cannot be read once archives, which are in directory, are gone: those written against one of them, among the archives of directory, of the other subdirectories of its parent, and of the parent. Bases match by index CRC-32 alone, as Archive.open matches (a renamed base still decodes), so an archive with the same index CRC-32 that stays among them is a copy that serves, and no archive depends on that CRC. An archive that cannot be read names no base and is nobody's.

jabara.files.refuse_to_orphan(directory: Path, archives: Sequence[Path]) → None[source]

Raise ValueError when deleting archives, which decompress does unless told to keep them, would leave a delta archive of a sibling checkpoint directory without its base. Decompress those first, or keep the archives.

class jabara.files.ParentScan(dirs: Sequence[Path])[source]

Bases: object

The indexes of the archives in the checkpoint directories dirs of one parent, read once and closed: which archive each delta archive is written against, and so in which order the directories can be restored.

A base is found by the file name and index CRC-32 that the delta archive records, among the archives of the other directories. An archive whose index cannot be read names no base and is nobody's; reading it fails where it is used.

archives(directory: Path) → list[Path][source]
sizes(directory: Path) → tuple[int, int][source]

The raw and the stored tensor bytes of the readable archives in directory.

resolve(archive: Path) → tuple[list[Path], list[BaseRef]][source]

The archives of the other directories that archive is written against, and the recorded bases that none holds.

chain(archive: Path) → tuple[list[Path], tuple[Path, BaseRef] | None][source]

The archives that archive needs, its bases and theirs in turn, nearest first, and the first base that no other directory holds with the archive that is written against it, or None when none is missing. A base that a chain reaches twice is listed once.

bases(directory: Path) → list[Path][source]

The base archives that the archives of directory need, those they are written against directly. A base of theirs that no other directory holds is as much a failure: the restore would stop at it. ValueError for a base that is missing, naming the archive written against it.

restore_order() → list[Path][source]

The directories, dependants first: a directory is restored before any directory that holds an archive it needs, because restoring deletes its archives. Natural order otherwise. ValueError for a cycle.

jabara.files.missing_base(ref: BaseRef) → str[source]
jabara.files.compress_dir(path: str | PathLike[str], *, keep: bool = False, threads: int | None = None, assign: Assigner | None = None, allow_lossy: bool = False, base: str | PathLike[str] | None = None) → list[ArchiveInfo][source]

Compress each file in the directory that a format takes there (*.safetensors, optimizer.pt, and the others that jabara.formats lists), in name order, and return one ArchiveInfo per file. Other files stay. With base, the directory of an earlier compressed checkpoint (or one archive of it), each file is delta-coded as compress_file codes it: every tensor against the tensor of the same name in any archive of the base, so the two checkpoints may split their tensors over files differently.

All or nothing, so the directory stays loadable without Jabara when anything fails: every archive is written and verified next to its original first, and the originals are deleted (unless keep) only once all are. A failure deletes the archives this call put in place, an existing archive it replaced included, and re-raises; every original is still in place, and an archive this call did not replace stays.

jabara.files.decompress_dir(path: str | PathLike[str], *, keep: bool = False, threads: int | None = None, base: str | PathLike[str] | Sequence[str | PathLike[str]] | None = None) → list[Path][source]

Restore every *.jbr file in the directory, in name order, and return the restored paths. Delta archives need base, as decompress_file does.

All or nothing, as compress_dir: every file is restored and checked first, and the archives are deleted (unless keep) only once all are. A failure deletes the files this call restored and re-raises; every archive stays.

jabara.files.export_weights(archive_path: str | PathLike[str], out: str | PathLike[str]) → None[source]

Write the tensors with role "weight" as a safetensors file.

jabara.files.load_records(path: str | PathLike[str], *, threads: int | None = None) → list[TensorRecord][source]

The tensors of an archive, a safetensors file, a torch file, or a checkpoint directory, as raw records.

A directory yields the files compress would take plus its archives, with each tensor name prefixed by the name of the checkpoint file and /; an archive counts under the name of the file it restores (model.safetensors.jbr as model.safetensors), so names match between a compressed and an uncompressed checkpoint directory. A directory that holds both a file and its archive raises ValueError.

The interface of a checkpoint file format. See DESIGN.md, "Checkpoint file formats".

class jabara.formats.base.Split(records: list[TensorRecord], source: dict[str, JsonValue], remainder: bytes = b'')[source]

Bases: NamedTuple

A checkpoint file taken apart: its tensors, and what restores the file around them.

records: list[TensorRecord]

The tensors, in the order join takes their bytes back.

source: dict[str, JsonValue]

What join needs besides the bytes, as JSON. The archive index stores it with kind.

remainder: bytes

The bytes of the file that are not tensor data, if the format keeps any. The archive stores them as one more tensor of dtype uint8 and role other, so a codec compresses them too.

class jabara.formats.base.CheckpointFormat[source]

Bases: ABC

Base class of every checkpoint file format. A subclass sets kind, names, in_directory, and frameworks, implements split and join, and is registered with @register_format.

join(split(path)) must rebuild the file byte for byte when the tensors come back bit for bit. split only reads: it never runs code that the file holds.

kind: ClassVar[str]

Recorded in the archive index as source["kind"]; a reader finds the format by it, so it never changes.

names: ClassVar[tuple[str, ...]]

fnmatch patterns of the file names this format takes when a file is named on its own.

in_directory: ClassVar[tuple[str, ...]]

fnmatch patterns of the file names compress_dir takes from a checkpoint directory.

frameworks: ClassVar[tuple[tuple[str, str], ...]]

(framework, file names) pairs for the formats reference page.

abstractmethod split(path: Path) → Split[source]

Take the file at path apart. Raises ArchiveFormatError for a file this format cannot take.

abstractmethod join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

Write the file at out from source, remainder, and the bytes of each record in the order split returned them. exact is true when every tensor came back bit for bit, so the file must come back byte for byte; a format that can check that does. Raises ArchiveFormatError for a source it cannot use.

The format registry: it maps a file name or an archive's source kind to a checkpoint file format.

jabara.formats.registry.register_format(cls: F) → F[source]

Class decorator that registers a format under its kind. Raises ValueError if the kind is already registered or a file-name pattern is taken by a format registered earlier.

jabara.formats.registry.formats() → list[CheckpointFormat][source]

The registered formats, in the order they were registered.

jabara.formats.registry.format_of_file(path: Path) → CheckpointFormat[source]

The format that takes a file of this name on its own. Raises ValueError naming the patterns otherwise.

jabara.formats.registry.format_in_directory(path: Path) → CheckpointFormat | None[source]

The format that compress_dir takes a file of this name with, or None to leave the file alone.

jabara.formats.registry.format_of_kind(kind: object) → CheckpointFormat | None[source]

The format whose archives record this source kind, or None.

jabara.formats.registry.directory_patterns() → list[str][source]

Every pattern compress_dir takes, for messages.

Parse and rebuild safetensors files without the safetensors package. See DESIGN.md.

jabara.formats.safetensors.read_safetensors(path: str | PathLike[str]) → tuple[bytes, list[TensorRecord]][source]

Return the header bytes of a safetensors file and its tensors in file order, backed by a memory map. Raises ArchiveFormatError if the file is not a valid safetensors file or holds a dtype that Jabara does not know.

jabara.formats.safetensors.write_safetensors(path: str | PathLike[str], header: bytes, tensors: Iterable[bytes]) → None[source]

Write a safetensors file from its header bytes and the tensor bytes in order. The file is written to a new temporary file next to path, synced to stable storage, and renamed at the end. Raises ValueError if the tensor bytes do not add up to the header's offsets.

class jabara.formats.safetensors.Safetensors[source]

Bases: CheckpointFormat

A safetensors file: a JSON header, then the bytes of every tensor. The header is kept as text.

kind: ClassVar[str] = 'safetensors'

Recorded in the archive index as source["kind"]; a reader finds the format by it, so it never changes.

names: ClassVar[tuple[str, ...]] = ('*.safetensors',)

fnmatch patterns of the file names this format takes when a file is named on its own.

in_directory: ClassVar[tuple[str, ...]] = ('*.safetensors',)

fnmatch patterns of the file names compress_dir takes from a checkpoint directory.

frameworks: ClassVar[tuple[tuple[str, str], ...]] = (('Hugging Face Transformers, Accelerate, PEFT, Diffusers, MLX', '*.safetensors'),)

(framework, file names) pairs for the formats reference page.

split(path: Path) → Split[source]

Take the file at path apart. Raises ArchiveFormatError for a file this format cannot take.

join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

Write the file at out from source, remainder, and the bytes of each record in the order split returned them. exact is true when every tensor came back bit for bit, so the file must come back byte for byte; a format that can check that does. Raises ArchiveFormatError for a source it cannot use.

The zip files that torch.save writes, taken apart without unpickling them. See DESIGN.md.

torch.save writes a zip whose members are stored, not compressed: data.pkl, the pickle of the object, and one member data/<key> per tensor storage, which holds the storage's bytes as they are in memory. The split keeps the storage members as tensors and every other byte of the file (local headers, data.pkl, the central directory) as the remainder, so the file comes back byte for byte.

The dtype and size of each storage are read from the persistent ids in data.pkl with pickletools, which only parses opcodes: no class is imported and no code in the file runs. Tensor names and roles need the object itself, so they come from torch.load(weights_only=True), which refuses any class that is not on PyTorch's allow-list; when it refuses, or torch is not installed, every storage keeps a name from its key and the role other.

class jabara.formats.torch_zip.TorchZip[source]

Bases: CheckpointFormat

A file torch.save wrote in its zip layout (PyTorch 1.6 and later), whatever object it holds.

kind: ClassVar[str] = 'torch-zip'

Recorded in the archive index as source["kind"]; a reader finds the format by it, so it never changes.

names: ClassVar[tuple[str, ...]] = ('*.pt', '*.pth', '*.bin', '*.ckpt')

fnmatch patterns of the file names this format takes when a file is named on its own.

in_directory: ClassVar[tuple[str, ...]] = ('optimizer.pt', 'optimizer.bin', 'pytorch_model*.bin', '*.ckpt', 'mp_rank_*_model_states.pt', '*_optim_states.pt', 'model_optim_rng.pt')

fnmatch patterns of the file names compress_dir takes from a checkpoint directory.

frameworks: ClassVar[tuple[tuple[str, str], ...]] = (('Hugging Face Transformers', 'optimizer.pt, pytorch_model*.bin'), ('Accelerate', 'optimizer.bin, pytorch_model*.bin'), ('PyTorch Lightning', '*.ckpt'), ('DeepSpeed', 'mp_rank_*_model_states.pt, *_optim_states.pt'), ('Megatron-LM (torch format)', 'model_optim_rng.pt'), ('PyTorch', '*.pt, *.pth, *.bin, named on their own'))

(framework, file names) pairs for the formats reference page.

split(path: Path) → Split[source]

Take the file at path apart. Raises ArchiveFormatError for a file this format cannot take.

join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

Write the file at out from source, remainder, and the bytes of each record in the order split returned them. exact is true when every tensor came back bit for bit, so the file must come back byte for byte; a format that can check that does. Raises ArchiveFormatError for a source it cannot use.

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.

class jabara.formats.splice.Span(start: int, end: int, meta: TensorMeta, crc_at: tuple[int, ...] = ())[source]

Bases: NamedTuple

Where one tensor's bytes sit in the file, and what it is.

start: int

Alias for field number 0

end: int

Alias for field number 1

meta: TensorMeta

Alias for field number 2

crc_at: tuple[int, ...]

Where the file records the CRC-32 of exactly these bytes (a zip member that holds only the tensor).

class jabara.formats.splice.Checksum(start: int, end: int, crc_at: tuple[int, ...])[source]

Bases: NamedTuple

A CRC-32 the file records over a range that holds tensors and other bytes (a zip member with a header).

start: int

Alias for field number 0

end: int

Alias for field number 1

crc_at: tuple[int, ...]

Alias for field number 2

class jabara.formats.splice.Source(*, size: Annotated[int, Ge(ge=0)], crc32: Annotated[int, Ge(ge=0)], storages: list[tuple[Annotated[int, Ge(ge=0)], Annotated[int, Ge(ge=0)], list[Annotated[int, Ge(ge=0)]]]], members: list[tuple[Annotated[int, Ge(ge=0)], Annotated[int, Ge(ge=0)], list[Annotated[int, Ge(ge=0)]]]] = [])[source]

Bases: BaseModel

What join reads from the archive index.

size: NonNegativeInt
crc32: NonNegativeInt
storages: list[tuple[NonNegativeInt, NonNegativeInt, list[NonNegativeInt]]]

Per tensor in file order: offset, length, and where the file records the tensor's own CRC-32.

members: list[tuple[NonNegativeInt, NonNegativeInt, list[NonNegativeInt]]]

Per range with a CRC-32 of its own: offset, length, and where the file records it.

jabara.formats.splice.open_map(path: Path, what: str) → mmap[source]

The file mapped read-only. ArchiveFormatError for an empty file or a Jabara archive.

jabara.formats.splice.cut(path: Path, raw: mmap, spans: Sequence[Span], checksums: Sequence[Checksum] = ()) → tuple[list[TensorRecord], dict[str, JsonValue], bytes][source]

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.

jabara.formats.splice.join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

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.

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.

jabara.formats.npy.dtype_name(dtype: dtype[generic]) → str | None[source]

The Jabara dtype name of a little-endian (or single-byte) NumPy dtype, or None for any other dtype.

jabara.formats.npy.array_span(raw: mmap, start: int, end: int, name: str, bad: Callable[[str], ArchiveFormatError]) → Span[source]

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

class jabara.formats.npy.Npy[source]

Bases: CheckpointFormat

A NumPy .npy file: one array.

kind: ClassVar[str] = 'npy'

Recorded in the archive index as source["kind"]; a reader finds the format by it, so it never changes.

names: ClassVar[tuple[str, ...]] = ('*.npy',)

fnmatch patterns of the file names this format takes when a file is named on its own.

in_directory: ClassVar[tuple[str, ...]] = ()

fnmatch patterns of the file names compress_dir takes from a checkpoint directory.

frameworks: ClassVar[tuple[tuple[str, str], ...]] = (('NumPy', '*.npy'),)

(framework, file names) pairs for the formats reference page.

split(path: Path) → Split[source]

Take the file at path apart. Raises ArchiveFormatError for a file this format cannot take.

join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

Write the file at out from source, remainder, and the bytes of each record in the order split returned them. exact is true when every tensor came back bit for bit, so the file must come back byte for byte; a format that can check that does. Raises ArchiveFormatError for a source it cannot use.

class jabara.formats.npy.Npz[source]

Bases: 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: ClassVar[str] = 'npz'

Recorded in the archive index as source["kind"]; a reader finds the format by it, so it never changes.

names: ClassVar[tuple[str, ...]] = ('*.npz',)

fnmatch patterns of the file names this format takes when a file is named on its own.

in_directory: ClassVar[tuple[str, ...]] = ()

fnmatch patterns of the file names compress_dir takes from a checkpoint directory.

frameworks: ClassVar[tuple[tuple[str, str], ...]] = (('NumPy (np.savez), MLX (mx.savez)', '*.npz'),)

(framework, file names) pairs for the formats reference page.

split(path: Path) → Split[source]

Take the file at path apart. Raises ArchiveFormatError for a file this format cannot take.

join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

Write the file at out from source, remainder, and the bytes of each record in the order split returned them. exact is true when every tensor came back bit for bit, so the file must come back byte for byte; a format that can check that does. Raises ArchiveFormatError for a source it cannot use.

GGUF files, the format of llama.cpp and the tools around it. See DESIGN.md.

A GGUF file is a header (magic, version, tensor and key-value counts), the key-value metadata, one entry per tensor (name, dimensions, type, offset), then the tensor data, each tensor at an offset aligned to general.alignment (32 by default) from the start of the data section. The header is parsed with struct alone. A tensor of a float or integer type keeps its dtype and the role weight (float) or other; a quantized tensor is kept as uint8 with the role other, its bytes as they are, padding up to the next tensor included.

class jabara.formats.gguf.Gguf[source]

Bases: CheckpointFormat

A GGUF file (llama.cpp): the header and the metadata kept as they are, every tensor compressed.

kind: ClassVar[str] = 'gguf'

Recorded in the archive index as source["kind"]; a reader finds the format by it, so it never changes.

names: ClassVar[tuple[str, ...]] = ('*.gguf',)

fnmatch patterns of the file names this format takes when a file is named on its own.

in_directory: ClassVar[tuple[str, ...]] = ()

fnmatch patterns of the file names compress_dir takes from a checkpoint directory.

frameworks: ClassVar[tuple[tuple[str, str], ...]] = (('llama.cpp, and the tools that convert models for it', '*.gguf'),)

(framework, file names) pairs for the formats reference page.

split(path: Path) → Split[source]

Take the file at path apart. Raises ArchiveFormatError for a file this format cannot take.

join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

Write the file at out from source, remainder, and the bytes of each record in the order split returned them. exact is true when every tensor came back bit for bit, so the file must come back byte for byte; a format that can check that does. Raises ArchiveFormatError for a source it cannot use.

HDF5 files (Keras .weights.h5, legacy Keras .h5) and Keras 3 .keras files, through the optional h5py. See DESIGN.md.

h5py reports where each dataset of contiguous layout sits in the file; Jabara compresses those bytes and keeps every other byte of the file (the HDF5 metadata, small datasets that HDF5 stores inside their header) as they are. A chunked, filtered (compressed), external, or virtual dataset is refused: its bytes are not in one place. A .keras file is a zip whose members are stored as they are; its model.weights.h5 member is read the same way.

class jabara.formats.hdf5.Hdf5[source]

Bases: CheckpointFormat

An HDF5 file, such as the .weights.h5 that Keras 3 writes or a legacy Keras .h5 model.

kind: ClassVar[str] = 'hdf5'

Recorded in the archive index as source["kind"]; a reader finds the format by it, so it never changes.

names: ClassVar[tuple[str, ...]] = ('*.h5', '*.hdf5')

fnmatch patterns of the file names this format takes when a file is named on its own.

in_directory: ClassVar[tuple[str, ...]] = ()

fnmatch patterns of the file names compress_dir takes from a checkpoint directory.

frameworks: ClassVar[tuple[tuple[str, str], ...]] = (('Keras 3 (save_weights), legacy Keras, h5py', '*.weights.h5, *.h5, *.hdf5'),)

(framework, file names) pairs for the formats reference page.

split(path: Path) → Split[source]

Take the file at path apart. Raises ArchiveFormatError for a file this format cannot take.

join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

Write the file at out from source, remainder, and the bytes of each record in the order split returned them. exact is true when every tensor came back bit for bit, so the file must come back byte for byte; a format that can check that does. Raises ArchiveFormatError for a source it cannot use.

class jabara.formats.hdf5.Keras[source]

Bases: CheckpointFormat

A Keras 3 .keras file: a zip of config.json, metadata.json, and model.weights.h5, stored as they are.

kind: ClassVar[str] = 'keras'

Recorded in the archive index as source["kind"]; a reader finds the format by it, so it never changes.

names: ClassVar[tuple[str, ...]] = ('*.keras',)

fnmatch patterns of the file names this format takes when a file is named on its own.

in_directory: ClassVar[tuple[str, ...]] = ()

fnmatch patterns of the file names compress_dir takes from a checkpoint directory.

frameworks: ClassVar[tuple[tuple[str, str], ...]] = (('Keras 3 (model.save)', '*.keras'),)

(framework, file names) pairs for the formats reference page.

split(path: Path) → Split[source]

Take the file at path apart. Raises ArchiveFormatError for a file this format cannot take.

join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) → None[source]

Write the file at out from source, remainder, and the bytes of each record in the order split returned them. exact is true when every tensor came back bit for bit, so the file must come back byte for byte; a format that can check that does. Raises ArchiveFormatError for a source it cannot use.

Comparison

Comparing codec assignments on the same tensors. See DESIGN.md, "Comparison".

Every run is in memory: no file is read or written. A row's seconds are the codec's own encode and decode over the chunks, not the cost of a real save or load; BenchRow says exactly what they cover and what a real save or load adds. End-to-end save and load times belong to the experiment harness, which measures them on real files.

No memory number is reported: a tracemalloc peak counts mostly the payloads held, misses the memory native code allocates, and grows with threads, so it does not compare codecs.

The chunks of every tensor of a role are in flight together on the pool, as write_archive and a read of several tensors code them; with threads=1 nothing runs in parallel. A tensor whose codec's Codec.with_threads returns a copy (zipnn/1 does) is the exception: it is coded alone, one chunk after another with all threads threads inside each chunk, as write_archive and Archive.read run it.

jabara.bench.WARMUP_PASSES = 1

Untimed rounds that run before the timed ones. In a round, each candidate in turn encodes and then decodes once.

jabara.bench.WARMUP_BYTES = 65536

The largest slice of a tensor, in bytes, that the warm-up before the first row codes with each codec.

jabara.bench.SPIN_SECONDS = 0.1

Seconds that every thread about to code a timed pass stays busy, untimed, right before the pass. See DESIGN.md, "Comparison": on one machine a 100 ms load of all cores by threads of their own removed the effect of the other candidates of a call on the time of two codecs, and 30 ms did not. This spin narrowed the spread of a candidate measured alone there; it moved the effect of the other candidates in both directions.

class jabara.bench.CodecUse(*, codec_id: str, params: dict[str, JsonValue], tensors: int)[source]

Bases: BaseModel

A codec id and its full parameters, and how many tensors of a row it coded.

codec_id: str

The id of the codec.

params: dict[str, JsonValue]

The codec's full parameters, defaults filled in.

tensors: int

How many tensors of the row it coded.

class jabara.bench.BenchEnvironment(*, jabara: str, python: str, platform: str, machine: str, cpu_model: str | None, cpu_count: int | None, load_average_1m: float | None, threads: int, repeats: int, warmup_passes: int, spin_seconds: float, chunk_size: int, numpy: str, zstandard: str, optional_packages: dict[str, str])[source]

Bases: BaseModel

Where and how the numbers were taken. load_average_1m is read once, before the first candidate runs. cpu_model is the processor name the OS reports (None where it reports none). optional_packages holds the versions of the optional packages a codec can load (zipnn, torch) that are loaded when the run ends.

jabara: str

The version of Jabara.

python: str

The Python version, as platform.python_version() returns it.

platform: str

The string platform.platform() returns.

machine: str

The string platform.machine() returns.

cpu_model: str | None

The processor name the OS reports; None when it reports none.

cpu_count: int | None

The number of CPUs; None when unknown.

load_average_1m: float | None

The one-minute load average, read once before the first candidate runs; None where the OS has none.

threads: int

The size of the thread pool.

repeats: int

How many timed runs each row has.

warmup_passes: int

How many untimed passes ran before the timed runs.

spin_seconds: float

How long, in seconds, the threads about to code each timed pass were kept busy, untimed, right before it.

chunk_size: int

The chunk size in bytes.

numpy: str

The version of NumPy.

zstandard: str

The version of zstandard.

optional_packages: dict[str, str]

The versions of the optional packages loaded when the run ends.

class jabara.bench.BenchRow(*, candidate: str, role: str, codecs: list[CodecUse], raw_bytes: int, stored_bytes: int, encode_seconds: float, encode_seconds_all: list[float], decode_seconds: float | None, decode_seconds_all: list[float] | None, decode_error: str | None, lossless: bool, needs_base: bool, check_decode: bool, bit_exact: bool, max_abs_err: float | None, fallback_tensors: int)[source]

Bases: BaseModel

One candidate on all tensors of one role.

encode_seconds_all holds each of repeats wall-clock runs (time.perf_counter), in run order, of Codec.encode over every chunk of every tensor of the role, after warmup_passes untimed passes; encode_seconds is the smallest. The chunks run as write_archive runs them: on the container's thread pool, or one after another with the copy that Codec.with_threads returns. A run includes slicing the chunks and the base reference and handing them to the pool or the copy, and nothing else. decode_seconds_all and decode_seconds are the same for Codec.decode plus the length and CRC-32 check of each decoded chunk that Archive.read also does. When any decode pass fails that check, decode_error holds the reader's message and both decode fields are None, so a broken codec has no decode time to rank. Throughput is raw_bytes / seconds. Each timed run starts right after the pool's threads and the calling thread have run a busy loop for BenchEnvironment.spin_seconds; see DESIGN.md, "Comparison", for what that was observed to change.

These seconds are the codec's share of a save or load, not its cost. A real save (write_archive) also computes the CRC-32 of the input, decodes the whole base tensor first when needs_base, decodes every chunk once more to check it when check_decode, and writes the file. A real load (Archive.read) also decodes the whole base tensor first when needs_base, and reads the file. needs_base is true when a tensor of the row is coded with a delta codec; check_decode is true when one is coded with a lossy codec, so it is not lossless.

codecs lists each distinct codec id and full parameters (defaults filled in, as an archive index records them) that coded the role's tensors, with the number of tensors each coded. stored_bytes is the sum of chunk payload lengths from one untimed encode pass, without the archive index and magic. lossless is the codecs' own claim; bit_exact compares the decoded bytes with the input and is false when decoding failed. fallback_tensors counts the tensors for which the candidate chose a delta codec but the base had no reference, so they were coded with the choice's fallback.

candidate: str

The name of the candidate.

role: str

The role of the tensors the row covers.

codecs: list[CodecUse]

The codecs that coded the role's tensors, with how many tensors each coded.

raw_bytes: int

The tensor bytes before coding.

stored_bytes: int

The sum of the chunk payload lengths from one untimed encode pass.

encode_seconds: float

The smallest of encode_seconds_all.

encode_seconds_all: list[float]

The wall-clock seconds of each timed encode run, in run order.

decode_seconds: float | None

The smallest of decode_seconds_all; None when a decode failed.

decode_seconds_all: list[float] | None

The wall-clock seconds of each timed decode run; None when a decode failed.

decode_error: str | None

The reader's message when a decode pass failed; otherwise None.

lossless: bool

True when every codec of the row is lossless.

needs_base: bool

True when a tensor of the row is coded with a delta codec.

check_decode: bool

True when a tensor of the row is coded with a lossy codec, so the writer decodes each chunk to check it.

bit_exact: bool

Whether the decoded bytes equal the input; false when decoding failed.

max_abs_err: float | None

The largest absolute difference between the decoded values and the input, recomputed from the decoded bytes; None when a decode failed.

fallback_tensors: int

How many tensors were coded with the choice's fallback because the base had no reference.

class jabara.bench.BenchReport(*, bench: Literal[1], environment: BenchEnvironment, rows: list[BenchRow])[source]

Bases: BaseModel

The result of compare: the environment of the run and one row per candidate and role. model_dump_json() writes the file that the results viewer reads.

bench: Literal[1]

The report version, always 1.

environment: BenchEnvironment

Where and how the numbers were taken.

rows: list[BenchRow]

One row per candidate and role.

jabara.bench.candidates_for(names: Sequence[str] | None = None, *, with_base: bool = False) → dict[str, Assigner][source]

Candidates keyed by codec id, each applied to float tensors with UniformAssigner.

Without names, every registered lossless codec that needs no base, plus the delta codecs if with_base, except a codec whose optional package is missing (its encode of one float32 value raises MissingDependencyError): that one is skipped with a UserWarning naming it. Named codecs are used as given, lossy ones included, and a missing package raises when compare runs them. A delta codec stores a tensor the base lacks with bytegroup-zstd/1.

jabara.bench.compare(tensors: Sequence[TensorRecord], candidates: Mapping[str, Assigner], *, base: Sequence[TensorRecord] | None = None, threads: int | None = None, repeats: int = 1) → BenchReport[source]

Encode and decode tensors in memory with every candidate, one row per candidate and role.

Chunking, the thread pool, the delta reference slicing, and the decode checks are the container's own functions (encode_chunks, seal_chunks, decode_chunks), so a row measures what write_archive and Archive.read ask of the codec, without the file. See BenchRow for what the seconds include and exclude, and BenchEnvironment for what is recorded about the run. Before timing, each row does WARMUP_PASSES untimed passes, and the timed passes run round-robin across the candidates of a role. Right before each timed encode and decode, the pool's threads and the calling thread spin for SPIN_SECONDS, untimed. bit_exact and max_abs_err are recomputed from the decoded bytes, never taken from a codec's claim. Lossy candidates run without any opt-in; base holds the tensors that delta candidates refer to, and a delta tensor with no match in it uses the choice's fallback or raises MissingBaseError. A candidate that chose a delta codec for some tensors but found a reference for none of them raises MissingBaseError instead of reporting rows that measure only its fallback.

Command line

Command-line interface built with typed-argument-parser. See DESIGN.md, "CLI".

jabara.cli.main(argv: list[str] | None = None) → None[source]

Run the jabara command with argv, or with sys.argv when argv is None.

The whole argument list is parsed and checked before a command runs, so a usage error (exit 2) or a help request (exit 0) changes nothing. A JabaraError, OSError, or ValueError from a command prints one line to standard error and exits with status 1.

class jabara.cli.Listing(*, path: str, tensors: list[TensorStats])[source]

Bases: BaseModel

One archive and the stats of its tensors. jabara ls --json prints a list of these.

path: str

The path of the archive.

tensors: list[TensorStats]

The stats of each tensor.

Hugging Face Trainer

Compress the checkpoints of one Hugging Face Trainer instance. See DESIGN.md, "Adapters".

This adapter relies on private Trainer methods that transformers does not keep stable: _save_checkpoint, _load_from_checkpoint, _load_optimizer_and_scheduler, and _load_best_model, and on the checkpoint file names model*.safetensors, pytorch_model*.bin, and optimizer.pt. The tests cover transformers 5.20.2 (Python 3.10) and 5.24.1; pyproject.toml allows >=5.0, so other releases are untested. A transformers release that renames one of these methods or changes its signature breaks attach.

An interrupted save (an Exception, KeyboardInterrupt, or SystemExit raised after the Trainer has written the checkpoint) leaves every *.safetensors file and optimizer.pt as its original, as its original beside a verified archive, or as that archive alone, with no temporary file:

  • Interrupted while the archives are written: the archives this save wrote are removed and every original is there, so the plain Trainer loads the checkpoint. An older save's archive beside an original may stay.

  • Interrupted once all are written, while the originals are deleted: some files exist only as archives, and the checkpoint needs Jabara.

A resume with Jabara attached reads each state as the Trainer saved it, using an original where there is one, and leaves the directory as it found it, even when the resume itself is interrupted (DESIGN.md lists what a hard crash leaves). It never deletes an original beside its archive, so such an original stays until the Trainer saves that step again, which leaves the checkpoint compressed, or deletes it as an old checkpoint.

jabara.hf.check_arguments(args: TrainingArguments, *, threads: int | None = None) → None[source]

Raise ValueError for the settings attach refuses that TrainingArguments and threads already show.

Call it before building the Trainer: Trainer(...) creates the Hub repository for push_to_hub before attach can refuse the hub_strategy. attach repeats these checks, and also refuses DeepSpeed and FSDP, which only the built Trainer reports.

jabara.hf.attach(trainer: Trainer, *, threads: int | None = None, assign: Assigner | None = None, allow_lossy: bool = False, delta: Literal['first'] | None = None) → None[source]

Compress every checkpoint trainer saves, and restore it for resume and load_best_model_at_end.

Compression runs synchronously at the end of each save. Attaching again replaces the earlier settings. Raises ValueError, before changing anything, for threads below 1, a Hub upload strategy that uploads checkpoint folders, more than one process, DeepSpeed, or FSDP.

With delta="first" each checkpoint but the first is saved as a delta against the oldest earlier checkpoint that is fully compressed with full archives, and save_total_limit rotation keeps that base. Refused with save_total_limit=1, and for any other value.

jabara.hf.detach(trainer: Trainer) → None[source]

Undo attach. Checkpoints already compressed stay compressed and need Jabara to resume.

PyTorch Lightning

PyTorch Lightning CheckpointIO that stores checkpoints as Jabara archives. See DESIGN.md, "Adapters".

class jabara.lightning.JabaraCheckpointIO(*, threads: int | None = None, assign: Assigner | None = None, delta: str | None = None)[source]

Bases: CheckpointIO

Lossless: load_checkpoint returns the dict save_checkpoint received, tensors bit for bit.

Every OrderedDict that carries _metadata, wherever it sits in the checkpoint (the module state_dict, the averaged model of StochasticWeightAveraging), comes back with it, as save_state keeps it; other values must be tensors, plain JSON values, or dicts, lists, and tuples of them, or saving raises UnsupportedStateError.

save_checkpoint(checkpoint: dict[str, Any], path: str | PathLike[str], storage_options: object = None) → None[source]

Write checkpoint to path as an archive, creating parent directories. Raises ValueError for a URL path, TypeError if storage_options is given, UnsupportedStateError for a value Jabara cannot store, and LossyNotAllowedError if assign picks a lossy codec.

load_checkpoint(path: str | PathLike[str], map_location: object = None, weights_only: bool | None = None) → dict[str, Any][source]

Return the checkpoint dict that was saved at path, with tensors on map_location (CPU if None). weights_only is ignored. Raises ValueError if map_location is not None, a str, or a torch.device, or names the meta device.

remove_checkpoint(path: str | PathLike[str]) → None[source]

Delete the file at path if it exists.

Errors

Exceptions raised by Jabara.

exception jabara.errors.JabaraError[source]

Bases: Exception

Base class for every error Jabara raises.

exception jabara.errors.ArchiveFormatError[source]

Bases: JabaraError

The file is not a Jabara archive this version can read.

exception jabara.errors.ChecksumError[source]

Bases: JabaraError

A decoded chunk does not match its recorded checksum.

exception jabara.errors.UnknownCodecError[source]

Bases: JabaraError

An archive or an assigner names a codec that is not registered.

exception jabara.errors.UnsupportedStateError[source]

Bases: JabaraError

A nested state holds a value Jabara cannot store without pickle.

exception jabara.errors.MissingBaseError[source]

Bases: JabaraError

A delta codec needs a base tensor, but no base was supplied or the base has no matching tensor.

exception jabara.errors.BaseMismatchError[source]

Bases: JabaraError

The supplied base archive is not the one a delta archive was written against.

exception jabara.errors.LossyNotAllowedError[source]

Bases: JabaraError

The assigner chose a lossy codec but the caller did not opt in with allow_lossy.

exception jabara.errors.UnsupportedDtypeError[source]

Bases: JabaraError

A codec cannot handle the tensor's dtype.

exception jabara.errors.MissingDependencyError[source]

Bases: JabaraError

A codec needs an optional package that is not installed.

exception jabara.errors.NonFiniteError[source]

Bases: JabaraError

A lossy codec was given NaN or an infinity, or a range it cannot represent.

exception jabara.errors.RolesUnknownWarning[source]

Bases: UserWarning

A checkpoint file was compressed without the names and roles of its tensors, which only loading it gives.