Python API¶
このページは、src/jabara の docstring とシグネチャから生成している。モジュールは、コアの型からアダプタの順に並ぶ。
型¶
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
DefaultAssignersends tobytegroup-zstd/1and the quantizers accept.
- class jabara.types.TensorMeta(*, name: str, dtype: str, shape: tuple[Annotated[int, Ge(ge=0)], ...], role: str = 'other')[ソース]¶
ベースクラス:
BaseModelThe name, dtype, shape, and role of a tensor.
dtypemust be a name inDTYPE_ITEMSIZE, andshapeholds 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
weightoradam_m;otherwhen 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])[ソース]¶
ベースクラス:
objectA tensor as raw little-endian bytes (
data) with itsmeta.len(data)equalsmeta.nbytes.datais 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.
コーデック¶
The codec interface. See DESIGN.md, "Codec interface".
- class jabara.codecs.base.NoParams[ソース]¶
ベースクラス:
BaseModelThe 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)[ソース]¶
ベースクラス:
BaseModelA 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)[ソース]¶
ベースクラス:
BaseModelA work a codec builds on, and how.
jabara codecsand 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.
- class jabara.codecs.base.Codec(params: BaseModel | None = None)[ソース]¶
ベースクラス:
ABCBase class of every codec. A subclass sets
idandlossless, optionallyneeds_ref,Params,dtypes,extraandreferences, and implementsencodeanddecodefor one chunk of one tensor. A codec with threads of its own also overrideswith_threads. The first sentence of the class docstring is the codec's one-line description injabara 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))returnsxbyte for byte for every chunk.
- needs_ref: ClassVar[bool] = False¶
True for a delta codec:
encodeanddecodethen receive the same chunk of the base tensor asref.
- Params¶
The pydantic model of the codec's parameters (frozen,
extra="forbid").NoParamsfor a codec without any.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[ソース]¶
Return the encoded bytes of one chunk.
refis the same chunk of the base tensor; only a codec withneeds_refreads it.
- abstractmethod decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) bytes | bytearray | memoryview[ソース]¶
Return the
raw_lengthbytes that were encoded, asbytes, as a newbytearray, or as a memoryview of unsigned bytes (formatB, one contiguous dimension) over a new buffer, which the caller then owns. A codec whose library returns abytearray, or that builds its output in a NumPy array, needs no copy. The container checks the type where it takes the result and raisesTypeErrornaming 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[ソース]¶
Return a copy of this codec that codes one chunk with at most
threadsthreads 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 sameidandparams(the container raisesTypeErrorotherwise), 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 onthreads. 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[ソース]¶
Class decorator that registers a codec under its
id. RaisesValueErrorif the id is already registered.
- jabara.codecs.registry.get_codec(codec_id: str, params: Mapping[str, JsonValue] | None = None) Codec[ソース]¶
Return a codec instance for
codec_id, configured withparams, a JSON object that the codec'sParamsmodel checks. RaisesUnknownCodecErrorfor an unknown id andpydantic.ValidationErrorfor invalid parameters.
Built-in lossless codecs: raw/1, zstd/1, and bytegroup-zstd/1.
- class jabara.codecs.builtin.RawCodec(params: BaseModel | None = None)[ソース]¶
ベースクラス:
CodecStores 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))returnsxbyte for byte for every chunk.
- encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) bytes[ソース]¶
Return a copy of the chunk.
- decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) bytes[ソース]¶
Return a copy of the payload. Raises
ValueErrorif its length is notraw_length.
- class jabara.codecs.builtin.ZstdCodec(params: BaseModel | None = None)[ソース]¶
ベースクラス:
CodecCompresses 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))returnsxbyte 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)[ソース]¶
ベースクラス:
BaseModellevelis the Zstandard compression level.- level: int¶
- encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) bytes[ソース]¶
Return the chunk compressed with Zstandard.
- decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) bytes[ソース]¶
Return the decompressed chunk. Raises
ValueErrorif the frame declares more thanraw_lengthbytes or its size is notraw_length.
- class jabara.codecs.builtin.ByteGroupZstdCodec(params: BaseModel | None = None)[ソース]¶
ベースクラス:
CodecSplits 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))returnsxbyte 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)[ソース]¶
ベースクラス:
BaseModellevelis the Zstandard compression level of every plane.- level: int¶
- encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) bytes[ソース]¶
Return the plane lengths followed by the compressed planes. Raises
ValueErrorif the chunk is not a multiple of the item size.
- decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) bytes | memoryview[ソース]¶
Rebuild the chunk from its planes, as a memoryview of a new array. Raises
ValueErrorfor 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] = {})[ソース]¶
ベースクラス:
BaseModelinneris the id of the lossless codec that codes the difference, andinner_paramsare 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)[ソース]¶
ベースクラス:
_DeltaCodecCodes 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)[ソース]¶
ベースクラス:
_DeltaCodecCodes the wrap-around difference of the chunk and the base chunk, read as unsigned integers of the item size, with the inner codec.
complex128raisesUnsupportedDtypeError.- 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][ソース]¶
Widen little-endian float bytes to float64; bfloat16 goes through its float32 bit pattern.
- class jabara.codecs.quant.QuantParams(*, level: int = 3)[ソース]¶
ベースクラス:
BaseModellevelis 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)[ソース]¶
ベースクラス:
_Quant88-bit codes for 255 equal steps from the chunk minimum to its maximum.
Code
cstands forlo + c * scale.Per chunk,
scale = (max - min) / 255(the exact quotient). Withtinythe smallest positive subnormal of the dtype,abs(x - x_hat) <= m * scale / 2 + 2**-48 * max(abs(x)) + tiny, wheremis 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.0included.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.0if the chunk holds a-0.0, else to+0.0, so a chunk that mixes0.0and-0.0decodes all its zeros to-0.0. When the minimum is negative, a zero decodes to+0.0or to a nonzero value within the bound, so no zero decodes to-0.0.Payload: the table size in bytes (uint16), the table (entry
cislo + c * scalekept inside[min, max]and rounded to the dtype, forcup 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[ソース]¶
Return the table followed by the Zstandard-compressed codes. Raises
UnsupportedDtypeErrorfor a dtype that is not a float, andNonFiniteErrorfor NaN, an infinity, or a range that overflows float64.
- decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) memoryview[ソース]¶
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)[ソース]¶
ベースクラス:
_Quant8Logarithmic 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, withstep = (ln(max) - ln(min)) / 254; codecstands forexp(ln_min + (c - 1) * step). Withstepthe exact quotient andmandtinyas 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[ソース]¶
Return the table, the sign plane, and the Zstandard-compressed codes. Raises
UnsupportedDtypeErrorfor a dtype that is not a float, andNonFiniteErrorfor NaN, an infinity, or a range that overflows float64.
- decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) memoryview[ソース]¶
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)[ソース]¶
ベースクラス:
CodecThe zipnn package, with Zstandard as its entropy coder.
Lossless. Handles float16, bfloat16, and float32. Any other dtype raises
UnsupportedDtypeError.The third-party
zipnnpackage is imported on first use. It imports torch, so the first call loads torch into the process. This import hides theFutureWarningabouttorch.jit.scriptthat torch issues.zipnnholds 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_threadshands it the caller's thread budget instead; the bytes it writes are the same for every thread count. An instance fromget_codecuses 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))returnsxbyte 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[ソース]¶
Return a copy that runs each
zipnncall onthreadsthreads.
- encode(data: memoryview, meta: TensorMeta, ref: memoryview | None = None) bytes[ソース]¶
Return the chunk compressed with
zipnn. RaisesUnsupportedDtypeErrorfor a dtype other than float16, bfloat16, and float32, andMissingDependencyErrorif thezipnnpackage is not installed.
- decode(payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) bytes | bytearray[ソース]¶
Return the chunk decompressed with
zipnn. Raises the same errors asencode.
割り当て¶
Choosing a codec per tensor. See DESIGN.md, "Assignment".
- class jabara.assign.CodecChoice(*, codec_id: str, params: dict[str, JsonValue] = {}, fallback: CodecChoice | None = None)[ソース]¶
ベースクラス:
BaseModelA codec id with its parameters.
paramsis checked against the codec'sParamsmodel.fallbackis 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[ソース]¶
ベースクラス:
ABCPicks the codec for each tensor. Subclass it and implement
choose.- abstractmethod choose(meta: TensorMeta) CodecChoice[ソース]¶
Return the
CodecChoicefor the tensor thatmetadescribes.
- class jabara.assign.DefaultAssigner[ソース]¶
ベースクラス:
Assignerbytegroup-zstd/1for float dtypes andzstd/1for everything else.- choose(meta: TensorMeta) CodecChoice[ソース]¶
Return the default choice for the dtype of
meta.
- class jabara.assign.UniformAssigner(choice: CodecChoice)[ソース]¶
ベースクラス:
AssignerApplies one choice to float tensors and the default choice to every other tensor.
- choose(meta: TensorMeta) CodecChoice[ソース]¶
Return
choicefor a float tensor and the default choice otherwise.
- class jabara.assign.RoleAssigner(by_role: Mapping[str, CodecChoice], default: Assigner | None = None)[ソース]¶
ベースクラス:
AssignerPicks a choice by tensor role. A role that
by_roledoes not list goes todefault, which isDefaultAssigner()when omitted.- choose(meta: TensorMeta) CodecChoice[ソース]¶
Return the choice for the role of
meta, or the default's choice if the role is not listed.
役割¶
State schemas: set the role of each tensor from its path in the nested state. See DESIGN.md.
- class jabara.schemas.StateSchema[ソース]¶
ベースクラス:
ABCSets the role of each tensor from its path in the nested state. Subclass it and implement
role.
- class jabara.schemas.OptimizerSchema[ソース]¶
ベースクラス:
StateSchemaRoles by the last path element:
exp_avgisadam_m,exp_avg_sqisadam_v,max_exp_avg_sqisadam_vmax,momentum_bufferismomentum,stepisstep, and anything else isother.- 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'}¶
- class jabara.schemas.MuonSchema[ソース]¶
ベースクラス:
OptimizerSchemaLike
OptimizerSchema, butmomentum_bufferismuon_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[ソース]¶
ベースクラス:
StateSchemaGives every tensor the role
weight.
アーカイブ¶
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_sizeofwrite_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)[ソース]¶
ベースクラス:
BaseModelWhat
write_archivereturns: 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)[ソース]¶
ベースクラス:
BaseModelThe codec and sizes of one tensor, read from the index.
max_abs_erris 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;
Nonefor 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)])[ソース]¶
ベースクラス:
BaseModelThe index entry of one chunk: its offset, its stored length, its raw length (1 to
MAX_CHUNK_SIZEbytes), 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])[ソース]¶
ベースクラス:
TensorMetaThe 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 arenbytes.- 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;
Nonefor a lossless tensor.
- chunks: list[ChunkEntry]¶
The tensor's chunks, in order.
- class jabara.container.BaseRef(*, name: str, index_crc: int)[ソース]¶
ベースクラス:
BaseModelNames 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)[ソース]¶
ベースクラス:
BaseModelThe 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
baselists 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_statesaved; 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.
- jabara.container.encode_chunks(codec: Codec, meta: TensorMeta, data: memoryview, lengths: Sequence[int], ref_all: memoryview | None, pool: ThreadPoolExecutor | None) list[bytes][ソース]¶
Encode each chunk of one tensor with
codec;ref_allis 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]][ソース]¶
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][ソース]¶
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[ソース]¶
Whether the base tensor
baseis the delta reference ofmeta: 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, andjabara.benchall 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[ソース]¶
Write
tensorsto an archive atpathand return its sizes. Each tensor is coded chunk by chunk with the codec thatassignpicks,DefaultAssignerif None.tensorsmay be lazy: withthreadsabove 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 topath, synced to stable storage, and renamed at the end. RaisesLossyNotAllowedErrorfor a lossy codec unlessallow_lossy,MissingBaseErrorfor a delta tensor with no base match and no fallback,BaseMismatchErrorif a base is a delta archive opened without its own base, andValueErrorfor apaththat is a base archive itself, a duplicate tensor name, a wrong data length, a lossy decode of the wrong length, amax_abs_errthat is not finite, askeletonorsourcethat would not read back,threadsbelow 1, orchunk_sizeaboveMAX_CHUNK_SIZE.
- class jabara.container.Archive(path: str, f: BinaryIO, index: ArchiveIndex, index_crc: int, bases: list[Archive])[ソース]¶
ベースクラス:
objectA reader for one archive, usable as a context manager. Build it with
Archive.open.baseis the open full archive that a delta archive was written against, or the several that a format 2 archive names.pathis the path it was opened with,indexthe validatedArchiveIndex,index_crcthe CRC-32 of the index bytes (what a delta archive records of its base), andindex_by_namemaps each tensor name to itsTensorEntry.- index_by_name: dict[str, TensorEntry]¶
- classmethod open(path: str | PathLike[str], *, base: Archive | Sequence[Archive] | None = None) Archive[ソース]¶
Open the archive at
path. RaisesArchiveFormatErrorfor a file that is not a readable archive, including an index that contradicts itself or the file (seeChunkEntry,TensorEntry, and the unique names ofArchiveIndex) or a chunk outside the data area or overlapping another, andBaseMismatchErrorwhenbaseis 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.basemay hold more archives than the index names.
- meta(name: str) TensorMeta[ソース]¶
Return the
TensorMetaofname. RaisesKeyErrorif there is no such tensor.
- chunk_lengths(name: str) list[int][ソース]¶
Return the raw length of each chunk of
name. RaisesKeyErrorif there is no such tensor.
- read(name: str, *, threads: int | None = None) bytes[ソース]¶
Return the raw little-endian bytes of
name, checked against the chunk checksums. RaisesChecksumErroron a mismatch,MissingBaseErrorfor a delta tensor when no base was given,BaseMismatchErrorwhen the base lacks a tensor of the same name, dtype, and shape, andKeyErrorfor an unknown name.
- verify(*, threads: int | None = None) None[ソース]¶
Decode every tensor and check every checksum. Raises the first error that
readwould raise.
- stats() list[TensorStats][ソース]¶
Return the codec and sizes of every tensor.
入れ子の状態¶
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]]][ソース]¶
Split a nested state into a JSON skeleton and its tensors. A leaf for which
is_tensoris true becomes{"$t": name}, with the path joined by/as its name, or{"$t": [name, attrs]}whenattrsgives it a non-empty dict of JSON attributes (whatunflatten'srebuildneeds besides the bytes). The_metadataattribute of anOrderedDict(a modulestate_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. RaisesUnsupportedStateErrorfor 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[ソース]¶
Rebuild the nested state from a skeleton and a mapping of tensors by name. A tensor stored with attributes becomes
rebuild(tensor, attrs), and anOrderedDictstored with$metadatagets it back as_metadata. RaisesArchiveFormatError, naming the path in the skeleton, for a malformed skeleton, a tensor missing fromtensorsor inside$metadata, or attributes with norebuild.
torch の状態¶
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][ソース]¶
The tensor leaves of a nested state as records, named and given roles the way
save_statedoes.
- 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[ソース]¶
Write a nested state of tensors and plain values to an archive at
path, with roles fromschema(OptimizerSchemaif None). Annn.Parameterleaf and a tensor'srequires_gradare kept in the skeleton. Returns theArchiveInfo. RaisesUnsupportedStateErrorfor a value that cannot be stored without pickle (a tensor subclass included) and for a sparse or meta tensor,UnsupportedDtypeErrorfor a dtype that Jabara does not support, and the errors ofwrite_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[ソース]¶
Read an archive that
save_statewrote, or thatcompress_filewrote from a torch file, and return the same nested state, with every tensor on the devicemap_locationnames (None is CPU),nn.Parameterleaves asnn.Parameter,requires_gradas saved, and everyOrderedDictwith the_metadatait had (a modulestate_dictloads with its module versions). A delta archive needsbase, the open archive it was written against. An archive of a torch file is restored to a temporary file and read withtorch.load(weights_only=True), which refuses a file that holds other objects than tensors and plain values. RaisesValueErrorfor amap_locationthat is not None, astr, or atorch.device, or that names the meta device, before the archive is opened, andArchiveFormatErrorfor an archive of anything else.
ファイルとディレクトリ¶
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]][ソース]¶
The base archives
basenames, open: none for None, the archive itself for a file, and every*.jbrfile 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.BaseMismatchErrornames 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[ソース]¶
The format of
src, a filecompress_filetakes. RaisesFileNotFoundErrororValueErrorotherwise.
- 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[ソース]¶
Compress one file next to itself. With
base, an archive of an earlier checkpoint or a directory of such archives, float tensors are stored asxor-delta/1against the tensor of the same name, dtype, and shape in them unlessassignsays 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[ソース]¶
Write the file that
archive, an open archive of a file in a registered format, was made from, atout. RaisesArchiveFormatErrorfor 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[ソース]¶
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][ソース]¶
The files
compress_dirtakes from the directorypath, 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.ckptthat the Lightning plugin writes.
- jabara.files.checkpoint_dirs(path: str | PathLike[str]) list[Path][ソース]¶
The checkpoint directories of the parent
path: its immediate subdirectories that hold a filecompress_dirtakes or a*.jbrarchive, in natural order of name, thenpathitself last if it holds such a file. A Hugging Faceoutput_dirkeeps the final model beside itscheckpoint-*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. RaisesFileNotFoundErrororNotADirectoryErrorfor apaththat is no directory.
- jabara.files.dependants(directory: Path, archives: Sequence[Path]) list[Path][ソース]¶
The delta archives that cannot be read once
archives, which are indirectory, are gone: those written against one of them, among the archives ofdirectory, of the other subdirectories of its parent, and of the parent. Bases match by index CRC-32 alone, asArchive.openmatches (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[ソース]¶
Raise
ValueErrorwhen deletingarchives, whichdecompressdoes 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])[ソース]¶
ベースクラス:
objectThe indexes of the archives in the checkpoint directories
dirsof 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.
- sizes(directory: Path) tuple[int, int][ソース]¶
The raw and the stored tensor bytes of the readable archives in
directory.
- resolve(archive: Path) tuple[list[Path], list[BaseRef]][ソース]¶
The archives of the other directories that
archiveis written against, and the recorded bases that none holds.
- chain(archive: Path) tuple[list[Path], tuple[Path, BaseRef] | None][ソース]¶
The archives that
archiveneeds, 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][ソース]¶
The base archives that the archives of
directoryneed, 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.ValueErrorfor a base that is missing, naming the archive written against it.
- 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][ソース]¶
Compress each file in the directory that a format takes there (
*.safetensors,optimizer.pt, and the others thatjabara.formatslists), in name order, and return oneArchiveInfoper file. Other files stay. Withbase, the directory of an earlier compressed checkpoint (or one archive of it), each file is delta-coded ascompress_filecodes 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][ソース]¶
Restore every
*.jbrfile in the directory, in name order, and return the restored paths. Delta archives needbase, asdecompress_filedoes.All or nothing, as
compress_dir: every file is restored and checked first, and the archives are deleted (unlesskeep) 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[ソース]¶
Write the tensors with role "weight" as a safetensors file.
- jabara.files.load_records(path: str | PathLike[str], *, threads: int | None = None) list[TensorRecord][ソース]¶
The tensors of an archive, a safetensors file, a torch file, or a checkpoint directory, as raw records.
A directory yields the files
compresswould 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.jbrasmodel.safetensors), so names match between a compressed and an uncompressed checkpoint directory. A directory that holds both a file and its archive raisesValueError.
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'')[ソース]¶
ベースクラス:
NamedTupleA checkpoint file taken apart: its tensors, and what restores the file around them.
- records: list[TensorRecord]¶
The tensors, in the order
jointakes their bytes back.
- source: dict[str, JsonValue]¶
What
joinneeds besides the bytes, as JSON. The archive index stores it withkind.
- 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
uint8and roleother, so a codec compresses them too.
- class jabara.formats.base.CheckpointFormat[ソース]¶
ベースクラス:
ABCBase class of every checkpoint file format. A subclass sets
kind,names,in_directory, andframeworks, implementssplitandjoin, and is registered with@register_format.join(split(path))must rebuild the file byte for byte when the tensors come back bit for bit.splitonly 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, ...]]¶
fnmatchpatterns of the file names this format takes when a file is named on its own.
- in_directory: ClassVar[tuple[str, ...]]¶
fnmatchpatterns of the file namescompress_dirtakes from a checkpoint directory.
- frameworks: ClassVar[tuple[tuple[str, str], ...]]¶
(framework, file names) pairs for the formats reference page.
- abstractmethod split(path: Path) Split[ソース]¶
Take the file at
pathapart. RaisesArchiveFormatErrorfor a file this format cannot take.
- abstractmethod join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) None[ソース]¶
Write the file at
outfromsource,remainder, and the bytes of each record in the ordersplitreturned them.exactis 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. RaisesArchiveFormatErrorfor asourceit 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[ソース]¶
Class decorator that registers a format under its
kind. RaisesValueErrorif the kind is already registered or a file-name pattern is taken by a format registered earlier.
- jabara.formats.registry.formats() list[CheckpointFormat][ソース]¶
The registered formats, in the order they were registered.
- jabara.formats.registry.format_of_file(path: Path) CheckpointFormat[ソース]¶
The format that takes a file of this name on its own. Raises
ValueErrornaming the patterns otherwise.
- jabara.formats.registry.format_in_directory(path: Path) CheckpointFormat | None[ソース]¶
The format that
compress_dirtakes a file of this name with, or None to leave the file alone.
- jabara.formats.registry.format_of_kind(kind: object) CheckpointFormat | None[ソース]¶
The format whose archives record this source kind, or None.
- jabara.formats.registry.directory_patterns() list[str][ソース]¶
Every pattern
compress_dirtakes, 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]][ソース]¶
Return the header bytes of a safetensors file and its tensors in file order, backed by a memory map. Raises
ArchiveFormatErrorif 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[ソース]¶
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. RaisesValueErrorif the tensor bytes do not add up to the header's offsets.
- class jabara.formats.safetensors.Safetensors[ソース]¶
ベースクラス:
CheckpointFormatA 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',)¶
fnmatchpatterns of the file names this format takes when a file is named on its own.
- in_directory: ClassVar[tuple[str, ...]] = ('*.safetensors',)¶
fnmatchpatterns of the file namescompress_dirtakes 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[ソース]¶
Take the file at
pathapart. RaisesArchiveFormatErrorfor a file this format cannot take.
- join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) None[ソース]¶
Write the file at
outfromsource,remainder, and the bytes of each record in the ordersplitreturned them.exactis 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. RaisesArchiveFormatErrorfor asourceit 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[ソース]¶
ベースクラス:
CheckpointFormatA file
torch.savewrote 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')¶
fnmatchpatterns 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')¶
fnmatchpatterns of the file namescompress_dirtakes 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[ソース]¶
Take the file at
pathapart. RaisesArchiveFormatErrorfor a file this format cannot take.
- join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) None[ソース]¶
Write the file at
outfromsource,remainder, and the bytes of each record in the ordersplitreturned them.exactis 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. RaisesArchiveFormatErrorfor asourceit 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, ...] = ())[ソース]¶
ベースクラス:
NamedTupleWhere 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, ...])[ソース]¶
ベースクラス:
NamedTupleA 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)]]]] = [])[ソース]¶
ベースクラス:
BaseModelWhat
joinreads 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[ソース]¶
The file mapped read-only.
ArchiveFormatErrorfor 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][ソース]¶
The records, the
source, and the remainder for tensors atspans.ArchiveFormatErrorfor 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[ソース]¶
Write the file at
outfrom whatcutreturned. Withexact, 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[ソース]¶
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[ソース]¶
The array of the
.npybytesraw[start:end], namedname: roleweightfor a float array, anduint8with roleotherfor a dtype Jabara does not carry (its bytes are kept as they are).
- class jabara.formats.npy.Npy[ソース]¶
ベースクラス:
CheckpointFormatA NumPy
.npyfile: 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',)¶
fnmatchpatterns of the file names this format takes when a file is named on its own.
- in_directory: ClassVar[tuple[str, ...]] = ()¶
fnmatchpatterns of the file namescompress_dirtakes 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[ソース]¶
Take the file at
pathapart. RaisesArchiveFormatErrorfor a file this format cannot take.
- join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) None[ソース]¶
Write the file at
outfromsource,remainder, and the bytes of each record in the ordersplitreturned them.exactis 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. RaisesArchiveFormatErrorfor asourceit cannot use.
- class jabara.formats.npy.Npz[ソース]¶
ベースクラス:
CheckpointFormatA NumPy
.npzfile fromnp.savez: a zip of.npymembers, 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',)¶
fnmatchpatterns of the file names this format takes when a file is named on its own.
- in_directory: ClassVar[tuple[str, ...]] = ()¶
fnmatchpatterns of the file namescompress_dirtakes 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[ソース]¶
Take the file at
pathapart. RaisesArchiveFormatErrorfor a file this format cannot take.
- join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) None[ソース]¶
Write the file at
outfromsource,remainder, and the bytes of each record in the ordersplitreturned them.exactis 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. RaisesArchiveFormatErrorfor asourceit 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[ソース]¶
ベースクラス:
CheckpointFormatA 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',)¶
fnmatchpatterns of the file names this format takes when a file is named on its own.
- in_directory: ClassVar[tuple[str, ...]] = ()¶
fnmatchpatterns of the file namescompress_dirtakes 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[ソース]¶
Take the file at
pathapart. RaisesArchiveFormatErrorfor a file this format cannot take.
- join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) None[ソース]¶
Write the file at
outfromsource,remainder, and the bytes of each record in the ordersplitreturned them.exactis 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. RaisesArchiveFormatErrorfor asourceit 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[ソース]¶
ベースクラス:
CheckpointFormatAn HDF5 file, such as the
.weights.h5that Keras 3 writes or a legacy Keras.h5model.- 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')¶
fnmatchpatterns of the file names this format takes when a file is named on its own.
- in_directory: ClassVar[tuple[str, ...]] = ()¶
fnmatchpatterns of the file namescompress_dirtakes 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[ソース]¶
Take the file at
pathapart. RaisesArchiveFormatErrorfor a file this format cannot take.
- join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) None[ソース]¶
Write the file at
outfromsource,remainder, and the bytes of each record in the ordersplitreturned them.exactis 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. RaisesArchiveFormatErrorfor asourceit cannot use.
- class jabara.formats.hdf5.Keras[ソース]¶
ベースクラス:
CheckpointFormatA Keras 3
.kerasfile: a zip ofconfig.json,metadata.json, andmodel.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',)¶
fnmatchpatterns of the file names this format takes when a file is named on its own.
- in_directory: ClassVar[tuple[str, ...]] = ()¶
fnmatchpatterns of the file namescompress_dirtakes 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[ソース]¶
Take the file at
pathapart. RaisesArchiveFormatErrorfor a file this format cannot take.
- join(source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool) None[ソース]¶
Write the file at
outfromsource,remainder, and the bytes of each record in the ordersplitreturned them.exactis 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. RaisesArchiveFormatErrorfor asourceit cannot use.
比較¶
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)[ソース]¶
ベースクラス:
BaseModelA 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])[ソース]¶
ベースクラス:
BaseModelWhere and how the numbers were taken.
load_average_1mis read once, before the first candidate runs.cpu_modelis the processor name the OS reports (Nonewhere it reports none).optional_packagesholds 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;
Nonewhen it reports none.
- cpu_count: int | None¶
The number of CPUs;
Nonewhen unknown.
- load_average_1m: float | None¶
The one-minute load average, read once before the first candidate runs;
Nonewhere 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)[ソース]¶
ベースクラス:
BaseModelOne candidate on all tensors of one role.
encode_seconds_allholds each ofrepeatswall-clock runs (time.perf_counter), in run order, ofCodec.encodeover every chunk of every tensor of the role, afterwarmup_passesuntimed passes;encode_secondsis the smallest. The chunks run aswrite_archiveruns them: on the container's thread pool, or one after another with the copy thatCodec.with_threadsreturns. A run includes slicing the chunks and the base reference and handing them to the pool or the copy, and nothing else.decode_seconds_allanddecode_secondsare the same forCodec.decodeplus the length and CRC-32 check of each decoded chunk thatArchive.readalso does. When any decode pass fails that check,decode_errorholds the reader's message and both decode fields areNone, so a broken codec has no decode time to rank. Throughput israw_bytes / seconds. Each timed run starts right after the pool's threads and the calling thread have run a busy loop forBenchEnvironment.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 whenneeds_base, decodes every chunk once more to check it whencheck_decode, and writes the file. A real load (Archive.read) also decodes the whole base tensor first whenneeds_base, and reads the file.needs_baseis true when a tensor of the row is coded with a delta codec;check_decodeis true when one is coded with a lossy codec, so it isnot lossless.codecslists 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_bytesis the sum of chunk payload lengths from one untimed encode pass, without the archive index and magic.losslessis the codecs' own claim;bit_exactcompares the decoded bytes with the input and is false when decoding failed.fallback_tensorscounts the tensors for which the candidate chose a delta codec but the base had no reference, so they were coded with the choice'sfallback.- candidate: str¶
The name of the candidate.
- role: str¶
The role of the tensors the row covers.
- 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;Nonewhen a decode failed.
- decode_seconds_all: list[float] | None¶
The wall-clock seconds of each timed decode run;
Nonewhen 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;
Nonewhen a decode failed.
- fallback_tensors: int¶
How many tensors were coded with the choice's
fallbackbecause the base had no reference.
- class jabara.bench.BenchReport(*, bench: Literal[1], environment: BenchEnvironment, rows: list[BenchRow])[ソース]¶
ベースクラス:
BaseModelThe 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.
- jabara.bench.candidates_for(names: Sequence[str] | None = None, *, with_base: bool = False) dict[str, Assigner][ソース]¶
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 ifwith_base, except a codec whose optional package is missing (its encode of one float32 value raisesMissingDependencyError): that one is skipped with aUserWarningnaming it. Named codecs are used as given, lossy ones included, and a missing package raises whencompareruns them. A delta codec stores a tensor the base lacks withbytegroup-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[ソース]¶
Encode and decode
tensorsin 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 whatwrite_archiveandArchive.readask of the codec, without the file. SeeBenchRowfor what the seconds include and exclude, andBenchEnvironmentfor what is recorded about the run. Before timing, each row doesWARMUP_PASSESuntimed 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 forSPIN_SECONDS, untimed.bit_exactandmax_abs_errare recomputed from the decoded bytes, never taken from a codec's claim. Lossy candidates run without any opt-in;baseholds the tensors that delta candidates refer to, and a delta tensor with no match in it uses the choice'sfallbackor raisesMissingBaseError. A candidate that chose a delta codec for some tensors but found a reference for none of them raisesMissingBaseErrorinstead of reporting rows that measure only its fallback.
コマンドライン¶
Command-line interface built with typed-argument-parser. See DESIGN.md, "CLI".
- jabara.cli.main(argv: list[str] | None = None) None[ソース]¶
Run the
jabaracommand withargv, or withsys.argvwhenargvis 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, orValueErrorfrom a command prints one line to standard error and exits with status 1.
- class jabara.cli.Listing(*, path: str, tensors: list[TensorStats])[ソース]¶
ベースクラス:
BaseModelOne archive and the stats of its tensors.
jabara ls --jsonprints 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[ソース]¶
Raise
ValueErrorfor the settingsattachrefuses thatTrainingArgumentsandthreadsalready show.Call it before building the
Trainer:Trainer(...)creates the Hub repository forpush_to_hubbeforeattachcan refuse thehub_strategy.attachrepeats these checks, and also refuses DeepSpeed and FSDP, which only the builtTrainerreports.
- jabara.hf.attach(trainer: Trainer, *, threads: int | None = None, assign: Assigner | None = None, allow_lossy: bool = False, delta: Literal['first'] | None = None) None[ソース]¶
Compress every checkpoint
trainersaves, and restore it for resume andload_best_model_at_end.Compression runs synchronously at the end of each save. Attaching again replaces the earlier settings. Raises
ValueError, before changing anything, forthreadsbelow 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, andsave_total_limitrotation keeps that base. Refused withsave_total_limit=1, and for any other value.
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)[ソース]¶
ベースクラス:
CheckpointIOLossless:
load_checkpointreturns the dictsave_checkpointreceived, tensors bit for bit.Every
OrderedDictthat carries_metadata, wherever it sits in the checkpoint (the modulestate_dict, the averaged model ofStochasticWeightAveraging), comes back with it, assave_statekeeps it; other values must be tensors, plain JSON values, or dicts, lists, and tuples of them, or saving raisesUnsupportedStateError.- save_checkpoint(checkpoint: dict[str, Any], path: str | PathLike[str], storage_options: object = None) None[ソース]¶
Write
checkpointtopathas an archive, creating parent directories. RaisesValueErrorfor a URL path,TypeErrorifstorage_optionsis given,UnsupportedStateErrorfor a value Jabara cannot store, andLossyNotAllowedErrorifassignpicks a lossy codec.
- load_checkpoint(path: str | PathLike[str], map_location: object = None, weights_only: bool | None = None) dict[str, Any][ソース]¶
Return the checkpoint dict that was saved at
path, with tensors onmap_location(CPU if None).weights_onlyis ignored. RaisesValueErrorifmap_locationis not None, astr, or atorch.device, or names the meta device.
エラー¶
Exceptions raised by Jabara.
- exception jabara.errors.JabaraError[ソース]¶
ベースクラス:
ExceptionBase class for every error Jabara raises.
- exception jabara.errors.ArchiveFormatError[ソース]¶
ベースクラス:
JabaraErrorThe file is not a Jabara archive this version can read.
- exception jabara.errors.ChecksumError[ソース]¶
ベースクラス:
JabaraErrorA decoded chunk does not match its recorded checksum.
- exception jabara.errors.UnknownCodecError[ソース]¶
ベースクラス:
JabaraErrorAn archive or an assigner names a codec that is not registered.
- exception jabara.errors.UnsupportedStateError[ソース]¶
ベースクラス:
JabaraErrorA nested state holds a value Jabara cannot store without pickle.
- exception jabara.errors.MissingBaseError[ソース]¶
ベースクラス:
JabaraErrorA delta codec needs a base tensor, but no base was supplied or the base has no matching tensor.
- exception jabara.errors.BaseMismatchError[ソース]¶
ベースクラス:
JabaraErrorThe supplied base archive is not the one a delta archive was written against.
- exception jabara.errors.LossyNotAllowedError[ソース]¶
ベースクラス:
JabaraErrorThe assigner chose a lossy codec but the caller did not opt in with
allow_lossy.
- exception jabara.errors.UnsupportedDtypeError[ソース]¶
ベースクラス:
JabaraErrorA codec cannot handle the tensor's dtype.
- exception jabara.errors.MissingDependencyError[ソース]¶
ベースクラス:
JabaraErrorA codec needs an optional package that is not installed.
- exception jabara.errors.NonFiniteError[ソース]¶
ベースクラス:
JabaraErrorA lossy codec was given NaN or an infinity, or a range it cannot represent.