"""PyTorch Lightning `CheckpointIO` that stores checkpoints as Jabara archives. See DESIGN.md, "Adapters"."""
from __future__ import annotations
import os
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast
from fsspec.core import split_protocol
from lightning.pytorch.plugins.io import CheckpointIO
from jabara.assign import Assigner
from jabara.container import _check_threads
from jabara.schemas import OptimizerSchema
from jabara.torch import load_state, save_state
from jabara.types import Role
if TYPE_CHECKING:
import torch
class _CheckpointSchema(OptimizerSchema):
def role(self, path: tuple[object, ...]) -> Role:
if path[:1] == ("state_dict",):
return "weight"
return super().role(path)
def _local(path: str | os.PathLike[str]) -> str | os.PathLike[str]:
"""Refuse anything fsspec reads as a URL (`s3://`, `memory://`, `file://`), which Lightning would route to a
remote filesystem but `save_state` would treat as a relative local path.
"""
if split_protocol(os.fspath(path))[0] is not None:
raise ValueError(f"{path}: JabaraCheckpointIO reads and writes local files only; pass a plain path")
return path
[docs]
class JabaraCheckpointIO(CheckpointIO):
"""Lossless: `load_checkpoint` returns the dict `save_checkpoint` received, tensors bit for bit.
Every `OrderedDict` that carries `_metadata`, wherever it sits in the checkpoint (the module `state_dict`,
the averaged model of `StochasticWeightAveraging`), comes back with it, as `save_state` keeps it; other values
must be tensors, plain JSON values, or dicts, lists, and tuples of them, or saving raises `UnsupportedStateError`.
"""
def __init__(
self, *, threads: int | None = None, assign: Assigner | None = None, delta: str | None = None
) -> None:
if delta is not None:
raise ValueError(
"JabaraCheckpointIO writes full archives only: Lightning's ModelCheckpoint rewrites last.ckpt in place "
"and removes the checkpoints it ranks worst, in any order, through remove_checkpoint, so a base "
"could not be kept safely. Use jabara.hf.attach(trainer, delta='first') or `jabara compress "
"--recursive --delta first` on a directory of checkpoints"
)
_check_threads(threads)
self.threads = threads
self.assign = assign
[docs]
def save_checkpoint(
self, checkpoint: dict[str, Any], path: str | os.PathLike[str], storage_options: object = None
) -> None:
"""Write `checkpoint` to `path` as an archive, creating parent directories. Raises `ValueError` for a URL path,
`TypeError` if `storage_options` is given, `UnsupportedStateError` for a value Jabara cannot store, and
`LossyNotAllowedError` if `assign` picks a lossy codec.
"""
if storage_options is not None:
raise TypeError("JabaraCheckpointIO.save_checkpoint does not take storage_options")
path = _local(path)
Path(path).parent.mkdir(parents=True, exist_ok=True)
save_state(
checkpoint,
path,
schema=_CheckpointSchema(),
threads=self.threads,
assign=self.assign,
)
[docs]
def load_checkpoint(
self,
path: str | os.PathLike[str],
map_location: object = None,
weights_only: bool | None = None, # noqa: ARG002, FBT001 - CheckpointIO.load_checkpoint's signature
) -> dict[str, Any]:
"""Return the checkpoint dict that was saved at `path`, with tensors on `map_location` (CPU if None).
`weights_only` is ignored. Raises `ValueError` if `map_location` is not None, a `str`, or a `torch.device`,
or names the meta device.
"""
# load_state checks map_location at run time (DESIGN.md), and the archive holds the dict save_checkpoint got.
state = load_state(
_local(path), map_location=cast("str | torch.device | None", map_location), threads=self.threads
)
return cast("dict[str, Any]", state)
[docs]
def remove_checkpoint(self, path: str | os.PathLike[str]) -> None:
"""Delete the file at `path` if it exists."""
local = Path(_local(path))
if os.path.exists(local):
local.unlink()