"""Compress the checkpoints of one Hugging Face `Trainer` instance. See DESIGN.md, "Adapters".
This adapter relies on private `Trainer` methods that transformers does not keep stable: `_save_checkpoint`,
`_load_from_checkpoint`, `_load_optimizer_and_scheduler`, and `_load_best_model`, and on the checkpoint file
names `model*.safetensors`, `pytorch_model*.bin`, and `optimizer.pt`. The tests cover transformers 5.20.2 (Python 3.10) and 5.24.1;
`pyproject.toml` allows `>=5.0`, so other releases are untested. A transformers release that renames one of
these methods or changes its signature breaks `attach`.
An interrupted save (an `Exception`, `KeyboardInterrupt`, or `SystemExit` raised after the Trainer has written
the checkpoint) leaves every `*.safetensors` file and `optimizer.pt` as its original, as its original beside a
verified archive, or as that archive alone, with no temporary file:
- Interrupted while the archives are written: the archives this save wrote are removed and every original is
there, so the plain Trainer loads the checkpoint. An older save's archive beside an original may stay.
- Interrupted once all are written, while the originals are deleted: some files exist only as archives, and
the checkpoint needs Jabara.
A resume with Jabara attached reads each state as the Trainer saved it, using an original where there is one,
and leaves the directory as it found it, even when the resume itself is interrupted (DESIGN.md lists what a
hard crash leaves). It never deletes an original beside its archive, so such an original stays until the
Trainer saves that step again, which leaves the checkpoint compressed, or deletes it as an old checkpoint.
"""
from __future__ import annotations
import os
import re
import shutil
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Literal
from jabara.assign import Assigner
from jabara.container import Archive, _check_threads
from jabara.errors import BaseMismatchError, JabaraError
from jabara.files import (
SUFFIX,
ParentScan,
checkpoint_dirs,
checkpoint_files,
compress_dir,
decompress_file,
missing_base,
)
if TYPE_CHECKING:
import torch
from transformers import Trainer, TrainingArguments
# The weights files the Trainer's loaders read, of those `compress_dir` takes.
_WEIGHTS = (f"*.safetensors{SUFFIX}", f"pytorch_model*.bin{SUFFIX}")
_OPTIMIZER = (f"optimizer.pt{SUFFIX}",)
_ABSENT = object()
@dataclass(frozen=True)
class _Attachment:
previous: dict[str, object]
wrappers: dict[str, Callable[..., None]]
@contextmanager
def _keep_mtime(directory: str) -> Iterator[None]:
# The Trainer rotates checkpoints by directory mtime; touching an old checkpoint would make it look newest.
st = Path(directory).stat()
try:
yield
finally:
os.utime(directory, ns=(st.st_atime_ns, st.st_mtime_ns))
@contextmanager
def _restored(directory: str | None, patterns: tuple[str, ...], threads: int | None) -> Iterator[None]:
if directory is None or not os.path.isdir(directory):
yield
return
restored: list[Path] = []
with _keep_mtime(directory):
try:
for archive in sorted(a for pattern in patterns for a in Path(directory).glob(pattern)):
original = archive.with_suffix("")
# An original next to its archive wins: the archive was made from it or is older. Not deleted, since
# the two cases look alike (DESIGN.md, "jabara.hf", interrupted saves).
if not original.exists():
# Registered before the restore starts: an interrupt after its rename must still remove it.
restored.append(original)
decompress_file(archive, keep=True, threads=threads, base=_bases_of(archive))
yield
finally:
# Remove every restored file even if one removal fails, so none is left to be mistaken for a crash leftover.
errors: list[OSError] = []
for path in restored:
try:
path.unlink(missing_ok=True)
except OSError as e:
errors.append(e)
if errors:
raise errors[0]
def _bases_of(archive: Path) -> list[Path] | None:
"""The archives that the delta archive `archive` is written against, found among the sibling checkpoint directories
by file name and index CRC-32; None for a full archive. `BaseMismatchError` names a base that no sibling holds."""
with Archive.open(archive) as a:
if not a.index.base_refs():
return None
found, missing = ParentScan(checkpoint_dirs(archive.parent.parent)).resolve(archive)
if missing:
raise BaseMismatchError(f"{archive}: {missing_base(missing[0])}")
return found
def _checkpoints(run_dir: str) -> list[Path]:
return [d for d in Path(run_dir).glob("checkpoint-*") if d.is_dir() and re.fullmatch(r"checkpoint-[0-9]+", d.name)]
def _step(directory: Path) -> int:
return int(directory.name.split("-")[1])
def _is_full(directory: Path) -> bool:
"""Whether every checkpoint file of `directory` has its archive and no archive is a delta: a usable base."""
archives = sorted(directory.glob(f"*{SUFFIX}"))
if not archives or any(not p.with_name(p.name + SUFFIX).exists() for p in checkpoint_files(directory)):
return False
for a in archives:
try:
with Archive.open(a) as opened:
if opened.index.base_refs():
return False
except (JabaraError, OSError):
return False # a damaged archive is no base; it must not stop every later save
return True
def _first_base(run_dir: str, directory: Path) -> Path | None:
"""The oldest earlier checkpoint that is a usable base; None when there is none, and the new one is then written
in full and becomes the base of the later ones."""
return next(
(d for d in sorted(_checkpoints(run_dir), key=_step) if _step(d) < _step(directory) and _is_full(d)), None
)
def _rotate(run_dir: str, limit: int | None, newest: Path, best: str | None) -> None:
"""The Trainer's rotation, except that a checkpoint that a kept one needs as its base is kept too, and counts
toward `limit`. Like the Trainer, it keeps the newest and the best checkpoint, and keeps at least that many."""
if limit is None or limit <= 0:
return
dirs = sorted(_checkpoints(run_dir), key=lambda d: (d.stat().st_mtime_ns, _step(d)))
scan = ParentScan(dirs)
needs = {d: {b.parent for a in scan.archives(d) for b in scan.resolve(a)[0]} for d in dirs}
protected: set[Path] = set()
best_dir = next((d for d in dirs if best and d.resolve() == Path(best).resolve()), None)
pending = [d for d in (newest, best_dir) if d in dirs]
while pending:
d = pending.pop()
if d not in protected:
protected.add(d)
pending += needs[d]
remaining = list(dirs)
for d in dirs:
if len(remaining) <= max(limit, len(protected)):
break
if d not in protected and not any(d in needs[o] for o in remaining if o != d):
shutil.rmtree(d, ignore_errors=True)
remaining.remove(d)
[docs]
def check_arguments(args: TrainingArguments, *, threads: int | None = None) -> None:
"""Raise `ValueError` for the settings `attach` refuses that `TrainingArguments` and `threads` already show.
Call it before building the `Trainer`: `Trainer(...)` creates the Hub repository for `push_to_hub` before
`attach` can refuse the `hub_strategy`. `attach` repeats these checks, and also refuses DeepSpeed and FSDP, which
only the built `Trainer` reports.
"""
from transformers.trainer_utils import HubStrategy
_check_threads(threads)
if args.push_to_hub and args.hub_strategy in (HubStrategy.CHECKPOINT, HubStrategy.ALL_CHECKPOINTS):
raise ValueError(
f"hub_strategy={HubStrategy(args.hub_strategy).value!r} uploads checkpoint folders in the background, "
"which would race with compression; use 'every_save' or 'end'"
)
if args.world_size > 1:
raise ValueError("jabara.hf supports single-process training only")
def _check_delta(delta: str | None, args: TrainingArguments) -> None:
if delta not in (None, "first"):
raise ValueError(f"delta must be None or 'first', not {delta!r}")
if delta is not None and args.save_total_limit == 1:
# At the end of training the Trainer deletes every checkpoint but the best when the limit is 1: the base too.
raise ValueError("delta checkpoints need save_total_limit other than 1: the Trainer would delete their base")
[docs]
def attach(
trainer: Trainer,
*,
threads: int | None = None,
assign: Assigner | None = None,
allow_lossy: bool = False,
delta: Literal["first"] | None = None,
) -> None:
"""Compress every checkpoint `trainer` saves, and restore it for resume and `load_best_model_at_end`.
Compression runs synchronously at the end of each save. Attaching again replaces the earlier settings. Raises
`ValueError`, before changing anything, for `threads` below 1, a Hub upload strategy that uploads checkpoint
folders, more than one process, DeepSpeed, or FSDP.
With `delta="first"` each checkpoint but the first is saved as a delta against the oldest earlier checkpoint that
is fully compressed with full archives, and `save_total_limit` rotation keeps that base. Refused with
`save_total_limit=1`, and for any other value.
"""
from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
check_arguments(trainer.args, threads=threads)
_check_delta(delta, trainer.args)
# The flags Trainer.__init__ derives from the accelerator's plugins (and, for XLA, from args.fsdp_config).
# Both engines save sharded state in their own layouts and load it through their own code, past the loaders
# wrapped below, so a resume would meet archives nothing restores.
if trainer.is_deepspeed_enabled:
raise ValueError("jabara.hf does not support DeepSpeed: it saves and loads sharded checkpoints itself")
if trainer.is_fsdp_enabled or trainer.is_fsdp_xla_enabled:
raise ValueError("jabara.hf does not support FSDP: it saves and loads sharded checkpoints itself")
detach(trainer)
save_checkpoint = trainer._save_checkpoint # noqa: SLF001 - the hooks this adapter wraps (module docstring)
load_from_checkpoint = trainer._load_from_checkpoint # noqa: SLF001 - the hooks this adapter wraps (module docstring)
load_optimizer_and_scheduler = trainer._load_optimizer_and_scheduler # noqa: SLF001 - the hooks this adapter wraps (module docstring)
load_best_model = trainer._load_best_model # noqa: SLF001 - the hooks this adapter wraps (module docstring)
def _save_checkpoint(model: torch.nn.Module, trial: object) -> None:
run_dir = trainer._get_output_dir(trial=trial) # noqa: SLF001 - where Trainer._save_checkpoint saves
limit = trainer.args.save_total_limit
if delta is not None:
_check_delta(delta, trainer.args)
# The Trainer rotates inside its save, before the new checkpoint is compressed, and would delete a base.
trainer.args.save_total_limit = None
try:
save_checkpoint(model, trial)
finally:
if delta is not None:
trainer.args.save_total_limit = limit
# Joined as Trainer._save_checkpoint joins it, so the path is spelled as the Trainer spelled it.
directory = os.path.join(run_dir, f"{PREFIX_CHECKPOINT_DIR}-{trainer.state.global_step}") # noqa: PTH118 - see above
with _keep_mtime(directory):
base = _first_base(run_dir, Path(directory)) if delta is not None else None
compress_dir(directory, threads=threads, assign=assign, allow_lossy=allow_lossy, base=base)
if delta is not None:
_rotate(run_dir, limit, Path(directory), trainer.state.best_model_checkpoint)
def _load_from_checkpoint(resume_from_checkpoint: str, model: torch.nn.Module | None = None) -> None:
with _restored(resume_from_checkpoint, _WEIGHTS, threads):
load_from_checkpoint(resume_from_checkpoint, model)
def _load_optimizer_and_scheduler(checkpoint: str | None) -> None:
with _restored(checkpoint, _OPTIMIZER, threads):
load_optimizer_and_scheduler(checkpoint)
def _load_best_model() -> None:
with _restored(trainer.state.best_model_checkpoint, _WEIGHTS, threads):
load_best_model()
wrappers: dict[str, Callable[..., None]] = {
"_save_checkpoint": _save_checkpoint,
"_load_from_checkpoint": _load_from_checkpoint,
"_load_optimizer_and_scheduler": _load_optimizer_and_scheduler,
"_load_best_model": _load_best_model,
}
previous = {name: trainer.__dict__.get(name, _ABSENT) for name in wrappers}
trainer.__dict__.update(wrappers)
trainer.__dict__["_jabara"] = _Attachment(previous, wrappers)
[docs]
def detach(trainer: Trainer) -> None:
"""Undo `attach`. Checkpoints already compressed stay compressed and need Jabara to resume."""
attachment = trainer.__dict__.get("_jabara")
if attachment is None:
return
for name, wrapper in attachment.wrappers.items():
if trainer.__dict__.get(name) is not wrapper:
raise RuntimeError(f"Trainer.{name} was replaced after jabara.hf.attach; detaching would drop that change")
for name, value in attachment.previous.items():
if value is _ABSENT:
del trainer.__dict__[name]
else:
trainer.__dict__[name] = value
del trainer.__dict__["_jabara"]