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

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

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 What the Trainer adapter does inside a 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 Choose codecs per role), and a lossy assigner needs allow_lossy=True (see Opt in to a lossy codec and read the recorded error).

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

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

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

plain = make_trainer(make_arguments())
try:
    plain.train(resume_from_checkpoint="out/checkpoint-2")
except ValueError as error:
    print(error)
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.

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

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

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:

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

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