# Jabara documentation > The English documentation of Jabara (https://jabara.iamtatsuki05.com/docs/), one page after another, generated from the Markdown sources in docs/ of https://github.com/iamtatsuki05/jabara. Blocks such as ```{testcode} and ```{testoutput} are MyST directives: example code and the output that a test checks. The Python API reference is generated from docstrings and is not in this file: read it at https://jabara.iamtatsuki05.com/docs/reference/api.html. --- Source: https://jabara.iamtatsuki05.com/docs/ # Jabara Jabara compresses the checkpoints of a training run: the model weights and the optimizer state. Lossless compression, deltas against an earlier checkpoint, and quantization all implement one codec interface, so you can use, compare, and add codecs in the same way. Jabara is for checkpoints that you keep and read back, to resume a run or to analyse it, such as the checkpoints of a seed sweep. It is not a format to serve a model from. {doc}`explanation/use-cases` describes each case, what Jabara does in it, and what it costs. By default, every tensor is restored bit for bit, and every read checks a CRC-32 per chunk. Writing an archive with a lossy codec requires `allow_lossy=True`, and the archive records the largest error that the codec introduced. You can use Jabara from the `jabara` command, from Python, or through the adapters for the Hugging Face `Trainer` and PyTorch Lightning. --- Source: https://jabara.iamtatsuki05.com/docs/getting-started/installation.html # Installation Jabara needs Python 3.10 or newer. It is not on PyPI yet, so install it from a clone into a virtual environment. Outside one, `pip install .` stops with `externally-managed-environment` on a Python that your operating system or Homebrew manages. With uv, `uv sync` creates `.venv` and installs the locked dependencies of the core and of each extra that you name with `--extra`. `--no-dev` leaves out the test tools: ```console $ git clone https://github.com/iamtatsuki05/jabara $ cd jabara $ uv sync --no-dev --extra torch $ source .venv/bin/activate ``` With pip, create and activate the virtual environment, then install: ```console $ git clone https://github.com/iamtatsuki05/jabara $ cd jabara $ python -m venv .venv $ source .venv/bin/activate $ pip install ".[torch]" ``` On Windows, run `.venv\Scripts\activate` in place of the `source` line. Later pages assume that the environment is active. With uv, you can instead start each command with `uv run`. The core depends on `numpy`, `zstandard`, and `pydantic`. It does not import torch and needs no GPU. ## Optional extras Each optional feature needs its extra. Name it after `--extra` for uv, or in brackets for pip. `uv sync --no-dev --extra hf --extra zipnn` and `pip install ".[hf,zipnn]"` install the same two extras. | Extra | Installs | Needed for | | --- | --- | --- | | `torch` | `torch` | `jabara.torch` (`save_state`, `load_state`), the names and roles of the tensors of a `torch.save` file when `jabara compress` or `jabara bench` reads one (without it they are `storage/` with the role `other`), and `jabara decompress` of an archive that Jabara 0.1.0 wrote from a torch file | | `hf` | `torch`, `transformers`, `accelerate` | `jabara.hf`, the Hugging Face `Trainer` adapter | | `lightning` | `torch`, `lightning` | `jabara.lightning`, the PyTorch Lightning plugin | | `zipnn` | `zipnn` | the `zipnn/1` codec, which raises `MissingDependencyError` without it (`jabara bench` skips it with a notice on stderr) | | `yaml` | `pyyaml` | `--config` with a `.yaml` or `.yml` file; without it the command prints how to install it and exits with status 1 (see {doc}`../how-to/run-from-a-config-file`) | | `hdf5` | `h5py` | `jabara compress` and `jabara bench` on HDF5 files (`*.h5`, `*.hdf5`, a Keras `*.weights.h5`) and Keras `*.keras` files; without it they exit with status 1 and name the extra | ## Check the installation `jabara codecs` lists the registered codecs: ```console $ jabara codecs bytegroup-zstd/1 quant8-linear/1 quant8-log/1 raw/1 sub-delta/1 xor-delta/1 zipnn/1 zstd/1 ``` ## Develop Jabara `uv sync` in the clone installs the locked dependencies of the `dev` group, which holds the packages of every extra and the test tools. `uv run tox` runs the tests, Ruff, and mypy. Next, follow the {doc}`tutorial`. --- Source: https://jabara.iamtatsuki05.com/docs/getting-started/tutorial.html # Tutorial: compress and restore a checkpoint In this tutorial you compress a small checkpoint directory with the `jabara` command, inspect it, verify it, and restore it. Then you do the same from Python with `save_state` and `load_state`. You need Jabara with the `torch` extra in an active virtual environment (see {doc}`installation`). The checkpoint script also needs the `safetensors` package. Install it into the same environment: ```console $ pip install safetensors ``` In an environment from `uv sync`, run `uv pip install safetensors` instead, because uv environments have no `pip`. ## Make a checkpoint directory In an empty directory, save this script as `make_checkpoint.py` (`docs/_snippets/make_checkpoint.py` in the clone, or [on GitHub](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_checkpoint.py)). It trains a model of two 256 by 256 linear layers for three AdamW steps with a fixed seed. Then it writes the weights, the optimizer state, and the trainer state under the file names of a Hugging Face `Trainer` checkpoint. ```python """Write checkpoint-1000/, a small checkpoint directory with the files a Hugging Face Trainer saves.""" import json from pathlib import Path import torch from safetensors.torch import save_file torch.manual_seed(0) model = torch.nn.Sequential(torch.nn.Linear(256, 256), torch.nn.ReLU(), torch.nn.Linear(256, 256)) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) for _ in range(3): batch = torch.randn(32, 256) optimizer.zero_grad() torch.nn.functional.mse_loss(model(batch), batch).backward() optimizer.step() checkpoint = Path("checkpoint-1000") checkpoint.mkdir(exist_ok=True) save_file(model.state_dict(), checkpoint / "model.safetensors") torch.save(optimizer.state_dict(), checkpoint / "optimizer.pt") (checkpoint / "trainer_state.json").write_text(json.dumps({"global_step": 1000})) ``` Run it: ```console $ python make_checkpoint.py ``` You now have `checkpoint-1000`, a directory with `model.safetensors`, `optimizer.pt`, and `trainer_state.json`. ## Compress the directory ```console $ jabara compress checkpoint-1000 checkpoint-1000/model.safetensors.jbr: ... -> ... bytes (...% of original) checkpoint-1000/optimizer.pt.jbr: ... -> ... bytes (...% of original) ``` Each line names a new archive and gives the tensor bytes before and after compression, and the stored size as a percentage of the original. Jabara wrote and verified both archives, then deleted `model.safetensors` and `optimizer.pt`. In a directory, `jabara compress` takes only the `*.safetensors` files and `optimizer.pt`, so `trainer_state.json` is unchanged. ## Inspect the archives ```console $ jabara ls checkpoint-1000 checkpoint-1000/model.safetensors.jbr: 4 tensors, ... -> ... bytes (...% of original) 0.bias float32 [256] weight bytegroup-zstd/1 ... -> ... bytes (...% of original) 0.weight float32 [256, 256] weight bytegroup-zstd/1 ... -> ... bytes (...% of original) 2.bias float32 [256] weight bytegroup-zstd/1 ... -> ... bytes (...% of original) 2.weight float32 [256, 256] weight bytegroup-zstd/1 ... -> ... bytes (...% of original) checkpoint-1000/optimizer.pt.jbr: 13 tensors, ... -> ... bytes (...% of original) state/0/step float32 [] step bytegroup-zstd/1 ... -> ... bytes (...% of original) state/0/exp_avg float32 [256, 256] adam_m bytegroup-zstd/1 ... -> ... bytes (...% of original) state/0/exp_avg_sq float32 [256, 256] adam_v bytegroup-zstd/1 ... -> ... bytes (...% of original) state/1/step float32 [] step bytegroup-zstd/1 ... -> ... bytes (...% of original) state/1/exp_avg float32 [256] adam_m bytegroup-zstd/1 ... -> ... bytes (...% of original) state/1/exp_avg_sq float32 [256] adam_v bytegroup-zstd/1 ... -> ... bytes (...% of original) state/2/step float32 [] step bytegroup-zstd/1 ... -> ... bytes (...% of original) state/2/exp_avg float32 [256, 256] adam_m bytegroup-zstd/1 ... -> ... bytes (...% of original) state/2/exp_avg_sq float32 [256, 256] adam_v bytegroup-zstd/1 ... -> ... bytes (...% of original) state/3/step float32 [] step bytegroup-zstd/1 ... -> ... bytes (...% of original) state/3/exp_avg float32 [256] adam_m bytegroup-zstd/1 ... -> ... bytes (...% of original) state/3/exp_avg_sq float32 [256] adam_v bytegroup-zstd/1 ... -> ... bytes (...% of original) (remainder) uint8 [...] other bytegroup-zstd/1 ... -> ... bytes (...% of original) ``` Each tensor line gives the name, dtype, shape, role, and codec. Jabara gives each tensor a role from its place in the state. Every tensor of a safetensors file has the role `weight`. In the optimizer state, `exp_avg` has the role `adam_m` and `exp_avg_sq` has the role `adam_v`. An assigner picks the codec of each tensor. With no assigner, Jabara uses `DefaultAssigner`, which gives these `float32` tensors `bytegroup-zstd/1`. ## Verify the archives ```console $ jabara verify checkpoint-1000 ok checkpoint-1000/model.safetensors.jbr ok checkpoint-1000/optimizer.pt.jbr ``` `verify` decodes every chunk and checks its CRC-32. A damaged archive makes it print `jabara: ` and exit with status 1. ## Restore the directory ```console $ jabara decompress checkpoint-1000 checkpoint-1000/model.safetensors checkpoint-1000/optimizer.pt ``` `model.safetensors` and `optimizer.pt` match the files that the script wrote byte for byte. The archives are deleted. Add `--keep` to `compress` or `decompress` to keep the input files. With `--recursive`, these commands take a directory that holds several checkpoints, such as `checkpoint-1000` and `checkpoint-2000` side by side. ## Do the same from Python `save_state` writes a nested state of tensors and plain values to an archive. Load the optimizer state from `optimizer.pt` and save it: ```{testsetup} import runpy runpy.run_path(f"{SNIPPETS}/make_checkpoint.py") ``` ```{testcode} import torch from jabara.torch import save_state state = torch.load("checkpoint-1000/optimizer.pt", weights_only=True) info = save_state(state, "optimizer.jbr") print(info.path) ``` ```{testoutput} optimizer.jbr ``` Open the archive to inspect and verify it. `stats()` gives one entry per tensor, and `verify()` raises an error if a chunk does not match its checksum: ```{testcode} from jabara.container import Archive with Archive.open("optimizer.jbr") as archive: archive.verify() for stat in archive.stats(): print(stat.meta.name, stat.meta.role, stat.codec) ``` ```{testoutput} state/0/step step bytegroup-zstd/1 state/0/exp_avg adam_m bytegroup-zstd/1 state/0/exp_avg_sq adam_v bytegroup-zstd/1 state/1/step step bytegroup-zstd/1 state/1/exp_avg adam_m bytegroup-zstd/1 state/1/exp_avg_sq adam_v bytegroup-zstd/1 state/2/step step bytegroup-zstd/1 state/2/exp_avg adam_m bytegroup-zstd/1 state/2/exp_avg_sq adam_v bytegroup-zstd/1 state/3/step step bytegroup-zstd/1 state/3/exp_avg adam_m bytegroup-zstd/1 state/3/exp_avg_sq adam_v bytegroup-zstd/1 ``` `load_state` returns the same nested state. Compare it with the state that you saved: ```{testcode} from jabara.torch import load_state restored = load_state("optimizer.jbr") print(restored["param_groups"] == state["param_groups"]) print(all( torch.equal(restored["state"][i][key], state["state"][i][key]) for i in state["state"] for key in state["state"][i] )) ``` ```{testoutput} True True ``` The restored state loads into an optimizer like the output of `torch.load`: ```{testcode} model = torch.nn.Sequential(torch.nn.Linear(256, 256), torch.nn.ReLU(), torch.nn.Linear(256, 256)) optimizer = torch.optim.AdamW(model.parameters()) optimizer.load_state_dict(restored) ``` ## Next steps - {doc}`../reference/cli` lists every command and its options. - {doc}`../reference/codecs` lists the built-in codecs. - {doc}`../reference/api` documents `save_state`, `load_state`, `Archive`, and the rest of the Python API. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/hugging-face-trainer.html # Use Jabara with the Hugging Face Trainer Jabara can compress every checkpoint that a Hugging Face `Trainer` saves, and the `Trainer` can resume from a compressed checkpoint. Jabara supports single-process training only. Install Jabara with the `hf` extra (see {doc}`../getting-started/installation`). The examples train a tiny, randomly initialized GPT-2 on CPU. Save this file as `tiny_trainer.py` (`docs/_snippets/tiny_trainer.py` in the clone), because the examples import it. Your own script keeps its `TrainingArguments` and `Trainer`. ```python """A tiny randomly initialised GPT-2 and a Hugging Face Trainer for it that trains on CPU in a few seconds.""" from typing import Any import torch from transformers import GPT2Config, GPT2LMHeadModel, Trainer, TrainingArguments from transformers.trainer_callback import PrinterCallback def make_arguments(output_dir: str = "out", **kwargs: Any) -> TrainingArguments: return TrainingArguments( output_dir=output_dir, max_steps=4, save_steps=2, per_device_train_batch_size=4, use_cpu=True, report_to=[], disable_tqdm=True, logging_strategy="no", **kwargs, ) def make_trainer(args: TrainingArguments) -> Trainer: torch.manual_seed(0) model = GPT2LMHeadModel( GPT2Config(vocab_size=64, n_positions=16, n_embd=32, n_layer=2, n_head=2, bos_token_id=0, eos_token_id=1) ) data = [{"input_ids": ids, "labels": ids} for ids in torch.randint(0, 64, (32, 16))] trainer = Trainer(model=model, args=args, train_dataset=data, eval_dataset=data[:8]) trainer.remove_callback(PrinterCallback) # it prints the training summary, which these pages do not show return trainer ``` [`scripts/integrations/transformers`](https://github.com/iamtatsuki05/jabara/blob/main/scripts/integrations/transformers/README.md) adds the same calls to the official `run_clm.py` example behind a `--jabara` flag, with the commands to run it and the lines that it adds. ## Compress every checkpoint Check the arguments, build the `Trainer`, and attach Jabara before you train: ```{testcode} import jabara.hf from tiny_trainer import make_arguments, make_trainer args = make_arguments() jabara.hf.check_arguments(args) trainer = make_trainer(args) jabara.hf.attach(trainer) trainer.train() ``` `attach` changes this `Trainer` instance only. Each save first writes the usual checkpoint, including the `Trainer`'s rotation of old checkpoints. Jabara then replaces the model files (`*.safetensors`) and `optimizer.pt` with verified archives. The save returns after the archives are written, so a checkpoint is never half compressed while training goes on (see {doc}`../explanation/synchronous-save`). `attach` also takes `threads`, `assign`, and `allow_lossy`. `threads` sets the size of the thread pool that codes the chunks. `assign` is an assigner (see {doc}`choose-codecs`), and a lossy assigner needs `allow_lossy=True` (see {doc}`lossy`). ### Call `check_arguments` before you build the Trainer When `push_to_hub` is set, `Trainer(...)` creates the Hub repository before `attach` can refuse the configuration. `jabara.hf.check_arguments(args)` refuses it from the `TrainingArguments` alone, before anything is created. Pass it the same `threads` as `attach`. `attach` repeats these checks. Only `attach` can refuse DeepSpeed and FSDP, because only a built `Trainer` reports them. ## What a checkpoint directory holds ```{testcode} import os names = sorted(os.listdir("out/checkpoint-4")) print([n for n in names if n.endswith(".jbr")]) print("model.safetensors" in names, "optimizer.pt" in names) print("trainer_state.json" in names, "scheduler.pt" in names) ``` ```{testoutput} ['model.safetensors.jbr', 'optimizer.pt.jbr'] False False True True ``` The weights and the optimizer state are archives. A model that `save_pretrained` splits over several files, `model-00001-of-00002.safetensors` and the rest, gets one archive per file, and `model.safetensors.index.json` stays as it is. The other files stay as the `Trainer` wrote them: `trainer_state.json`, `scheduler.pt`, `rng_state.pth`, and the configuration files. To inspect the archives, run `jabara ls` or `jabara verify` on the directory. After Jabara adds or removes files, it sets the directory's modification time back. The `Trainer` rotates checkpoints by that time, so Jabara does not change which checkpoint looks newest. ## Resume Attach Jabara to the resuming `Trainer` too: ```{testcode} before = sorted(os.listdir("out/checkpoint-2")) resumed = make_trainer(make_arguments()) jabara.hf.attach(resumed) resumed.train(resume_from_checkpoint="out/checkpoint-2") print(resumed.state.global_step) print(sorted(os.listdir("out/checkpoint-2")) == before) ``` ```{testoutput} 4 True ``` The `Trainer` opens `model.safetensors`, or the files that `model.safetensors.index.json` lists, and `optimizer.pt` by name. For each load, the attached `Trainer` restores them next to their archives, runs the original loader, and deletes them. The archives stay untouched, and the directory ends as it was. The resume prints `There were missing keys in the checkpoint model loaded: ['lm_head.weight']`, as it does without Jabara. The model ties `lm_head.weight` to the embeddings, so no weights are lost. Without `attach`, the same call fails, because the directory holds no `model.safetensors`: ```{testcode} plain = make_trainer(make_arguments()) try: plain.train(resume_from_checkpoint="out/checkpoint-2") except ValueError as error: print(error) ``` ```{testoutput} Can't find a valid checkpoint at out/checkpoint-2 ``` ## Load the best model at the end `load_best_model_at_end` needs no extra step. The attached `Trainer` restores the weights of `state.best_model_checkpoint` from their archive before it loads them. ```{testcode} args = make_arguments( "best", eval_strategy="steps", eval_steps=2, load_best_model_at_end=True, metric_for_best_model="loss" ) best = make_trainer(args) jabara.hf.attach(best) best.train() print(sorted(n for n in os.listdir(best.state.best_model_checkpoint) if n.endswith(".jbr"))) ``` ```{testoutput} ['model.safetensors.jbr', 'optimizer.pt.jbr'] ``` ## Recover from an interrupted save or resume An `Exception`, `KeyboardInterrupt`, or `SystemExit` during a save leaves each model file and `optimizer.pt` in one of three states. Every archive on disk is complete and verified, and no temporary file remains. - **The original alone.** The interrupt came while the archives were written. Jabara removed the archives of this save, so a `Trainer` without Jabara can load the directory. - **The original beside its archive.** The interrupt came after all archives were written and verified, while Jabara was deleting the originals. The archive encodes the original. - **The archive alone.** The original of this file was deleted. Only a `Trainer` with Jabara attached can load the directory. An older save into the same directory can also leave an archive beside an original. That archive may not encode the original, and nothing on disk tells the two cases apart. A resume with Jabara attached reads the original where there is one, and the archive otherwise. It leaves the directory as it found it, even when the resume is interrupted, and never deletes an original that sits beside an archive. To recover, treat the original as the file that the `Trainer` saved, and pick one of these: - To keep the directory compressed, remove each archive that sits beside an original, and compress again. This also replaces a stale archive from an older save. - To make the directory loadable without Jabara, remove each archive that sits beside an original. Then run `jabara decompress` on the directory to restore the remaining archives. - To let the `Trainer` do it, save the same step again. The save overwrites the originals and ends with the checkpoint compressed. This example creates the second state by restoring `optimizer.pt` next to its archive. Then it removes the archive and compresses the directory again: ```{testcode} from jabara.files import SUFFIX, compress_dir, decompress_file checkpoint = "out/checkpoint-4" decompress_file(f"{checkpoint}/optimizer.pt{SUFFIX}", keep=True) print(sorted(n for n in os.listdir(checkpoint) if n.startswith("optimizer"))) os.remove(f"{checkpoint}/optimizer.pt{SUFFIX}") compress_dir(checkpoint) print(sorted(n for n in os.listdir(checkpoint) if n.startswith("optimizer"))) ``` ```{testoutput} ['optimizer.pt', 'optimizer.pt.jbr'] ['optimizer.pt.jbr'] ``` A hard crash, such as a power loss or `SIGKILL`, runs no cleanup. It can leave a `*.tmp` file, which you can delete, and an archive beside every original. A resume uses the originals. A crash during a resume can leave a restored original beside its archive. That file is complete, and a later resume uses it. While a directory holds an original beside its archive, `jabara compress` and `jabara decompress` refuse the directory. Remove one file of the pair first. ## Save checkpoints as deltas `delta="first"` saves each checkpoint as a delta against the oldest earlier checkpoint of the run that is fully compressed, which is the first one: ```text jabara.hf.attach(trainer, delta="first") ``` - `save_total_limit` still applies, but the base is kept: a checkpoint that a kept checkpoint needs as its base is never deleted and counts toward the limit. With `save_total_limit=2` the run keeps its first and its newest checkpoint. The adapter rotates the checkpoints itself in this mode, and keeps the newest and the best one, as the `Trainer` does. - `save_total_limit=1` is refused with `ValueError`: at the end of training the `Trainer` then deletes every checkpoint but the best, base included. - A resume or `load_best_model_at_end` finds the base among the sibling checkpoint directories by file name and index CRC-32. If none holds it, the resume stops with `BaseMismatchError` before it restores anything, and names the missing base. - After an interrupted save the checkpoint holds its originals, which are no base. The next save is written in full, or against an older checkpoint, and nothing is deleted by the interrupted one. - Do not delete or move the first checkpoint yourself. Only `"first"` exists: a chain would keep every checkpoint, which no limit can rotate. ## Refused configurations `check_arguments` and `attach` raise `ValueError` with these messages: ```{testcode} from unittest import mock from transformers import TrainingArguments def refusal(args, **kwargs): try: jabara.hf.check_arguments(args, **kwargs) except ValueError as error: print(error) refusal(make_arguments("o"), threads=0) refusal(make_arguments("o", push_to_hub=True, hub_strategy="checkpoint")) with mock.patch.object(TrainingArguments, "world_size", new_callable=mock.PropertyMock, return_value=2): refusal(make_arguments("o")) # a stand-in for a launch with two processes ``` ```{testoutput} threads must be at least 1, got 0 hub_strategy='checkpoint' uploads checkpoint folders in the background, which would race with compression; use 'every_save' or 'end' jabara.hf supports single-process training only ``` `hub_strategy='all_checkpoints'` is refused the same way. `attach` also refuses DeepSpeed and FSDP, with `jabara.hf does not support DeepSpeed: it saves and loads sharded checkpoints itself` and `jabara.hf does not support FSDP: it saves and loads sharded checkpoints itself`. Every refusal comes before `attach` changes anything. ## Stop compressing `jabara.hf.detach(trainer)` puts back the methods that `attach` replaced, so later saves are plain. Checkpoints that are already compressed stay compressed, and resuming from them still needs Jabara attached. ```{testcode} stopped = make_trainer(make_arguments("stopped")) jabara.hf.attach(stopped) jabara.hf.detach(stopped) stopped.train() print(sorted(n for n in os.listdir("stopped/checkpoint-4") if n.startswith(("model", "optimizer")))) ``` ```{testoutput} ['model.safetensors', 'optimizer.pt'] ``` If you replaced one of the four patched methods after `attach`, `detach` raises `RuntimeError` and changes nothing. A second `attach` on the same `Trainer` replaces the earlier settings. ## Compatibility `jabara.hf` patches four private methods of `Trainer` that transformers does not keep stable, and relies on the checkpoint file names `model*.safetensors` and `optimizer.pt`. The tests cover transformers 5.20.2 and 5.24.1. A release that renames one of those methods or changes its signature breaks `attach`. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/pytorch-lightning.html # Use Jabara with PyTorch Lightning With `JabaraCheckpointIO`, a Lightning `Trainer` stores its checkpoints as Jabara archives and resumes from them. Install Jabara with the `lightning` extra (see {doc}`../getting-started/installation`). The examples fit a tiny model on CPU. Save this file as `tiny_lightning.py` (`docs/_snippets/tiny_lightning.py` in the clone), because the examples import it. Your own `LightningModule` and `Trainer` take its place. ```python """A tiny LightningModule, a data loader, and a Trainer factory that fits on CPU in a few seconds.""" import lightning as L import torch from lightning.pytorch.callbacks import ModelCheckpoint from lightning.pytorch.plugins.io import CheckpointIO from torch.utils.data import DataLoader, TensorDataset class Regressor(L.LightningModule): def __init__(self) -> None: super().__init__() self.net = torch.nn.Sequential(torch.nn.Linear(8, 16), torch.nn.Tanh(), torch.nn.Linear(16, 1)) def training_step(self, batch: list[torch.Tensor], batch_idx: int) -> torch.Tensor: x, y = batch return torch.nn.functional.mse_loss(self.net(x), y) def configure_optimizers(self) -> torch.optim.Optimizer: return torch.optim.AdamW(self.parameters(), lr=1e-2) def make_loader() -> DataLoader[tuple[torch.Tensor, ...]]: x = torch.randn(32, 8, generator=torch.Generator().manual_seed(1)) return DataLoader(TensorDataset(x, x.sum(dim=1, keepdim=True)), batch_size=8) def make_trainer(plugin: CheckpointIO, max_epochs: int = 2) -> L.Trainer: L.seed_everything(0) return L.Trainer( max_epochs=max_epochs, accelerator="cpu", devices=1, logger=False, enable_progress_bar=False, enable_model_summary=False, callbacks=[ModelCheckpoint(dirpath="checkpoints", every_n_epochs=1, save_top_k=-1)], plugins=[plugin], ) ``` [`scripts/integrations/pytorch_lightning`](https://github.com/iamtatsuki05/jabara/blob/main/scripts/integrations/pytorch_lightning/README.md) adds the same plugin to the official Lightning `imagenet.py` example behind a `--jabara` flag, with the commands to run it and the lines that it adds. ## Pass the plugin to the Trainer `JabaraCheckpointIO` is a Lightning `CheckpointIO`. Pass it in `plugins`, and every checkpoint file that Lightning writes is a Jabara archive, at the path that Lightning chooses. Here `ModelCheckpoint` writes one per epoch: ```{testcode} import os from jabara.lightning import JabaraCheckpointIO from tiny_lightning import Regressor, make_loader, make_trainer trainer = make_trainer(JabaraCheckpointIO()) trainer.fit(Regressor(), make_loader()) print(sorted(os.listdir("checkpoints"))) ``` ```{testoutput} ['epoch=0-step=4.ckpt', 'epoch=1-step=8.ckpt'] ``` The files keep their `.ckpt` names, but they are Jabara archives, not files for `torch.load`. `JabaraCheckpointIO` reads them, and `jabara ls`, `jabara verify`, and `jabara.container.Archive` open them like any other archive. Two Lightning calls cannot read them (see "What reads an archive" below). The constructor takes `threads` and `assign`, an assigner (see {doc}`choose-codecs`). `threads` below 1 raises `ValueError`. The plugin has no `allow_lossy` and never writes a lossy tensor, so an assigner that picks a lossy codec makes the save fail with `LossyNotAllowedError`. It writes full archives only: `JabaraCheckpointIO(delta="first")` raises `ValueError`. `ModelCheckpoint` rewrites `last.ckpt` in place and removes the checkpoints it ranks worst, in any order, so a base could not be kept safely. To store deltas, use the {doc}`hugging-face-trainer` adapter, or run `jabara compress --recursive --delta first` on a directory of checkpoints. Importing `jabara.lightning` imports torch and Lightning, so even the import needs the `lightning` extra. The core modules never import torch. ## What is stored The plugin saves the checkpoint dictionary that Lightning passes to it: the model weights, the optimizer state, the loop state, and the callback state. Each tensor becomes an archive entry with a role: ```{testcode} from collections import Counter from jabara.container import Archive with Archive.open("checkpoints/epoch=1-step=8.ckpt") as archive: print(sorted(Counter(stat.meta.role for stat in archive.stats()).items())) ``` ```{testoutput} [('adam_m', 4), ('adam_v', 4), ('other', 1), ('step', 4), ('weight', 4)] ``` Tensors under `state_dict` have the role `weight`. The rest follow `OptimizerSchema`: the first and second moments of AdamW are `adam_m` and `adam_v`, and a tensor with an unknown name is `other`. Here the `other` tensor is the `kth_value` that `ModelCheckpoint` keeps. Every tensor keeps its dtype, shape, and bits. Every value that is not a tensor must be a plain JSON value, or a dict, list, or tuple of them. Any other value makes the save raise `UnsupportedStateError`, which names the place in the checkpoint. The plugin never uses pickle. It does not support `storage_options`, and `save_checkpoint` raises `TypeError` if you pass it. ## Resume Pass the path to `fit` as usual, on a `Trainer` with the plugin, because only the plugin reads the archive: ```{testcode} resumed = make_trainer(JabaraCheckpointIO(), max_epochs=3) resumed.fit(Regressor(), make_loader(), ckpt_path="checkpoints/epoch=1-step=8.ckpt") print(resumed.current_epoch, resumed.global_step) ``` ```{testoutput} 3 12 ``` `load_checkpoint` returns the saved dictionary with every tensor bit for bit. `map_location` can be `None`, a string, or a `torch.device`. A dict or a callable, which `TorchCheckpointIO` accepts, raises `ValueError`. The plugin ignores `weights_only`, because it never unpickles. ## What reads an archive On a `Trainer` with the plugin, `Trainer.fit`, `validate`, `test`, and `predict` with `ckpt_path` read an archive, because they go through the plugin. Two Lightning calls open the file with `torch.load` themselves, so they cannot read an archive: - `LightningModule.load_from_checkpoint(path)`. - `LightningCLI` with `--ckpt_path` for any subcommand, in Lightning 2.5.5 and later. It reads the hyperparameters of the checkpoint to merge them into the model configuration. Earlier versions do not read the file. Both raise `UnpicklingError`: ```{testcode} try: Regressor.load_from_checkpoint("checkpoints/epoch=1-step=8.ckpt") except Exception as error: print(type(error).__name__) ``` ```{testoutput} UnpicklingError ``` To load a module for inference, read the archive with `load_state` and load its `state_dict`, which equals the model's `state_dict` bit for bit: ```{testcode} import torch from jabara.torch import load_state state = load_state("checkpoints/epoch=1-step=8.ckpt") model = Regressor() model.load_state_dict(state["state_dict"]) print(all(torch.equal(a, b) for a, b in zip(model.parameters(), trainer.lightning_module.parameters()))) ``` ```{testoutput} True ``` `load_from_checkpoint` builds the model from the hyperparameters in the file and accepts a file object. To use it, save the dictionary from `load_state` to an in-memory buffer: ```{testcode} import io buffer = io.BytesIO() torch.save(state, buffer) buffer.seek(0) model = Regressor.load_from_checkpoint(buffer) ``` To get a plain checkpoint that every Lightning call reads, restore the archive. `decompress_file` and `jabara decompress` accept only a path that ends in `.jbr`, so first copy the archive to such a name. The restored file has no `.jbr`, and `LightningCLI` reads it too: ```{testcode} import shutil from jabara.files import decompress_file shutil.copy("checkpoints/epoch=1-step=8.ckpt", "restored.ckpt.jbr") restored = decompress_file("restored.ckpt.jbr") model = Regressor.load_from_checkpoint(restored) print(restored) ``` ```{testoutput} restored.ckpt ``` ## Local paths only The plugin reads and writes local files only. A path with a URL scheme (`s3://`, `gs://`, `memory://`, and `file://`) raises `ValueError` before anything is touched. Write a `file://` path as a plain path. A `Trainer` whose `default_root_dir` or `ModelCheckpoint(dirpath=...)` is remote fails at its first save. ```{testcode} try: JabaraCheckpointIO().save_checkpoint({}, "s3://bucket/last.ckpt") except ValueError as error: print(error) ``` ```{testoutput} s3://bucket/last.ckpt: JabaraCheckpointIO reads and writes local files only; pass a plain path ``` --- Source: https://jabara.iamtatsuki05.com/docs/how-to/pytorch-loop.html # Save and load state in a plain PyTorch loop `save_state` and `load_state` save and load the model and the optimizer state of your own training loop. Install Jabara with the `torch` extra (see {doc}`../getting-started/installation`). The {doc}`../getting-started/tutorial` shows a first save and load. ## Save and load in your loop `save_state` takes a nested state and a path, and `load_state` returns the same nested state. Save the weights and the optimizer state to two archives, as the `Trainer` adapter does: ```{testcode} import torch from jabara.schemas import WeightsSchema from jabara.torch import load_state, save_state torch.manual_seed(0) model = torch.nn.Linear(4, 2) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-2) for _ in range(3): optimizer.zero_grad() model(torch.randn(8, 4)).square().mean().backward() optimizer.step() save_state(model.state_dict(), "model.jbr", schema=WeightsSchema()) save_state(optimizer.state_dict(), "optimizer.jbr") model.load_state_dict(load_state("model.jbr")) optimizer.load_state_dict(load_state("optimizer.jbr")) ``` `save_state` returns an `ArchiveInfo` with the raw and the stored size. The schema sets each tensor's role (see "Choose roles with a schema" below). The restored state has the same container types, key types, key order, dtypes, shapes, and bits as the saved state. Each tensor keeps its `requires_grad` flag, and an `nn.Parameter` comes back as an `nn.Parameter`. ## What `save_state` accepts A tensor leaf is an object whose type is exactly `torch.Tensor` or `nn.Parameter`, in any dtype that Jabara supports, including `bfloat16`, `bool`, and the complex types. A conjugate or negative view is stored as the values it shows. A non-contiguous tensor is stored contiguous. Tensors on a GPU are copied to CPU first. The other leaves are `None`, `bool`, `int`, `str`, and `float`, including `inf` and `nan`. Containers are `dict`, `list`, `tuple`, and `collections.OrderedDict`. Dict keys can be strings or other plain values, such as the integer keys of an optimizer's `state`. ## What it refuses Anything else raises an error that names its place in the state. Jabara never falls back to pickle, so a load never imports a class that the archive names. ```{testcode} import collections from jabara.errors import JabaraError class Tagged(torch.Tensor): pass for state in [ {"w": torch.zeros(2).as_subclass(Tagged)}, {"seen": {1, 2}}, {"counts": collections.defaultdict(int)}, {"sparse": torch.eye(2).to_sparse()}, {"meta": torch.empty(2, device="meta")}, {"q": torch.zeros(2, dtype=torch.float8_e4m3fn)}, ]: try: save_state(state, "refused.jbr") except JabaraError as error: print(type(error).__name__, error) ``` ```{testoutput} UnsupportedStateError cannot store ...Tagged at 'w' UnsupportedStateError cannot store builtins.set at 'seen' UnsupportedStateError cannot store collections.defaultdict at 'counts' UnsupportedStateError tensor 'sparse': a sparse_coo tensor has no dense data to store UnsupportedStateError tensor 'meta': a meta tensor has no dense data to store UnsupportedDtypeError tensor 'q': dtype torch.float8_e4m3fn is not supported ``` A tensor subclass is refused, because it would come back as its base class, and restoring the subclass would mean importing a class that the archive names. A `set`, a custom object, and an instance of a `dict`, `list`, or `tuple` subclass are refused for the same reason. Convert such values before you save, for example with `tensor.as_subclass(torch.Tensor)`, `list(values)`, or `dict(counts)`. ## Load onto a device `load_state` moves every tensor to `map_location`, which is `"cpu"` by default. It takes `None`, which keeps the tensors on the CPU, a string such as `"cpu"`, or a `torch.device`. Unlike `torch.load`, it takes no dict or callable. On a machine with a GPU, pass `map_location="cuda"`. ```{testcode} for location in [None, "cpu", torch.device("cpu")]: print(load_state("model.jbr", map_location=location)["weight"].device) ``` ```{testoutput} cpu cpu cpu ``` ## Choose roles with a schema A tensor's role is a label that assigners and analysis read (see {doc}`../explanation/tensor-roles`). A schema sets it from the tensor's path in the nested state. When you pass no schema, `save_state` uses `OptimizerSchema`. It knows the names that optimizers use, so the tensors of a model's `state_dict`, named `weight` and `bias`, get the role `other`: ```{testcode} from jabara.container import Archive save_state(model.state_dict(), "unlabelled.jbr") for path in ["unlabelled.jbr", "model.jbr", "optimizer.jbr"]: with Archive.open(path) as archive: print(path, sorted({stat.meta.role for stat in archive.stats()})) ``` ```{testoutput} unlabelled.jbr ['other'] model.jbr ['weight'] optimizer.jbr ['adam_m', 'adam_v', 'step'] ``` `WeightsSchema` gives every tensor the role `weight`, which `jabara export-weights` and `RoleAssigner` read. To keep the model and the optimizer in one archive, subclass a schema and set the role of the weights by their path: ```{testcode} from jabara.schemas import OptimizerSchema class TrainingSchema(OptimizerSchema): def role(self, path): return "weight" if path[:1] == ("model",) else super().role(path) state = {"model": model.state_dict(), "optimizer": optimizer.state_dict()} save_state(state, "training.jbr", schema=TrainingSchema()) with Archive.open("training.jbr") as archive: print(sorted({stat.meta.role for stat in archive.stats()})) ``` ```{testoutput} ['adam_m', 'adam_v', 'step', 'weight'] ``` `MuonSchema` differs from `OptimizerSchema` in one name: it gives `momentum_buffer` the role `muon_momentum`. {doc}`extend` shows how to write a schema for another optimizer. To check a schema before you save, call `tensor_records(state, schema)`. It returns the records that `save_state` would write, with their names and roles. ## Other options `save_state` also takes `threads`, `assign` (see {doc}`choose-codecs`), `allow_lossy` (see {doc}`lossy`), and `base` (see {doc}`delta-checkpoints`). `load_state` takes `threads` and `base`. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/compress-many-runs.html # Compress the checkpoints of many runs A seed sweep or a hyperparameter search leaves one folder per run, each with several checkpoint directories. This guide compresses all of them with `--recursive`, checks the archives, and measures whether a delta against another run would help. It assumes that you know `jabara compress` and `jabara verify` (see the {doc}`../getting-started/tutorial`). To compress the checkpoints while the runs train, attach Jabara to each run instead (see {doc}`hugging-face-trainer` and {doc}`pytorch-lightning`). ## Before you start Start in an empty directory. Save [make_runs.py](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_runs.py) there. Like the {doc}`../getting-started/tutorial`, it needs the `torch` extra and `safetensors`. It trains two small runs with the seeds 0 and 1, and each run keeps two checkpoints in the layout of a Hugging Face `Trainer`: ```python """Write runs/seed-0/ and runs/seed-1/, two small runs that each keep checkpoint-2/ and checkpoint-4/.""" import json from pathlib import Path import torch from safetensors.torch import save_file for seed in (0, 1): torch.manual_seed(seed) model = torch.nn.Sequential(torch.nn.Linear(256, 256), torch.nn.ReLU(), torch.nn.Linear(256, 256)) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) for step in range(1, 5): batch = torch.randn(32, 256) optimizer.zero_grad() torch.nn.functional.mse_loss(model(batch), batch).backward() optimizer.step() if step % 2 == 0: checkpoint = Path(f"runs/seed-{seed}/checkpoint-{step}") checkpoint.mkdir(parents=True, exist_ok=True) save_file(model.state_dict(), checkpoint / "model.safetensors") torch.save(optimizer.state_dict(), checkpoint / "optimizer.pt") (checkpoint / "trainer_state.json").write_text(json.dumps({"global_step": step})) ``` ```console $ python make_runs.py ``` You now have `runs/seed-0/checkpoint-2`, `runs/seed-0/checkpoint-4`, `runs/seed-1/checkpoint-2`, and `runs/seed-1/checkpoint-4`. ## Compress one checkpoint directory ```console $ jabara compress runs/seed-0/checkpoint-2 runs/seed-0/checkpoint-2/model.safetensors.jbr: ... -> ... bytes (...% of original) runs/seed-0/checkpoint-2/optimizer.pt.jbr: ... -> ... bytes (...% of original) ``` `jabara compress` takes one checkpoint directory. Given `runs/seed-0` it prints `jabara: runs/seed-0: no *.safetensors files or optimizer.pt to compress; it holds 2 checkpoint directories (checkpoint-2, checkpoint-4), pass --recursive to take them all` and exits with status 1. ## Compress every checkpoint of a run `--recursive` takes the checkpoint directories one level below its `PATH`. The layout here has two levels, so run the command once per run. `runs` alone holds no checkpoint directory of its own, and `jabara compress runs --recursive` finds nothing. ```console $ jabara compress runs/seed-0 --recursive runs/seed-0/checkpoint-2: skipped, already compressed runs/seed-0/checkpoint-4/model.safetensors.jbr: ... -> ... bytes (...% of original) runs/seed-0/checkpoint-4/optimizer.pt.jbr: ... -> ... bytes (...% of original) runs/seed-0/checkpoint-4: 2 archives, ... -> ... bytes (...% of original) total: 2 checkpoints, 1 skipped, ... -> ... bytes (...% of original) $ jabara compress runs/seed-1 --recursive runs/seed-1/checkpoint-2/model.safetensors.jbr: ... -> ... bytes (...% of original) runs/seed-1/checkpoint-2/optimizer.pt.jbr: ... -> ... bytes (...% of original) runs/seed-1/checkpoint-2: 2 archives, ... -> ... bytes (...% of original) runs/seed-1/checkpoint-4/model.safetensors.jbr: ... -> ... bytes (...% of original) runs/seed-1/checkpoint-4/optimizer.pt.jbr: ... -> ... bytes (...% of original) runs/seed-1/checkpoint-4: 2 archives, ... -> ... bytes (...% of original) total: 2 checkpoints, 0 skipped, ... -> ... bytes (...% of original) ``` `runs/seed-0/checkpoint-2` was compressed in the previous section, so it is skipped. If the command stops, run it again: it skips the checkpoints that are done. A failure stops the run at that checkpoint. The checkpoints before it are done, and the rest stay as they were. Each checkpoint deletes its originals only after it has written and verified every archive in it. To keep the originals, for example until you have copied the archives to other storage, pass `--keep`. `--dry-run` lists what would be compressed and changes nothing. ## Check the archives ```console $ jabara verify runs/seed-0 --recursive ok runs/seed-0/checkpoint-2/model.safetensors.jbr ok runs/seed-0/checkpoint-2/optimizer.pt.jbr ok runs/seed-0/checkpoint-4/model.safetensors.jbr ok runs/seed-0/checkpoint-4/optimizer.pt.jbr $ jabara verify runs/seed-1 --recursive ok runs/seed-1/checkpoint-2/model.safetensors.jbr ok runs/seed-1/checkpoint-2/optimizer.pt.jbr ok runs/seed-1/checkpoint-4/model.safetensors.jbr ok runs/seed-1/checkpoint-4/optimizer.pt.jbr ``` `verify --recursive` checks every archive and does not stop at the first failure. It prints `FAILED : ` for each archive that fails, and exits with status 1. ## Measure a delta against another run A delta archive stores a checkpoint as its difference from a base (see {doc}`delta-checkpoints`). Jabara has not measured how well a checkpoint of one run compresses against a checkpoint of another run. For runs that start from different random weights, there is no reason to expect a gain. Measure it on your own checkpoints before you store anything that way. `jabara bench` reads both directories, compressed or not, and writes no file: ```console $ jabara bench runs/seed-1/checkpoint-4 --base runs/seed-0/checkpoint-4 --candidates bytegroup-zstd/1,xor-delta/1 --repeats 1 ... threads, best of 1, 1 warm-up, chunk ... bytes bytegroup-zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact bytegroup-zstd/1 step: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact bytegroup-zstd/1 adam_m: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact bytegroup-zstd/1 adam_v: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact xor-delta/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact xor-delta/1 step: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact xor-delta/1 adam_m: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact xor-delta/1 adam_v: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact ``` Store a delta only for the roles where the `xor-delta/1` row is smaller than the `bytegroup-zstd/1` row. For runs that start from the same pretrained weights, use those weights, compressed, as the base. `jabara compress DIR --base BASE` codes a whole checkpoint directory against an archive or a compressed directory, and every archive written against a base needs that base to be read. ## Resume one of the runs Run `jabara decompress` on a checkpoint directory, or `jabara decompress runs/seed-0 --recursive` on a whole run, to write the original files back, then resume with your framework as usual. With the `Trainer` adapter attached, the `Trainer` resumes from the archives directly (see {doc}`hugging-face-trainer`). The adapter reads a delta archive when its base checkpoint is a sibling directory; otherwise restore it first with `jabara decompress FILE --base ARCHIVE`. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/choose-codecs.html # Choose codecs per role An assigner can give the weights and each kind of optimizer state their own codec. It picks a `CodecChoice` for each tensor from its `TensorMeta`, which includes the tensor's role (see {doc}`../explanation/tensor-roles`). Pass the assigner as `assign=` to `save_state`, `write_archive`, `compress_file`, `compress_dir`, `jabara.hf.attach`, or `JabaraCheckpointIO`. With no assigner, Jabara uses `DefaultAssigner`: `bytegroup-zstd/1` for float dtypes and `zstd/1` for the rest. ## Before you start Start in an empty directory. Save [make_checkpoint.py](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_checkpoint.py) there and run it. Like the {doc}`../getting-started/tutorial`, it needs the `torch` extra and `safetensors`. It writes `checkpoint-1000/`, which the examples use. ```console $ python make_checkpoint.py ``` ## Pick codecs with `RoleAssigner` `RoleAssigner` maps each role name to a `CodecChoice`. A role that the mapping does not list goes to `default`, which is `DefaultAssigner()` when you leave it out. ```{testsetup} import runpy runpy.run_path(f"{SNIPPETS}/make_checkpoint.py") ``` ```{testcode} import torch from jabara.assign import CodecChoice, RoleAssigner from jabara.container import Archive from jabara.torch import save_state state = torch.load("checkpoint-1000/optimizer.pt", weights_only=True) assigner = RoleAssigner( { "adam_m": CodecChoice(codec_id="zstd/1", params={"level": 9}), "adam_v": CodecChoice(codec_id="zstd/1", params={"level": 9}), } ) save_state(state, "optimizer.jbr", assign=assigner) with Archive.open("optimizer.jbr") as archive: for role, codec in sorted({(s.meta.role, s.codec) for s in archive.stats()}): print(role, codec) ``` ```{testoutput} adam_m zstd/1 adam_v zstd/1 step bytegroup-zstd/1 ``` The first and second moments use `zstd/1` at level 9. The mapping does not list `step`, so the default assigner gives those tensors `bytegroup-zstd/1`. `params` holds the codec's parameters. The codec's `Params` model checks them, and its defaults fill in what you leave out. The archive records the codec id and the full parameters of each tensor, so a reader builds the same codec. {doc}`../reference/codecs` lists the codecs and their parameters. A choice that names an unknown codec raises `UnknownCodecError`, and parameters that the codec does not accept raise `pydantic.ValidationError`. Both errors are raised when the archive is written, not when you build the assigner. ## The other built-in assigners - `UniformAssigner(choice)` applies one choice to every float tensor and `DefaultAssigner` to the rest. - `RoleAssigner(by_role, default=...)` takes another assigner as `default`, so `RoleAssigner({"weight": ...}, default=UniformAssigner(...))` sends every other role to one codec. A role is any string. The built-in schemas produce `weight`, `adam_m`, `adam_v`, `adam_vmax`, `momentum`, `muon_momentum`, `step`, and `other`. A schema that you write can add more (see {doc}`extend`). ## Choose from the command line `jabara compress` has no option to pick a codec. It uses the default assigner, or `xor-delta/1` against a base when you pass `--base` (see {doc}`delta-checkpoints`). To use a `RoleAssigner`, call `compress_file` or `save_state` from Python. To decide, run `jabara bench`. It runs each candidate codec on every role of a checkpoint and prints one row per candidate and role, so you can compare codecs for the first and the second moments separately: ```console $ jabara bench checkpoint-1000/optimizer.pt --candidates zstd/1,bytegroup-zstd/1 --repeats 1 ... threads, best of 1, 1 warm-up, chunk ... bytes zstd/1 step: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact zstd/1 adam_m: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact zstd/1 adam_v: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact bytegroup-zstd/1 step: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact bytegroup-zstd/1 adam_m: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact bytegroup-zstd/1 adam_v: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact ``` {doc}`compare-codecs` explains the rows. `jabara ls` on an archive shows the codec of every tensor. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/delta-checkpoints.html # Store a checkpoint as a difference against a base A delta archive stores a checkpoint as the difference from an earlier one, its base. This guide assumes that you know `jabara compress` and `jabara decompress` (see the {doc}`../getting-started/tutorial`). A delta codec codes each chunk of a float tensor against the same chunk of the tensor with the same name in the base. The default, `xor-delta/1`, XORs the bytes of the two chunks and codes the result with `bytegroup-zstd/1`. The restore is exact. The base is a full archive, or another delta archive when each checkpoint is coded against the one before it (see "Code each checkpoint against the one before it"). ## Before you start Start in an empty directory. Save [make_checkpoint.py](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_checkpoint.py) there and run it. Like the {doc}`../getting-started/tutorial`, it needs the `torch` extra and `safetensors`. It writes `checkpoint-1000/`, which the examples use. ```console $ python make_checkpoint.py ``` ## Make a second checkpoint Save this script as `make_next_checkpoint.py` (`docs/_snippets/make_next_checkpoint.py` in the clone, or [on GitHub](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_next_checkpoint.py)). It trains three more AdamW steps from `checkpoint-1000` and writes `checkpoint-1100` with the same file names: ```python """Write checkpoint-1100/ by training 3 more AdamW steps from checkpoint-1000/ (run make_checkpoint.py first).""" import json from pathlib import Path import torch from safetensors.torch import load_file, save_file torch.manual_seed(1) model = torch.nn.Sequential(torch.nn.Linear(256, 256), torch.nn.ReLU(), torch.nn.Linear(256, 256)) model.load_state_dict(load_file("checkpoint-1000/model.safetensors")) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3) optimizer.load_state_dict(torch.load("checkpoint-1000/optimizer.pt", weights_only=True)) for _ in range(3): batch = torch.randn(32, 256) optimizer.zero_grad() torch.nn.functional.mse_loss(model(batch), batch).backward() optimizer.step() checkpoint = Path("checkpoint-1100") checkpoint.mkdir(exist_ok=True) save_file(model.state_dict(), checkpoint / "model.safetensors") torch.save(optimizer.state_dict(), checkpoint / "optimizer.pt") (checkpoint / "trainer_state.json").write_text(json.dumps({"global_step": 1100})) ``` ```console $ python make_next_checkpoint.py ``` ## Use the command line Compress the earlier checkpoint on its own and keep the file. Compress the later one against that archive. Restore it with the same `--base`, then compare the codecs on it: ```console $ jabara compress checkpoint-1000/model.safetensors --keep checkpoint-1000/model.safetensors.jbr: ... -> ... bytes (...% of original) $ jabara compress checkpoint-1100/model.safetensors --base checkpoint-1000/model.safetensors.jbr checkpoint-1100/model.safetensors.jbr: ... -> ... bytes (...% of original) $ jabara decompress checkpoint-1100/model.safetensors.jbr --base checkpoint-1000/model.safetensors.jbr checkpoint-1100/model.safetensors $ jabara bench checkpoint-1100/model.safetensors --base checkpoint-1000/model.safetensors.jbr --repeats 1 ... threads, best of 1, 1 warm-up, chunk ... bytes bytegroup-zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact raw/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact sub-delta/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact xor-delta/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact $ jabara bench checkpoint-1100/ --candidates zstd/1,quant8-linear/1 --repeats 1 --json {"bench":1,"environment":...,"rows":...} ``` 1. The first command keeps `model.safetensors`, because its archive is the base of the next one. 2. The second command writes a delta archive, verifies it, and deletes `checkpoint-1100/model.safetensors`. `--base` takes an archive or a directory (see the next section). The command has no codec option. Float tensors get `xor-delta/1`, and the rest get `zstd/1`. 3. `decompress` needs the same base, and so does `verify`. `decompress` writes the original file back and deletes the archive. 4. With `--base`, `bench` adds the delta codecs to the candidates. A `zipnn/1` row follows `xor-delta/1` only when the optional `zipnn` package is installed. Without it, `bench` prints `jabara: skipped zipnn/1: ...` on stderr. 5. The second `bench` reads a directory, runs the two named codecs, and prints the report as one line of JSON with the keys `bench`, `environment`, and `rows`. `...` stands for the parts that differ from run to run. A lossy candidate such as `quant8-linear/1` needs no opt-in, because `bench` writes no archive. The base for `bench` can be any path that `bench` reads: an archive, a safetensors file, a torch file, or a directory. To compare only some codecs, name them: ```console $ jabara bench checkpoint-1100/model.safetensors --base checkpoint-1000/model.safetensors.jbr --candidates xor-delta/1,bytegroup-zstd/1 --repeats 1 ... threads, best of 1, 1 warm-up, chunk ... bytes xor-delta/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact bytegroup-zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact ``` ## Compress a whole checkpoint directory Give `--base` the directory of the earlier checkpoint to code every file of the later one against it. Every checkpoint file in the base directory needs its archive. `checkpoint-1000/model.safetensors.jbr` is there from the previous section, so compress the optimizer state too: ```console $ jabara compress checkpoint-1000/optimizer.pt --keep checkpoint-1000/optimizer.pt.jbr: ... -> ... bytes (...% of original) $ jabara compress checkpoint-1100 --base checkpoint-1000 checkpoint-1100/model.safetensors.jbr: ... -> ... bytes (...% of original) checkpoint-1100/optimizer.pt.jbr: ... -> ... bytes (...% of original) $ jabara decompress checkpoint-1100 --base checkpoint-1000 checkpoint-1100/model.safetensors checkpoint-1100/optimizer.pt ``` - Each tensor is coded against the tensor of the same name, dtype, and shape in any archive of the base directory. The two checkpoints may therefore split their weights over files differently, as when a model is saved with another `max_shard_size`. - The base directory must be compressed. A checkpoint file there without its archive is refused before anything is written. - `decompress` and `verify` take the same directory and find each base archive by the CRC-32 of its index. If one is missing or changed, they name it, exit with status 1, and leave every file as it was. - A single file takes a base directory too: `jabara compress checkpoint-1100/optimizer.pt --base checkpoint-1000`. ## Code a whole run against its first checkpoint A training run leaves `checkpoint-1000`, `checkpoint-1100`, and more in one directory. `--recursive` takes them all, and `--delta first` stores the first one as full archives and every other one as a delta against it: ```text $ jabara compress run --recursive --delta first $ jabara verify run --recursive $ jabara decompress run --recursive ``` `verify --recursive` and `decompress --recursive` find the base archives among the archives of the other checkpoints, and `decompress --recursive` restores the first checkpoint last. With `first`, every delta archive names a full archive. Add `--dry-run` to `compress` to see what it would do. The {doc}`../reference/cli` page has the details: the order of the checkpoints, the line that a failure prints, and the skipped checkpoints that let you run a command again. Keep the first checkpoint for as long as you need the others. Do not delete or move it while they are compressed. `decompress` of the first checkpoint on its own is refused until the others are restored, or until you pass `--keep`. The Hugging Face adapter can write the same layout, and keeps the first checkpoint when the `Trainer` rotates old ones (see {doc}`hugging-face-trainer`). ## Code each checkpoint against the one before it `--delta previous` codes each checkpoint against the checkpoint before it, so the archives form a chain: the second is a delta of the first, the third a delta of the second, and so on. The commands are the same as for `first`: ```text $ jabara compress run --recursive --delta previous $ jabara verify run --recursive $ jabara decompress run --recursive ``` A checkpoint added to the run later is coded against the last one by the next `compress --recursive --delta previous`. The archive format has no new field: each archive names only its own base, and a reader follows the chain by those names and index CRC-32 values. Jabara 0.1.0 never writes a chain. What a chain costs: - A restore follows the chain. Restoring the checkpoint at position *k* decodes *k* archives per tensor, and `decompress --recursive` and `verify --recursive` of a whole parent decode about *n*²/2 archives per tensor for *n* checkpoints. With `first` a restore decodes one extra archive per tensor, whichever checkpoint it restores. - One lost or damaged archive loses every checkpoint after it. With `first`, only the first checkpoint is that important. - `decompress` of a checkpoint that a later one is coded against is refused until the later ones are restored, or until you pass `--keep`. To restore the last checkpoint alone, give the one before it as the base, and Jabara finds the rest of the chain beside it: `jabara decompress run/checkpoint-3000 --base run/checkpoint-2000`. - A broken link stops the command before it restores or deletes anything, and the message names the missing archive: `jabara: : : base (index crc ) is missing or changed` for a link behind the archive's own base, where `` is the archive that was written against it. When to use which. `previous` is smaller when the run keeps drifting away from its first checkpoint, as these measurements show. Use it when most checkpoints are rarely read and disk is the constraint, and keep a long run as several parents so that no chain gets long. Use `first` when any checkpoint may be needed at any time, or when you cannot risk the chain. Illustrative measurements, not Jabara's benchmark. Setup: one Apple silicon laptop, Python 3.13, two threads, eight checkpoints per run, every archive written with the default delta codec, each size and time measured once (the restore time is the median of three runs, with the files already in the cache). The two synthetic runs hold three 1024 by 1024 matrices drawn from a normal distribution with standard deviation 0.02, and every checkpoint adds a normal step with standard deviation 0.0001 to every element of the one before, as `float32` or as `bfloat16`. The third run trains a four-layer GPT-2 with 192-wide layers and a 2048-token vocabulary, initialised at random, on 64 fixed random token sequences with AdamW at a learning rate of 0.0001, saving `model.safetensors` and `optimizer.pt` every 10 steps. Sizes are the bytes of the archives over the bytes of the files; restore is `jabara decompress` of the last checkpoint, and verify is `jabara verify --recursive` of the whole run. | Run (files of all eight checkpoints) | Coding | Stored, % of the files | Restore the last checkpoint, s | Verify the whole run, s | | --- | --- | --- | --- | --- | | `float32` steps, 101 MB | full | 85.5 | 0.02 | 0.08 | | | `first` | 69.6 | 0.04 | 0.21 | | | `previous` | 67.6 | 0.13 | 0.53 | | `bfloat16` steps, 50 MB | full | 71.1 | 0.02 | 0.06 | | | `first` | 39.2 | 0.03 | 0.15 | | | `previous` | 35.3 | 0.10 | 0.40 | | GPT-2 with optimizer, 210 MB | full | 83.8 | 0.04 | 0.22 | | | `first` | 82.2 | 0.10 | 0.58 | | | `previous` | 79.2 | 0.45 | 1.85 | In every run `previous` stores less than `first`, by 2 percentage points (`float32`), 4 (`bfloat16`), and 3 (GPT-2), and its restore time grows with the length of the chain: for the last of eight checkpoints it is 5 to 11 times that of full coding, against 1.5 to 2.5 times for `first`. The GPT-2 run changes every weight by a large step between saves, so deltas help little; a run that changes less between saves gains more. The sizes depend on the step between checkpoints and on the dtype, so measure your own checkpoints with `jabara bench CHECKPOINT --base EARLIER`. ## Use Python `compress_file`, `decompress_file`, `compress_dir`, and `decompress_dir` take `base` as the path of an archive or a directory, and `save_state` and `load_state` take it as an open `Archive` or a list of them. This example stores the optimizer state of the later checkpoint against the earlier one: ```{testsetup} import runpy runpy.run_path(f"{SNIPPETS}/make_checkpoint.py") runpy.run_path(f"{SNIPPETS}/make_next_checkpoint.py") ``` ```{testcode} import torch from jabara.assign import CodecChoice, UniformAssigner from jabara.container import Archive from jabara.torch import load_state, save_state earlier = torch.load("checkpoint-1000/optimizer.pt", weights_only=True) later = torch.load("checkpoint-1100/optimizer.pt", weights_only=True) save_state(earlier, "optimizer-1000.jbr") delta = UniformAssigner(CodecChoice(codec_id="xor-delta/1", fallback=CodecChoice(codec_id="bytegroup-zstd/1"))) with Archive.open("optimizer-1000.jbr") as base: save_state(later, "optimizer-1100.jbr", assign=delta, base=base) restored = load_state("optimizer-1100.jbr", base=base) print(all( torch.equal(restored["state"][i][key], later["state"][i][key]) for i in later["state"] for key in later["state"][i] )) ``` ```{testoutput} True ``` Give a delta `CodecChoice` a `fallback` for the tensors that the base cannot supply (see "Tensors the base does not match" below). Without one, the write raises `MissingBaseError` for such a tensor. ## What the archive records about its base A delta archive records the file name of its base, without the directory, and the CRC-32 of the base's index. When its tensors refer to several base archives, it records a list of them and is archive format 2, which Jabara 0.1.0 refuses with `ArchiveFormatError`. `jabara ls` does not show them, so read them from the index with `base_refs()`, which gives a list in either case: ```{testcode} with Archive.open("optimizer-1100.jbr") as archive, Archive.open("optimizer-1000.jbr") as base: (ref,) = archive.index.base_refs() print(ref.name) print(ref.index_crc == base.index_crc) ``` ```{testoutput} optimizer-1000.jbr True ``` A reader checks the CRC, not the name, so you can rename or move the base archive. An archive in which no tensor ended up as a delta records no base and needs none. ## When the base is missing or different ```{testcode} from jabara.errors import JabaraError other = {key: value + 1 for key, value in earlier["state"][0].items()} save_state(other, "other.jbr") for base_path in [None, "other.jbr"]: base = None if base_path is None else Archive.open(base_path) try: load_state("optimizer-1100.jbr", base=base) except JabaraError as error: print(type(error).__name__) finally: if base is not None: base.close() ``` ```{testoutput} MissingBaseError BaseMismatchError ``` - With no base, reading a delta tensor raises `MissingBaseError`. On the command line, `decompress` and `verify` print `jabara: : tensor '' is a delta and needs its base archive` and exit with status 1. - With a base whose index CRC differs from the recorded one, opening the archive raises `BaseMismatchError` with both CRC values. Use the archive that the checkpoint was written against. - Writing against a base that is a delta archive opened without its own base raises `BaseMismatchError`: decoding the base needs its base. Open it with its base (`Archive.open(delta, base=...)`), or give a directory, where the command line and `jabara.files` find the base of a delta archive among the archives beside it. A base that is missing then raises `BaseMismatchError` naming the archive written against it and the base it lacks. Keep the base archive for as long as you need the archives that refer to it. Without it, they cannot be read. ## Tensors the base does not match A base tensor is the reference for a tensor when the name, the dtype, and the shape are equal. The role plays no part. A tensor without a reference uses the choice's `fallback`, and the archive records the fallback codec for it: ```{testcode} earlier = {"a": torch.randn(64), "b": torch.randn(64)} later = {"a": torch.randn(64), "b": torch.randn(32), "c": torch.randn(64)} save_state(earlier, "small-1.jbr") with Archive.open("small-1.jbr") as base: save_state(later, "small-2.jbr", assign=delta, base=base) with Archive.open("small-2.jbr") as archive: for stat in archive.stats(): print(stat.meta.name, stat.codec) ``` ```{testoutput} a xor-delta/1 b bytegroup-zstd/1 c bytegroup-zstd/1 ``` `b` changed shape and `c` is new, so both use the fallback. On the command line, the fallback is `bytegroup-zstd/1` for float tensors, and the other tensors use `zstd/1`. `jabara.bench.compare` counts these tensors in `fallback_tensors`. A delta candidate that finds a reference for none of its tensors raises `MissingBaseError`, because its row would measure only the fallback. {doc}`compare-codecs` explains the rows. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/lossy.html # Opt in to a lossy codec and read the recorded error Jabara is lossless unless you opt in. A lossy codec (`quant8-linear/1` or `quant8-log/1`) stores a float tensor as 8-bit codes, so the restored tensor is close to the saved one but not equal to it. A run resumed from lossy optimizer state is not a bit-exact continuation of the run that saved it. This guide assumes that you can pick codecs per role (see {doc}`choose-codecs`). ## Before you start Start in an empty directory. Save [make_checkpoint.py](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_checkpoint.py) there and run it. Like the {doc}`../getting-started/tutorial`, it needs the `torch` extra and `safetensors`. It writes `checkpoint-1000/`, which the examples use. ```console $ python make_checkpoint.py ``` ## Opt in with `allow_lossy` An assigner that picks a lossy codec makes the write raise `LossyNotAllowedError`, and no archive appears under the final name: ```{testsetup} import runpy runpy.run_path(f"{SNIPPETS}/make_checkpoint.py") ``` ```{testcode} import os import torch from jabara.assign import CodecChoice, RoleAssigner from jabara.errors import LossyNotAllowedError from jabara.torch import save_state state = torch.load("checkpoint-1000/optimizer.pt", weights_only=True) assigner = RoleAssigner( {"adam_m": CodecChoice(codec_id="quant8-linear/1"), "adam_v": CodecChoice(codec_id="quant8-log/1")} ) try: save_state(state, "lossy.jbr", assign=assigner) except LossyNotAllowedError as error: print(error) print(os.path.exists("lossy.jbr")) ``` ```{testoutput} tensor 'state/0/exp_avg': codec quant8-linear/1 is lossy False ``` Pass `allow_lossy=True` to confirm the choice. Tensors that the assigner gives a lossless codec stay lossless. Here the `step` tensors keep `bytegroup-zstd/1`: ```{testcode} save_state(state, "lossy.jbr", assign=assigner, allow_lossy=True) ``` The other entry points handle the opt-in as follows: - `compress_file`, `compress_dir`, and `write_archive` take `allow_lossy` and `assign`. - `jabara.hf.attach(trainer, assign=..., allow_lossy=True)` applies to every checkpoint. Without `allow_lossy`, the error propagates out of `Trainer.train`. - `JabaraCheckpointIO` has no `allow_lossy` and never writes a lossy tensor. - `jabara compress` cannot pick a lossy codec. - `jabara bench` runs lossy candidates without an opt-in, because it writes no archive. A lossy row does not mean that `compress` accepts the codec. ## What the two codecs bound Both codecs quantize each chunk on its own and need a float dtype (`float16`, `bfloat16`, `float32`, or `float64`). Decoding is deterministic: a payload decodes to the same bytes on every machine. Encoding with `quant8-log/1` can differ between platforms, because it builds its table with the platform's `log` and `exp`. The same input can then give a different payload, and a different file. A chunk with NaN, an infinity, or a value range that overflows `float64` raises `NonFiniteError`. Nothing is clamped. - `quant8-linear/1` places up to 256 levels evenly between the chunk's minimum and maximum. The error bound depends on the chunk's range, so one large value in a chunk raises the error of all its small values. - `quant8-log/1` places levels evenly on the logarithm of the magnitude, and stores the sign and exact zeros separately. The error bound grows with each value's magnitude, so a small value's error stays small next to the value. {doc}`../reference/codecs` gives the exact bounds and the payload layouts. ## Read the recorded error The writer decodes each lossy chunk once, compares it with the input, and stores the largest absolute difference over the tensor as `max_abs_err`. A lossless tensor stores `None`. The value is in the tensor's own units, so compare it with the tensor's scale, not with the value of another tensor: ```{testcode} from jabara.container import Archive from jabara.torch import load_state restored = load_state("lossy.jbr") with Archive.open("lossy.jbr") as archive: for stat in archive.stats()[:3]: print(stat.meta.name, stat.codec, stat.lossless, stat.max_abs_err is None) stat = archive.stats()[1] difference = (restored["state"][0]["exp_avg"].double() - state["state"][0]["exp_avg"].double()).abs().max() print(float(difference) == stat.max_abs_err) ``` ```{testoutput} state/0/step bytegroup-zstd/1 True True state/0/exp_avg quant8-linear/1 False False state/0/exp_avg_sq quant8-log/1 False False True ``` The last line shows that `max_abs_err` equals the measured difference between the saved and the restored tensor. `jabara ls --json` gives the same fields for each tensor, `lossless` and `max_abs_err`, but the text output of `jabara ls` does not. `jabara bench` prints `max_abs_err=` on a lossy row, and marks the row `NOT EXACT` when its tensors do not decode bit for bit. ## What `verify` checks For a lossy tensor, the checksum of each chunk is the CRC-32 of the decoded bytes, not of the original bytes. `Archive.verify()` and `jabara verify` decode every chunk and check that checksum. A pass means that the archive is intact and decodes to the values that the writer measured. It cannot tell how close those values are to the original, because the archive does not hold the original. The recorded `max_abs_err` tells you that. ```{testcode} with Archive.open("lossy.jbr") as archive: archive.verify() ``` --- Source: https://jabara.iamtatsuki05.com/docs/how-to/export-weights.html # Export weights to a standard safetensors file You can write the weights in a Jabara archive to a safetensors file that any tool can load, without restoring the whole checkpoint. `jabara export-weights ARCHIVE OUT` and `jabara.files.export_weights(archive_path, out)` write the tensors with the role `weight`. The command refuses an `OUT` that exists: it prints `jabara: OUT: already exists` and exits with status 1. `export_weights` replaces an existing `out` file without an error. ## Before you start Start in an empty directory. Save [make_checkpoint.py](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_checkpoint.py) there and run it. Like the {doc}`../getting-started/tutorial`, it needs the `torch` extra and `safetensors`. It writes `checkpoint-1000/`, which the examples use. ```console $ python make_checkpoint.py ``` ## Export an archive of a safetensors file Every tensor of an archive made from a `*.safetensors` file has the role `weight`, and the archive keeps the file's header, so the output is the original file, byte for byte. The archive stays in place. If `checkpoint-1000/model.safetensors.jbr` already exists, skip the first command, because `jabara compress` refuses a directory that holds both a file and its archive: ```console $ jabara compress checkpoint-1000/model.safetensors --keep checkpoint-1000/model.safetensors.jbr: ... -> ... bytes (...% of original) $ jabara export-weights checkpoint-1000/model.safetensors.jbr exported.safetensors ``` `export-weights` prints nothing. To share the model while the checkpoint stays compressed, run it on the `model.safetensors.jbr` that the Hugging Face `Trainer` adapter writes. In Python, make the same call and check that the file equals the original: ```{testsetup} import runpy runpy.run_path(f"{SNIPPETS}/make_checkpoint.py") ``` ```{testcode} import filecmp from jabara.files import compress_file, export_weights compress_file("checkpoint-1000/model.safetensors", keep=True) export_weights("checkpoint-1000/model.safetensors.jbr", "exported.safetensors") print(filecmp.cmp("checkpoint-1000/model.safetensors", "exported.safetensors", shallow=False)) ``` ```{testoutput} True ``` A second call with the same `out` replaces the file: ```{testcode} from pathlib import Path Path("exported.safetensors").write_bytes(b"not a safetensors file") export_weights("checkpoint-1000/model.safetensors.jbr", "exported.safetensors") print(filecmp.cmp("checkpoint-1000/model.safetensors", "exported.safetensors", shallow=False)) ``` ```{testoutput} True ``` ## Export from `save_state` For any other archive, the output holds the tensors with the role `weight`, under their archive names and in archive order, and leaves out the rest. Save a model's `state_dict` with `WeightsSchema` so that every tensor has that role (see {doc}`pytorch-loop`): ```{testcode} import torch from safetensors.torch import load_file from jabara.schemas import WeightsSchema from jabara.torch import save_state model = torch.nn.Linear(4, 2) save_state(model.state_dict(), "model.jbr", schema=WeightsSchema()) export_weights("model.jbr", "linear.safetensors") exported = load_file("linear.safetensors") print(sorted(exported)) print(all(torch.equal(exported[name], tensor) for name, tensor in model.state_dict().items())) ``` ```{testoutput} ['bias', 'weight'] True ``` The header is padded with spaces to a multiple of 8 bytes. A dtype that safetensors cannot hold raises `UnsupportedDtypeError`. ## When there is nothing to export An archive with no `weight` tensor raises `ArchiveFormatError`, and the command prints `jabara: : no tensors with role 'weight'` and exits with status 1. By default, two kinds of archive have none: - The archive of `optimizer.pt`, whose tensors are optimizer state. - The archive that `jabara compress` makes of a `.pt` or `.pth` file. `compress` gives those files the optimizer roles, so the tensors of a model `state_dict` get the role `other`. For a `.pt` file, load it and call `save_state` with `WeightsSchema` as above. `export-weights` takes no base, so it cannot read a delta archive (see {doc}`delta-checkpoints`). --- Source: https://jabara.iamtatsuki05.com/docs/how-to/run-from-a-config-file.html # Run from a config file A run that you repeat, such as the compression of every checkpoint of a sweep, is easier to review and to share when its options sit in a file. Every command that has options takes `--config FILE`, where `FILE` is JSON (`.json`), YAML (`.yaml` or `.yml`), or TOML (`.toml`). The options on the command line win over the file, and the file wins over the defaults. ## Before you start Start in an empty directory. Save [make_checkpoint.py](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_checkpoint.py) there and run it. Like the {doc}`../getting-started/tutorial`, it needs the `torch` extra and `safetensors`. It writes `checkpoint-1000/`, which the examples use. Save the three files below next to it: [config-compress.toml](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/config-compress.toml), [config-verify.json](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/config-verify.json), and [config-bench.yaml](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/config-bench.yaml). ```console $ python make_checkpoint.py ``` ## Write the file The keys of a file are the long names of the options of the command, with underscores, and the names of its positional arguments. `compress` takes `path`, `keep`, `threads`, and `base`. A TOML file: ```toml path = "checkpoint-1000" keep = true threads = 2 ``` The same keys in JSON, for `verify`: ```json { "path": "checkpoint-1000", "threads": 2 } ``` And in YAML, for `bench`. A list of strings is how a file names `candidates`: ```yaml path: checkpoint-1000/model.safetensors candidates: [raw/1, zstd/1] repeats: 1 ``` Reading YAML needs PyYAML, which the `yaml` extra installs: `pip install ".[yaml]"` from the clone. JSON and TOML need nothing more. Python 3.10 reads TOML with `tomli`, which Jabara installs for it. ## See the settings, then run `--show-config` prints the settings that the command would use, as JSON, and exits. It runs nothing, so it is safe to try on a new file: ```console $ jabara compress --config config-compress.toml --show-config { "command": "compress", "config": "config-compress.toml", "settings": { "base": null, "delta": null, "dry_run": false, "keep": true, "path": "checkpoint-1000", "recursive": false, "threads": 2 } } ``` Without it, the command runs as if you had written the options on the command line: ```console $ jabara compress --config config-compress.toml checkpoint-1000/model.safetensors.jbr: ... -> ... bytes (...% of original) checkpoint-1000/optimizer.pt.jbr: ... -> ... bytes (...% of original) $ jabara verify --config config-verify.json ok checkpoint-1000/model.safetensors.jbr ok checkpoint-1000/optimizer.pt.jbr $ jabara bench --config config-bench.yaml ... threads, best of 1, 1 warm-up, chunk ... bytes raw/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact ``` ## Override a value on the command line An option on the command line replaces the same key of the file, wherever `--config` stands. Positional arguments fill from the left: a path on the command line replaces `path`, and the file supplies the ones that you leave out. One file can serve many runs: ```console $ jabara compress --config config-compress.toml --threads 4 --keep=false --show-config { "command": "compress", "config": "config-compress.toml", "settings": { "base": null, "delta": null, "dry_run": false, "keep": false, "path": "checkpoint-1000", "recursive": false, "threads": 4 } } ``` ## What a file may hold - The whole file is checked even where the command line replaces a value, so a bad value in the file is an error even then. - A key that the command does not have is a usage error, so a misspelled key never goes unnoticed. `config` and `show_config` are not keys. - A value must have the type of its option: a string for a path, an integer for a count such as `threads`, `true` or `false` for a switch such as `keep`, a list of strings for `candidates`. A value of the wrong type, such as `threads = "2"`, or one that the option refuses, such as `threads = 0`, is a usage error. So is `null`. - A suffix other than `.json`, `.yaml`, `.yml`, and `.toml`, a file that does not parse, and a top level that is not a mapping are usage errors too. - A usage error from a file prints one line, `jabara: : `, names the key where there is one, runs nothing, and exits with status 2. A file that is missing or unreadable exits with status 1, as any missing input does. A YAML file without PyYAML exits with status 1 and says how to install it. - Only `compress`, `decompress`, `ls`, `verify`, `export-weights`, `bench`, and `codecs` take `--config`. `help` and `man` have no options to set. - A file holds the options of one command. To run several commands, call `jabara` once for each. - YAML is read with `safe_load`, so a file cannot build Python objects. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/compare-codecs.html # Compare codecs on your own checkpoint `jabara bench` and `jabara.bench.compare` run candidate codecs on your own tensors. A comparison runs every candidate on the same tensors, with the same chunking and the same thread pool, in memory. It writes no archive and no file. The report has one row for each candidate and role. ## Before you start Start in an empty directory. Save [make_checkpoint.py](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_checkpoint.py) there and run it. Like the {doc}`../getting-started/tutorial`, it needs the `torch` extra and `safetensors`. It writes `checkpoint-1000/`, which the examples use. ```console $ python make_checkpoint.py ``` ## Run it from the command line Name the candidates and set `--repeats`. Without `--candidates`, `bench` runs every lossless codec that needs no base, plus the delta codecs when you pass `--base`. It skips a codec whose optional package is missing and names it in a `jabara: skipped ...` line on stderr. Stdout holds only the report. ```console $ jabara bench checkpoint-1000/model.safetensors --candidates raw/1,zstd/1,bytegroup-zstd/1 --repeats 3 ... threads, best of 3, 1 warm-up, chunk ... bytes raw/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact bytegroup-zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact ``` `--base` adds the delta codecs (see {doc}`delta-checkpoints`), and `--json` prints the report as JSON. `PATH` can be an archive, a safetensors file, a torch file, or a directory. ## Run it from Python `load_records` reads the same inputs as the command, `candidates_for` builds one candidate for each codec id, and `compare` runs them: ```{testsetup} import runpy runpy.run_path(f"{SNIPPETS}/make_checkpoint.py") runpy.run_path(f"{SNIPPETS}/make_next_checkpoint.py") ``` ```{testcode} from jabara.bench import BenchReport, candidates_for, compare from jabara.files import load_records new = load_records("checkpoint-1100/model.safetensors") old = load_records("checkpoint-1000/model.safetensors") candidates = candidates_for(["bytegroup-zstd/1", "xor-delta/1"]) report = compare(new, candidates, base=old, repeats=3, threads=1) for row in report.rows: print(row.candidate, row.role, row.needs_base, row.check_decode, row.bit_exact, row.fallback_tensors) print(report.environment.threads, report.environment.repeats, report.environment.warmup_passes) print(BenchReport.model_validate_json(report.model_dump_json()) == report) ``` ```{testoutput} bytegroup-zstd/1 weight False False True 0 xor-delta/1 weight True False True 0 1 3 1 True ``` `report.model_dump_json()` is the JSON that `jabara bench --json` prints. {doc}`../reference/schemas` gives its JSON schema. ## What the seconds include and exclude `encode_seconds` and `decode_seconds` time the codec's work on the chunks in memory: `Codec.encode`, or `Codec.decode` plus the length and CRC-32 check of each decoded chunk. Throughput is the raw bytes divided by those seconds. The seconds leave out creating the thread pool, building the codecs, joining the chunks, comparing the output, and file access. They are the codec's share of a save or a load, not the time of the whole operation. Two flags mark the rows where a save or a load does more work that no row times: - `needs_base` is true when a tensor of the row uses a delta codec. A save and a load decode the whole base tensor first. - `check_decode` is true when a tensor of the row uses a lossy codec. A save decodes it once more to check it and to compute `max_abs_err`. Every save also computes the CRC-32 of the input and writes the file, and every load reads the file. To time a whole save or load, time `compress_file` and `decompress_file` on your files. ## Warm-up, round order, and repeats Before the first row, each distinct codec and parameter set codes a slice of at most 64 KiB, so that no row pays for starting the pool's threads or for a codec's lazy imports. Then each role runs `warmup_passes` untimed rounds (one) and `repeats` timed rounds. In a round, each candidate in turn encodes and decodes once. The candidate order reverses on every other timed round, so a steady drift in the machine's speed does not favour one candidate in every round. Right before each timed encode and each timed decode, the pool's threads and the calling thread run an untimed busy loop for 0.1 s, which the report records in `spin_seconds`. {doc}`../reference/cli` describes the output line. `encode_seconds` and `decode_seconds` are the smallest of the timed runs, and `encode_seconds_all` and `decode_seconds_all` hold every run in order. Keep these limits in mind: - With `repeats=1`, the one timed round runs in the order that you gave, so a candidate's position affects its time. With an odd `repeats`, one more round runs forward than in reverse. - The warm-up and the order reversal are meant to limit position effects, but their effect has not been measured. If a conclusion rests on a small difference, run each order or repeat the run. - A difference between two candidates that is smaller than the spread of their `_all` lists does not rank them. - `jabara bench` defaults to `--repeats 3`, and `compare` to `repeats=1`. ## Rows that need a second look - **`fallback_tensors`.** The number of tensors for which the candidate chose a delta codec, found no reference in the base, and used its fallback. For those tensors, the row measures the fallback codec. A delta candidate with no reference for any tensor raises `MissingBaseError` instead of producing a row. - **`decode_error`.** A decode pass raised `ChecksumError`. The row keeps the reader's message, `decode_seconds` and `max_abs_err` are `None`, and `bit_exact` is false. A broken codec has no decode time, so it cannot rank as fast. The command prints `decode failed ()` in place of the decode throughput. - **`bit_exact` and `lossless`.** `lossless` is the codec's own flag, and `bit_exact` is recomputed from the decoded bytes. The command exits with status 0 even with a `NOT EXACT` row, so read the lines. - **`stored_bytes`.** The sum of the chunk payload lengths. It leaves out the index and the magic bytes of an archive, so it is not a file size. - **`threads`.** The size of the thread pool that codes the chunks. How a row scales with it is the codec's own behaviour, so compare rows only from reports made with the same `threads`. The report does not measure memory. ## Measure each candidate in its own process for numbers you publish Candidates in one call can change each other's times. One cause is the memory allocator: the memory that one candidate frees decides how many new pages the next one must fault in. The busy loop reduces this effect for some candidates and increases it for others, so one call is still not fair. [DESIGN.md, "Comparison"](https://github.com/iamtatsuki05/jabara/blob/main/DESIGN.md#comparison-jabarabench) gives the sizes of these effects on one machine, with and without the busy loop. A process cannot reset its allocator, so for numbers that you publish, run each candidate in its own process. Each `jabara bench` command is one process, so name one candidate per command: ```console $ jabara bench checkpoint-1000/model.safetensors --candidates zstd/1 --repeats 3 ... threads, best of 3, 1 warm-up, chunk ... bytes zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact $ jabara bench checkpoint-1000/model.safetensors --candidates bytegroup-zstd/1 --repeats 3 ... threads, best of 3, 1 warm-up, chunk ... bytes bytegroup-zstd/1 weight: ... bytes (...% of original), encode ... MB/s, decode ... MB/s, exact ``` Add `--json` to keep each report. Sizes, `bit_exact`, and `decode_error` are the same as in one call with all the candidates. Times still vary from process to process, so run each command more than once and compare the spread before you rank two candidates. ## Timings are not comparable across machines or settings A time depends on the processor, the load on the machine, `threads`, `repeats`, the chunk size, and the library versions. A report's `environment` records them: `cpu_model`, `cpu_count`, `load_average_1m`, `threads`, `repeats`, `warmup_passes`, `spin_seconds`, `chunk_size`, and the versions of Python, `numpy`, `zstandard`, and the optional packages. Compare two reports only when their environments agree on those fields. Sizes do not depend on the machine's speed or load, but they can change with another `zstandard` version, which `environment` also records. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/use-from-an-agent.html # Use Jabara from an AI agent A coding agent runs `jabara` the way a script does: without a terminal, reading the output and the exit status. This page shows how to give an agent the Jabara skill in Claude Code, Codex, GitHub Copilot, Gemini CLI, Cursor, and other agents that read the open Agent Skills format, what the command guarantees to a program that runs it, and what an agent session looks like. ## Install the skill The repository ships one agent skill in [skills/jabara/](https://github.com/iamtatsuki05/jabara/tree/main/skills/jabara): `SKILL.md` and the `reference.md` that it links. It tells the agent when to use Jabara and when not to, the safe order of commands, how to read the results, and the rules that keep a checkpoint from being lost. Both files are plain Markdown, and the agents below are pointed at this one folder; nothing is copied into other places in the repository. Two files make the repository installable as a plugin: `.claude-plugin/` for Claude Code, Codex, and GitHub Copilot, and `.cursor-plugin/` for Cursor. Copilot's own documentation names `.github/plugin/marketplace.json` for a marketplace; Copilot CLI 1.0.117 installed from the `.claude-plugin/` one in the check below. Both point at `skills/`. An agent without a plugin system reads the skill from a folder, and `.agents/skills/` is the folder that most of them share. To use it, copy `skills/jabara/` there, for every project in `~/.agents/skills/jabara/` or for one project in `.agents/skills/jabara/`. | Agent | How the skill gets there | Checked | | --- | --- | --- | | Claude Code | plugin marketplace | not run for this change; this is the path that the manifests were first written for | | Codex | plugin marketplace, or `.agents/skills/` | codex-cli 0.172.0, 2026-12-01: `codex plugin marketplace add`, `codex plugin add`, `codex plugin list` on a local checkout, with a scratch `CODEX_HOME`; the skill landed in the plugin cache | | GitHub Copilot CLI | plugin marketplace, or `.agents/skills/` | Copilot CLI 1.0.117, 2026-12-01: `copilot plugin marketplace add`, `copilot plugin install`, "Installed 1 skill", with a scratch home | | Gemini CLI | `gemini skills install` | Gemini CLI 0.38.2, 2026-12-01: `gemini skills link` and `gemini skills list` listed the skill, with a scratch home; `install` itself, which clones from GitHub, was not run | | Cursor | plugin marketplace, or `.agents/skills/` | not run; the manifest follows the field list in the plugin reference, read 2026-12-01 at the address that cursor.com redirects to (docs.grok.com) | | opencode, Windsurf, Cline, Goose | `.agents/skills/` or the folder in the section below | not run; the folders come from each tool's published documentation, read 2026-12-01 | "Checked" says what was run, on which version, and when. Codex, Copilot CLI, and Gemini CLI answered for the skill in this repository. The agents marked "not run" were not started, so their rows rest on documentation. The VS Code and cloud-agent surfaces of GitHub Copilot were not tried either. ### Claude Code ```text /plugin marketplace add iamtatsuki05/jabara /plugin install jabara@jabara ``` Claude Code loads the skill when a task matches its description, such as compressing or verifying a checkpoint directory. Without the plugin, copy `skills/jabara/` to `~/.claude/skills/jabara/` or to `.claude/skills/jabara/` in one project. ### Codex ```text codex plugin marketplace add iamtatsuki05/jabara codex plugin add jabara@jabara codex plugin list ``` `codex plugin list` shows `jabara@jabara` as installed and enabled. Restart Codex if a session was already open. Without the plugin, copy `skills/jabara/` to `~/.agents/skills/jabara/` or to `.agents/skills/jabara/` in the repository; Codex reads that folder from the working directory up to the repository root. ### GitHub Copilot In the Copilot CLI: ```text copilot plugin marketplace add iamtatsuki05/jabara copilot plugin install jabara@jabara copilot plugin list ``` Copilot also reads skills from `.github/skills/`, `.claude/skills/`, and `.agents/skills/` in a repository, and from `~/.copilot/skills/` and `~/.agents/skills/` for every project. Which of these a surface supports depends on the surface, so check the one you use. ### Gemini CLI ```text gemini skills install https://github.com/iamtatsuki05/jabara.git --path skills/jabara --consent gemini skills list ``` `install` puts the skill in `~/.gemini/skills/`; add `--scope workspace` to put it in the project's `.gemini/skills/` instead. Gemini CLI also reads `.agents/skills/` in the workspace and `~/.agents/skills/`. ### Cursor In Cursor, open Customize, choose the option to add a plugin from a GitHub repository, and enter `iamtatsuki05/jabara`; the repository has the `.cursor-plugin/marketplace.json` that this needs. Without the plugin, copy `skills/jabara/` to `.cursor/skills/jabara/` or `.agents/skills/jabara/` in a project, or to `~/.cursor/skills/jabara/` for every project. ### opencode, Windsurf, Cline, Goose These read a skill from a folder; none of them has a manifest that the repository needs to carry. - opencode: `.agents/skills/`, `.claude/skills/`, or `.opencode/skills/` in a project, and `~/.agents/skills/` or `~/.config/opencode/skills/` for every project. - Windsurf: `.agents/skills/` or `.devin/skills/` in a project, and `~/.agents/skills/` or `~/.config/devin/skills/` for every project. `.windsurf/skills/` is the older folder. - Cline: `.cline/skills/` or `.claude/skills/` in a project, and `~/.cline/skills/` for every project. Cline does not list `.agents/skills/`. - Goose: `.agents/skills/` in a project and `~/.agents/skills/` for every project. Amp and other agents were not checked. If yours reads `SKILL.md` files, put the folder where its documentation says; if it does not, point it at `skills/jabara/SKILL.md`. ## The command contract These hold for every command, and `tests/jabara/test_agent_contract.py` checks them: - No command prompts or reads standard input. Every input is an argument. Every command writes to standard output and standard error and returns, except that `jabara man` opens the `man` pager when standard output is a terminal; when it is not, `jabara man compress` prints the roff source of the page to standard output and exits 0. An agent should use `jabara help COMMAND` instead. - Results go to standard output, and errors and warnings to standard error. The output is the same with or without a terminal, except that on Python 3.14 and later the usage errors are coloured on a terminal; `NO_COLOR=1` turns that off. - The exit status is 0 on success, 1 when the command failed or refused, and 2 for a usage error. With status 1, standard error ends with one line, `jabara: `, which names the file, and standard output is empty, except that `verify` on a directory has already printed `ok` for the archives before the one that failed, and a `--recursive` run has printed the lines of the checkpoints it finished. With status 2, no command ran, and standard error holds the usage line and an error line; bare `jabara` prints the short overview instead, with no error line. - A command that fails or refuses leaves every file as it was. `compress` and `decompress` on a directory are all or nothing. With `--recursive` each checkpoint is all or nothing, and the run stops at the first failure: the checkpoints before it stay done. - `ls --json` prints a list of objects with the keys `path` and `tensors`, and `bench --json` prints one line, a report with the schema in {doc}`../reference/schemas`. The other commands print text lines that start with a path, as {doc}`../reference/cli` describes. - `--help`, `codecs`, and a usage error do not import torch, so they answer in a fraction of a second. Status 1 has many causes: a file that does not exist, a checksum mismatch, a missing base, an output that already exists. Read the message to tell them apart. `compress`, `decompress`, `verify`, and `ls` take `--recursive` for a parent of checkpoint directories, such as a Trainer's `output_dir`. Before a recursive compress, run `jabara compress --dry-run --recursive PATH`: it lists the checkpoints in order and the files, and changes nothing. See {doc}`compress-many-runs` and {doc}`delta-checkpoints`. Only two commands delete files, and only after every output is written and verified: - `compress` deletes the checkpoint files it compressed. - `decompress` deletes the archives it restored. `--keep` keeps them. No other command deletes or overwrites a file. ## Documentation for agents - [llms.txt](https://jabara.iamtatsuki05.com/llms.txt) lists every page of the site and of this documentation with one line each. - [llms-full.txt](https://jabara.iamtatsuki05.com/llms-full.txt) is the English documentation in one Markdown file, generated from the sources, so an agent can read all of it in one request. - `jabara help COMMAND` (or `jabara COMMAND -H`) prints the full help of a command: what it reads, writes, and prints, every option, and examples. Start there. `jabara -h` and `jabara COMMAND -h` print a short form. ## An agent session Start in an empty directory. Save [make_checkpoint.py](https://github.com/iamtatsuki05/jabara/blob/main/docs/_snippets/make_checkpoint.py) there and run it. It needs the `torch` extra and `safetensors`, and writes `checkpoint-1000/`. ```console $ python make_checkpoint.py ``` Asked to save disk space on this checkpoint, an agent that follows the skill first checks the installation, then compresses with `--keep`, so the originals stay until the archives are verified: ```console $ jabara codecs bytegroup-zstd/1 quant8-linear/1 quant8-log/1 raw/1 sub-delta/1 xor-delta/1 zipnn/1 zstd/1 $ jabara compress --keep checkpoint-1000 checkpoint-1000/model.safetensors.jbr: ... -> ... bytes (...% of original) checkpoint-1000/optimizer.pt.jbr: ... -> ... bytes (...% of original) $ jabara verify checkpoint-1000 ok checkpoint-1000/model.safetensors.jbr ok checkpoint-1000/optimizer.pt.jbr ``` Both archives printed `ok`, so the agent deletes `checkpoint-1000/model.safetensors` and `checkpoint-1000/optimizer.pt` by name. `trainer_state.json` was never touched. Had it run `jabara compress checkpoint-1000` without `--keep`, the command would have verified the archives and deleted the originals itself. Run again on the same directory, `jabara compress --keep checkpoint-1000` changes nothing. It exits with status 1 and prints a line such as `jabara: checkpoint-1000: holds both model.safetensors and model.safetensors.jbr; remove one` while the originals are still there, and `jabara: checkpoint-1000: no *.safetensors files or optimizer.pt to compress` once they are gone. The skill tells the agent how to read both. --- Source: https://jabara.iamtatsuki05.com/docs/how-to/extend.html # Add a codec, an assigner, a state schema, or a file format You can add a codec, an assigner, a state schema, or a checkpoint file format without changing the rest of Jabara. Each is a subclass of an abstract base class. The four examples of a codec, an assigner, and a state schema are complete scripts in `examples/extend/` in the clone. Each defines its class, writes an archive in a temporary directory, and checks what it reads back. The repository's tests run all four. A file format is shown with a built-in one and its test. ## Add a codec A codec turns one chunk of one tensor into bytes and back. Subclass `Codec`, set `id` and `lossless`, implement `encode` and `decode`, and register the class with `@register_codec`. This codec splits each chunk into byte planes and compresses each plane with `lzma` from the standard library: ```python """A codec: split each tensor into byte planes and compress every plane with lzma from the standard library.""" import lzma import struct import tempfile from pathlib import Path import numpy as np from jabara.assign import CodecChoice, UniformAssigner from jabara.codecs import Codec, register_codec from jabara.container import Archive, write_archive from jabara.types import TensorMeta, TensorRecord @register_codec class ByteGroupLzma(Codec): id = "bytegroup-lzma/1" lossless = True def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes: planes = np.frombuffer(data, dtype=np.uint8).reshape(-1, meta.itemsize).T packed = [lzma.compress(plane.tobytes()) for plane in planes] return struct.pack(f"<{len(packed)}Q", *map(len, packed)) + b"".join(packed) def decode(self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) -> bytes: size = meta.itemsize lengths = struct.unpack(f"<{size}Q", payload[: 8 * size]) out, pos = np.empty((size, raw_length // size), dtype=np.uint8), 8 * size for i, n in enumerate(lengths): out[i] = np.frombuffer(lzma.decompress(payload[pos : pos + n]), dtype=np.uint8) pos += n return np.transpose(out).tobytes() weights = np.random.default_rng(0).standard_normal((64, 64)).astype("/`. The archive stores it, and a reader looks up the codec by it. Change the version when the payload format changes. `register_codec` raises `ValueError` for an id that is already registered, so import a module that registers a codec only once. - `meta` gives the tensor's dtype, shape, and role, so the codec can choose a strategy from them. `data` and `payload` are `memoryview` objects, and `encode` returns `bytes`. - `decode` returns `bytes`, a new `bytearray`, or a `memoryview` of unsigned bytes (format `B`, one contiguous dimension) over a new buffer, which the caller then owns. Any other type raises `TypeError` that names the codec, and so does a `memoryview` that is not one-dimensional, of format `B`, and contiguous, such as `arr.data` of a `float32` array or a strided view. - A codec that builds its output in a `bytearray` or a NumPy array can return it without a copy. This matters on the thread pool, because a copy of a whole chunk holds the GIL, and the pool's threads then copy one chunk at a time. - For a lossless codec, `decode(encode(x))` must return the same bytes as `x` for every chunk whose length is a multiple of `meta.itemsize`, including a chunk of length zero. `decode` receives `raw_length`, the length of the bytes that it must return. - Jabara codes chunks on a thread pool, the chunks of different tensors at the same time, and several threads can call one codec instance at the same time. Keep no per-call state on `self`. - A lossy codec sets `lossless = False` and must be deterministic: the same payload always decodes to the same bytes. The writer then needs `allow_lossy=True` (see {doc}`lossy`). - A delta codec sets `needs_ref = True` and receives the same chunk of the base tensor as `ref` (see {doc}`delta-checkpoints`). The `jabara` command knows only the built-in codecs. A codec that your module registers works in Python code that imports the module, with `write_archive`, `save_state`, and `jabara.bench.compare`. ## Add a codec with parameters A codec declares its settings as a nested `Params` model, a pydantic `BaseModel` with `frozen=True` and `extra="forbid"`, and reads them from `self.params`. This codec compresses each chunk with `zlib` from the standard library and takes the compression level as a parameter: ```python """A codec with a validated parameter: zlib from the standard library, with its compression level as a `Params`.""" import tempfile import zlib from pathlib import Path import numpy as np from pydantic import BaseModel, JsonValue, ValidationError from jabara.assign import CodecChoice, UniformAssigner from jabara.codecs import Codec, register_codec from jabara.container import Archive, write_archive from jabara.types import TensorMeta, TensorRecord @register_codec class ZlibCodec(Codec): id = "zlib/1" lossless = True class Params(BaseModel, frozen=True, extra="forbid"): level: int = 6 params: Params def encode(self, data: memoryview, meta: TensorMeta, ref: memoryview | None = None) -> bytes: return zlib.compress(data, self.params.level) def decode(self, payload: memoryview, meta: TensorMeta, raw_length: int, ref: memoryview | None = None) -> bytes: return zlib.decompress(payload) weights = np.random.default_rng(0).standard_normal((64, 64)).astype(" CodecChoice: if meta.role.startswith("adam_"): return CodecChoice(codec_id="quant8-linear/1") # lossy: write_archive needs allow_lossy=True return CodecChoice(codec_id="bytegroup-zstd/1") rng = np.random.default_rng(0) arrays = { role: (rng.standard_normal(4096) * scale).astype(" str: return ROLES.get(str(path[-1]), "other") if path else "other" state = { "state": { 0: {"step": np.array([10], " str | None: """The Jabara dtype name of a little-endian (or single-byte) NumPy dtype, or None for any other dtype.""" if dtype.byteorder == ">" or dtype.hasobject or dtype.fields is not None or dtype.subdtype is not None: return None name = dtype.name return name if name in DTYPE_ITEMSIZE and np.dtype(name).itemsize == dtype.itemsize else None def array_span(raw: mmap.mmap, start: int, end: int, name: str, bad: Callable[[str], ArchiveFormatError]) -> Span: """The array of the `.npy` bytes `raw[start:end]`, named `name`: role `weight` for a float array, and `uint8` with role `other` for a dtype Jabara does not carry (its bytes are kept as they are).""" if raw[start : start + 6] != _MAGIC or end - start < 10: # noqa: PLR2004 - the magic, version, and length raise bad(f"{name} is not a .npy array") version = raw[start + 6] if version not in _VERSIONS: raise bad(f"{name} is a .npy array of version {version}, which Jabara does not know") size = 2 if version == 1 else 4 # the header length is a uint16 in version 1, a uint32 later begin = start + 8 + size + int.from_bytes(raw[start + 8 : start + 8 + size], "little") if begin > end: raise bad(f"{name} has a .npy header longer than the array") try: header = ast.literal_eval(raw[start + 8 + size : begin].decode("latin1")) dtype, shape = np.dtype(header["descr"]), tuple(int(n) for n in header["shape"]) fortran = bool(header.get("fortran_order")) except (ValueError, TypeError, KeyError, SyntaxError, MemoryError, RecursionError, OverflowError) as e: raise bad(f"{name} has a .npy header that does not parse ({type(e).__name__})") from e known = dtype_name(dtype) if known is None or any(n < 0 for n in shape) or int(np.prod(shape)) * dtype.itemsize != end - begin: meta = TensorMeta(name=name, dtype="uint8", shape=(end - begin,), role="other") else: # A Fortran-order array is recorded with its shape but its bytes in column order: no role invites a lossy # codec that would read them in row order. role = "weight" if known in FLOAT_DTYPES and not fortran else "other" meta = TensorMeta(name=name, dtype=known, shape=shape, role=role) return Span(begin, end, meta) @register_format class Npy(CheckpointFormat): """A NumPy `.npy` file: one array.""" kind = "npy" names = ("*.npy",) in_directory = () frameworks = (("NumPy", "*.npy"),) def split(self, path: Path) -> Split: raw = splice.open_map(path, "a .npy file") def bad(msg: str) -> ArchiveFormatError: return ArchiveFormatError(f"{path}: {msg}") span = array_span(raw, 0, len(raw), "array", bad) return Split(*splice.cut(path, raw, [span])) def join( self, source: dict[str, JsonValue], remainder: bytes, tensors: Iterable[bytes], out: Path, *, exact: bool ) -> None: splice.join(source, remainder, tensors, out, exact=exact) ``` Its test writes a file with `np.save`, compresses and restores it, and compares the bytes: ```python @pytest.mark.parametrize( "array", [ rng.standard_normal((16, 8)).astype(" None: path = tmp_path / "array.npy" np.save(path, array) ((dtype, shape, role),) = round_trip(path).values() if array.dtype.byteorder == ">": assert (dtype, role) == ("uint8", "other") else: fortran = array.ndim > 1 and array.flags.f_contiguous and not array.flags.c_contiguous assert (shape, role) == (array.shape, "weight" if array.dtype.kind == "f" and not fortran else "other") ``` - `kind` is stored in the archive index, and `decompress_file` finds the format by it, so never change it. `register_format` raises `ValueError` for a kind or a name pattern that is already registered. - `names` are the `fnmatch` patterns of a file that is named on its own. `in_directory` are the patterns of the files that `compress_dir` and `jabara compress DIR` take from a checkpoint directory; leave out files that a checkpoint keeps beside its tensors, such as a scheduler state. `Npy` takes none, because a directory may hold `.npy` files that are data, not a checkpoint. - `split` finds where each tensor sits in the file as a `Span` and hands the spans to `jabara.formats.splice.cut`, which returns the records, the `source` that the archive index stores, and every other byte of the file as the `remainder`. Jabara stores the remainder as one more tensor, `(remainder)`, always losslessly. `join` hands them to `splice.join`, which writes the file back. A format can also build a `Split` itself. - `split` must not run code that the file holds. `Npy` reads the header, a Python literal, with `ast.literal_eval`, which runs no code. An array of Python objects is a pickle; its bytes are kept as `uint8` and never read as objects. - `join(split(f))` must rebuild `f` byte for byte when the tensors come back bit for bit. `exact` tells `join` whether they did: it is false when a lossy codec stored some tensor. A file with checksums of its own, such as a zip, passes where it records them to `cut` (`Span.crc_at`, `Checksum`), and `splice.join` rewrites them after a lossy restore. - The `jabara` command knows only the built-in formats, which {doc}`../reference/formats` lists with the size of each entry. A format that your module registers works in Python code that imports the module, with `compress_file`, `decompress_file`, `compress_dir`, and `load_records`. --- Source: https://jabara.iamtatsuki05.com/docs/explanation/use-cases.html # Who Jabara is for Jabara is for training checkpoints that you keep and read back later, to resume a run or to analyse it. It is not a format to serve a model from or to load a model from again and again. A checkpoint that can resume training holds the weights and the optimizer state. With Adam and FP32 tensors, the two moments take twice the bytes of the weights. A run saves such a checkpoint many times, and a sweep of N runs that each keep K checkpoints stores N × K of them. ## What it saves and what it costs On 12 checkpoints of four fine-tuning runs of SmolLM2-135M, SmolLM2-360M, and Qwen2.5-0.5B, with FP32 weights and optimizer state, the lossless codecs that need no base, apart from `raw/1`, stored the tensors in 82.9% (`zipnn/1`) to 92.1% (`zstd/1`) of their bytes. The default, `bytegroup-zstd/1`, stored 84.1%. The [results viewer](https://jabara.iamtatsuki05.com/results/) shows these reports per role, and {doc}`archivers` compares them with `tar` and `zstd` on the same checkpoints. Saving and loading take longer than without Jabara. For one 1.6 GB checkpoint of SmolLM2-135M, a save with the `Trainer` adapter took 6.4 s, against 0.8 s for the `Trainer`'s own save and 4.0 s for that save followed by an fsync. A load took 5.0 s against 0.4 s with a warm page cache, and 7.4 s against 4.2 s with a cold one. All of these numbers come from short runs of small models, on one machine for each measurement. ## Many runs: seed sweeps and hyperparameter searches Jabara compresses every checkpoint of every run on its own and without loss, so a sweep saves the sum of what its checkpoints save. Attach Jabara to each run so that its checkpoints are compressed when they are saved, or compress the checkpoint directories after the runs finish (see {doc}`../how-to/compress-many-runs`). A delta against another run is a different matter. Runs that start from the same pretrained weights can store their weights against an archive of those weights. How much that saves has not been measured, and for runs that start from different random weights there is no reason to expect a gain. `jabara bench --base` measures it on your own checkpoints without writing a file. ## Long runs that resume often On preemptible or time-limited machines, a run saves often so that it loses little work. The `Trainer` adapter and the PyTorch Lightning plugin compress each checkpoint inside the save, and a resume from the archives gets back every tensor bit for bit (see {doc}`../how-to/hugging-face-trainer` and {doc}`../how-to/pytorch-lightning`). In a resume test of SmolLM2-135M over 100 steps with deterministic kernels, the training loss was the same at every step as after a resume from the original checkpoint. A save with the `Trainer` adapter returns only after the archives are written and verified, so training waits longer at each save (see {doc}`synchronous-save`). The `Trainer` adapter supports single-process training only. ## Intermediate checkpoints kept for analysis Training dynamics, probing, checkpoint averaging, and picking the best step afterwards all read old checkpoints, and lossless storage keeps compression error out of their results. Archives restore every tensor bit for bit by default (see {doc}`lossless-by-default`). `jabara export-weights` writes the weights of one archive as a plain safetensors file without restoring the optimizer state (see {doc}`../how-to/export-weights`). A later checkpoint of the same run can be stored as a delta against an earlier one (see {doc}`../how-to/delta-checkpoints`). Against a checkpoint 50 steps earlier, `xor-delta/1` stored the weights in 69.1% of their bytes. For the first moment, both delta codecs stored more than `bytegroup-zstd/1` without a base. A delta archive cannot be the base of another one, so every delta refers to a full archive. Deltas between checkpoints further apart than 50 steps were not measured. ## A run that someone else resumes A release of the weights alone lets others evaluate a model but not resume its training where it stopped. A compressed checkpoint directory keeps the optimizer state and the trainer's other files. The recipient installs Jabara, runs `jabara verify` on the copy, and runs `jabara decompress` or resumes with an adapter attached. A delta archive needs its base. Send the base with it, and run `jabara verify` and `jabara decompress` on the delta archive with `--base`. The `Trainer` adapter resumes from a delta archive when its base checkpoint is a sibling directory. ## Work on checkpoint compression To compare a new codec with the built-in ones on real optimizer state, add it with one subclass and run `jabara bench` on your checkpoints (see {doc}`../how-to/extend` and {doc}`../how-to/compare-codecs`). Every candidate runs on the same tensors with the same chunking and number of threads. For a lossy codec, a small measured error is not enough. In a resume test, the 8-bit quantizer with the smaller measured error raised the training loss, so check a lossy codec by resuming from it (see {doc}`../how-to/lossy`). ## What it is not for A framework cannot memory-map an archive or load it in parallel. Jabara decodes every archive first. `jabara decompress` and the `Trainer` adapter write the original files back before the framework reads them, and only then do memory-mapping and parallel loading of shards apply. For a model that you serve or load often, that restore cost cancels the fast loading of safetensors, so keep a plain safetensors copy for that, for example from `jabara export-weights`. In Python, `Archive.read` returns one tensor by name without restoring the rest. --- Source: https://jabara.iamtatsuki05.com/docs/explanation/archivers.html # Jabara and general-purpose archivers `tar` and `zip` pack a checkpoint directory into one file, and `zip`, `gzip`, and `zstd` compress files as streams of bytes. Jabara reads the tensors in those files and codes each tensor with a codec chosen for its role and dtype. The table compares the two approaches on a checkpoint that holds `model.safetensors` and `optimizer.pt`. | Property | `tar`, `zip`, `gzip`, `zstd` | Jabara | | --- | --- | --- | | Unit of work | The bytes of each file | Tensors, each with a name, a dtype, a shape, and a role | | What the compressor sees | One byte stream per file or per archive | One tensor at a time, so it can group the bytes of floats, code a tensor against the same tensor of an earlier checkpoint, or quantize it | | Integrity check | `gzip` stores a CRC-32 of the data, and `zip` a CRC-32 of each file. A `zstd` frame can carry a checksum, which the `zstd` command adds by default. `tar` has a checksum of each header, not of the data. | A CRC-32 of every chunk, checked on every read, and a CRC-32 of the index. `jabara compress` verifies each archive before it deletes the original. | | Reading one item | `zip` lists its files in a central directory, so you can extract one file. `tar` has no index. | The index at the end of the archive lists every tensor, and `Archive.read` returns one tensor by name. | | Delta against an earlier checkpoint | `zstd --patch-from` compresses a file against a reference file, at the level of bytes | Each tensor against the tensor of the same name in a base archive. The archive records the base, and a reader refuses a different one. | | Lossy coding | None | Only with `allow_lossy=True`. The archive stores the largest error of each tensor. | | Use from training code | A script around the tool, and an unpack step before a resume | The `Trainer` adapter, the Lightning plugin, or `save_state` and `load_state`. A resume reads the archives. | | Comparing methods | Run each tool on its own | `jabara bench` runs codecs on the same tensors with the same chunking and threads | ## Sizes On the 12 checkpoints of the four fine-tuning runs described in {doc}`use-cases`, `tar` piped to `zstd -3` stored the two checkpoint files in 92.3% of their bytes. Jabara's per-tensor `zstd/1` at the same level stored 92.1% of the tensor bytes, `bytegroup-zstd/1` 84.1%, and `zipnn/1` 82.9%. The denominators differ. The first counts the bytes of the files, which also hold a header and, in `optimizer.pt`, pickle data. The others count the bytes of the tensors. `zip` and `gzip` were not measured. ## Where the general-purpose tools are the better choice - None of them needs a Python package, and `tar` and `gzip` come with most Unix-like systems. Jabara is not on PyPI yet. - They take any file. `jabara compress` takes the files of the formats in {doc}`../reference/formats`, and in a directory only the file names listed there. It leaves the other files of a checkpoint directory, such as `trainer_state.json`, as they are, so Jabara is not a backup tool. - Their formats have published specifications: RFC 1952 for `gzip`, RFC 8878 for Zstandard, and the APPNOTE of PKWARE for `zip`. Jabara's archive format is at version 1 (see {doc}`../reference/archive-format`). - They run outside the training loop. A save with Jabara inside the loop takes longer than a plain save (see {doc}`use-cases`), and a framework cannot memory-map an archive. To send a whole checkpoint directory as one file, run `tar` on the directory after Jabara has compressed it. --- Source: https://jabara.iamtatsuki05.com/docs/explanation/tensor-roles.html # Tensor roles A role is a label on a tensor: `weight`, `adam_m`, `adam_v`, `adam_vmax`, `momentum`, `muon_momentum`, `step`, or `other`. It is not part of the tensor's bytes. A state schema sets it from the tensor's path in the saved state, and an assigner can read it to pick a codec. ## Why a tensor has a role A role lets a codec or an analysis treat first moments, second moments, and weights differently. An assigner reads the role of each tensor to pick its codec, so the weights can keep one codec while a moment uses another (see {doc}`../how-to/choose-codecs`). `jabara bench` and `jabara.bench.compare` report one row per candidate and role. ## Why the role is a label, not data The role is not in the bytes, so it plays no part in matching a tensor to its base. A delta archive reads back against a base tensor with the same name, dtype, and shape, whatever role either carries. A new optimizer needs a new schema, not a new archive format (see {doc}`../how-to/extend`). ## Where the roles come from `OptimizerSchema` sets the role from the last element of a tensor's path: `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`. `MuonSchema` gives `momentum_buffer` the role `muon_momentum`. `WeightsSchema` gives every tensor `weight`, and every tensor of a safetensors file is a `weight`. The default schema of `save_state` is `OptimizerSchema`, so the tensors of a model's `state_dict` get the role `other` unless you pass `WeightsSchema` (see {doc}`../how-to/pytorch-loop`). --- Source: https://jabara.iamtatsuki05.com/docs/explanation/lossless-by-default.html # Lossless by default Jabara restores every tensor bit for bit unless you opt in to a lossy codec, so that training resumes as if it had never stopped. A checkpoint that restores approximately cannot promise that. You therefore ask for approximation in code, per tensor, and the archive records the error that it introduced. ## What is verified, and when - **Every read, every chunk.** Each chunk stores a CRC-32 of the bytes that a reader must produce. A reader checks it after decoding and raises `ChecksumError` on a mismatch. For a lossless chunk these are the original bytes, so a pass means that the original is back. - **Every compression of a file.** `compress_file` writes the archive under a temporary name, reopens and verifies it, and only then renames it and deletes the source. An archive under its final name has been verified. `compress_dir` verifies every archive before it deletes any original. - **Every lossy write.** The writer decodes each lossy chunk once and stores the largest absolute difference from the input as `max_abs_err`. The checksum of a lossy chunk covers the decoded bytes, so `verify` confirms that the archive decodes to what the writer measured. It cannot confirm closeness to the original, which the archive does not hold (see {doc}`../how-to/lossy`). - **On demand.** `jabara verify` and `Archive.verify()` decode everything and check every checksum. - **The index.** The index has its own CRC-32, and the file has a magic number at each end. A reader rejects a file that it does not understand before it touches a chunk. ## What lossless means for each file type A file in any format that `jabara compress` takes, safetensors or a `torch.save` zip, is restored byte for byte (see {doc}`../reference/formats`). An archive that Jabara 0.1.0 wrote from a torch file is restored with the same nested types, key order, dtypes, shapes, and tensor bits, NaN and `-0.0` included, but its file bytes can differ, because that restore pickles the state again with `torch.save`. ## The opt-in A codec declares whether it is lossless. A write whose assigner picks a lossy codec raises `LossyNotAllowedError` unless the caller passes `allow_lossy=True`. The PyTorch Lightning plugin and `jabara compress` offer no such opt-in, so they never write a lossy tensor. `jabara bench` runs lossy candidates freely, because it writes nothing. --- Source: https://jabara.iamtatsuki05.com/docs/explanation/synchronous-save.html # What the Trainer adapter does inside a save `jabara.hf.attach` compresses a checkpoint inside the `Trainer`'s save call. The call is synchronous: the save returns after the archives are written and verified, and no thread outlives it. Training waits for the compression. ## What a save does The `Trainer` first writes its usual files, including its rotation of old checkpoints. Then Jabara turns every `*.safetensors` file and `optimizer.pt` of the new checkpoint directory into a verified `.jbr` archive. It deletes the originals only after all archives are written. If one archive fails, the checkpoint stays uncompressed, and an error such as `LossyNotAllowedError` propagates out of `Trainer.train`. An interrupted save leaves each file as the original, the archive, or both. A resume with Jabara attached loads the original where there is one, and the archive otherwise. A hard crash can also leave a `*.tmp` file, which a resume ignores and you can delete (see {doc}`../how-to/hugging-face-trainer`). ## What `threads` sets `threads` sets the size of the thread pool that codes chunks in parallel. All tensors of a file share the pool, so the chunks of different tensors are coded at the same time, and a checkpoint of many small tensors is not limited to one thread. Two kinds of tensor are exceptions. A delta tensor reads its base tensor first, so it starts only when the chunks before it are done, and delta tensors of one chunk are coded one at a time. A tensor whose codec runs threads of its own, such as `zipnn/1`, is coded alone, and the codec gets all `threads` threads for each chunk. Files are coded one after another. The comparison report times the codec's share of the wait, not the whole save (see {doc}`../how-to/compare-codecs`). ## Why the Hub strategies are refused With `hub_strategy` set to `checkpoint` or `all_checkpoints`, the `Trainer` uploads the checkpoint directory in the background. That upload would race with compression, so `check_arguments` and `attach` refuse both strategies. --- Source: https://jabara.iamtatsuki05.com/docs/explanation/scope.html # Scope Jabara is a library for storing checkpoints and for comparing ways to store them. ## What Jabara does not do - **It does not introduce a compression method.** Zstandard, byte grouping, XOR and subtraction deltas, and 8-bit quantization are known techniques. Jabara puts them behind one interface, so you can use, compare, and extend them in the same way. It does not aim to beat other codecs on stored size. - **It does not compress on a GPU.** It needs no GPU and runs on CPU in the training loop. - **It does not support multi-process training, DeepSpeed, or FSDP in the Hugging Face Trainer adapter.** `attach` refuses all three. DeepSpeed and FSDP save and load sharded state with their own code, which never calls the loaders that the adapter wraps. Weights that `save_pretrained` splits over several `*.safetensors` files are a different case: `attach` compresses each file. - **It does not read or write remote paths in the PyTorch Lightning plugin.** A URL path is refused. - **It runs no pickle.** `save_state` and the Lightning plugin store tensors, plain values, and dicts, lists, and tuples of them, and refuse a tensor subclass or a custom object, so their archives hold no pickle data. A file that `torch.save` wrote is a pickle, because PyTorch's file format uses one. `jabara compress` takes such a file apart without running it: it reads the storages from the zip and keeps the pickle's bytes as they are, and `jabara decompress` writes them back. Only the names and roles of the tensors need `torch.load(..., weights_only=True)`, which unpickles only tensors and plain types; for a file that it refuses, the tensors keep the role `other`. Loading a restored file is up to you, as it was before compression. - **It does not code several tensors jointly.** The codec interface sees one chunk of one tensor at a time. A method that prunes or quantizes weights together with their optimizer moments, as ExCP does, does not fit this interface. Whether one interface can cover such methods is an open question, and Jabara does not claim to. - **It does not measure a whole save or load in `bench`.** The report times the codec's share, in memory. ## What it keeps replaceable The codec, the assigner, the state schema, the checkpoint file format, and the framework adapter can each change without touching the rest (see {doc}`../how-to/extend`). --- Source: https://jabara.iamtatsuki05.com/docs/reference/cli.html # Command line The `jabara` command compresses, restores, lists, verifies, and compares checkpoints. `PATH` is a checkpoint file or directory. The command sections below are generated from the argument parser. ## Commands ### `jabara compress` ```text jabara compress [-h] [--threads N] [--base BASE] [--recursive] [--keep] [--dry-run] [--delta MODE] [--config FILE] [--show-config] PATH ``` Compress a checkpoint file, or the files it recognises in a checkpoint directory. With --base BASE (an archive of an earlier checkpoint, or the directory of one), float tensors are stored as differences from the tensors of the same name in it. With --recursive, PATH holds several checkpoint directories (checkpoint-100, checkpoint-200, ...): each is compressed in turn as a directory is, the first failure stops the run, --delta first codes every checkpoint but the first against the first, and --delta previous codes each against the one before it, a chain that restores in order. --dry-run lists what would be compressed and changes nothing. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `PATH` | a file, a checkpoint directory, or with --recursive their parent [path] | | `--threads N` | worker threads (default: up to 8) [positive integer] | | `--base BASE` | an archive of an earlier checkpoint, or its directory [path] | | `--recursive` | take every checkpoint directory in PATH, one level down (also --recursive=true or --recursive=false) | | `--keep` | keep the input files (also --keep=true or --keep=false) | | `--dry-run` | print what would be compressed, with its size on disk, and change nothing (also --dry-run=true or --dry-run=false) | | `--delta MODE` | with --recursive: first or previous, the checkpoint each one is coded against | | `--config FILE` | read options from a .json, .yaml, .yml, or .toml file [path] | | `--show-config` | print the settings to be used, as JSON, and exit | ### `jabara decompress` ```text jabara decompress [-h] [--threads N] [--base BASE] [--recursive] [--keep] [--config FILE] [--show-config] PATH ``` Restore the original file from an archive, or every archive in a directory. An archive written with --base needs the same --base BASE here. With --recursive, PATH holds several checkpoint directories: each is restored in turn as a directory is, dependants of another checkpoint's archives first, and the first failure stops the run. Without --keep, a checkpoint whose archives a sibling checkpoint still needs as its base is not restored before that sibling. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `PATH` | an archive, a checkpoint directory, or with --recursive their parent [path] | | `--threads N` | worker threads (default: up to 8) [positive integer] | | `--base BASE` | an archive of an earlier checkpoint, or its directory [path] | | `--recursive` | take every checkpoint directory in PATH, one level down (also --recursive=true or --recursive=false) | | `--keep` | keep the input files (also --keep=true or --keep=false) | | `--config FILE` | read options from a .json, .yaml, .yml, or .toml file [path] | | `--show-config` | print the settings to be used, as JSON, and exit | ### `jabara ls` ```text jabara ls [-h] [--json] [--recursive] [--config FILE] [--show-config] PATH ``` List the tensors of an archive, or of every archive in a directory. A directory without one is an error. With --recursive, PATH holds several checkpoint directories, and the archives of each are listed. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `PATH` | an archive or a directory, or with --recursive their parent [path] | | `--json` | print JSON (also --json=true or --json=false) | | `--recursive` | take every checkpoint directory in PATH, one level down (also --recursive=true or --recursive=false) | | `--config FILE` | read options from a .json, .yaml, .yml, or .toml file [path] | | `--show-config` | print the settings to be used, as JSON, and exit | ### `jabara verify` ```text jabara verify [-h] [--threads N] [--base BASE] [--recursive] [--config FILE] [--show-config] PATH ``` Decode every chunk of an archive, or of every archive in a directory, and check its checksum. A directory without an archive is an error. A delta archive needs --base BASE, as for decompress. With --recursive, PATH holds several checkpoint directories: every archive of each is checked, a delta archive against the archives of the other checkpoints that it names, and a failure does not stop the others. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `PATH` | an archive or a directory, or with --recursive their parent [path] | | `--threads N` | worker threads (default: up to 8) [positive integer] | | `--base BASE` | the base archive of a delta archive, or its directory [path] | | `--recursive` | take every checkpoint directory in PATH, one level down (also --recursive=true or --recursive=false) | | `--config FILE` | read options from a .json, .yaml, .yml, or .toml file [path] | | `--show-config` | print the settings to be used, as JSON, and exit | ### `jabara export-weights` ```text jabara export-weights [-h] [--config FILE] [--show-config] ARCHIVE OUT ``` Write the weight tensors of ARCHIVE as a safetensors file. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `ARCHIVE` | [path] | | `OUT` | the safetensors file to write; must not exist [path] | | `--config FILE` | read options from a .json, .yaml, .yml, or .toml file [path] | | `--show-config` | print the settings to be used, as JSON, and exit | ### `jabara bench` ```text jabara bench [-h] [--json] [--base BASE] [--repeats N] [--threads N] [--candidates a,b,c] [--config FILE] [--show-config] PATH ``` Compare codecs in memory on the tensors of PATH: an archive, a safetensors or torch file, or a directory. Default candidates are the lossless codecs that need no base; with --base (a path of the same kinds) the delta codecs join them. --candidates a,b,c names codecs instead, lossy ones included. It takes no --recursive: it holds every tensor in memory, and a parent of several checkpoints would multiply that. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `PATH` | an archive, a safetensors or torch file, or a directory [path] | | `--json` | print the report as JSON (also --json=true or --json=false) | | `--base BASE` | the base tensors, a path of the same kinds [path] | | `--repeats N` | timed runs per codec [positive integer, default 3] | | `--threads N` | worker threads (default: up to 8) [positive integer] | | `--candidates a,b,c` | the codecs to compare instead of the default ones [codec ids, comma-separated] | | `--config FILE` | read options from a .json, .yaml, .yml, or .toml file [path] | | `--show-config` | print the settings to be used, as JSON, and exit | ### `jabara codecs` ```text jabara codecs [-h] [--long] [--json] [--config FILE] [--show-config] [ID] ``` List the registered codecs: their ids, or with --long, --json or an ID what each is and builds on. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `ID` | show everything about this codec | | `--long` | show each codec's properties and references (also --long=true or --long=false) | | `--json` | print JSON: a list of codecs, or one codec for an ID (also --json=true or --json=false) | | `--config FILE` | read options from a .json, .yaml, .yml, or .toml file [path] | | `--show-config` | print the settings to be used, as JSON, and exit | ### `jabara help` ```text jabara help [-h] [COMMAND] ``` Print the full help of jabara or of a command. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `COMMAND` | a command; jabara itself without it [command name] | ### `jabara man` ```text jabara man [-h] [COMMAND] ``` Show the manual page of jabara or of a command. | Argument | Description | | --- | --- | | `-h, -H, --help` | print the short (-h) or the full help and exit | | `COMMAND` | a command; jabara itself without it [command name] | ## Files and directories - `compress` on a file takes `*.safetensors`, `*.pt`, `*.pth`, `*.bin`, `*.ckpt`, `*.npy`, `*.npz`, `*.gguf`, `*.h5`, `*.hdf5`, and `*.keras`, and writes `.jbr` next to it. On a directory it takes the regular files named `*.safetensors`, `optimizer.pt`, `optimizer.bin`, `pytorch_model*.bin`, `*.ckpt`, `mp_rank_*_model_states.pt`, `*_optim_states.pt`, or `model_optim_rng.pt`, not recursively, and leaves every other file alone. {doc}`formats` lists the frameworks that write these files. `decompress` writes each file back byte for byte when its archive is lossless. The files of a sharded model, such as `model-00001-of-00002.safetensors`, get one archive each, and `model.safetensors.index.json` stays. A directory with none of them is an error. - `decompress` on a file takes `*.jbr` and writes the name without the suffix. It refuses to write over a file that exists. On a directory it restores every `*.jbr` file. - Before they change anything, `compress` and `decompress` refuse a file that sits next to its own archive (`model.safetensors` beside `model.safetensors.jbr`). Remove one of the two first. - On a directory, `compress` and `decompress` are all or nothing. They write and verify every output first, then delete the inputs unless you pass `--keep`. If one file fails, they delete the outputs that they wrote, and every input stays in place. - `ls` and `verify` take an archive or a directory. On a directory they read its `*.jbr` files, and a directory with no archive is an error. - For `compress`, `decompress`, and `verify`, `--base` names an archive of an earlier checkpoint, or the directory of that checkpoint, for a file and for a directory alike. With a directory, each tensor is coded against the tensor of the same name in any of its archives, and the directory must hold no checkpoint file without its archive. An archive written with `compress --base` needs a `--base` that holds its base archives for `decompress` and `verify`. For `bench`, `--base` is a path of any kind that `bench` reads. - `export-weights` writes the tensors with the role `weight` to a safetensors file. - For an archive of a safetensors file, every tensor has that role, and the output is the original file, byte for byte. - For any other archive, the output holds the tensors with the role `weight` and leaves the rest out. An archive made with `save_state` and `WeightsSchema` has only such tensors. - `compress` gives the tensors of a torch file the optimizer roles by their path, so the tensors of a model `state_dict` get the role `other`. `export-weights` refuses that archive, prints `jabara: model.pt.jbr: no tensors with role 'weight'` and exits with status 1. The same holds for an archive of `optimizer.pt`. - `OUT` must not exist. - `export-weights` takes no base, so it cannot read a delta archive. - `bench` reads an archive, a file that `compress` takes, or a directory. In a directory it reads the files that `compress` takes and the `*.jbr` files, and prefixes each tensor name with the file name and `/`. An archive counts under the name of the file that it restores, so a compressed and an uncompressed directory give the same tensor names. A directory that holds a file and its archive is an error. `bench` cannot read a delta archive. ## A parent directory of checkpoints `compress`, `decompress`, `verify`, and `ls` take `--recursive`. `PATH` is then a parent, such as the `output_dir` of a Hugging Face `Trainer`, and the command works on its checkpoints one after the other. - A checkpoint directory directly holds a regular file that `compress` takes in a directory, or a `*.jbr` archive. The checkpoints are the immediate subdirectories that are checkpoint directories, in natural order of name (`checkpoint-200` before `checkpoint-1000`), then `PATH` itself last if it is one. A directory such as `best` sorts before `checkpoint-*`, and with `--delta` it becomes the first checkpoint, so check the order with `--dry-run`. The walk goes one level down, never deeper, and skips hidden directories and symbolic links to directories. Files that are not checkpoint files are never touched. `jabara.files.checkpoint_dirs(path)` returns the same list in Python. - Without `--recursive`, a `PATH` that holds no file of its own to work on is still an error. The message names the checkpoint directories that it found and suggests `--recursive`. - `compress` and `decompress` take one checkpoint at a time, each all or nothing, and stop at the first failure. The checkpoints before it stay done, so disk space is freed as the run goes. The one that failed and the later ones stay as they were. The command exits with status 1 and prints one line, `jabara: : ; stopped there: checkpoints done or skipped before it, this one and after it left as they were`. Before it changes anything, the command refuses a file beside its own archive in any checkpoint. - A checkpoint with nothing to do prints `: skipped, already compressed` (`already decompressed` for `decompress`) and is not an error. After a stop, run the same command again. - `compress --dry-run` works with any `PATH`. It prints what would be compressed and its size on disk, after the same refusals, without reading a tensor and without changing anything. - `compress --recursive --delta first` compresses the first checkpoint, in the order above, as full archives, or uses it as it is if it holds only full archives. It codes every other checkpoint, `PATH` itself included, against that first one, as `--base` does for a directory. A first checkpoint that holds a delta archive is refused. `compress --recursive --delta previous` codes every checkpoint but the first against the checkpoint before it in that order, so the archives form a chain, and a checkpoint compressed earlier stays as it is: a later run codes a new checkpoint against the last one. A restore follows the chain: the checkpoint at position *k* decodes *k* archives per tensor, and one lost archive loses every checkpoint after it. Use `first` when any checkpoint may be needed at any time, and `previous` when most are rarely read and disk is the constraint (the how-to guide has measurements). `--delta` needs `--recursive` and cannot be combined with `--base`, and `--recursive` cannot be combined with `--base`: each is a usage error. - `decompress --recursive` and `verify --recursive` find the base archives of a delta archive among the archives of the other checkpoints, by the recorded file name and index CRC-32. `decompress --recursive` restores the checkpoints that hold delta archives before the ones they need, so in a chain the last checkpoint goes first. It checks every base first, down each chain, so a base that no checkpoint holds stops it before it restores anything. For a link behind an archive's own base, the message names both archives: `: : base (index crc ) is missing or changed`. - `decompress` of a checkpoint directory or of one archive, without `--keep`, is refused before it changes anything when a sibling checkpoint holds a delta archive written against an archive that it would delete, and no copy of that archive (the same index CRC-32) remains in a sibling. Decompress those first, or pass `--keep`. `decompress --recursive` makes the same check for `PATH` itself, whose siblings are not checkpoints of the parent. A delta archive whose base lies outside the parent stops `decompress --recursive`: restore that checkpoint on its own with `--base`. - Do not delete or move a checkpoint of a parent compressed with `--delta` while a later one is compressed. `jabara.hf.attach(trainer, delta="first")` writes the `first` layout and keeps the first checkpoint when the `Trainer` rotates old ones. - `bench` takes no `--recursive`. It holds every tensor in memory, and a parent would multiply that. ## Output Sizes are tensor bytes, not file sizes: `` counts the bytes of the tensors, and `` counts their encoded chunks. The percentage is `100 * stored / raw` with one decimal, or `empty` when `raw` is 0. - `compress` prints one line per archive: `: -> bytes (

