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

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

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")))
['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 Choose codecs per role). 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 Use Jabara with the 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:

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()))
[('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:

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

try:
    Regressor.load_from_checkpoint("checkpoints/epoch=1-step=8.ckpt")
except Exception as error:
    print(type(error).__name__)
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:

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

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:

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

try:
    JabaraCheckpointIO().save_checkpoint({}, "s3://bucket/last.ckpt")
except ValueError as error:
    print(error)
s3://bucket/last.ckpt: JabaraCheckpointIO reads and writes local files only; pass a plain path