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 Tutorial: compress and restore a checkpoint).

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 there and run it. Like the Tutorial: compress and restore a checkpoint, it needs the torch extra and safetensors. It writes checkpoint-1000/, which the examples use.

$ 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). It trains three more AdamW steps from checkpoint-1000 and writes checkpoint-1100 with the same file names:

"""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}))
$ 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:

$ 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:

$ 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:

$ 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:

$ 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 Command line 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 Use Jabara with the 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:

$ 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: <archive>: <owner>: base <name> (index crc <c>) is missing or changed for a link behind the archive's own base, where <owner> 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:

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

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

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()
MissingBaseError
BaseMismatchError
  • With no base, reading a delta tensor raises MissingBaseError. On the command line, decompress and verify print jabara: <archive>: tensor '<name>' 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:

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)
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. Compare codecs on your own checkpoint explains the rows.