% of original)`. - `decompress` prints the path of each restored file. - With `--recursive`, `compress` and `decompress` print their usual lines for each checkpoint, then `

: archives, -> bytes (

% of original)`, and at the end `total: checkpoints, skipped, -> bytes (

% of original)`. `` counts every checkpoint found, and `` the skipped ones. `decompress` takes the sizes from the archives before it restores them. - `compress --dry-run` prints `: would compress, bytes on disk` per file and a last line `total: files, bytes on disk`. With `--recursive` it also prints `

: files, bytes on disk` per checkpoint (followed by `, delta against ` with `--delta`), and the last line is `total: checkpoints, skipped, files, bytes on disk`. - `ls` prints one line per archive, `: tensors, -> bytes (

% of original)`, then one line per tensor with its name, dtype, shape, role, codec, and sizes. `ls --json` prints a JSON list of objects with the keys `path` and `tensors`, also with `--recursive`. - `verify` prints `ok ` for each archive. `verify --recursive` checks every archive and does not stop at the first failure. It prints `FAILED : ` for an archive that fails, such as `base (index crc ) is missing or changed`, and exits with status 1 after `jabara: of archives failed`. - `export-weights` prints nothing. - `codecs` prints one codec id per line. {doc}`codecs` describes `codecs --long`, `codecs ID`, and `codecs --json`. - `bench` prints a header line, ` threads, best of , warm-up, chunk bytes`, then one line per candidate and role: sizes, encode and decode throughput in MB/s (10^6 bytes per second), and `exact` or `NOT EXACT`. Throughput is the raw bytes divided by the smallest of the timed runs. A run times only the codec's encode or decode of the chunks in memory, not file access. `` untimed rounds run first. In every round, each candidate in turn encodes and decodes once, and the candidate order reverses on every other timed round. Right before each timed encode and decode, the pool's threads and the calling thread run a busy loop for 0.1 s, untimed. A lossy row that decoded adds `max_abs_err=`. When a decode failed, the line says `decode failed ()` in place of the decode throughput. When a delta candidate fell back for some tensors, the line ends with `, 1 tensor used the fallback` for one tensor and `, tensors used the fallback` for more. The command exits 0 even with a `NOT EXACT` row. `bench --json` prints the report described in {doc}`schemas`. ## Parsing rules `jabara` parses and checks the whole argument list before it runs a command, so an argument list that it refuses, or that asks for help, changes no file. The first of these rules that matches decides: 1. `-h`, `-H`, or `--help`, spelled exactly that way and placed anywhere, prints the help of the command named first, or the overview if the first argument is not a command. `-h` prints the short help, and `-H` and `--help` print the full help. It exits 0 and runs nothing. Another spelling, such as `-hx`, `-hh`, or `--help=x`, is a usage error. No other short flag exists. 2. `--` is a usage error wherever it stands. 3. Every other argument that starts with `-` must be a flag of the command. It is never a path or a value. Write a path that starts with `-` as `./-name`. An unknown flag, a misspelled flag, a prefix of a flag (`--kee`), and a flag of another command are usage errors. 4. Every other argument is a string. Nothing is read as a Python literal, so `run#2`, `123`, `a,b`, and `True` are paths. An empty path, such as the one an unset `"$CKPT"` gives, is a usage error. A missing positional argument or a surplus one is a usage error. 5. `--keep`, `--json`, `--recursive`, and `--dry-run` are switches. `--keep`, `--keep=true`, and `--keep=false` are accepted, and any other value, such as `--keep=0`, is a usage error. A switch takes no separate value, so in `--keep false` the word `false` is a surplus argument. 6. `--threads` and `--repeats` take a positive integer in ASCII digits, as `--threads 2` or `--threads=2`. `--candidates` takes one codec id, or several separated by commas. A flag given twice takes the last value. ## Configuration files `compress`, `decompress`, `ls`, `verify`, `export-weights`, `bench`, and `codecs` take `--config FILE`, a `.json`, `.yaml`, `.yml`, or `.toml` file that holds a mapping. {doc}`../how-to/run-from-a-config-file` shows one of each. - The keys are the destinations of the command's own options and arguments: the long option names with underscores (`base`, `keep`, `threads`, `candidates`) and the names of the positional arguments (`path`, `archive`, `out`). The generated sections above list them. An option that a later version adds is a key without another change. - The precedence is the command line, then the file, then the defaults. A positional argument on the command line replaces the same one of the file, and the command line fills them from the left. - The values have the types of the command line: a string for a path, an integer for a count, `true` or `false` for a switch, and a list of strings for `candidates`. Each value goes through the checks of its option, so `threads = 0` fails as `--threads 0` does. A key that the command lacks, a value of another type, `null`, a suffix that is not listed, text that does not parse, and a top level that is not a mapping are usage errors. `config` and `show_config` are not keys. - A usage error from a file prints one line, `jabara: : key '': ` or `jabara: : `, and exits with status 2. A file that cannot be read exits with status 1. A YAML file without PyYAML exits with status 1 and says to install `jabara[yaml]`. - `--show-config` prints `{"command": ..., "config": ..., "settings": {...}}` as JSON, with every key of the command, and exits with status 0. It runs nothing. - YAML is read with PyYAML's `safe_load`. TOML is read with `tomllib`, or with `tomli` on Python 3.10. ## Help and manual pages `jabara help COMMAND` prints the same text as `jabara COMMAND --help`. `jabara` with no argument prints the short overview on standard error and exits 2, as a usage error. The package installs a manual page for `jabara` and for each command, such as `jabara-compress(1)`, under `share/man/man1` of its environment. `man jabara` finds them when the environment's `bin` directory is on `PATH`, as in an activated virtual environment or after `pipx install`. `uv tool install` does not link them. `jabara man COMMAND` shows the same page anywhere. When standard output is not a terminal, it prints the page's roff source. ## Exit status | Status | When | | --- | --- | | 0 | The command succeeded, or help was printed. | | 1 | The command raised a `JabaraError`, an `OSError`, or a `ValueError`. `jabara` prints one line, `jabara: `, to standard error. | | 2 | Usage error. `jabara` prints the usage line and one error line to standard error, and runs no command. A bad configuration file gives one line, `jabara: : `, and no usage line. | Any other exception is not caught and ends the command with a Python traceback. --- Source: https://jabara.iamtatsuki05.com/docs/reference/codecs.html # Built-in codecs A codec turns one chunk of one tensor into bytes and back. Its id has the form `/`, and an archive records the id and the full parameters of the codec of every tensor. The table and the sections below are generated from the codec registry. The dtypes column lists the dtypes that a codec encodes, and any other dtype raises `UnsupportedDtypeError`. - With no assigner, Jabara uses `DefaultAssigner`: `bytegroup-zstd/1` for `float16`, `bfloat16`, `float32`, and `float64`, and `zstd/1` for every other dtype. - A lossless codec decodes every chunk to the exact bytes it encoded. - An archive can use a lossy codec only when the caller passes `allow_lossy=True`. Otherwise `write_archive` raises `LossyNotAllowedError`. The archive records the largest absolute error of each lossy tensor in `max_abs_err`. - A codec that needs a base codes a tensor as its difference from the tensor with the same name, dtype, and shape in an earlier archive, the base. When the base has no such tensor, the writer uses the `fallback` of the `CodecChoice`, or raises `MissingBaseError` if there is none. Reading a delta tensor without its base raises `MissingBaseError`. - `get_codec(codec_id, params)` checks `params` against the codec's `Params` model and raises `pydantic.ValidationError` for an unknown or invalid parameter. A delta codec also builds its inner codec, so an unknown `inner` raises `UnknownCodecError`, and an inner codec that is lossy or needs a base raises `ValueError`. Each codec section names the works the codec builds on, and how it relates to each. "wraps" means that the codec calls this library. "describes" means that the work describes the method or the format of a library that the codec wraps. "related" means that the work has the same idea, and the codec is this project's own and does not reproduce the work's method. `jabara codecs` prints the codec ids. `jabara codecs --long` adds what this page gives for each codec and whether its extra is installed, `jabara codecs ID` shows one codec, and `--json` prints the same as JSON: ```console $ jabara codecs raw/1 raw/1: Stores the bytes unchanged. type: lossless; needs no base; dtypes: every dtype; parameters: none ``` | Codec | Type | Needs a base | Dtypes | Parameters and defaults | | --- | --- | --- | --- | --- | | [`bytegroup-zstd/1`](#codec-bytegroup-zstd-1) | lossless | no | all | `level = 3` | | [`quant8-linear/1`](#codec-quant8-linear-1) | lossy | no | `float16`, `bfloat16`, `float32`, `float64` | `level = 3` | | [`quant8-log/1`](#codec-quant8-log-1) | lossy | no | `float16`, `bfloat16`, `float32`, `float64` | `level = 3` | | [`raw/1`](#codec-raw-1) | lossless | no | all | none | | [`sub-delta/1`](#codec-sub-delta-1) | lossless | yes | all except `complex128` | `inner = "bytegroup-zstd/1"`, `inner_params = {}` | | [`xor-delta/1`](#codec-xor-delta-1) | lossless | yes | all | `inner = "bytegroup-zstd/1"`, `inner_params = {}` | | [`zipnn/1`](#codec-zipnn-1) | lossless | no | `float16`, `bfloat16`, `float32` | none | | [`zstd/1`](#codec-zstd-1) | lossless | no | all | `level = 3` | Dtype names: `bool`, `uint8`, `int8`, `uint16`, `int16`, `float16`, `bfloat16`, `uint32`, `int32`, `float32`, `uint64`, `int64`, `float64`, `complex64`, `complex128`. (codec-bytegroup-zstd-1)= ## `bytegroup-zstd/1` Class: {py:class}`jabara.codecs.builtin.ByteGroupZstdCodec`. 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`. Parameters: `level` is the Zstandard compression level of every plane. References: - related: [ZipNN: Lossless Compression for AI Models](https://doi.org/10.1109/CLOUD67622.2025.00028). Hershcovitch et al., 2025 (paper). - related: [Lossless Compression for LLM Tensor Incremental Snapshots](https://arxiv.org/abs/2505.09810). Waddington and Constantinescu, 2025 (paper). - wraps: [python-zstandard](https://github.com/indygreg/python-zstandard). Gregory Szorc, 2025 (implementation). (codec-quant8-linear-1)= ## `quant8-linear/1` Class: {py:class}`jabara.codecs.quant.Quant8LinearCodec`. 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. Parameters: `level` is the Zstandard compression level of the 8-bit codes. References: - related: [BitSnap: Checkpoint Sparsification and Quantization in LLM Training](https://arxiv.org/abs/2511.12376). Peng et al., 2025 (paper). - wraps: [python-zstandard](https://github.com/indygreg/python-zstandard). Gregory Szorc, 2025 (implementation). (codec-quant8-log-1)= ## `quant8-log/1` Class: {py:class}`jabara.codecs.quant.Quant8LogCodec`. 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. Parameters: `level` is the Zstandard compression level of the 8-bit codes. References: - related: [8-bit Optimizers via Block-wise Quantization](https://arxiv.org/abs/2110.02861). Dettmers et al., 2021 (paper). - wraps: [python-zstandard](https://github.com/indygreg/python-zstandard). Gregory Szorc, 2025 (implementation). (codec-raw-1)= ## `raw/1` Class: {py:class}`jabara.codecs.builtin.RawCodec`. Stores the bytes unchanged. (codec-sub-delta-1)= ## `sub-delta/1` Class: {py:class}`jabara.codecs.delta.SubDeltaCodec`. 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`. Parameters: `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. References: - related: [ULPack: Reference-Conditioned Lossless Compression of Checkpoint Trajectories](https://arxiv.org/abs/2610.14184). Ashok, 2026 (paper). (codec-xor-delta-1)= ## `xor-delta/1` Class: {py:class}`jabara.codecs.delta.XorDeltaCodec`. Codes the bitwise XOR of the chunk and the same chunk of the base, with the inner codec. Accepts every dtype. Parameters: `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. References: - related: [ZipNN: Lossless Compression for AI Models](https://doi.org/10.1109/CLOUD67622.2025.00028). Hershcovitch et al., 2025 (paper). - related: [Lossless Compression for LLM Tensor Incremental Snapshots](https://arxiv.org/abs/2505.09810). Waddington and Constantinescu, 2025 (paper). (codec-zipnn-1)= ## `zipnn/1` Class: {py:class}`jabara.codecs.zipnn.ZipNNCodec`. 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. It needs the `zipnn` extra. References: - wraps: [ZipNN: A Lossless Compression Library for AI pipelines](https://github.com/zipnn/zipnn). ZipNN Contributors, 2026 (implementation). - describes: [ZipNN: Lossless Compression for AI Models](https://doi.org/10.1109/CLOUD67622.2025.00028). Hershcovitch et al., 2025 (paper). (codec-zstd-1)= ## `zstd/1` Class: {py:class}`jabara.codecs.builtin.ZstdCodec`. Compresses the whole chunk with Zstandard. Parameters: `level` is the Zstandard compression level. References: - wraps: [python-zstandard](https://github.com/indygreg/python-zstandard). Gregory Szorc, 2025 (implementation). - wraps: [Zstandard - Fast real-time compression algorithm](https://github.com/meta/zstd). Meta Platforms, Inc. and affiliates, 2025 (implementation). - describes: [Zstandard Compression and the 'application/zstd' Media Type](https://www.rfc-editor.org/info/rfc8878). Collet and Kucherawy, 2021 (specification). --- Source: https://jabara.iamtatsuki05.com/docs/reference/formats.html # Checkpoint file formats A format takes a checkpoint file apart into tensors and puts it back together. `jabara compress` and `compress_file` take a file in any supported format below, and `jabara decompress` writes it back byte for byte when the archive is lossless. The tables are generated from the format registry, `jabara.formats`, which also lists the formats that no entry takes and why. - `safetensors`: the JSON header is kept as text, and every tensor is compressed. - `torch-zip`: any file that `torch.save` wrote in its zip layout (PyTorch 1.6 and later). Each tensor storage is compressed, and the bytes around the storages (the pickle, the zip headers) are kept as one more tensor, `(remainder)`. The pickle is never run: the dtype and size of each storage are read from its opcodes. Tensor names and roles come from `torch.load(weights_only=True)`. When that refuses the file because it holds a class outside PyTorch's allow-list (a DeepSpeed ZeRO optimizer state, a Megatron-LM checkpoint with its `argparse.Namespace`, Lightning hyperparameters kept as an object), every storage gets the role `other`, the command prints one `jabara:` line on stderr, and the file is still compressed and restored byte for byte. A role-based assigner then chooses no lossy codec for it. - `torch-zip` refuses, and leaves as it is, a `torch.save` file in the legacy format from before PyTorch 1.6 and a zip whose members are compressed. - `npy` and `npz`: a NumPy array file, and a zip of them from `np.savez` (MLX's `mx.savez` writes the same). The header is read with `ast.literal_eval`, which runs no code. An array of a dtype that Jabara does not carry (big-endian, structured, Python objects) is kept as `uint8` bytes with the role `other`; an array of Python objects is never unpickled. A Fortran-order array keeps its dtype and shape but gets the role `other`, because its bytes are in column order. An `.npz` from `np.savez_compressed` is refused, because deflating a member again gives the original bytes only with the same zlib build. - `gguf`: a GGUF file, version 2 or 3, read with `struct` alone. The header and the metadata stay as they are. A tensor of a float or integer type keeps its dtype; a quantized tensor is kept as `uint8` bytes with the role `other`. A file of metadata alone, with no tensor, is kept whole. - `hdf5` and `keras`: an HDF5 file, such as a Keras 3 `.weights.h5`, and a Keras 3 `.keras` zip, which holds one. They need the `hdf5` extra (`h5py`), which reports where each dataset sits in the file. A chunked, compressed, external, or virtual dataset is refused, because its bytes are not in one place. Datasets under `optimizer/` (Keras 3) and `optimizer_weights/` (legacy Keras) get the role `other`. - In a checkpoint directory, `compress` takes only the file names that the formats list for a directory, so `scheduler.pt`, `rng_state.pth`, `training_args.bin`, and `scheduler.bin` stay as they are; `.npy`, `.npz`, `.gguf`, `.h5`, and `.keras` files are taken only when named on their own, since a directory may hold such files as data. A file named on its own may have any name that a format's patterns match: `*.safetensors`, `*.pt`, `*.pth`, `*.bin`, `*.ckpt`, `*.npy`, `*.npz`, `*.gguf`, `*.h5`, `*.hdf5`, `*.keras`. - To add a format, see {doc}`../how-to/extend`. The second table gives the size of each entry: its class, and its whole module. All but `safetensors` share `jabara.formats.splice`, which cuts the tensors out and puts them back, and the zip formats share the reader of stored zip members. | Framework | Files | Format | Status | | --- | --- | --- | --- | | llama.cpp, and the tools that convert models for it | *.gguf | `gguf` | supported | | Keras 3 (save_weights), legacy Keras, h5py | *.weights.h5, *.h5, *.hdf5 | `hdf5` | supported | | Keras 3 (model.save) | *.keras | `keras` | supported | | NumPy | *.npy | `npy` | supported | | NumPy (np.savez), MLX (mx.savez) | *.npz | `npz` | supported | | Hugging Face Transformers, Accelerate, PEFT, Diffusers, MLX | *.safetensors | `safetensors` | supported | | Hugging Face Transformers | optimizer.pt, pytorch_model*.bin | `torch-zip` | supported | | Accelerate | optimizer.bin, pytorch_model*.bin | `torch-zip` | supported | | PyTorch Lightning | *.ckpt | `torch-zip` | supported | | DeepSpeed | mp_rank_*_model_states.pt, *_optim_states.pt | `torch-zip` | supported | | Megatron-LM (torch format) | model_optim_rng.pt | `torch-zip` | supported | | PyTorch | *.pt, *.pth, *.bin, named on their own | `torch-zip` | supported | | TensorFlow (tf.train.Checkpoint) | *.index, *.data-*-of-* | none | not supported: the index is a table of protocol buffers that only TensorFlow's reader parses | | JAX: Orbax, TensorStore | a directory of zarr or OCDBT files | none | not supported: each array is split into chunks, usually compressed, over many files | | PaddlePaddle | *.pdparams, *.pdopt | none | not supported: a plain pickle, whose arrays are found only by running it | | MindSpore | *.ckpt | none | not supported: protocol buffers of MindSpore's own schema | | ONNX | *.onnx | none | not supported: a protocol buffer that holds the graph; its tensors need a protobuf parser | | Core ML | *.mlmodel, *.mlpackage | none | not supported: a protocol buffer specification with its own weight file | | TensorRT | *.engine, *.plan | none | not supported: an engine built for one GPU and TensorRT version, in a private layout | | PyTorch Distributed Checkpoint | *.distcp, .metadata | none | not supported: one zip per tensor written back to back, and a .metadata file that only pickle.load reads | | NumPy (np.savez_compressed) | *.npz with compressed members | none | not supported: deflating a member again gives the original bytes only with the same zlib build | | PyTorch before 1.6 | *.pt, *.pth | none | not supported: a plain pickle, which Jabara does not run | | Format | Class | Class lines | Module lines | | --- | --- | --- | --- | | `gguf` | {py:class}`jabara.formats.gguf.Gguf` | 18 | 142 | | `hdf5` | {py:class}`jabara.formats.hdf5.Hdf5` | 16 | 126 | | `keras` | {py:class}`jabara.formats.hdf5.Keras` | 21 | 126 | | `npy` | {py:class}`jabara.formats.npy.Npy` | 17 | 94 | | `npz` | {py:class}`jabara.formats.npy.Npz` | 23 | 94 | | `safetensors` | {py:class}`jabara.formats.safetensors.Safetensors` | 26 | 136 | | `torch-zip` | {py:class}`jabara.formats.torch_zip.TorchZip` | 48 | 260 | --- Source: https://jabara.iamtatsuki05.com/docs/reference/archive-format.html # Archive format An archive is one file, conventionally named `.jbr`. The writer produces it front to back in one pass, and a reader starts from the end. This page describes version 1, the only version. ## Layout ```text offset 0 MAGIC 8 bytes b"JABARA\x00\x01" chunks ... encoded chunks, back to back index N bytes UTF-8 JSON N 8 bytes unsigned little-endian crc 4 bytes CRC-32 of the index bytes, unsigned little-endian end MAGIC_END 8 bytes b"\x01\x00ARABAJ" ``` ## Index The index is the JSON form of the pydantic model `jabara.container.ArchiveIndex`, whose JSON schema is in {doc}`schemas`. This archive holds one tensor stored with `raw/1`, so the chunk length equals the raw length: ```{testcode} import numpy as np from jabara.assign import CodecChoice, UniformAssigner from jabara.container import Archive, write_archive from jabara.types import TensorMeta, TensorRecord meta = TensorMeta(name="w", dtype="float32", shape=(2, 2), role="weight") record = TensorRecord(meta, np.arange(4, dtype="` of the writer. | | `tensors` | One entry per tensor, in the order that the writer received them. | | `skeleton` | The nested structure of a saved state, as `jabara.skeleton.flatten` returns it, with each tensor replaced by a reference to its name. `save_state` writes one. `null` when the writer was given none. | | `source` | What the archive restores to. Jabara writes `{"kind": "tensors"}` (plain tensors, no file to restore, and the value when the writer was given none), `{"kind": "safetensors", "header": ""}`, and `{"kind": "torch"}` (a state written by `save_state`). | | `base` | `null`, unless a tensor uses a delta codec. Then it is `{"name": "", "index_crc": }`, or, when the delta tensors refer to several base archives, a list of two or more such objects. A tensor's reference is in the first archive of the list that holds a tensor of the same name, dtype, and shape. | A tensor entry has the fields of `TensorMeta` (`name`, `dtype`, `shape`, `role`) and these: | Field | Meaning | | --- | --- | | `codec` | The codec id. | | `params` | The full parameters of the codec, defaults included. | | `lossless` | The `lossless` flag of the codec. | | `max_abs_err` | For a lossy codec, the largest absolute difference between the input and the decoded values over the tensor, measured by the writer. `null` for a lossless codec. | | `chunks` | The chunks of the tensor, in order. A zero-byte tensor has none. | A chunk entry has `offset` and `length`, the position and size of the encoded chunk in the file, `raw_length`, the size of the decoded chunk, and `crc32`, the CRC-32 (`zlib.crc32`) of the bytes that a reader must produce. Those are the original bytes for a lossless codec and the decoded bytes for a lossy one. ## Chunks - The writer splits the raw bytes of each tensor into chunks of `chunk_size` bytes, rounded down to a whole number of items and never less than one item. The default is 16 MiB (`CHUNK_SIZE`). The largest allowed value is 256 MiB (`MAX_CHUNK_SIZE`). - Each chunk is coded on its own, so chunks can be coded in parallel on a thread pool of `threads` workers, the chunks of different tensors at the same time. The writer writes the chunks in tensor and chunk order, whatever order they finish in. - A delta tensor has the same chunk boundaries as its reference in the base, so the reference of chunk *k* is chunk *k* of the base tensor. ## What a reader checks - Before it reads any chunk, `Archive.open` raises `ArchiveFormatError` for a wrong magic number at either end, an index whose CRC-32 does not match, an unknown `format`, or an index that contradicts itself or the file. The index must have unique tensor names, chunk sizes that are whole numbers of items and add up to the size of each tensor, and chunks that lie between the magic number and the index without overlapping. - After decoding a chunk, a reader compares its length and CRC-32 with the index and raises `ChecksumError` on a mismatch. - A delta archive needs its base. Reading a delta tensor without it raises `MissingBaseError`, and reading it with a base that has no tensor of the same name, dtype, and shape raises `BaseMismatchError`. Opening a delta archive with base archives that lack one with a recorded `index_crc` also raises `BaseMismatchError`, naming it. A delta archive may refer to another delta archive (`jabara compress --recursive --delta previous`), so restoring one needs the archive and every archive behind it, down to a full one. The index has no field for a chain: each archive names only its own base, by file name and index CRC-32, and the format version is unchanged. Jabara 0.1.0 never writes a chain, and given the middle archive of one as the base it raises `MissingBaseError` when it reads a delta tensor. ## How the writer protects the file - `write_archive` writes to a new temporary file next to the target, named after it with `..tmp` added. The writer creates it so that it cannot replace an existing file. It syncs the file to disk, renames it to the target, and on POSIX syncs the directory. A crash never leaves a partly written archive under the final name. On macOS, `fsync` does not flush the write cache of the drive. - `write_archive` accepts a lazy iterable of records, such as a generator. It reads the bytes of each record in place, without a copy. With `threads` above 1, it takes the next record while chunks of earlier records are still being coded. The bytes of a record must not change until `write_archive` returns, so a generator must make a new buffer for each record. A generator that refills one buffer goes undetected: the archive then holds wrong bytes, and no error is raised. - `write_archive` refuses, before it creates the file, a `skeleton` or `source` that would not read back, such as JSON nested deeper than the reader's parser accepts. - For a lossy tensor, the writer decodes every chunk once, compares it with the input, and records the result in `max_abs_err`. It raises `ValueError` if the error is not finite. --- Source: https://jabara.iamtatsuki05.com/docs/reference/schemas.html # JSON schemas Two JSON formats have published schemas, generated from the pydantic models with `model_json_schema()`. ## Archive index The index at the end of every archive is an `ArchiveIndex` (see {doc}`archive-format`). Read one with `ArchiveIndex.model_validate_json(...)`, or open the archive with `Archive.open` and use `archive.index`. ```json { "$defs": { "BaseRef": { "additionalProperties": false, "description": "Names the base archive of a delta archive by file name and index CRC-32.", "properties": { "index_crc": { "title": "Index Crc", "type": "integer" }, "name": { "title": "Name", "type": "string" } }, "required": [ "name", "index_crc" ], "title": "BaseRef", "type": "object" }, "ChunkEntry": { "additionalProperties": false, "description": "The index entry of one chunk: its offset, its stored length, its raw length (1 to `MAX_CHUNK_SIZE` bytes),\nand the CRC-32 of the bytes a reader must produce.", "properties": { "crc32": { "maximum": 4294967295, "minimum": 0, "title": "Crc32", "type": "integer" }, "length": { "minimum": 0, "title": "Length", "type": "integer" }, "offset": { "minimum": 0, "title": "Offset", "type": "integer" }, "raw_length": { "maximum": 268435456, "minimum": 1, "title": "Raw Length", "type": "integer" } }, "required": [ "offset", "length", "raw_length", "crc32" ], "title": "ChunkEntry", "type": "object" }, "JsonValue": {}, "TensorEntry": { "additionalProperties": false, "description": "The index entry of one tensor: its metadata, the codec id and parameters, `lossless`, `max_abs_err`, and its\nchunks. Each chunk's raw length is a multiple of the item size, and together they are `nbytes`.", "properties": { "chunks": { "items": { "$ref": "#/$defs/ChunkEntry" }, "title": "Chunks", "type": "array" }, "codec": { "title": "Codec", "type": "string" }, "dtype": { "title": "Dtype", "type": "string" }, "lossless": { "title": "Lossless", "type": "boolean" }, "max_abs_err": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "title": "Max Abs Err" }, "name": { "title": "Name", "type": "string" }, "params": { "additionalProperties": { "$ref": "#/$defs/JsonValue" }, "title": "Params", "type": "object" }, "role": { "default": "other", "title": "Role", "type": "string" }, "shape": { "items": { "minimum": 0, "type": "integer" }, "title": "Shape", "type": "array" } }, "required": [ "name", "dtype", "shape", "codec", "params", "lossless", "max_abs_err", "chunks" ], "title": "TensorEntry", "type": "object" } }, "additionalProperties": false, "description": "The JSON index at the end of an archive. `model_json_schema()` is the schema of the format.", "properties": { "base": { "anyOf": [ { "$ref": "#/$defs/BaseRef" }, { "items": { "$ref": "#/$defs/BaseRef" }, "type": "array" }, { "type": "null" } ], "title": "Base" }, "format": { "enum": [ 1, 2 ], "title": "Format", "type": "integer" }, "skeleton": { "$ref": "#/$defs/JsonValue" }, "source": { "$ref": "#/$defs/JsonValue" }, "tensors": { "items": { "$ref": "#/$defs/TensorEntry" }, "title": "Tensors", "type": "array" }, "writer": { "title": "Writer", "type": "string" } }, "required": [ "format", "writer", "tensors", "skeleton", "source", "base" ], "title": "ArchiveIndex", "type": "object" } ``` ## Comparison report `jabara bench --json` prints a `BenchReport`, and `jabara.bench.compare` returns one. `report.model_dump_json()` returns the JSON text that the results viewer reads. A report has an `environment`, which records the machine, the versions, and the settings of the run, and one row per candidate and role. ```json { "$defs": { "BenchEnvironment": { "additionalProperties": false, "description": "Where and how the numbers were taken. `load_average_1m` is read once, before the first candidate runs.\n`cpu_model` is the processor name the OS reports (`None` where it reports none). `optional_packages` holds the\nversions of the optional packages a codec can load (`zipnn`, `torch`) that are loaded when the run ends.", "properties": { "chunk_size": { "title": "Chunk Size", "type": "integer" }, "cpu_count": { "anyOf": [ { "type": "integer" }, { "type": "null" } ], "title": "Cpu Count" }, "cpu_model": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "title": "Cpu Model" }, "jabara": { "title": "Jabara", "type": "string" }, "load_average_1m": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "title": "Load Average 1M" }, "machine": { "title": "Machine", "type": "string" }, "numpy": { "title": "Numpy", "type": "string" }, "optional_packages": { "additionalProperties": { "type": "string" }, "title": "Optional Packages", "type": "object" }, "platform": { "title": "Platform", "type": "string" }, "python": { "title": "Python", "type": "string" }, "repeats": { "title": "Repeats", "type": "integer" }, "spin_seconds": { "title": "Spin Seconds", "type": "number" }, "threads": { "title": "Threads", "type": "integer" }, "warmup_passes": { "title": "Warmup Passes", "type": "integer" }, "zstandard": { "title": "Zstandard", "type": "string" } }, "required": [ "jabara", "python", "platform", "machine", "cpu_model", "cpu_count", "load_average_1m", "threads", "repeats", "warmup_passes", "spin_seconds", "chunk_size", "numpy", "zstandard", "optional_packages" ], "title": "BenchEnvironment", "type": "object" }, "BenchRow": { "additionalProperties": false, "description": "One candidate on all tensors of one role.\n\n`encode_seconds_all` holds each of `repeats` wall-clock runs (`time.perf_counter`), in run order, of\n`Codec.encode` over every chunk of every tensor of the role, after `warmup_passes` untimed passes;\n`encode_seconds` is the smallest. The chunks run as `write_archive` runs them: on the container's thread pool,\nor one after another with the copy that `Codec.with_threads` returns. A run includes slicing the chunks and\nthe base reference and handing them to the pool or the copy, and nothing else. `decode_seconds_all` and\n`decode_seconds` are the same for `Codec.decode` plus the length and CRC-32 check of each decoded chunk that\n`Archive.read` also does. When any decode pass fails that check, `decode_error` holds the reader's message and\nboth decode fields are `None`, so a broken codec has no decode time to rank. Throughput is\n`raw_bytes / seconds`. Each timed run starts right after the pool's threads and the calling thread have run a busy\nloop for `BenchEnvironment.spin_seconds`; see DESIGN.md, \"Comparison\", for what that was observed to change.\n\nThese seconds are the codec's share of a save or load, not its cost. A real save (`write_archive`) also\ncomputes the CRC-32 of the input, decodes the whole base tensor first when `needs_base`, decodes every chunk\nonce more to check it when `check_decode`, and writes the file. A real load (`Archive.read`) also decodes the\nwhole base tensor first when `needs_base`, and reads the file. `needs_base` is true when a tensor of the row is\ncoded with a delta codec; `check_decode` is true when one is coded with a lossy codec, so it is `not lossless`.\n\n`codecs` lists each distinct codec id and full parameters (defaults filled in, as an archive index records\nthem) that coded the role's tensors, with the number of tensors each coded. `stored_bytes` is the sum of chunk\npayload lengths from one untimed encode pass, without the archive index and magic. `lossless` is the codecs'\nown claim; `bit_exact` compares the decoded bytes with the input and is false when decoding failed.\n`fallback_tensors` counts the tensors for which the candidate chose a delta codec but the base had no\nreference, so they were coded with the choice's `fallback`.", "properties": { "bit_exact": { "title": "Bit Exact", "type": "boolean" }, "candidate": { "title": "Candidate", "type": "string" }, "check_decode": { "title": "Check Decode", "type": "boolean" }, "codecs": { "items": { "$ref": "#/$defs/CodecUse" }, "title": "Codecs", "type": "array" }, "decode_error": { "anyOf": [ { "type": "string" }, { "type": "null" } ], "title": "Decode Error" }, "decode_seconds": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "title": "Decode Seconds" }, "decode_seconds_all": { "anyOf": [ { "items": { "type": "number" }, "type": "array" }, { "type": "null" } ], "title": "Decode Seconds All" }, "encode_seconds": { "title": "Encode Seconds", "type": "number" }, "encode_seconds_all": { "items": { "type": "number" }, "title": "Encode Seconds All", "type": "array" }, "fallback_tensors": { "title": "Fallback Tensors", "type": "integer" }, "lossless": { "title": "Lossless", "type": "boolean" }, "max_abs_err": { "anyOf": [ { "type": "number" }, { "type": "null" } ], "title": "Max Abs Err" }, "needs_base": { "title": "Needs Base", "type": "boolean" }, "raw_bytes": { "title": "Raw Bytes", "type": "integer" }, "role": { "title": "Role", "type": "string" }, "stored_bytes": { "title": "Stored Bytes", "type": "integer" } }, "required": [ "candidate", "role", "codecs", "raw_bytes", "stored_bytes", "encode_seconds", "encode_seconds_all", "decode_seconds", "decode_seconds_all", "decode_error", "lossless", "needs_base", "check_decode", "bit_exact", "max_abs_err", "fallback_tensors" ], "title": "BenchRow", "type": "object" }, "CodecUse": { "additionalProperties": false, "description": "A codec id and its full parameters, and how many tensors of a row it coded.", "properties": { "codec_id": { "title": "Codec Id", "type": "string" }, "params": { "additionalProperties": { "$ref": "#/$defs/JsonValue" }, "title": "Params", "type": "object" }, "tensors": { "title": "Tensors", "type": "integer" } }, "required": [ "codec_id", "params", "tensors" ], "title": "CodecUse", "type": "object" }, "JsonValue": {} }, "additionalProperties": false, "description": "The result of `compare`: the environment of the run and one row per candidate and role. `model_dump_json()`\nwrites the file that the results viewer reads.", "properties": { "bench": { "const": 1, "title": "Bench", "type": "integer" }, "environment": { "$ref": "#/$defs/BenchEnvironment" }, "rows": { "items": { "$ref": "#/$defs/BenchRow" }, "title": "Rows", "type": "array" } }, "required": [ "bench", "environment", "rows" ], "title": "BenchReport", "type": "object" } ``` --- Source: https://jabara.iamtatsuki05.com/docs/reference/api.html # 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 ```{eval-rst} .. automodule:: jabara.types ``` ## Codecs ```{eval-rst} .. automodule:: jabara.codecs.base .. automodule:: jabara.codecs.registry .. automodule:: jabara.codecs.builtin .. automodule:: jabara.codecs.delta .. automodule:: jabara.codecs.quant .. automodule:: jabara.codecs.zipnn ``` ## Assignment ```{eval-rst} .. automodule:: jabara.assign ``` ## Roles ```{eval-rst} .. automodule:: jabara.schemas ``` ## Archives ```{eval-rst} .. automodule:: jabara.container ``` ## Nested state ```{eval-rst} .. automodule:: jabara.skeleton ``` ## Torch state ```{eval-rst} .. automodule:: jabara.torch ``` ## Files and directories ```{eval-rst} .. automodule:: jabara.files .. automodule:: jabara.formats.base .. automodule:: jabara.formats.registry .. automodule:: jabara.formats.safetensors .. automodule:: jabara.formats.torch_zip .. automodule:: jabara.formats.splice .. automodule:: jabara.formats.npy .. automodule:: jabara.formats.gguf .. automodule:: jabara.formats.hdf5 ``` ## Comparison ```{eval-rst} .. automodule:: jabara.bench ``` ## Command line ```{eval-rst} .. automodule:: jabara.cli :no-members: .. autofunction:: jabara.cli.main .. autoclass:: jabara.cli.Listing ``` ## Hugging Face Trainer ```{eval-rst} .. automodule:: jabara.hf ``` ## PyTorch Lightning ```{eval-rst} .. automodule:: jabara.lightning ``` ## Errors ```{eval-rst} .. automodule:: jabara.errors ```