Source code for kempnerforge.checkpoint.layout

"""Where a checkpoint keeps its DCP shards, and whether a step directory holds a whole save.

A save without pipeline parallelism writes one DCP index, ``.metadata``, at the top of its
``step_N`` directory: the flat layout. A save under pipeline parallelism writes one per stage,
in ``pp0/`` to ``pp{n-1}/``, and records ``n`` as ``pp`` in the checkpoint's ``metadata.json``.
A checkpoint saved before that record existed shows its degree only by the stage directories it
holds.

Beside the shards, a save's rank 0 writes ``train_state.pt`` and then ``metadata.json``.
``is_complete_checkpoint`` says whether a step directory holds every file of a save, by the
rule auto-resume applies, so code that reads a run's checkpoints while the run saves them
agrees with it.
"""

from __future__ import annotations

import json
import logging
import os
import re
from collections.abc import Iterable, Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import Any

import torch.distributed.checkpoint as dcp

logger = logging.getLogger(__name__)

DCP_INDEX_FILE = ".metadata"
METADATA_FILE = "metadata.json"
TRAIN_STATE_FILE = "train_state.pt"
PP_DEGREE_KEY = "pp"
_OPTIMIZER_KEY = "optimizer"
_STAGE_DIR = re.compile(r"pp(\d+)")


