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

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.

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

for location in [None, "cpu", torch.device("cpu")]:
    print(load_state("model.jbr", map_location=location)["weight"].device)
cpu
cpu
cpu

Choose roles with a schema

A tensor's role is a label that assigners and analysis read (see 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:

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

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()}))
['adam_m', 'adam_v', 'step', 'weight']

MuonSchema differs from OptimizerSchema in one name: it gives momentum_buffer the role muon_momentum. Add a codec, an assigner, a state schema, or a file format 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 Choose codecs per role), allow_lossy (see Opt in to a lossy codec and read the recorded error), and base (see Store a checkpoint as a difference against a base). load_state takes threads and base.