[docs] @dataclass(frozen=True) class SavedLayout: """How a checkpoint lays out its DCP shards. ``stages`` is 0 for the flat layout, and otherwise the number of pipeline stages, each with its own DCP index in ``pp{k}/``. ``recorded`` is whether the checkpoint's ``metadata.json`` records ``stages``; when it does not, ``stages`` is the number of stage directories the checkpoint holds. """ stages: int recorded: bool = False @property def flat(self) -> bool: """Whether the checkpoint was saved without pipeline parallelism.""" return self.stages == 0
[docs] def describe(self) -> str: """The layout in words, as the errors that refuse it name it.""" if self.flat: return "saved without pipeline parallelism, with one DCP index at its top" dirs = "pp0/" if self.stages == 1 else f"pp0/ to pp{self.stages - 1}/" if self.recorded: return ( f"saved with pipeline parallelism at pp={self.stages}, with one DCP index per " f"stage in {dirs}" ) return ( f"saved with pipeline parallelism before the degree was recorded, with " f"{self.stages} stage directories ({dirs})" )
[docs] def stage_dir(ckpt_dir: Path, stage: int) -> Path: """The directory that holds pipeline stage ``stage``'s DCP shards in ``ckpt_dir``.""" return ckpt_dir / f"pp{stage}"
def _found_stage_dirs(ckpt_dir: Path) -> list[Path]: if not ckpt_dir.is_dir(): return [] found = [ (int(match[1]), d) for d in ckpt_dir.iterdir() if d.is_dir() and (match := _STAGE_DIR.fullmatch(d.name)) ] return [d for _, d in sorted(found)] def _read_record(ckpt_dir: Path) -> Mapping[str, Any]: path = ckpt_dir / METADATA_FILE try: meta = json.loads(path.read_text()) except (FileNotFoundError, NotADirectoryError): return {} except Exception as e: logger.warning(f"Could not read the pipeline degree from {path}: {e}") return {} return meta if isinstance(meta, dict) else {} def _recorded_degree(meta: Mapping[str, Any], path: Path) -> int | None: degree = meta.get(PP_DEGREE_KEY) if degree is None: return None if isinstance(degree, bool) or not isinstance(degree, int) or degree < 1: logger.warning(f"{path} records {PP_DEGREE_KEY}={degree!r}, which is not a pipeline degree") return None return degree
[docs] def saved_layout(ckpt_dir: Path, meta: Mapping[str, Any] | None = None) -> SavedLayout | None: """How ``ckpt_dir`` lays out its DCP shards, None when it holds no DCP index. The degree ``metadata.json`` records comes first. Without one, a ``.metadata`` at the top makes the layout flat, and ``pp{k}/`` directories make it a stage layout of as many stages, whether or not each holds its index yet. A record of something other than a positive integer is logged and counts as none. Args: ckpt_dir: The checkpoint directory. meta: The JSON object the checkpoint's ``metadata.json`` holds, when the caller has read it. Without it the file is read here, and one that cannot be read is logged and counts as recording no degree. """ record = _read_record(ckpt_dir) if meta is None else meta recorded = _recorded_degree(record, ckpt_dir / METADATA_FILE) if recorded is not None: return SavedLayout(recorded, recorded=True) if (ckpt_dir / DCP_INDEX_FILE).exists(): return SavedLayout(0) found = _found_stage_dirs(ckpt_dir) return SavedLayout(len(found)) if found else None
[docs] def stage_dirs(ckpt_dir: Path, layout: SavedLayout) -> list[Path]: """The stage directories of ``layout`` in ``ckpt_dir``, in stage order. These are ``pp0/`` to ``pp{n-1}/`` when ``metadata.json`` records ``n``, whether or not each exists, and otherwise the ``pp{k}/`` directories ``ckpt_dir`` holds. """ if layout.recorded: return [stage_dir(ckpt_dir, k) for k in range(layout.stages)] return _found_stage_dirs(ckpt_dir)
def _holds_optimizer(saved_keys: Iterable[str]) -> bool: """Return whether a checkpoint's keys include the optimizer entry, in either layout.""" return any(key == _OPTIMIZER_KEY or key.startswith(f"{_OPTIMIZER_KEY}.") for key in saved_keys) def _optimizer_state_saved(dcp_dirs: Iterable[Path]) -> bool: """Whether a DCP index in ``dcp_dirs`` holds optimizer state. An index that cannot be read is logged and counted as holding none, which leaves the load to report it. """ for dcp_dir in dcp_dirs: try: saved_keys = dcp.FileSystemReader(str(dcp_dir)).read_metadata().state_dict_metadata except Exception as e: logger.warning( f"Could not read {dcp_dir / DCP_INDEX_FILE} to tell whether it holds " f"optimizer state: {e}" ) continue if _holds_optimizer(saved_keys): return True return False def _listed(names: list[str]) -> str: """Directory names as a phrase, such as ``pp1/ and pp2/``.""" dirs = [f"{name}/" for name in names] return dirs[0] if len(dirs) == 1 else f"{', '.join(dirs[:-1])} and {dirs[-1]}" def _incomplete_reason( ckpt_dir: Path, num_stages: int | None = None, require_train_state: bool = True ) -> str | None: """Why ``ckpt_dir`` is not a complete save, None when it is (see ``is_complete_checkpoint``).""" layout = saved_layout(ckpt_dir) if layout is None: return f"it holds no DCP index ({DCP_INDEX_FILE})" dcp_dirs = [ckpt_dir] if layout.flat else stage_dirs(ckpt_dir, layout) unsaved = [d.name for d in dcp_dirs if not (d / DCP_INDEX_FILE).exists()] if unsaved: verb = "has" if len(unsaved) == 1 else "have" return f"{_listed(unsaved)} {verb} no DCP index ({DCP_INDEX_FILE})" if not layout.flat and not layout.recorded and num_stages is not None and num_stages > 1: absent = [ stage_dir(ckpt_dir, k).name for k in range(num_stages) if not (stage_dir(ckpt_dir, k) / DCP_INDEX_FILE).exists() ] if absent: return ( f"it records no pipeline degree, this run has {num_stages} stages, and " f"{_listed(absent)} {'is' if len(absent) == 1 else 'are'} not there" ) if not require_train_state: return None if (ckpt_dir / TRAIN_STATE_FILE).exists(): if (ckpt_dir / METADATA_FILE).exists(): return None return f"it has {TRAIN_STATE_FILE} but no {METADATA_FILE}, which rank 0 writes after it" if _optimizer_state_saved(dcp_dirs): return f"it holds optimizer state but no {TRAIN_STATE_FILE}" return None
[docs] def is_complete_checkpoint( ckpt_dir: str | os.PathLike[str], num_stages: int | None = None, *, require_train_state: bool = True, ) -> bool: """Whether ``ckpt_dir`` holds a complete save, by the rule auto-resume applies. ``resolve_resume_path`` picks a checkpoint this accepts whenever there is one, and so does the fallback of an exact resume in ``CheckpointManager.load``. Code that reads a run's checkpoints while the run saves them, such as a process that evaluates each saved step, calls it to count the same steps as saved. A save is complete when every DCP index of its layout is there (see ``saved_layout``): ``.metadata`` at the top of a checkpoint saved without pipeline parallelism, and in each of ``pp0/`` to ``pp{n-1}/`` of one that records its pipeline degree ``n``. A stage checkpoint saved before the degree was recorded needs an index in every ``pp{k}/`` it holds and, with ``num_stages``, in ``pp0/`` to ``pp{num_stages - 1}/``, since a stage that stopped before its save began leaves no directory. With ``require_train_state``, a checkpoint whose shards hold optimizer state, or that has a ``train_state.pt``, also needs ``train_state.pt`` and ``metadata.json``. A save's rank 0 writes the two, ``metadata.json`` after ``train_state.pt``: after every stage's shards when the save is synchronous, and while they flush when it is asynchronous, so either may land first. A checkpoint with neither optimizer state nor ``train_state.pt``, such as an ``hf-to-dcp`` import, needs neither file. To tell which it is, the DCP index is read only when ``train_state.pt`` is absent; reading it unpickles it, as a load does. An index that cannot be read is logged and counted as holding no optimizer state, which leaves the load to report it. With ``require_train_state`` and ``num_stages``, a process that polls a live run gets a step only once its save has written every file, except a save made before the optimizer's first step: its shards hold no optimizer state, so, like an import, it counts once its DCP indexes are there, before rank 0 writes ``train_state.pt`` and ``metadata.json``. It then drops out while ``train_state.pt`` is there without ``metadata.json``, and counts again once ``metadata.json`` lands, so a poller counts a step the first time this accepts it. Without ``num_stages``, a pipeline-parallel save can count early too: it records its degree only in ``metadata.json``, which can land after the first stage's index, so it counts once the stage directories that exist hold their indexes, before a later stage has created its own. Args: ckpt_dir: A ``step_N`` directory, or a link to one such as ``latest``. num_stages: The pipeline degree of the run that reads the checkpoint, or None. It counts only for a stage checkpoint that records no degree, as a live save does until its ``metadata.json`` lands: one that records it is complete at its own degree, and a load refuses a degree the run cannot load. require_train_state: True for a resume, which restores the step, LR schedule and data position from ``train_state.pt``; False for a reader of the weights alone, such as ``scripts/eval.py``, which needs only the DCP shards. Returns: Whether the save is complete; False for a path that is no directory, or one that holds no DCP index. """ return _incomplete_reason(Path(ckpt_dir), num_stages, require_train_state) is None