Source code for kempnerforge.checkpoint.manager

"""Checkpoint manager for distributed checkpointing.

Uses PyTorch Distributed Checkpoint (DCP) for model and optimizer state,
which supports automatic resharding: a checkpoint saved on N GPUs loads on M,
under another ``dp_shard``, ``dp_replicate`` (HSDP), ``tp`` or ``ep`` layout,
with the model and optimizer state as saved. A stage checkpoint loads only at
the pipeline degree it was saved with (see ``SavedLayout``), and a checkpoint
of an MoE model only into the expert layout, packed or not, that saved it (see
``check_saved_experts``).

Non-distributed state (scheduler, dataloader, training meta, RNG) is saved
separately as a torch file written by rank 0 and broadcast from rank 0 on
load. Scheduler and training meta restore from that single copy on every
rank. Dataloader and RNG state are per-rank: every rank's payload is gathered
into a versioned envelope at save time, and on an exact resume
(``load(exact_resume=True)``) each rank restores its own entry from the
broadcast (see ``kempnerforge.checkpoint.state``). Any other load (a
``load_path`` warm start, evaluation) restores rank 0's single copy on every
rank. A weights-only warm start (``exclude_keys=["optimizer", "train_state"]``)
reads no ``train_state.pt``, so it restores neither and checks no topology.

Resharding model and optimizer state is therefore free, but an exact resume
is not: a rank's RNG streams, and a loader cursor kept per rank, are valid
only on the world size and data-parallel layout that saved them, so an exact
resume under a changed topology raises on every rank. Setting
``checkpoint.ignore_rank_state_mismatch`` resumes it anyway: step, model,
optimizer and scheduler resume onto the new topology and the random streams
restart fresh, while the saved data position carries over where every rank's
loader can place it on the new layout, and every rank restarts at the first
sample where one cannot. That position is the one the saved rank 0 reached,
which a ``StatefulDataLoader`` counts across all data-parallel ranks, or for a
stream on the saved data-parallel size the one each data-parallel rank saved
for its own part. An envelope the flag lets through for another reason
(unreadable or incomplete) restores neither loader nor RNG state. A checkpoint
saved before per-rank state was recorded cannot show whether the topology
changed, so under the flag it resumes as if it had.
"""

from __future__ import annotations

import contextlib
import errno
import json
import logging
import os
import pickle
import re
import shutil
import socket
import stat
import threading
import time
import uuid
from collections.abc import Callable, Collection, Container, Iterable, Iterator, Mapping, Sequence
from datetime import timedelta
from functools import partial
from pathlib import Path
from typing import Any, Protocol, TypeGuard, cast

import torch
import torch.distributed as dist
import torch.distributed.checkpoint as dcp
from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import _CHECKPOINT_PREFIX
from torch.distributed.checkpoint import DefaultLoadPlanner, DefaultSavePlanner
from torch.distributed.checkpoint._nested_dict import flatten_state_dict
from torch.distributed.checkpoint._traverse import traverse_state_dict_v_2_3
from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE, Metadata, TensorStorageMetadata
from torch.distributed.checkpoint.state_dict import (
    get_model_state_dict,
    get_optimizer_state_dict,
    set_model_state_dict,
    set_optimizer_state_dict,
)

from kempnerforge.checkpoint.async_save import AsyncCheckpointer
from kempnerforge.checkpoint.expert_layout import (
    ExpertLayout,
    check_saved_experts,
    expert_layout,
    moe_layers,
    state_dict_name,
)
from kempnerforge.checkpoint.layout import (
    METADATA_FILE,
    PP_DEGREE_KEY,
    TRAIN_STATE_FILE,
    SavedLayout,
    _holds_optimizer,
    _incomplete_reason,
    is_complete_checkpoint,
    saved_layout,
    stage_dir,
)
from kempnerforge.checkpoint.ownership import claim_checkpoint_dir, release_checkpoint_dir
from kempnerforge.checkpoint.state import (
    PER_RANK_KEY,
    RankStateMismatchError,
    build_per_rank_envelope,
    build_train_state,
    capture_rank_state,
    dp_coordinates,
    restore_train_state,
    saved_data_position,
    select_rank_state,
)
from kempnerforge.config.checkpoint import is_weights_only, validate_exclude_keys
from kempnerforge.config.optimizer import WEIGHT_DECAY_SCOPES, checked_lr_multipliers
from kempnerforge.config.schema import AsyncCheckpointMode, CheckpointConfig
from kempnerforge.data.dataloader import (
    DataPositionError,
    StatefulDataLoader,
    StreamingDataLoader,
)
from kempnerforge.distributed.utils import agree_across_ranks

logger = logging.getLogger(__name__)

_TRAIN_STATE_FILE = TRAIN_STATE_FILE
_METADATA_FILE = METADATA_FILE
_OPTIM_STATE_PREFIX = "optimizer.state."
_OPTIM_PARAM_GROUPS_PREFIX = "optimizer.param_groups."
_NEVER_STEPPED_KEY = "optimizer_never_stepped"
_NEVER_STEPPED_PREFIX = f"{_NEVER_STEPPED_KEY}."
_OPTIM_PREFIX = "optimizer."
_MODEL_PREFIX = "model."
_UNRECORDED_WEIGHT_DECAY_SCOPE = "exclude_norms_and_biases"
_TRANSIENT_REMOVE_ERRNOS = frozenset({errno.ENOTEMPTY, errno.EBUSY, errno.ENOENT})
_REMOVE_RETRY_DELAYS = (0.05, 0.1, 0.2, 0.4)
TrackingSource = Callable[[], list[dict[str, str]]]
CheckpointRecord = Callable[[str, dict[str, str]], None]
_MetadataOutcome = tuple[dict[str, Any] | None, str | None]
_FreezeExpectation = list[dict[str, Any]] | Callable[[int], list[dict[str, Any]]]


[docs] class CheckpointRegistrar(Protocol): """Records checkpoints with the logging backends, which this module never imports."""
[docs] def checkpoint_fields(self, step: int) -> dict[str, dict[str, str]]: """Fields each backend adds to its record of the checkpoint saved at ``step``, by backend. Called on rank 0 inside ``save()``, so it must answer from what it holds, never a server. """ ...
[docs] def register_checkpoint(self, step: int, directory: Path, record: CheckpointRecord) -> None: """Register the checkpoint at ``directory`` once ``latest`` points at it. Called on rank 0 when the checkpoint is committed, so it must not block. ``record`` adds fields to a backend's record in that checkpoint's ``metadata.json``, from any thread, later. """ ...
def _saved_optimizer_param_groups(saved_keys: Iterable[str]) -> int: """Count the optimizer param groups among a DCP checkpoint's keys.""" return len( { key.removeprefix(_OPTIM_PARAM_GROUPS_PREFIX).split(".", 1)[0] for key in saved_keys if key.startswith(_OPTIM_PARAM_GROUPS_PREFIX) } )
[docs] def derived_buffer_owners(model: torch.nn.Module) -> dict[str, tuple[torch.nn.Module, str]]: """Map the state-dict key of each buffer a module lists in ``derived_buffers`` to its owner. A module lists there the buffers it gained after its checkpoints were first written and derives from its other state when a load lacks them, as the sigmoid router does for its FP32 masters. Each key maps to the module and the buffer's name; a buffer another module holds under the same name is not one of them. The keys are named as ``get_model_state_dict`` names them (see ``state_dict_name``). """ owners: dict[str, tuple[torch.nn.Module, str]] = {} for name, module in model.named_modules(): prefix = state_dict_name(name) for buffer in getattr(module, "derived_buffers", ()): owners[f"{prefix}.{buffer}" if prefix else buffer] = (module, buffer) return owners
[docs] def drop_derived_model_keys( model_state: dict[str, Any], model: torch.nn.Module, saved_keys: Container[str] ) -> dict[str, Any]: """Take out of a load template the derived buffers its checkpoint predates. Only the buffers ``derived_buffer_owners`` maps are taken out, and only those the checkpoint, whose keys prefix the model's with ``model.``, lacks; any other key a checkpoint lacks still fails the load. Returns the entries taken out. Put back after the read, they let the strict ``set_model_state_dict`` find every key, under ``torch.compile`` too, and ``derive_buffers`` then recomputes them from the loaded state. """ owners = derived_buffer_owners(model) return { key: model_state.pop(key) for key in list(model_state) if key in owners and f"model.{key}" not in saved_keys }
[docs] def derive_buffers(model: torch.nn.Module, keys: Iterable[str]) -> None: """Have the owner of each derived buffer at ``keys`` recompute it from its loaded state. Only those buffers are derived; every other entry keeps the value loaded. Deriving may gather a parameter that FSDP2 shards, so every rank calls this with the same keys. Raises: TypeError: A module lists ``derived_buffers`` but has no ``derive_buffers``. """ owners = derived_buffer_owners(model) wanted: dict[torch.nn.Module, list[str]] = {} for key in keys: module, name = owners[key] wanted.setdefault(module, []).append(name) for module, names in wanted.items(): derive = getattr(module, "derive_buffers", None) if derive is None: raise TypeError( f"{type(module).__name__} lists derived_buffers but has no derive_buffers" ) derive(names)
def _saved_inner_groups( saved_keys: Iterable[str], outer: torch.optim.Optimizer, inner: Sequence[torch.optim.Optimizer], ) -> bool: """Whether a checkpoint's optimizer param groups include groups of ``inner``. ``outer`` is the optimizer that wraps ``inner``, such as Muon around its AdamW fallback. A group of ``inner`` shows by a setting that no group of ``outer`` has, such as AdamW's ``betas``, so the count of saved groups alone does not decide it: ``outer`` can have as many groups as the checkpoint holds of both. Args: saved_keys: The keys the checkpoint's DCP index lists. outer: The optimizer that wraps ``inner``. inner: The optimizers ``outer`` wraps. Returns: True when a saved group holds a setting only ``inner``'s groups have. """ own = {key for group in outer.param_groups for key in group} theirs = {key for opt in inner for group in opt.param_groups for key in group} - own for key in saved_keys: if not key.startswith(_OPTIM_PARAM_GROUPS_PREFIX): continue parts = key.removeprefix(_OPTIM_PARAM_GROUPS_PREFIX).split(".") if len(parts) > 1 and parts[1] in theirs: return True return False def _drop_legacy_group_keys( optim_state: dict[str, Any], owners: Sequence[torch.optim.Optimizer], saved_keys: Container[str], ) -> dict[str, Any]: """Drop from a load template the param-group keys its checkpoint predates. An optimizer lists in ``LEGACY_GROUP_DEFAULTS`` the keys its param groups gained after its checkpoints were first written, and fills each one in when it loads a group without it. Only those keys are dropped, and only from the groups whose saved copy lacks them; any other key a checkpoint lacks still fails the load. Args: optim_state: The load template; its ``param_groups`` lose the dropped keys. owners: The optimizer of each template group, in order. saved_keys: The keys the checkpoint's DCP index lists. Returns: The dropped keys with the values they resume with. """ dropped: dict[str, Any] = {} for index, (group, owner) in enumerate(zip(optim_state["param_groups"], owners, strict=True)): for key, value in getattr(owner, "LEGACY_GROUP_DEFAULTS", {}).items(): if key in group and f"{_OPTIM_PARAM_GROUPS_PREFIX}{index}.{key}" not in saved_keys: del group[key] dropped[key] = value return dropped def _take_groups_the_save_lacks( optim_state: dict[str, Any], owners: list[torch.optim.Optimizer], fixed: torch.optim.Optimizer | None, left_out: set[str], saved_groups: int, ) -> list[tuple[int, dict[str, Any]]] | None: """Take out of a load template the param groups that hold only parameters the save left out. An optimizer that keeps no empty param group, such as Muon's inner AdamW, saved no group for them, and neither does one whose groups follow the trainable modules, as under ``optimizer.lr_multipliers``, so the template has more groups than the checkpoint; without them, the template groups line up with the saved ones by position. Each taken group leaves ``owners`` too. Args: optim_state: The load template; its ``param_groups`` lose the taken groups. owners: The optimizer of each template group, kept in step with ``optim_state``. fixed: The optimizer none of whose groups may be taken, or None. It is the one the LR scheduler drives when the scheduler is not a ``LambdaLR``, whose saved per-group state is restored by position instead of laid out for the groups the optimizer has (see ``restore_train_state``). left_out: The parameters with neither saved state nor a never-stepped record. saved_groups: The number of param groups the checkpoint's index lists, 0 when it stores the optimizer as one opaque entry; nothing is taken then. Returns: The index and the group of each taken group, in ascending order of index. None, with nothing taken, when the checkpoint holds fewer groups than the template and taking the groups of ``left_out`` does not leave as many, or takes a group of ``fixed``. """ groups = optim_state["param_groups"] if not saved_groups or len(groups) <= saved_groups: return [] taken = [i for i, g in enumerate(groups) if g["params"] and set(g["params"]) <= left_out] if len(groups) - len(taken) != saved_groups or any(owners[i] is fixed for i in taken): return None for i in reversed(taken): del owners[i] return [(i, groups.pop(i)) for i in reversed(taken)][::-1] def _rate_taken_groups(optimizer: torch.optim.Optimizer, scheduler: Any, taken: list[int]) -> None: """Give the param groups a load took out the rate the restored schedule runs them at. A taken group comes back with the rate ``optimizer`` was built at, while a saved group comes back with the rate of its save, which the schedule set and an active phase's ``lr_scale`` scaled. Each taken group gets the rate a ``LambdaLR`` sets, its restored base rate times its lambda at the restored step, scaled as the first saved group with a nonzero rate is. Nothing changes for a scheduler without per-group lambdas. Args: optimizer: The optimizer ``scheduler`` drives. scheduler: The LR scheduler, its state restored. taken: The indices of the taken groups among ``optimizer``'s param groups. Raises: ValueError: ``scheduler`` holds other than one base rate and one lambda per param group of ``optimizer``, as a restored ``LambdaLR`` always does. """ groups = optimizer.param_groups base_lrs = getattr(scheduler, "base_lrs", None) lambdas = getattr(scheduler, "lr_lambdas", None) if not (isinstance(base_lrs, list) and isinstance(lambdas, list)): return epoch = scheduler.last_epoch rates = [base * fn(epoch) for _, base, fn in zip(groups, base_lrs, lambdas, strict=True)] saved = next((i for i, rate in enumerate(rates) if i not in taken and rate), None) scale = groups[saved]["lr"] / rates[saved] if saved is not None else 1.0 for i in taken: groups[i]["lr"] = rates[i] * scale def _intersect_freeze_meta_by_module( saved: list[dict[str, Any]], expected: list[dict[str, Any]], ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """Filter both freeze-metadata lists to the intersection of module keys. Used at checkpoint load time to make cross-arch resumes work cleanly: a Joint-Decoder checkpoint's ``vlm_freeze`` has only ``vision_encoder``; a Cross-Attention config's expected metadata has ``vision_encoder`` + ``cross_attention`` (auto-default in ``CrossAttentionConfig.module_patterns``). Loading JD into CA: the ``cross_attention`` entry is in ``expected`` but not in ``saved``, so it gets dropped from ``expected``; the remaining ``vision_encoder`` entries compare cleanly. Real semantic mismatches on shared keys are preserved. If both sides have ``vision_encoder`` but with different ``frozen`` values, the filtered lists differ and the caller raises. The lists are already canonicalized (sorted, deduped) by ``canonical_freeze_meta``, so the filter preserves canonical order. """ saved_keys = {e["module"] for e in saved} expected_keys = {e["module"] for e in expected} shared = saved_keys & expected_keys return ( [e for e in saved if e["module"] in shared], [e for e in expected if e["module"] in shared], ) def _never_stepped_record(optim_state: dict[str, Any]) -> dict[str, torch.Tensor]: """Record the parameters the optimizer holds without any state. An optimizer keeps state only for parameters that have received a gradient, and a checkpoint stores only what it keeps. A missing state and a state that never existed look the same once the optimizer is gone, so the save writes the distinction down while it still has it: one entry per parameter the param groups list and the state omits. The entries are tensors so that they stay separate keys in the checkpoint's own index, which is all the load reads; the value itself is never loaded. """ state = optim_state["state"] return { fqn: torch.zeros((), dtype=torch.bool) for group in optim_state["param_groups"] for fqn in group["params"] if not state.get(fqn) } def _params_recorded_never_stepped(fqns: set[str], saved_keys: Iterable[str]) -> set[str]: """Return the parameters in ``fqns`` the save recorded as holding no state. A record entry names one whole parameter, so the name is the rest of its key. A parameter whose state is simply absent is not recorded and stays in the load, which then fails on it, and a recorded parameter that also has saved state makes the two disagree, so the load fails rather than drop the state it does have. Each state key counts toward the longest parameter name it starts with, so a state of any layout marks its parameter. """ recorded: set[str] = set() with_state: set[str] = set() for key in saved_keys: if key.startswith(_NEVER_STEPPED_PREFIX): recorded.add(key.removeprefix(_NEVER_STEPPED_PREFIX)) elif key.startswith(_OPTIM_STATE_PREFIX): name = key.removeprefix(_OPTIM_STATE_PREFIX) while name and name not in fqns: name = name.rpartition(".")[0] with_state.add(name) recorded &= fqns contradicted = sorted(recorded & with_state) if contradicted: raise ValueError( f"{len(contradicted)} parameters are recorded as never stepped but have saved " f"optimizer state: {contradicted[:8]}" ) return recorded def _weights_route(ckpt_dir: Path) -> str: """How to carry the weights of a stage checkpoint into a run of another layout.""" return ( f"To carry its weights over, export them with scripts/convert_checkpoint.py dcp-to-hf " f"--dcp-dir {ckpt_dir} --dtype float32, which assembles every stage, import the export " f"with hf-to-dcp, which writes a checkpoint saved without pipeline parallelism, and set " f"checkpoint.load_path to that: a run at any pipeline degree, or none, starts from its " f"weights with a fresh optimizer, at step 0." ) def _dcp_keys(dcp_dir: Path) -> dict[str, Any]: """Return the keys the DCP index in ``dcp_dir`` lists, each with its storage metadata.""" return dcp.FileSystemReader(str(dcp_dir)).read_metadata().state_dict_metadata def _held_model_entries( model_state: Mapping[str, Any], every_rank: Iterable[str] ) -> dict[str, tuple[int, ...] | None]: """The entries a load reads into the model, by every key a DCP index can hold them under. Each entry of the load's ``{"model": ...}`` state is keyed as DCP flattens it, with its global shape, None for one that is not a tensor. A checkpoint saved before DCP flattened a nested entry that holds no tensor keeps it whole under the entry's own key, which DCP's load planner still reads, so that key is listed too, with no shape. So is each name in ``every_rank``. Raises: ValueError: The state flattens to the same key twice. """ state = {"model": dict(model_state)} flat, _ = flatten_state_dict(state) held: dict[str, tuple[int, ...] | None] = {} for key, value in flat.items(): held[key] = tuple(value.shape) if isinstance(value, torch.Tensor) else None def whole(path: tuple[str | int, ...], _value: Any) -> None: held.setdefault(".".join(map(str, path)), None) traverse_state_dict_v_2_3(state, whole) for name in every_rank: held.setdefault(f"{_MODEL_PREFIX}{name}", None) return held def _model_misfit( held: Mapping[str, tuple[int, ...] | None], saved: Mapping[str, Any] ) -> tuple[list[str], list[str], list[str]]: """Compare the model entries a load reads from a DCP index with what the index holds. ``held`` maps each key the entries can be held under to its global shape, None for an entry that is not a tensor (see ``_held_model_entries``); ``saved`` is the index's ``state_dict_metadata``. Returns: The model keys of the index that no held entry takes, sorted; a description of each held tensor the index holds at another size, in key order; and the keys of the held tensors the index does not hold, sorted. """ extra = sorted(key for key in saved if key.startswith(_MODEL_PREFIX) and key not in held) resized = [] missing = [] for key, shape in sorted(held.items()): if shape is None: continue if key not in saved: missing.append(key) continue meta = saved[key] if isinstance(meta, TensorStorageMetadata) and tuple(meta.size) != shape: resized.append(f"{key} (saved {list(meta.size)}, this run {list(shape)})") return extra, resized, missing def _misfit_message( where: Path, extra: Sequence[str], resized: Sequence[str], missing: Sequence[str], offer_override: bool, ) -> str: """Why the DCP index in ``where`` does not fit the model a load would read into it. ``offer_override`` names ``checkpoint.ignore_extra_model_tensors`` as the way to load the tensors the model shares with the checkpoint, for a load whose indexes hold every tensor it reads, each at its size. """ found = [] if extra: found.append( f"{len(extra)} model tensors this run's model does not have, such as {list(extra[:5])}" ) if resized: examples = ", ".join(resized[:5]) found.append(f"{len(resized)} model tensors of another size, such as {examples}") clauses = [f"holds {' and '.join(found)}"] if found else [] if missing: clauses.append( f"lacks {len(missing)} model tensors this run loads, such as {list(missing[:5])}" ) route = "" if offer_override: route = ( ", or, to start this model from the tensors it shares with the checkpoint and leave " "the others unread, set checkpoint.ignore_extra_model_tensors = true" ) return ( f"{where} {' and '.join(clauses)}, so it was saved from another model than this run " "builds (another model config, plugins list or component), and nothing is loaded. Resume " f"or warm start it with the model it was saved from{route}." ) def _read_metadata(ckpt_dir: Path) -> dict[str, Any]: """Return the JSON object a checkpoint's ``metadata.json`` holds. Raises: ValueError: ``metadata.json`` is absent or cannot be read, or does not hold a JSON object. """ metadata_path = ckpt_dir / _METADATA_FILE if not metadata_path.exists(): raise ValueError(f"{ckpt_dir} has no {_METADATA_FILE}") try: meta = json.loads(metadata_path.read_text()) except (OSError, ValueError) as e: raise ValueError(f"cannot read {metadata_path}: {e}") from e if not isinstance(meta, dict): raise ValueError(f"{metadata_path} does not hold a JSON object") return meta def _metadata_outcome(ckpt_dir: Path) -> _MetadataOutcome: """A read of a checkpoint's ``metadata.json``: the JSON object it holds, or why there is none, as ``(None, reason)``, the file being absent, unreadable or not a JSON object.""" try: return _read_metadata(ckpt_dir), None except ValueError as e: return None, str(e) except Exception as e: return None, f"{type(e).__name__}: {e}" def _recorded_weight_decay_scope(meta: Mapping[str, Any], metadata_path: Path) -> str: """Return the weight-decay scope a checkpoint's metadata ``meta`` records. A checkpoint whose metadata lacks the field was written under ``"exclude_norms_and_biases"``, the only grouping that existed before the scope was recorded. Raises: ValueError: ``meta`` records a scope outside ``WEIGHT_DECAY_SCOPES``. """ scope = meta.get("weight_decay_scope", _UNRECORDED_WEIGHT_DECAY_SCOPE) if scope not in WEIGHT_DECAY_SCOPES: raise ValueError( f"{metadata_path} records weight_decay_scope={scope!r}, which is not one of " f"{WEIGHT_DECAY_SCOPES}" ) return scope def _recorded_step(meta: Mapping[str, Any]) -> int | None: """The step a checkpoint's metadata ``meta`` records, None unless a non-negative integer.""" step = meta.get("step") if isinstance(step, bool) or not isinstance(step, int) or step < 0: return None return step def _fresh_optimizer_route(ckpt_dir: Path) -> str: """How to continue from ``ckpt_dir`` with a fresh optimizer, as a refusal names it.""" return ( f"continue from the checkpoint with a fresh optimizer: " f"checkpoint.load_path={str(ckpt_dir)!r} with " f'checkpoint.exclude_from_loading=["optimizer"] (add "train_state" to also restart the ' f"step, schedule and data position) and a checkpoint.dir that holds no checkpoint, " f"since training auto-resumes from a checkpoint there in place of load_path, optimizer " f"state included." ) @contextlib.contextmanager def _evaluation_point(optimizer: torch.optim.Optimizer) -> Iterator[None]: """Hold the parameters at ``optimizer``'s evaluation point inside the block. An optimizer that evaluates at another point than it trains at, as schedule-free AdamW does, has ``eval_params`` and ``train_params``: the block runs between them, and the parameters leave it at the training point again, bit for bit, also when the swap or the block raises. Any other optimizer leaves them as they are. ``kempnerforge.training.optimizer.evaluation_point`` does the same for the training loop; importing it here would close an import cycle. This one takes no model: no forward runs in a save, and FSDP2's state-dict hooks reshard every unit before the state is read. """ to_eval = getattr(optimizer, "eval_params", None) to_train = getattr(optimizer, "train_params", None) if to_eval is None or to_train is None: yield return try: to_eval() yield finally: to_train() def _canonical_patterns(record: object) -> dict[str, list[str]]: """Return a ``{module: patterns}`` record with each module's patterns sorted and unique. Raises: ValueError: ``record`` does not map module names to lists of strings. """ if not isinstance(record, dict) or not all( isinstance(module, str) and isinstance(patterns, list) and all(isinstance(pattern, str) for pattern in patterns) for module, patterns in record.items() ): raise ValueError(f"expected module names mapped to lists of patterns, got {record!r}") return {module: sorted(set(patterns)) for module, patterns in record.items()} def _checked_group_modules(record: object) -> list[str | None] | None: """Return a record of the module each optimizer param group names, None when there is none. Raises: ValueError: ``record`` is not a list of module names and nulls. """ if record is None: return None if not isinstance(record, list) or not all( module is None or isinstance(module, str) for module in record ): raise ValueError(f"expected a module name or null per param group, got {record!r}") return record def _recorded_lr_multipliers(meta: Mapping[str, Any], metadata_path: Path) -> dict[str, float]: """Return the ``lr_multipliers`` a checkpoint's metadata ``meta`` records. A checkpoint whose metadata lacks the field was saved without any. Raises: ValueError: The field does not hold a valid record. """ try: return checked_lr_multipliers(meta.get("lr_multipliers", {})) except ValueError as e: raise ValueError(f"{metadata_path} records an invalid LR multipliers record: {e}") from e def _recorded_lr_layout( meta: Mapping[str, Any], metadata_path: Path ) -> tuple[dict[str, list[str]], list[str | None] | None]: """Return the ``lr_module_patterns`` and ``lr_group_modules`` a checkpoint's metadata records. The first maps each module of its ``lr_multipliers`` to its patterns; the second names the module of each optimizer param group, in the order the checkpoint keeps them, None for a group of no listed module, and is None itself when the save recorded none. Raises: ValueError: A field does not hold a valid record. """ try: patterns = _canonical_patterns(meta.get("lr_module_patterns", {})) group_modules = _checked_group_modules(meta.get("lr_group_modules")) except ValueError as e: raise ValueError(f"{metadata_path} records an invalid LR multipliers record: {e}") from e return patterns, group_modules def _lr_record( metadata: _MetadataOutcome, ckpt_dir: Path, layout: bool ) -> tuple[dict[str, float], dict[str, list[str]], list[str | None] | None]: """Return the LR multipliers record of rank 0's read of a checkpoint's ``metadata.json``. That is its ``lr_multipliers`` and, with ``layout``, its ``lr_module_patterns`` and ``lr_group_modules`` (see ``_recorded_lr_layout``); without ``layout`` they come back empty and None, unread. Raises: ValueError: Rank 0 could not read ``metadata.json``, or a field read is not a valid record. """ meta, error = metadata if meta is None: raise ValueError(error) metadata_path = ckpt_dir / _METADATA_FILE multipliers = _recorded_lr_multipliers(meta, metadata_path) if not layout: return multipliers, {}, None return multipliers, *_recorded_lr_layout(meta, metadata_path) def _reset_to_fresh(optimizer: torch.optim.Optimizer) -> None: """Return ``optimizer`` to its freshly built state, keeping its param groups.""" optimizer.load_state_dict({"state": {}, "param_groups": optimizer.state_dict()["param_groups"]}) class _NeverSteppedStatePlanner(DefaultLoadPlanner): """Load planner that leaves out the optimizer state a checkpoint does not hold. Drops from the load the parameters the save recorded as never stepped, kept in ``never_stepped`` for the caller to confirm against the saved ``param_groups``, and the parameters in ``left_out``. Every other key stays required, including one whose state is missing without a record. Args: left_out: Names of parameters the saved optimizer did not hold. """ def __init__(self, left_out: Iterable[str] = ()) -> None: super().__init__() self.left_out = frozenset(left_out) self.never_stepped: set[str] = set() def set_up_planner( self, state_dict: STATE_DICT_TYPE, metadata: Metadata | None = None, is_coordinator: bool = False, ) -> None: optim_state = state_dict.get("optimizer") if optim_state is not None and metadata is not None: fqns = set(optim_state["state"]) self.never_stepped = _params_recorded_never_stepped(fqns, metadata.state_dict_metadata) for fqn in self.never_stepped | (self.left_out & fqns): del optim_state["state"][fqn] super().set_up_planner(state_dict, metadata, is_coordinator) def _restore_never_stepped( optim_state: dict[str, Any], never_stepped: set[str], where: Path ) -> None: """Give the recorded parameters empty optimizer state once the saved optimizer lists them. ``optim_state`` holds the loaded ``param_groups``, which list every parameter the saved optimizer held, stepped or not. A recorded parameter they do not list was never part of that optimizer, so the load fails instead of guessing its state. """ held = {fqn for group in optim_state["param_groups"] for fqn in group["params"]} unheld = sorted(never_stepped - held) if unheld: raise RuntimeError( f"Missing optimizer state in {where} for {len(unheld)} trainable parameters " f"the saved optimizer did not hold: {unheld[:8]}" ) optim_state["state"].update({fqn: {} for fqn in never_stepped}) def _params_the_save_left_out( fqns: Iterable[str], saved_keys: Iterable[str], layout: ExpertLayout | None = None ) -> set[str]: """Return the names in ``fqns`` that a checkpoint's optimizer did not hold. Names are compared without the activation-checkpoint wrapper's prefix, as DCP writes them, and under ``layout`` by the global names the checkpoint keeps each expert under, since a rank's local name for an expert names another expert on another rank. A checkpoint that stores the optimizer as one opaque entry leaves none out. Args: fqns: This rank's parameter names of the uncompiled model, with or without the activation-checkpoint wrapper's prefix. saved_keys: The keys the checkpoint's DCP index lists. layout: The model's expert-parallel layout, or None without expert parallelism. Returns: The names, without the wrapper's prefix and as this rank spells them, that have neither saved optimizer state nor a never-stepped record. """ keys = list(saved_keys) if "optimizer" in keys: return set() local = sorted({fqn.replace(_CHECKPOINT_PREFIX, "") for fqn in fqns}) saved_names = layout.global_names(local) if layout is not None else local needed = set(saved_names) covered: set[str] = set() for key in keys: if key.startswith(_NEVER_STEPPED_PREFIX): covered.add(key.removeprefix(_NEVER_STEPPED_PREFIX)) elif key.startswith(_OPTIM_STATE_PREFIX): fqn = key.removeprefix(_OPTIM_STATE_PREFIX) while fqn and fqn not in needed: fqn = fqn.rpartition(".")[0] covered.add(fqn) return {name for name, saved in zip(local, saved_names, strict=True) if saved not in covered} def _restore_left_out( optim_state: dict[str, Any], template_groups: list[list[str]], left_out: set[str], where: Path, ) -> None: """Give the parameters the saved optimizer did not hold empty state in a saved group. Each joins the saved group that holds another parameter of its group in the optimizer being loaded or, when no saved group does and the saved optimizer has as many groups, the saved group in its group's place if that group is empty, and takes that group's saved hyperparameters. Args: optim_state: The loaded optimizer state; its ``param_groups`` list the saved names. template_groups: The parameter names of each group of the optimizer being loaded, with every EP rank's experts under expert parallelism (see ``ExpertLayout.group_names``), as the save lists its groups. left_out: The names with neither saved state nor a never-stepped record. One in no group of ``template_groups`` only gets empty state. where: The checkpoint directory, named in the errors. Raises: RuntimeError: The saved groups list one of ``left_out``, so the saved optimizer held it and its state is missing, or no saved group fits a group of ``left_out``. """ saved_groups = optim_state["param_groups"] listed = {name for group in saved_groups for name in group["params"]} held_without_state = sorted(left_out & listed) if held_without_state: raise RuntimeError( f"Missing optimizer state in {where} for {len(held_without_state)} parameters " f"the saved optimizer held: {held_without_state[:8]}" ) same_layout = len(saved_groups) == len(template_groups) for index, names in enumerate(template_groups): missing = [name for name in names if name in left_out] if not missing: continue others = set(names) - left_out group = next((g for g in saved_groups if others & set(g["params"])), None) if group is None and same_layout and not saved_groups[index]["params"]: group = saved_groups[index] if group is None: raise RuntimeError( f"{where} has no param group for {len(missing)} parameters its optimizer did " f"not hold: {missing[:8]}. No saved group holds another parameter of their " "group or stands empty in its place." ) group["params"] = [*group["params"], *missing] optim_state["state"].update({name: {} for name in left_out}) def _check_saved_state_matches( optim_state: dict[str, Any], saved_keys: Iterable[str], where: Path ) -> None: """Fail if a parameter's saved optimizer state is not the state its optimizer now keeps. The save holds either another optimizer's state, or only part of this one's, as a ``schedule_free_adamw`` checkpoint written before each parameter kept its own ``step`` does, or a Lion checkpoint does for AdamW. Either way the run cannot continue exactly, so the load stops before DCP reads anything and says how to continue from the weights alone. """ kept = {fqn: set(state) for fqn, state in optim_state["state"].items()} saved: dict[str, set[str]] = {} for key in saved_keys: if not key.startswith(_OPTIM_STATE_PREFIX): continue name = key.removeprefix(_OPTIM_STATE_PREFIX) fqn = name while fqn and fqn not in kept: fqn = fqn.rpartition(".")[0] if fqn: saved.setdefault(fqn, set()).add(name.removeprefix(f"{fqn}.").split(".", 1)[0]) moved = sorted(fqn for fqn, entries in saved.items() if entries - kept[fqn] and kept[fqn]) if moved: first = moved[0] raise RuntimeError( f"{where} holds another optimizer's state for {len(moved)} parameters: " f"{moved[:8]}. {first} was saved with " f"{sorted(saved[first])} and is now kept with {sorted(kept[first])}: its optimizer " "changed since the save, e.g. optimizer.name or optimizer.muon_router changed, " "or Muon used to orthogonalize it before it routed parameters by module. " "To continue from these weights with a fresh optimizer, set " "checkpoint.load_path to this checkpoint and checkpoint.exclude_from_loading = " '["optimizer"], with a checkpoint.dir that holds no checkpoint yet.' ) short = sorted(fqn for fqn, entries in saved.items() if kept[fqn] - entries) if short: first = short[0] raise RuntimeError( f"{where} holds partial optimizer state for {len(short)} parameters: " f"{short[:8]}. {first} was saved without {sorted(kept[first] - saved[first])}, " "which its optimizer now keeps: another optimizer saved it (optimizer.name " "changed since the save), or an earlier version of this one did, e.g. " "schedule_free_adamw before each parameter kept its own step count, so the run " "cannot continue exactly. To continue from these weights with a fresh " "optimizer, set checkpoint.load_path to this checkpoint and " 'checkpoint.exclude_from_loading = ["optimizer"], with a checkpoint.dir that ' "holds no checkpoint yet." ) def _group_of(module: str | None) -> str: """Name the module of a param group, as the layout check reports it.""" return "no listed module" if module is None else f"module {module!r}" def _module_change(saved: Sequence[str | None], current: Sequence[str | None]) -> str | None: """Describe the first param group whose module differs between the save and this run.""" for index, (then, now) in enumerate(zip(saved, current, strict=False)): if then != now: return ( f"has optimizer param group {index} of {_group_of(then)}, where this run's " f"group {index} is of {_group_of(now)}" ) if len(saved) != len(current): return f"records {len(saved)} optimizer param groups, and this run has {len(current)}" return None def _check_saved_param_groups( optim_state: dict[str, Any], saved_keys: Collection[str], where: Path, groups_vary: bool, saved_modules: Sequence[str | None] | None = None, ) -> None: """Fail unless the checkpoint holds the param groups this run's optimizers hold. A checkpoint keeps each param group's settings under the group's position among its optimizers' groups, and the load maps a loaded group to this run's by the parameters it lists. When the groups are laid out otherwise than at the save, as under ``optimizer.lr_multipliers`` when other parameters are trainable, a position can hold another group, and a group can come back without settings. Checked when ``groups_vary``, as it is for a run with ``optimizer.lr_multipliers``, or when this run's groups or the saved ones name a module: the checkpoint must hold as many groups, each with every setting of this run's group there, and each naming a module exactly where this run's group does. ``saved_modules``, the module of each saved group as the save recorded them, None for a group of no listed module, must also match this run's groups one by one. """ groups = optim_state["param_groups"] names_module = any( key.startswith(_OPTIM_PARAM_GROUPS_PREFIX) and key.endswith(".module") for key in saved_keys ) if not (groups_vary or names_module or any("module" in group for group in groups)): return saved_count = _saved_optimizer_param_groups(saved_keys) if saved_count != len(groups): found = f"holds {saved_count} optimizer param groups, and this run {len(groups)}" else: for index, group in enumerate(groups): prefix = f"{_OPTIM_PARAM_GROUPS_PREFIX}{index}." missing = sorted(key for key in group if f"{prefix}{key}" not in saved_keys) if missing: found = f"has no {missing} in optimizer param group {index}, which this run's has" break if "module" not in group and f"{prefix}module" in saved_keys: found = f"names a module in optimizer param group {index}, and this run's does not" break else: change = None if saved_modules is not None: change = _module_change(saved_modules, [group.get("module") for group in groups]) if change is None: return found = change raise RuntimeError( f"{where} {found}: the param groups are laid out otherwise than at the save, as when " "other parameters are trainable under optimizer.lr_multipliers (a sigmoid router's " "expert_bias, which is no longer trained, for one), or their settings changed. " "Resume with the parameters trained at the save, or continue from these " "weights with a fresh optimizer: set checkpoint.load_path to this checkpoint and " 'checkpoint.exclude_from_loading = ["optimizer"], with a checkpoint.dir that holds ' "no checkpoint yet." ) def _fit_saved_optimizer( optim_state: dict[str, Any], owners: list[torch.optim.Optimizer], fixed: torch.optim.Optimizer | None, left_out: set[str], saved_keys: Collection[str], where: Path, groups_vary: bool, saved_modules: Sequence[str | None] | None = None, layout: ExpertLayout | None = None, ) -> list[tuple[int, dict[str, Any]]]: """Fit a load template to the checkpoint's optimizer state, then check that it fits. Checks that each parameter's saved state is of the kind it now keeps (see ``_check_saved_state_matches``), each of this rank's experts under the global name the checkpoint holds its state by when ``layout`` gives one, takes out the template groups the save kept no group for (see ``_take_groups_the_save_lacks``), drops the param-group keys the checkpoint predates (see ``_drop_legacy_group_keys``) and checks the groups that are left against the saved ones (see ``_check_saved_param_groups``). When the groups the save lacks cannot be taken, that check runs on the whole template first, so a layout it explains, such as other parameters trainable under ``optimizer.lr_multipliers``, fails with its message. Returns: The taken groups with their template positions, to put back after the load. Raises: RuntimeError: The checkpoint's optimizer state does not fit the template, or its param groups cannot be matched to the template's. """ states = optim_state if layout is not None: states = layout.to_global({"optimizer": optim_state})["optimizer"] _check_saved_state_matches(states, saved_keys, where) saved_groups = _saved_optimizer_param_groups(saved_keys) taken = _take_groups_the_save_lacks(optim_state, owners, fixed, left_out, saved_groups) if taken is None: _check_saved_param_groups(optim_state, saved_keys, where, groups_vary, saved_modules) raise RuntimeError( f"{where} holds {saved_groups} optimizer param groups and the optimizer being " f"loaded has {len(optim_state['param_groups'])}, so its groups cannot be matched " "to the saved ones. To continue from these weights with a fresh optimizer, set " "checkpoint.load_path to this checkpoint and checkpoint.exclude_from_loading = " '["optimizer"], with a checkpoint.dir that holds no checkpoint yet.' ) filled = _drop_legacy_group_keys(optim_state, owners, saved_keys) if filled: logger.warning( f"{where} is missing optimizer param-group keys {sorted(filled)}; " f"resuming with {filled}" ) _check_saved_param_groups(optim_state, saved_keys, where, groups_vary, saved_modules) return taken def _load_train_state(path: Path) -> dict[str, Any]: """Load ``train_state.pt`` under an explicit trust boundary. ``train_state.pt`` carries scheduler state, dataloader state and the caller's extra keys, so it is loaded with ``weights_only=False`` (i.e. full pickle): an object in the file whose class defines ``__reduce__`` can run arbitrary Python during ``torch.load``. On shared filesystems this is a real attack surface: anyone who can write into another user's checkpoint directory can run code in that user's training process on the next resume. Refuses to load a file not owned by the current UID, and warns about, but still loads, one that is group- or world-writable. It checks only the file's owner and mode, which makes the trust boundary visible but does not enforce it: a checkpoint the current user downloaded, copied or extracted from an archive is theirs and loads, and an attacker who can write as that user already wins. PyTorch also unpickles the DCP files' ``.metadata`` index and the shards' non-tensor values, unchecked, before this file is read. Load only checkpoints you trust. """ st = path.stat() uid = os.getuid() if st.st_uid != uid: raise PermissionError( f"Refusing to load {path}: owned by uid={st.st_uid}, current uid={uid}. " f"train_state.pt is a pickle and loading it executes arbitrary Python. " f"If you trust this checkpoint, chown it to the current user after inspection." ) if st.st_mode & (stat.S_IWGRP | stat.S_IWOTH): logger.warning( f"{path} is group/world-writable (mode={oct(st.st_mode & 0o777)}); " f"train_state.pt is a pickle and any writer can inject arbitrary code " f"at load time. Consider chmod g-w,o-w on the checkpoint directory." ) return torch.load(path, map_location="cpu", weights_only=False) def _names_backends(tracking: object) -> TypeGuard[list[dict[str, Any]]]: """True for a list of mappings that each name a ``backend``, the shape readers select on.""" return isinstance(tracking, list) and all( isinstance(entry, dict) and isinstance(entry.get("backend"), str) and entry["backend"].strip() for entry in tracking ) def _string_fields(fields: object) -> bool: """True for a mapping of strings to strings, what a tracking record can hold.""" return isinstance(fields, dict) and all( isinstance(key, str) and isinstance(value, str) for key, value in fields.items() ) def _replace_file(path: Path, text: str) -> None: """Replace ``path`` with ``text`` atomically: a temp file beside it, then a rename over it. An existing file keeps its mode, and its replacement is never readable more widely while it is written; a new one gets the mode a plain write would give it. """ try: mode: int | None = stat.S_IMODE(path.stat().st_mode) except FileNotFoundError: mode = None tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o666 if mode is None else 0o600) try: with os.fdopen(fd, "w") as f: if mode is not None: os.fchmod(f.fileno(), mode) f.write(text) f.flush() os.fsync(f.fileno()) os.replace(tmp, path) except BaseException: tmp.unlink(missing_ok=True) raise def _remove_tree(path: Path, lock: threading.Lock, delays: Iterator[float]) -> None: """Remove the directory ``path``, retrying while NFS briefly keeps it non-empty. ``ENOTEMPTY``, ``EBUSY`` and ``ENOENT`` are retried while ``path`` exists, each retry after waiting the next of ``delays``. Args: path: The directory to remove. lock: Held for each attempt and released during the waits. delays: The waits left, in seconds, which removals can share. Raises: OSError: Any other error, or a retried one once ``path`` is gone or ``delays`` is spent. """ while True: try: with lock: shutil.rmtree(path) return except OSError as e: if e.errno not in _TRANSIENT_REMOVE_ERRNOS or not path.exists(): raise delay = next(delays, None) if delay is None: raise time.sleep(delay) _URI_USERINFO = re.compile(r"(?<=://)[^/?#\s]+@") def _error_text(error: BaseException) -> str: """``error``'s message with the userinfo of every URI in it removed; never raises.""" try: return _URI_USERINFO.sub("", str(error)) except Exception: return f"<unprintable {type(error).__name__}>" def _attempt(action: Callable[..., object], *args: Any, **kwargs: Any) -> BaseException | None: """Call ``action(*args, **kwargs)``; return the error it raised, or ``None``. The error is an ``Exception`` or DCP's ``CheckpointException``, which derives from ``BaseException`` only; anything else, such as ``KeyboardInterrupt``, propagates. """ try: action(*args, **kwargs) except (Exception, dcp.CheckpointException) as e: return e return None
[docs] class CheckpointManager: """Manages save/load/cleanup of distributed checkpoints. Each checkpoint is stored in a subdirectory: ``{dir}/step_{N}/`` containing DCP shards and a non-distributed training state file. A ``latest`` symlink always points to the most recent checkpoint. Args: config: Checkpoint configuration. model: The model (FSDP-wrapped or plain). optimizer: The optimizer. pp_rank: This rank's pipeline stage, None without pipeline parallelism. Each stage saves its DCP shards in ``pp{pp_rank}/`` of the checkpoint (see ``kempnerforge.checkpoint.layout``), through ``process_group``. pp_size: The run's pipeline degree, which needs ``pp_rank``. Every save then records it in ``metadata.json`` as ``pp``. A load refuses, with a ``ValueError`` on every rank before anything is loaded, a stage checkpoint of another degree: one that records its degree, or, saved before the record existed, holds another number of stage directories. Without it, the degree is neither recorded nor compared. A pipeline-parallel run loads its stage's model weights from a checkpoint saved without pipeline parallelism, but refuses its optimizer state, and a run without pipeline parallelism refuses a stage checkpoint (see ``load``). dp_info: This rank's ``(dp_rank, dp_size)``, the data partition its loader reads. Recorded with the per-rank loader/RNG state and checked on load, so a resume under a different data-parallel layout is refused even at the same world size. None records no layout and checks only the world size. weight_decay_scope: The run's ``optimizer.weight_decay_scope``. When set, every save records it in ``metadata.json``, and a load that restores optimizer state on any rank raises ``ValueError`` on every rank, before anything is loaded, when the checkpoint was saved under a different scope. A checkpoint that holds no optimizer state, such as a converted one or one saved before the first step, loads under any scope with a fresh optimizer. A checkpoint whose ``metadata.json`` records no scope counts as ``"exclude_norms_and_biases"``, and one without the file is refused, since it records nothing. lr_multipliers: The run's ``optimizer.lr_multipliers``. When set, every save records a non-empty one in ``metadata.json``, with the patterns of its modules and, without pipeline parallelism, the module each optimizer param group names. A load of a checkpoint saved with other multipliers or patterns raises ``ValueError`` on every rank when it restores the checkpoint's optimizer state on any rank, before anything is loaded, or the scheduler state in its ``train_state.pt``, before anything from that file is restored. A load that restores neither, such as a weights-only warm start (``exclude_keys=["optimizer", "train_state"]``), goes ahead without checking the record. A checkpoint that records none counts as saved without multipliers. One whose ``metadata.json`` cannot be read, or holds an invalid record, is refused the same way when multipliers are set; without them it loads as one saved without multipliers, with a warning, and only a record of some is refused. With multipliers set, a load that restores optimizer state into param groups laid out otherwise than at the save, a group of another module at a position included, raises on every rank before anything is loaded. A restored scheduler state carries the saved schedule on in every group, a group of a module the checkpoint holds no group of at the saved peak times its multiplier (see ``restore_train_state``). module_patterns: Module name to fnmatch patterns, such as ``VLMConfig.module_patterns``. Required for every module ``lr_multipliers`` lists. group_timeout_sec: Collective timeout of the gloo group the manager creates to order its saves across ranks, ``distributed.nccl_timeout_sec`` in training. None leaves PyTorch's default. """
[docs] def __init__( self, config: CheckpointConfig, model: torch.nn.Module, optimizer: torch.optim.Optimizer, process_group=None, pp_rank: int | None = None, dp_info: tuple[int, int] | None = None, weight_decay_scope: str | None = None, lr_multipliers: Mapping[str, float] | None = None, module_patterns: Mapping[str, Sequence[str]] | None = None, group_timeout_sec: float | None = None, pp_size: int | None = None, ) -> None: self._dp_info = dp_coordinates(dp_info) if dp_info is not None else None if dp_info is not None and self._dp_info is None: raise ValueError( f"dp_info must be (dp_rank, dp_size) ints with 0 <= dp_rank < dp_size, " f"got {dp_info!r}" ) if pp_size is not None and (pp_rank is None or not 0 <= pp_rank < pp_size): raise ValueError( f"pp_size needs a pp_rank with 0 <= pp_rank < pp_size, got pp_rank={pp_rank!r} " f"and pp_size={pp_size!r}" ) self.config = config self.model = model self.optimizer = optimizer self.checkpointed_optimizers: list[torch.optim.Optimizer] = [ optimizer, *getattr(optimizer, "inner_optimizers", ()), ] self.base_dir = Path(config.dir) self._rank = dist.get_rank() if dist.is_initialized() else 0 self._world_size = dist.get_world_size() if dist.is_initialized() else 1 self._async_ckpt = AsyncCheckpointer(mode=config.async_mode) self._process_group = process_group self._pp_rank = pp_rank self._pp_size = pp_size self._weight_decay_scope = weight_decay_scope self._lr_multipliers = None if lr_multipliers is None else dict(lr_multipliers) listed = sorted(self._lr_multipliers or ()) patterns = module_patterns or {} missing = [module for module in listed if module not in patterns] if missing: raise ValueError(f"lr_multipliers needs module_patterns for {missing}") self._lr_module_patterns = {module: sorted(set(patterns[module])) for module in listed} self._pending_dataloader_state: dict[str, Any] | None = None self._pending_dataloader_warm_start = False self._pending_dataloader_carried = False self._pending_dataloader_missing = False self._restored_extra: dict[str, Any] = {} self._restored_optimizer = False self._pending_finalize: tuple[int, Path] | None = None self._inflight_dir: Path | None = None self._tracking_source: TrackingSource | None = None self._registrar: CheckpointRegistrar | None = None self._claim: str | None = None self._sidecar_lock = threading.Lock() self._sync_group: dist.ProcessGroup | None = None if dist.is_initialized(): self._sync_group = cast( "dist.ProcessGroup", dist.new_group(backend="gloo") if group_timeout_sec is None else dist.new_group(backend="gloo", timeout=timedelta(seconds=group_timeout_sec)), )
def _checkpoint_dir(self, step: int) -> Path: return self.base_dir / f"step_{step}" def _latest_link(self) -> Path: return self.base_dir / "latest" def _dcp_dir(self, ckpt_dir: Path) -> Path: """DCP shard directory for a checkpoint (per-stage subdir under PP).""" return ckpt_dir / f"pp{self._pp_rank}" if self._pp_rank is not None else ckpt_dir def _shard_dir(self, ckpt_dir: Path, layout: SavedLayout | None) -> Path: """The directory this rank reads ``ckpt_dir``'s DCP shards from, given its saved layout. ``layout`` is the one rank 0 found (see ``_agreed_load_dir``), so every rank takes the same branch. A flat checkpoint is read at its top, also by a pipeline stage, which loads its own layers from it, and a stage checkpoint in this rank's ``pp{k}/``. With no layout, the shards are read where this run's own layout keeps them. Raises: ValueError: ``layout`` is a stage layout, and this run has no pipeline parallelism or a pipeline degree, ``pp_size``, other than the checkpoint's. """ if layout is None: return self._dcp_dir(ckpt_dir) if layout.flat: return ckpt_dir if self._pp_rank is None: raise ValueError( f"{ckpt_dir} was {layout.describe()}, and this run has no pipeline parallelism, " f"so it reads one DCP index at the top of the checkpoint. " f"{_weights_route(ckpt_dir)}" ) if self._pp_size is not None and layout.stages != self._pp_size: raise ValueError( f"{ckpt_dir} was {layout.describe()}, and this run has pp={self._pp_size}: each " f"stage reads the stage directory of its own number, and another degree gives " f"each stage other layers. {_weights_route(ckpt_dir)}" ) return stage_dir(ckpt_dir, self._pp_rank) def _optimizer_across_layouts(self, ckpt_dir: Path) -> str: """Why a pipeline stage refuses the optimizer state of a checkpoint saved without PP.""" run = "this run is pipeline-parallel" if self._pp_size is not None: run = f"this run has pp={self._pp_size}" return ( f"{ckpt_dir} was {SavedLayout(0).describe()}, and {run}: each stage loads its model " f"weights from it, but not its optimizer state, whose param groups are those of the " f"whole model's optimizer, not of one stage's. To continue from its weights with a " f"fresh optimizer, set checkpoint.load_path={str(ckpt_dir)!r} with " f'checkpoint.exclude_from_loading = ["optimizer"] (add "train_state" to also ' f"restart the step, schedule and data position) and a checkpoint.dir that holds no " f"checkpoint yet, since training auto-resumes from a checkpoint there in place of " f"load_path." ) def _commit_latest(self, step: int, ckpt_dir: Path) -> None: """Atomically point `latest` at a now-durable checkpoint, register it, then prune. Rank 0 only. Called either inline (sync mode, DCP already durable) or deferred (async mode, after the flush future has resolved). Raises only while `latest` still names the previous checkpoint: once it names this one the checkpoint is committed, so an error while pruning is logged and the next commit prunes again. The new link is made under a temporary name of this host, process and call, so no other writer shares it, and is removed if the rename fails. """ latest = self._latest_link() tag = f"{socket.gethostname()}-{os.getpid()}-{uuid.uuid4().hex}" tmp_link = latest.with_name(f"{latest.name}.{tag}.tmp") tmp_link.symlink_to(ckpt_dir.name) try: tmp_link.rename(latest) except BaseException: tmp_link.unlink(missing_ok=True) raise logger.info(f"Checkpoint committed: {ckpt_dir} (step={step})") self._register_committed(step, ckpt_dir) try: self._cleanup() except Exception as e: logger.warning(f"Could not prune old checkpoints after committing {ckpt_dir} ({e})")
[docs] def claim_dir(self) -> None: """Make this run the owner of the checkpoint directory before it resumes or saves. Rank 0 records the run in ``<dir>/.owner`` (see ``claim_checkpoint_dir``), and every rank raises when that fails, so two live runs never share the directory. Every rank must call this. """ claims: list[str] = [] error: BaseException | None = None if self._rank == 0: error = _attempt(lambda: claims.append(claim_checkpoint_dir(self.base_dir))) self.agree(error, "Checkpoint directory claim") self._claim = claims[0] if claims else None
[docs] def release_dir(self) -> None: """Mark released the ``<dir>/.owner`` record that this rank's ``claim_dir`` wrote.""" if self._claim is not None: release_checkpoint_dir(self.base_dir, self._claim) self._claim = None
def _drain_pending_finalize( self, overwriting: Path | None = None, error: BaseException | None = None ) -> BaseException | None: """Commit a deferred async checkpoint once its flush is durable. Invoked on every rank after its pending DCP future has been awaited (next save() or an explicit wait()/flush), with the error that wait raised on this rank, if any. Under PP every rank first agrees that every stage's flush is durable, so a flush that failed on any rank raises on every rank and nothing is committed. Rank 0 then performs the symlink + cleanup; other ranks never touch the symlink, mirroring save(). A checkpoint pending in ``overwriting``, the directory a new save's flush is rewriting, is dropped uncommitted and unregistered; that save's own deferred commit points `latest` at it and registers it. Returns the error this rank still has to report: ``error``, or the one rank 0's commit raised. """ if self._pending_finalize is None: return error step, ckpt_dir = self._pending_finalize self._pending_finalize = None self._await_every_stage(error) if self._rank == 0 and error is None and ckpt_dir != overwriting: return _attempt(self._commit_latest, step, ckpt_dir) return error def _await_every_stage(self, error: BaseException | None) -> None: """Under PP, agree that every stage's DCP write is durable; a no-op otherwise. Each stage saves through its own process group, so this rank's write being durable covers its own stage only; without PP the save spans every rank. Every rank calls this once its own write has ended, with the error it raised, if any; under PP it then raises on every rank when any rank's write failed (see ``agree``). """ if self._pp_rank is not None: self.agree(error)
[docs] def agree(self, error: BaseException | None, what: str = "Checkpoint save") -> None: """Agree on the manager's dedicated gloo group that every rank's ``what`` succeeded. See ``agree_across_ranks``. The group is not the default process group that DCP's async-save background thread issues collectives on. """ agree_across_ranks(error, what, group=self._sync_group)
def _present_experts( self, dcp_state: dict[str, Any], load_from: Path | None = None, saved_keys: Mapping[str, Any] | None = None, ) -> tuple[dict[str, Any], ExpertLayout | None]: """``dcp_state`` as the checkpoint holds it, and the layout that translated it. Under expert parallelism each rank's experts are placed among all of them (see ``ExpertLayout``); otherwise ``dcp_state`` comes back with ``None``. Before a load from ``load_from``, a checkpoint whose MoE layers hold fewer experts than the model's, or hold them in the other expert layout, packed or not, is refused (see ``check_saved_experts``), reading its DCP index unless ``saved_keys`` holds it. Every rank must call this: they agree on the outcome before DCP's collectives, so a rank that fails raises on every rank. """ layout = expert_layout(self.model) check = load_from is not None and any(True for _ in moe_layers(self.model)) if layout is None and not check: return dcp_state, None def present() -> dict[str, Any]: if check: assert load_from is not None saved = saved_keys or _dcp_keys(load_from) check_saved_experts(self.model, saved, load_from) return layout.to_global(dcp_state) if layout is not None else dcp_state presented: list[dict[str, Any]] = [] what = "Checkpoint save" if load_from is None else "Checkpoint load" self.agree(_attempt(lambda: presented.append(present())), what) return presented[0], layout def _check_model_fits( self, model_state: Mapping[str, Any], every_rank: Iterable[str], dcp_dir: Path, restaged: bool, saved_keys: Mapping[str, Any], ) -> None: """Refuse, on every rank before any tensor is read, a checkpoint of another model. ``model_state`` is the model entry a load reads from ``dcp_dir``, as the checkpoint holds it (see ``_present_experts``), and ``every_rank`` names, as the checkpoint does, the experts that every expert-parallel rank of this rank's layers holds. Every rank sends rank 0 the index it reads with the global shape of each entry, keyed as DCP flattens it (see ``_held_model_entries``). Rank 0 reads each index once, or takes ``saved_keys``, its own read of ``dcp_dir``, and compares it with what the ranks that read it load together: every expert-parallel rank's experts and, when ``restaged``, every pipeline stage's layers. A model tensor the index holds that none of them loads, as a deeper model's layer, a tensor of another size, or a tensor a rank loads that the index lacks, as the router of an MoE layer that the checkpoint holds as a dense one, refuses the load, and rank 0 broadcasts the verdict, so every rank raises the same error or goes on. A pipeline stage that loads a checkpoint saved without pipeline parallelism outside a process group holds only its own layers, so the tensors the index holds beyond them are not counted. With ``checkpoint.ignore_extra_model_tensors``, rank 0 warns of the tensors no rank loads, which stay unread, and only a size change or a tensor an index lacks refuses. A refusal names that flag only when the indexes hold every tensor the ranks load, each at its size, so the flag would let the load through. A rank that cannot list its entries still enters every collective, sending why in their place, and rank 0 still broadcasts a verdict when comparing them fails, with why in its place: the rank that failed raises its own error and every other rank a ``RuntimeError`` naming it. Raises: ValueError: The checkpoint does not fit the model. Exception: On a rank that could not list its entries, or on rank 0 when comparing them failed, that error. RuntimeError: On every other rank, naming the ranks that failed; on every rank when rank 0 could not read an index. """ local_error: Exception | None = None held: dict[str, tuple[int, ...] | None] | str try: held = _held_model_entries(model_state, every_rank) except Exception as e: local_error = e held = f"{type(e).__name__}: {_error_text(e)}" mine = (str(dcp_dir), held) distributed = dist.is_initialized() gathered: list[Any] | None = [mine] if distributed: gathered = [None] * dist.get_world_size(self._sync_group) if self._rank == 0 else None dist.gather_object(mine, gathered, dst=0, group=self._sync_group) outcome: list[Exception | None] = [None] comparison_error: Exception | None = None if gathered is not None: try: known = {str(dcp_dir): saved_keys} if saved_keys else {} outcome[0] = self._model_misfit_error(gathered, known, restaged and not distributed) except Exception as e: comparison_error = e outcome[0] = RuntimeError( "Rank 0 could not compare the checkpoint with this run's model: " f"{type(e).__name__}: {_error_text(e)}" ) if distributed: dist.broadcast_object_list(outcome, src=0, group=self._sync_group) for error in (local_error, comparison_error, outcome[0]): if error is not None: raise error def _model_misfit_error( self, gathered: Sequence[tuple[str, Mapping[str, tuple[int, ...] | None] | str]], known: Mapping[str, Mapping[str, Any]], lone_stage: bool, ) -> Exception | None: """Rank 0's verdict for ``_check_model_fits``: the error every rank raises, or None. ``gathered`` holds, by rank, each rank's index and the shapes of the model entries it loads from it, or why it could not list them; ``known`` holds the indexes already read, by directory. With ``lone_stage`` the entries are one pipeline stage's part of the model the index holds, so tensors none of them loads are expected and not counted. """ failed = {rank: held for rank, (_, held) in enumerate(gathered) if isinstance(held, str)} if failed: first = min(failed) return RuntimeError( f"Comparing the model with the checkpoint failed on ranks {sorted(failed)}: " f"rank {first}: {failed[first]}" ) listed = [(index, held) for index, held in gathered if not isinstance(held, str)] held_by_index: dict[str, dict[str, tuple[int, ...] | None]] = {} for index, held in listed: merged = held_by_index.setdefault(index, {}) for key, shape in held.items(): if merged.get(key) is None: merged[key] = shape verdicts: list[tuple[str, list[str], list[str], list[str]]] = [] for index, held in held_by_index.items(): try: saved = known.get(index) or _dcp_keys(Path(index)) except Exception as e: return RuntimeError( f"Rank 0 could not read the DCP index in {index} to compare it with this " f"run's model: {type(e).__name__}: {_error_text(e)}" ) extra, resized, missing = _model_misfit(held, saved) verdicts.append((index, [] if lone_stage else extra, resized, missing)) complete = not any(resized or missing for _, _, resized, missing in verdicts) ignore_extra = self.config.ignore_extra_model_tensors if complete and ignore_extra: for index, extra, _, _ in verdicts: if extra: logger.warning( f"{index} holds {len(extra)} model tensors this run's model does not " f"have, such as {extra[:5]}; they are left unread, since " "checkpoint.ignore_extra_model_tensors is set" ) return None refusals = [ _misfit_message(Path(index), [] if ignore_extra else extra, resized, missing, complete) for index, extra, resized, missing in verdicts if (extra and not ignore_extra) or resized or missing ] return ValueError(" ".join(refusals)) if refusals else None
[docs] def set_tracking_source(self, source: TrackingSource | None) -> None: """Record the logging runs ``source`` reports in every later ``metadata.json``. ``source`` returns one JSON-ready record per live run, and is called on rank 0 only, inside ``save()``, so it must return promptly. The ``tracking`` key is omitted when it reports none, raises, or returns what JSON cannot write. ``None`` detaches it. """ if source is not None and not callable(source): raise TypeError( f"tracking source must be callable or None, got {type(source).__name__}" ) self._tracking_source = source
[docs] def set_checkpoint_registrar(self, registrar: CheckpointRegistrar | None) -> None: """Record every later checkpoint with the logging backends through ``registrar``. Both of its methods run on rank 0 only. ``checkpoint_fields`` is asked inside ``save()`` when a backend has a live run, and its fields join that save's ``tracking`` records. ``register_checkpoint`` gets each checkpoint once it is committed, with a ``record(backend, fields)`` that later adds fields to that backend's record, atomically and from any thread. A registrar that raises, or answers what a record cannot hold, costs only those fields or that registration, never the save or the commit. ``None`` detaches it. """ if registrar is not None and not all( callable(getattr(registrar, name, None)) for name in ("checkpoint_fields", "register_checkpoint") ): raise TypeError( "checkpoint registrar must have callable checkpoint_fields and " f"register_checkpoint, or be None; got {type(registrar).__name__}" ) self._registrar = registrar
def _with_checkpoint_fields( self, tracking: list[dict[str, str]], step: int ) -> list[dict[str, str]]: """``tracking`` plus the fields each backend adds for this save; as given if none.""" if self._registrar is None: return tracking try: added = self._registrar.checkpoint_fields(step) if not isinstance(added, dict): raise TypeError(f"expected a dict of fields by backend, got {type(added).__name__}") merged = [{**entry, **added.get(entry["backend"], {})} for entry in tracking] if not all(_string_fields(entry) for entry in merged): raise TypeError("fields must be strings") except Exception as e: logger.warning( "Could not add the checkpoint fields of step %s: %s", step, _error_text(e) ) return tracking return merged def _sidecar_text(self, meta: dict[str, Any]) -> str: """``meta`` as JSON, plus the run's ``weight_decay_scope`` when the manager has one, its ``lr_multipliers`` and their ``lr_module_patterns`` when it has a non-empty one, with the module of each checkpointed param group as ``lr_group_modules`` when every rank holds rank 0's groups, as without pipeline parallelism, the pipeline degree as ``pp`` when the manager has one, and the live tracking runs when the source can supply them. Everything that depends on the source sits inside one guard: it runs on rank 0 alone, so a raise here would strand the other ranks. A bad source costs the ``tracking`` key. """ if self._pp_size is not None: meta = {**meta, PP_DEGREE_KEY: self._pp_size} if self._weight_decay_scope is not None: meta = {**meta, "weight_decay_scope": self._weight_decay_scope} if self._lr_multipliers: meta = { **meta, "lr_multipliers": dict(sorted(self._lr_multipliers.items())), "lr_module_patterns": dict(sorted(self._lr_module_patterns.items())), } if self._pp_rank is None: meta["lr_group_modules"] = [ group.get("module") for optimizer in self.checkpointed_optimizers for group in optimizer.param_groups ] if self._tracking_source is not None: try: tracking = self._tracking_source() if tracking: if not _names_backends(tracking): raise TypeError("expected a list of mappings that each name a backend") tracking = self._with_checkpoint_fields(tracking, meta["step"]) return json.dumps({**meta, "tracking": tracking}, indent=2) except Exception as e: logger.warning( "Could not record the tracking runs in %s: %s", _METADATA_FILE, _error_text(e) ) return json.dumps(meta, indent=2) def _register_committed(self, step: int, ckpt_dir: Path) -> None: """Hand a just-committed checkpoint to the registrar, which must not block.""" if self._registrar is None: return try: self._registrar.register_checkpoint( step, ckpt_dir, partial(self._record, step, ckpt_dir) ) except Exception as e: logger.warning( "Could not register %s with the tracking backends: %s", ckpt_dir.name, _error_text(e), ) def _record(self, step: int, ckpt_dir: Path, backend: str, fields: dict[str, str]) -> None: """Add ``fields`` to ``backend``'s record in the ``metadata.json`` of step ``step``. The registrar's ``record``: callable from any thread, and it never raises. The file is read and replaced atomically under the sidecar lock, so a reader always sees a whole file and an amend never overwrites a newer save of the step. Only an existing record in that step's own sidecar is amended: a checkpoint removed since, or saved without that backend's record, is skipped quietly. """ path = ckpt_dir / _METADATA_FILE try: if not isinstance(backend, str) or not _string_fields(fields): raise TypeError("expected a backend name and fields of strings") with self._sidecar_lock: try: meta = json.loads(path.read_text()) except FileNotFoundError: logger.debug("%s is gone; the %s fields are not recorded", path, backend) return if not isinstance(meta, dict) or meta.get("step") != step: raise ValueError(f"it is not the metadata of step {step}") tracking = meta.get("tracking") if not _names_backends(tracking) or all(e["backend"] != backend for e in tracking): logger.debug("%s has no %s record; its fields are not recorded", path, backend) return meta["tracking"] = [ {**entry, **fields} if entry["backend"] == backend else entry for entry in tracking ] _replace_file(path, json.dumps(meta, indent=2)) except Exception as e: logger.warning( "Could not record the %s fields in %s: %s", backend, path, _error_text(e) ) def _gather_rank_states( self, dataloader: Any | None ) -> tuple[dict[str, Any] | None, BaseException | None]: """Collect every rank's own loader/RNG payload into a versioned envelope. Collective: every rank calls it once per ``save()``, whatever its own part of the save has raised so far. Uses the dedicated gloo group so the gather cannot interleave with DCP collectives an in-flight async flush is issuing on the default group from its background thread. Each rank captures and serializes its payload before the gather, and a rank whose capture raises enters the gather with no payload, so no rank is left waiting in it. Entries are keyed by each payload's own global rank rather than by gather position, so the envelope is correct under any group ordering. Each rank's ``dp_info`` rides along to record the data-parallel layout. Returns: The envelope and ``None``; or ``None`` and the error this rank reports: what its own capture raised, a ``RuntimeError`` naming the ranks whose capture failed, or what building the envelope raised, which every rank meets alike since it builds from the same gathered payloads. """ payload: bytes | None = None capture_error: Exception | None = None try: payload = pickle.dumps(capture_rank_state(dataloader)) except Exception as e: capture_error = e mine = (self._rank, self._dp_info, payload) gathered: list[Any] = [mine] if dist.is_initialized(): gathered = [None] * self._world_size dist.all_gather_object(gathered, mine, group=self._sync_group) if capture_error is not None: return None, capture_error failed = sorted(int(rank) for rank, _, data in gathered if data is None) if failed: return None, RuntimeError( f"Checkpoint save failed on ranks {failed}: they could not capture their " f"dataloader/RNG state" ) try: return self._build_envelope(gathered), None except Exception as e: return None, e def _build_envelope(self, gathered: list[Any]) -> dict[str, Any]: """The per-rank envelope from every rank's ``(rank, dp_info, serialized payload)``.""" entries = {int(rank): pickle.loads(data) for rank, _, data in gathered} coords = {int(rank): dp for rank, dp, _ in gathered} layout = coords if all(dp is not None for dp in coords.values()) else None return build_per_rank_envelope(entries, world_size=self._world_size, data_parallel=layout) def _gather_dp_layout(self) -> dict[int, tuple[int, int]] | None: """This run's global rank -> ``(dp_rank, dp_size)``, or None if unknown. Collective on the dedicated gloo group: each rank knows only its own coordinates, and the envelope check needs the whole layout so every rank reaches the same verdict. """ mine = (self._rank, self._dp_info) gathered: list[Any] = [mine] if dist.is_initialized(): gathered = [None] * self._world_size dist.all_gather_object(gathered, mine, group=self._sync_group) coords = {int(rank): dp for rank, dp in gathered} return coords if all(dp is not None for dp in coords.values()) else None def _per_rank_view(self, train_state: dict[str, Any]) -> tuple[dict[str, Any], bool]: """This rank's view of the broadcast train state on an exact resume. A checkpoint with a per-rank envelope: the view replaces the legacy single-copy ``rng``/``dataloader`` keys (always rank 0's) with this rank's own entry, selected by global rank. With an envelope it gathers the current data-parallel layout (a collective), so every rank must call it. ``load()`` calls it after the train-state broadcast, which every rank must reach, and after the checks of the broadcast state, which every rank passes or fails together; whether to gather depends on the broadcast state alone, so no rank waits in the gather for one that failed earlier in ``load()``. A topology or schema mismatch refuses the load unless ``checkpoint.ignore_rank_state_mismatch`` downgrades it to a warning (see ``_resume_past_mismatch``). The envelope check reads only state every rank shares, so all ranks restore, refuse, keep the data position or discard together. A legacy checkpoint (no envelope) keeps its old behavior, rank 0's single copy restoring on every rank, unless that flag is set (see ``_resume_without_rank_state``). Returns: The view, and whether its ``dataloader`` state is a saved data position carried onto a changed topology (see ``saved_data_position``) rather than this rank's own state. """ envelope = train_state.get(PER_RANK_KEY) if envelope is None: if self.config.ignore_rank_state_mismatch: return self._resume_without_rank_state(train_state) if self._world_size > 1 and self._rank == 0: logger.info( "Checkpoint has no per-rank state (legacy format); rank 0's " "dataloader/RNG state restores on every rank" ) return train_state, False view = {k: v for k, v in train_state.items() if k not in ("rng", "dataloader")} layout = self._gather_dp_layout() try: entry = select_rank_state( envelope, rank=self._rank, world_size=self._world_size, data_parallel=layout ) except ValueError as e: if not self.config.ignore_rank_state_mismatch: raise return self._resume_past_mismatch(view, envelope, e) view["rng"] = entry["rng"] if "dataloader" in entry: view["dataloader"] = entry["dataloader"] return view, False def _resume_past_mismatch( self, view: dict[str, Any], envelope: Any, error: ValueError ) -> tuple[dict[str, Any], bool]: """The view when ``checkpoint.ignore_rank_state_mismatch`` lets a refused resume through. A changed world size or data-parallel layout (``RankStateMismatchError``) keeps the data position when the envelope is sound on the topology that saved it: the view holds the saved loader state this rank resumes from, rank 0's, or for a stream on the saved data-parallel size the one its own data-parallel rank saved (see ``saved_data_position``), which ``apply_dataloader_state`` resumes on every rank where the loaders can place it on this layout and restarts on every rank where one cannot. Any other refusal drops the loader state too. No RNG state is restored either way, so the random streams restart from this run's seeds. Whether a position is kept depends only on the broadcast envelope, an error every rank met alike and the configured layout, so every rank keeps or drops it together. """ position = None reason = str(error) if isinstance(error, RankStateMismatchError): reason = error.mismatch try: position = saved_data_position(envelope, self._dp_info) except ValueError as e: reason = str(e) if position is None: logger.warning( f"Discarding saved per-rank dataloader/RNG state because " f"checkpoint.ignore_rank_state_mismatch=true: {reason}. Data order and " f"random streams restart fresh; model/optimizer/scheduler/step " f"still resume." ) return view, False view["dataloader"] = position logger.warning( f"Resuming on a changed topology because checkpoint.ignore_rank_state_mismatch=" f"true: {reason}. Kept: the saved data position, which every rank resumes from " f"where the loaders can place it on this layout, a stream on the saved " f"data-parallel size from the position its own data-parallel rank saved. Dropped: " f"every rank's saved RNG state, so the random streams restart from this run's " f"seeds. Model, optimizer, scheduler and step resume." ) return view, True def _resume_without_rank_state( self, train_state: dict[str, Any] ) -> tuple[dict[str, Any], bool]: """The view of a checkpoint with no per-rank state under ``ignore_rank_state_mismatch``. Such a checkpoint, saved before per-rank state was recorded, cannot show whether the world size or data-parallel layout changed, so the flag resumes it as if they had: the view keeps rank 0's single-copy data position, which ``apply_dataloader_state`` resumes on every rank where the loader can place it on this layout and restarts where it cannot, and drops rank 0's RNG state, so the random streams restart from this run's seeds. Reads only the broadcast train state, so every rank resumes alike. """ view = {k: v for k, v in train_state.items() if k != "rng"} carried = "dataloader" in view kept = ( "Kept: rank 0's data position, which every rank resumes from where its loader " "can place it on this layout. " if carried else "" ) logger.warning( f"The checkpoint holds no per-rank state, so whether the world size or " f"data-parallel layout changed is unknown, and checkpoint." f"ignore_rank_state_mismatch=true resumes it as if they did. {kept}Dropped: " f"rank 0's saved RNG state, so the random streams restart from this run's seeds." ) return view, carried
[docs] def save( self, step: int, tokens_seen: int = 0, scheduler: Any | None = None, dataloader: Any | None = None, extra: dict | None = None, ) -> None: """Save a checkpoint at the given step. An optimizer that evaluates at another point than it trains at, as schedule-free AdamW does, has the model saved at its evaluation point, the averaged weights ``x``, so every reader of the model entry alone gets them; the parameters are back at the training point when this returns, and ``load`` rebuilds that point. The swap back runs as soon as ``AsyncCheckpointer.save`` returns, which is safe only because the state is staged by then: both async modes stage synchronously, so every tensor is copied to CPU memory before ``dcp.async_save`` returns. The ``async`` mode passes no stager and gets torch's default, ``DefaultStager(StagingOptions(False, False, False, False))``; ``async_with_pinned_mem`` passes its pinned ``DefaultStager``, built with ``use_async_staging=False``, whose ``stage`` waits for its copies to finish. An asynchronous stager would let the write read the parameters after the swap back, so adding one means moving the swap back after staging completes. Under expert parallelism each EP rank holds a copy of every weight outside the routed experts. The training step keeps the copies equal, but a model stepped without ``average_non_expert_grads_`` can hold copies that differ in the last bits. DCP writes each chunk that several ranks hold from one of them, by default the one with the least to write so far, which could join chunks of different copies into one tensor. An EP save writes each such chunk from its lowest rank instead, so the checkpoint holds one EP rank's copy whole. Args: step: Current training step. tokens_seen: Total tokens processed. scheduler: LR scheduler to save. dataloader: Stateful dataloader to save. extra: Additional metadata. """ ckpt_dir = self._checkpoint_dir(step) ckpt_dir.mkdir(parents=True, exist_ok=True) self._inflight_dir = ckpt_dir dcp_dir = ckpt_dir / f"pp{self._pp_rank}" if self._pp_rank is not None else ckpt_dir dcp_dir.mkdir(parents=True, exist_ok=True) with _evaluation_point(self.optimizer): dcp_state: dict[str, Any] = {"model": get_model_state_dict(self.model)} if any(optimizer.state for optimizer in self.checkpointed_optimizers): optim_state = get_optimizer_state_dict(self.model, self.checkpointed_optimizers) dcp_state["optimizer"] = optim_state dcp_state[_NEVER_STEPPED_KEY] = _never_stepped_record(optim_state) dcp_state, layout = self._present_experts(dcp_state) save = self._async_ckpt.save if layout is not None: save = partial(save, planner=DefaultSavePlanner(dedup_save_to_lowest_rank=True)) flush_error = _attempt(self._async_ckpt.wait) error = flush_error if flush_error is None: error = _attempt( save, dcp_state, checkpoint_id=str(dcp_dir), process_group=self._process_group, ) sync_mode = self.config.async_mode == AsyncCheckpointMode.disabled drain_error = self._drain_pending_finalize(overwriting=ckpt_dir, error=flush_error) if drain_error is not None: error = drain_error per_rank, gather_error = self._gather_rank_states(dataloader) if error is None: error = gather_error if self._rank == 0 and error is None: error = _attempt( self._write_train_state, ckpt_dir, step, tokens_seen, scheduler, dataloader, extra, per_rank, ) if sync_mode: self._await_every_stage(error) if self._rank == 0 and error is None: error = _attempt(self._commit_latest, step, ckpt_dir) self.agree(error) if not sync_mode: self._pending_finalize = (step, ckpt_dir)
def _write_train_state( self, ckpt_dir: Path, step: int, tokens_seen: int, scheduler: Any | None, dataloader: Any | None, extra: dict | None, per_rank: dict[str, Any] | None = None, ) -> None: """Write ``train_state.pt`` and ``metadata.json`` into ``ckpt_dir``: rank 0's save() part. ``extra["vlm_freeze"]``, when present, is recorded in ``metadata.json`` as given: ``canonical_freeze_meta`` has already sorted and deduplicated it, so the comparison on load does not depend on order. ``extra["plugins"]``, when present, is recorded there too, for ``load`` to compare before reading any state. ``per_rank`` is the envelope ``save()`` gathered from every rank; omitting it writes a legacy train state carrying rank 0's loader/RNG state only. """ train_state = build_train_state( step=step, tokens_seen=tokens_seen, scheduler=scheduler, dataloader=dataloader, extra=extra, per_rank=per_rank, ) torch.save(train_state, ckpt_dir / _TRAIN_STATE_FILE) meta: dict[str, Any] = {"step": step, "tokens_seen": tokens_seen} for key in ("vlm_freeze", "plugins"): if extra is not None and key in extra: meta[key] = extra[key] text = self._sidecar_text(meta) with self._sidecar_lock: _replace_file(ckpt_dir / _METADATA_FILE, text) @property def has_pending_save(self) -> bool: """Whether ``wait()`` has an async save to drain or a ``latest`` commit to make. Always False with synchronous saves, which commit inside ``save()``. """ return self._async_ckpt.is_pending or self._pending_finalize is not None @property def flushing(self) -> bool: """Whether this rank's background write of the pending async save is still running. Never blocks. False with synchronous saves, and once the write has ended, whether it succeeded or failed. The training loop reduces it over every rank at each step and, once no rank's write is still running, calls ``wait()``, which moves ``latest`` to the save then rather than at the next save. """ return self._async_ckpt.is_flushing
[docs] def wait(self) -> None: """Block until any pending async checkpoint save completes. Once the flush is durable, commit its deferred `latest` symlink + cleanup. The training loop calls this at the first step boundary at which no rank's write is still running (see ``flushing``), and after the loop exits, so the final checkpoint's `latest` is committed before process teardown. A flush that failed on any rank raises on every rank, and nothing is committed. """ error = _attempt(self._async_ckpt.wait) self.agree(self._drain_pending_finalize(error=error))
[docs] def flush_pending_save(self) -> None: """Drain any in-flight async save before mutating model state. Called from the FreezeStage transition hook in the training loop: when a transition fires at step S, any save started at step S-1 must have written ``metadata.json`` with the pre-transition spec before the transition flips ``requires_grad``. Otherwise ``metadata.json`` lands with the post-transition spec attached to the pre-transition shards. Also commits the deferred `latest` symlink for that save, so a transition (or any caller draining the queue) leaves `latest` pointed at the now-durable checkpoint. A flush that failed on any rank raises on every rank, and nothing is committed. """ error = _attempt(self._async_ckpt.wait) self.agree(self._drain_pending_finalize(error=error))
[docs] def peek_saved_step(self, path: str | None = None) -> int | None: """Read ``step`` from a candidate checkpoint's ``metadata.json``, on this rank alone. Returns ``None`` if no checkpoint resolves, or its ``metadata.json`` is absent, cannot be read, does not hold a JSON object, or records no step that is a non-negative integer. ``load`` does not use it: a load takes the step its checks need from rank 0's read of the checkpoint it settles on (see ``vlm_freeze_expected``). """ ckpt_dir = self._resolve_load_path(path) if ckpt_dir is None: return None meta, _ = _metadata_outcome(ckpt_dir) return None if meta is None else _recorded_step(meta)
[docs] def load( self, path: str | None = None, scheduler: Any | None = None, dataloader: Any | None = None, exclude_keys: list[str] | None = None, vlm_freeze_expected: _FreezeExpectation | None = None, fresh_if_unheld: Iterable[str] = (), warm_start: bool = False, exact_resume: bool = False, plugins_expected: list[str] | None = None, ) -> tuple[int, int, dict[str, Any]]: """Load a checkpoint and restore all state. A load that restores optimizer state then calls the optimizer's ``train_params``, if it has one, so a schedule-free run resumes at the training point it was saved at. Args: path: Checkpoint path. If None, loads from ``config.load_path`` or the ``latest`` symlink. scheduler: LR scheduler to restore. dataloader: Stateful dataloader to restore. exclude_keys: State to skip: the DCP keys ``"model"`` and ``"optimizer"`` (e.g. ``["optimizer"]`` for fine-tuning), or ``["optimizer", "train_state"]`` for a weights-only warm start that loads the model alone and ignores ``train_state.pt`` (step, token count, scheduler, dataloader position, RNG) and the saved freeze metadata, so the new run starts at step 0 with its own schedule, data order and freeze. ``"train_state"`` in any other combination raises ``ValueError``. vlm_freeze_expected: Canonical freeze metadata (output of ``canonical_freeze_meta``) for the current run's VLMConfig, or a function that gives it for a step, such as ``freeze_meta_at_step`` with that config, which is called with the step the checkpoint's ``metadata.json`` records. It is compared with the freeze that file records, both from rank 0's read of the checkpoint the load settles on (see ``_check_vlm_freeze``), so every rank raises or goes on together; every rank must pass it or none. A mismatch raises ``ValueError`` unless the checkpoint config has ``ignore_freeze_mismatch=True``, in which case the load proceeds with a warning. fresh_if_unheld: Names of parameters the saved optimizer may not hold, the ones a freeze stage unfreezes after the build froze them. One with neither saved state nor a never-stepped record resumes with empty optimizer state, in the saved group of its group's other parameters or, when the saved optimizer has as many groups, in the empty saved group in its group's place. A group that holds only such parameters and that the saved optimizer did not keep, as Muon's inner AdamW keeps no empty group, resumes with the settings the optimizer being loaded gives it and empty state. warm_start: True when this load starts a new run from another run's checkpoint (``checkpoint.load_path``) rather than resuming this one. A data position that cannot carry over to this run's loader, passed here as ``dataloader`` or later to ``apply_dataloader_state``, then starts the data at its first sample with a warning, instead of raising ``DataPositionError``. exact_resume: True only when the run resumes from its own checkpoint (auto-resume). Each rank then restores its own dataloader/RNG state from the per-rank envelope, which must match this run's world size and data-parallel layout unless ``checkpoint.ignore_rank_state_mismatch`` is set: a changed topology, or a checkpoint with no per-rank state, then keeps the saved data position where the loader can place it and restarts the random streams. Every rank must pass the same value. False (a ``load_path`` warm start, evaluation, any other load) restores the single-copy ``rng``/``dataloader`` keys (rank 0's) on every rank with no topology check. The weights-only ``exclude_keys`` pair reads no train state: no rank restores loader/RNG state or enters the train-state broadcasts or the layout gather, and with ``exact_resume`` it raises. Every load takes the checkpoint rank 0 resolves (see ``_agreed_load_dir``); an exact resume that reads DCP shards falls back, when that checkpoint is not a complete save (see ``is_complete_checkpoint``), to the newest ``step_N`` beside it that is. Any other load takes its checkpoint as is. Whichever it takes, a load that reads DCP shards reads them as the layout rank 0 found there: a pipeline stage loads its model weights from a checkpoint saved without pipeline parallelism too (see ``_shard_dir``). plugins_expected: The run's ``plugins`` list, compared with the one the checkpoint's ``metadata.json`` records before any state is read (see ``_check_plugins``). Every rank must pass the same value. A weights-only warm start, which reads no train state, is not compared. Returns: Tuple of (step, tokens_seen, extra) where extra contains any additional keys saved via ``build_train_state(extra=...)``. Raises: FileNotFoundError: No checkpoint resolves although one was named, or the checkpoint holds optimizer state that this load restores but has no ``train_state.pt``. Raised before any state is loaded. ValueError: ``exclude_keys`` is not a list of distinct DCP keys, names ``"train_state"`` outside ``["optimizer", "train_state"]``, or is that pair with ``exact_resume``, raised before the path is resolved; the checkpoint was saved under another weight-decay scope, LR multipliers or patterns of their modules (see ``__init__``), or with another ``plugins`` list (see ``plugins_expected``); or, on an exact resume, its per-rank state does not fit this run's topology and ``checkpoint.ignore_rank_state_mismatch`` is off (see ``exact_resume``). Also, for a load that reads DCP shards, before any is read: the checkpoint was saved under pipeline parallelism and this run has none, or another pipeline degree (see ``pp_size`` in ``__init__``); or it was saved without pipeline parallelism, this run is pipeline-parallel, and the load would restore the optimizer state it holds. Each message names both layouts and the way to carry the weights over. And, for a load that reads the model, before any tensor is read: the checkpoint holds model tensors this run's model does not have, unless ``checkpoint.ignore_extra_model_tensors`` is set, or one of another size, or lacks one this run loads (see ``_check_model_fits``). It also records another VLM freeze (see ``vlm_freeze_expected``). RuntimeError: The saved optimizer state does not fit this run's optimizers, as when a name in ``fresh_if_unheld`` with neither saved state nor a never-stepped record is listed in the saved param groups, or no saved param group fits it, or the checkpoint holds fewer param groups than the optimizer and the missing ones are not groups of such names. Also, on every rank, when rank 0 could not read a DCP index to compare it with the model. A load that restores optimizer state refuses it on every rank together, before any state is loaded: each rank checks its own part of the checkpoint, and one all-reduce on the manager's gloo group, which every rank enters, has the other ranks raise a ``RuntimeError`` naming the ranks that refused. A second such all-reduce follows DCP's load, once each rank has restored the state of the parameters its checkpoint left out or never stepped, and before any state is set; every rank enters it too, also a pipeline stage whose checkpoint holds no optimizer state. """ self._restored_optimizer = False if exclude_keys is not None: validate_exclude_keys(exclude_keys, "exclude_keys") if exact_resume and is_weights_only(exclude_keys): raise ValueError( "exact_resume restores each rank's dataloader/RNG state from train_state.pt, " "which exclude_keys=['optimizer', 'train_state'] skips: a weights-only warm " "start begins a new run at step 0. Load it with exact_resume=False, or drop " "'train_state' from exclude_keys to resume." ) will_load_dcp = ( exclude_keys is None or "model" not in exclude_keys or "optimizer" not in exclude_keys ) ckpt_dir, ckpt_layout, metadata_read = self._agreed_load_dir( path, fall_back=exact_resume and will_load_dcp ) if ckpt_dir is None: requested = path if path is not None else self.config.load_path if requested: raise FileNotFoundError(f"Checkpoint not found: {requested}") logger.info("No checkpoint found; starting from scratch") self._restored_extra = {} return 0, 0, {} logger.info(f"Loading checkpoint: {ckpt_dir}") dcp_dir = self._shard_dir(ckpt_dir, ckpt_layout if will_load_dcp else None) restaged = ( will_load_dcp and self._pp_rank is not None and ckpt_layout is not None and ckpt_layout.flat ) load_train_state = not is_weights_only(exclude_keys) if not load_train_state and vlm_freeze_expected is not None: logger.warning( f"vlm_freeze_expected is not compared with {ckpt_dir}: a weights-only warm start " "applies the new run's freeze" ) metadata: _MetadataOutcome | None = None if vlm_freeze_expected is not None and load_train_state: metadata = self._broadcast_metadata(ckpt_dir, metadata_read) self._check_vlm_freeze(metadata, ckpt_dir, vlm_freeze_expected) if plugins_expected is not None and load_train_state: if metadata is None: metadata = self._broadcast_metadata(ckpt_dir, metadata_read) self._check_plugins(metadata, ckpt_dir, plugins_expected) load_model = exclude_keys is None or "model" not in exclude_keys optimizer_requested = exclude_keys is None or "optimizer" not in exclude_keys load_optim = optimizer_requested saved_keys, restored_on_any_rank = ( self._read_saved_keys(dcp_dir) if load_optim else ({}, False) ) if restaged and restored_on_any_rank: raise ValueError(self._optimizer_across_layouts(ckpt_dir)) saved_modules: list[str | None] | None = None lr_checked = False if restored_on_any_rank and ( self._weight_decay_scope is not None or self._lr_multipliers is not None ): if metadata is None: metadata = self._broadcast_metadata(ckpt_dir, metadata_read) if self._weight_decay_scope is not None: self._check_weight_decay_scope(metadata, ckpt_dir) if self._lr_multipliers is not None: saved_modules = self._check_lr_multipliers(metadata, ckpt_dir) lr_checked = True fresh_optimizer = load_optim and not _holds_optimizer(saved_keys) if fresh_optimizer: load_optim = False train_state_path = ckpt_dir / _TRAIN_STATE_FILE train_state_exists = load_train_state and self._train_state_exists(train_state_path) dcp_state: dict[str, Any] = {} optimizers = ( self._optimizers_saved_in(dcp_dir, saved_keys) if load_optim and train_state_exists else [] ) derived: dict[str, Any] = {} if load_model: dcp_state["model"] = get_model_state_dict(self.model) if derived_buffer_owners(self.model): model_keys = saved_keys if load_optim else _dcp_keys(dcp_dir) derived = drop_derived_model_keys(dcp_state["model"], self.model, model_keys) if derived: logger.info( f"{dcp_dir} predates {len(derived)} derived buffers, such as " f"{next(iter(derived))}; they start from the loaded state" ) check_error: BaseException | None = None left_out: set[str] = set() template_groups: list[list[str]] = [] unsaved_groups: list[tuple[int, dict[str, Any]]] = [] taken_scheduled: list[int] = [] if load_optim and not train_state_exists: check_error = FileNotFoundError( f"Cannot resume {ckpt_dir}: it holds optimizer state but no {_TRAIN_STATE_FILE}, " f"so loading it would continue its weights and optimizer moments from step 0 and " f"restart the LR schedule and the data stream. Its save stopped before writing " f"{_TRAIN_STATE_FILE}, or the file was lost. Restore the file, or set a new " f"checkpoint.dir with checkpoint.load_path pointing at an earlier complete " f"step_N to resume from it, or at this checkpoint with " f'checkpoint.exclude_from_loading = ["optimizer"] to start from its weights alone.' ) elif load_optim: dcp_state["optimizer"] = get_optimizer_state_dict(self.model, optimizers) template = cast("dict[str, Any]", dcp_state["optimizer"]) left_out = _params_the_save_left_out( fresh_if_unheld, saved_keys, expert_layout(self.model) ) & set(template["state"]) positions = [(o, k) for o in optimizers for k in range(len(o.param_groups))] owners = [optimizer for optimizer, _ in positions] positional = scheduler is not None and not isinstance( scheduler, torch.optim.lr_scheduler.LambdaLR ) fitted: list[list[tuple[int, dict[str, Any]]]] = [] check_error = _attempt( lambda: fitted.append( _fit_saved_optimizer( template, owners, self.optimizer if positional else None, left_out, saved_keys, dcp_dir, bool(self._lr_multipliers), saved_modules, expert_layout(self.model), ) ) ) unsaved_groups = fitted[0] if fitted else [] taken_scheduled = [ positions[index][1] for index, _ in unsaved_groups if positions[index][0] is self.optimizer ] template_groups = [list(group["params"]) for group in template["param_groups"]] if optimizer_requested: self.agree(check_error, "Checkpoint load") layout: ExpertLayout | None = None restore_error: BaseException | None = None if dcp_state: local_names = list(dcp_state.get("model", ())) dcp_state, layout = self._present_experts(dcp_state, dcp_dir, saved_keys) if load_model: every_rank = layout.group_names(local_names) if layout is not None else () self._check_model_fits( dcp_state["model"], every_rank, dcp_dir, restaged, saved_keys ) saved_left_out, saved_template_groups = left_out, template_groups if layout is not None: saved_left_out = set(layout.global_names(left_out)) saved_template_groups = [layout.group_names(names) for names in template_groups] planner = _NeverSteppedStatePlanner(saved_left_out) dcp.load( dcp_state, checkpoint_id=str(dcp_dir), process_group=self._process_group, planner=planner, ) if load_optim: optim_state = cast("dict[str, Any]", dcp_state["optimizer"]) def restore_unsaved() -> None: _restore_never_stepped(optim_state, planner.never_stepped, dcp_dir) _restore_left_out(optim_state, saved_template_groups, saved_left_out, dcp_dir) restore_error = _attempt(restore_unsaved) if planner.never_stepped: logger.info( f"{len(planner.never_stepped)} parameters the saved optimizer held were never " f"stepped and resume without state: {sorted(planner.never_stepped)[:8]}" ) if optimizer_requested: self.agree(restore_error, "Checkpoint load") if dcp_state: if layout is not None: dcp_state = layout.to_local(dcp_state) if load_optim: loaded_groups = cast("dict[str, Any]", dcp_state["optimizer"])["param_groups"] for index, group in unsaved_groups: loaded_groups.insert(index, group) if load_model: set_model_state_dict(self.model, {**dcp_state["model"], **derived}) if derived: derive_buffers(self.model, derived) if load_optim: set_optimizer_state_dict( self.model, optimizers, optim_state_dict=dcp_state["optimizer"] ) to_train = getattr(self.optimizer, "train_params", None) if to_train is not None: to_train() if left_out: logger.info( f"{len(left_out)} parameters that a freeze stage unfreezes were not in the " f"saved optimizer and resume without state: {sorted(left_out)[:8]}" ) if fresh_optimizer: for optimizer in self.checkpointed_optimizers: _reset_to_fresh(optimizer) if not load_train_state: logger.info( f"Weights-only warm start from {ckpt_dir}: its step, schedule, data position " "and RNG are not restored, and its freeze metadata is not compared" ) step, tokens_seen, extra = 0, 0, {} elif train_state_exists: train_state = self._broadcast_train_state(train_state_path) if ( self._lr_multipliers is not None and not lr_checked and scheduler is not None and "scheduler" in train_state ): if metadata is None: metadata = self._broadcast_metadata(ckpt_dir, metadata_read) self._check_lr_multipliers(metadata, ckpt_dir) held_position = "dataloader" in train_state carried = False if exact_resume: train_state, carried = self._per_rank_view(train_state) if "dataloader" in train_state: position = train_state["dataloader"] if dataloader is not None: del train_state["dataloader"] self._pending_dataloader_state = position self._pending_dataloader_warm_start = warm_start self._pending_dataloader_carried = carried self._pending_dataloader_missing = not held_position if dataloader is not None: self.apply_dataloader_state(dataloader) step, tokens_seen, extra = restore_train_state( train_state, scheduler=scheduler, dataloader=dataloader, lr_multipliers=self._lr_multipliers, ) if scheduler is not None and "scheduler" in train_state and taken_scheduled: _rate_taken_groups(self.optimizer, scheduler, taken_scheduled) logger.info(f"Resumed from step {step}, {tokens_seen:,} tokens seen") else: step, tokens_seen, extra = 0, 0, {} logger.info( f"{ckpt_dir} has no {_TRAIN_STATE_FILE}; the step counter, token count, LR " f"schedule, data position and RNG state start fresh at step 0" ) if fresh_optimizer and step > 0: logger.warning( f"{dcp_dir} holds no optimizer state at step {step}: resuming with a fresh " f"optimizer, so its moments restart from zero and this resume does not " f"continue the saved run exactly." ) elif fresh_optimizer: logger.info(f"{dcp_dir} holds no optimizer state; the optimizer starts fresh") self._restored_extra = dict(extra) self._restored_optimizer = load_optim return step, tokens_seen, extra
def _train_state_exists(self, path: Path) -> bool: """Whether ``path`` exists, as rank 0 sees it, on every rank. On NFS/Lustre independent stat() calls can disagree briefly across ranks. Ranks that disagree take different branches of ``load()``: some raise or skip the train state while the others wait in its broadcast and hang. Rank 0 checks, and its answer is broadcast. """ if not dist.is_initialized(): return path.exists() exists_flag = [path.exists() if self._rank == 0 else False] dist.broadcast_object_list(exists_flag, src=0) return bool(exists_flag[0]) def _read_saved_keys(self, dcp_dir: Path) -> tuple[dict[str, Any], bool]: """Return the keys this rank's DCP index in ``dcp_dir`` lists, and whether any rank's index holds optimizer state. With a weight-decay scope or LR multipliers every rank must call this. One all-reduce on the manager's gloo group, which every rank enters even when its own read failed, then tells every rank whether any rank's index holds optimizer state, so every rank gets the same answer; under PP each stage has its own index. Without either, no collective is issued and the answer is this rank's own. Raises: RuntimeError: Another rank could not read its DCP index. Exception: Whatever this rank's read of its DCP index raised. """ if self._weight_decay_scope is None and self._lr_multipliers is None: keys = _dcp_keys(dcp_dir) return keys, _holds_optimizer(keys) keys: dict[str, Any] = {} error: Exception | None = None try: keys = _dcp_keys(dcp_dir) except Exception as e: error = e return keys, self._optimizer_saved_on_any_rank(error, _holds_optimizer(keys)) def _optimizer_saved_on_any_rank(self, error: Exception | None, holds: bool) -> bool: """Return whether any rank's DCP index holds optimizer state, the same on every rank. Every rank passes the error its read of its index raised, or ``None``, and whether its index holds optimizer state. After one all-reduce on the manager's gloo group a rank with an error re-raises it, and every other rank raises a ``RuntimeError`` naming the ranks that failed. Without an initialized process group, ``error`` is raised if set. """ if not dist.is_initialized(): if error is not None: raise error return holds flags = torch.zeros(2, dist.get_world_size(self._sync_group), dtype=torch.int32) rank = dist.get_rank(self._sync_group) flags[0, rank] = int(error is not None) flags[1, rank] = int(holds) dist.all_reduce(flags, group=self._sync_group) if error is not None: raise error failed = flags[0].nonzero().flatten().tolist() if failed: raise RuntimeError(f"Could not read the DCP index of the checkpoint on ranks {failed}") return bool(flags[1].any()) def _broadcast_train_state(self, path: Path) -> dict[str, Any]: """Return rank 0's read of the ``train_state.pt`` at ``path`` on every rank. Rank 0 alone reads the file (``_load_train_state``) and broadcasts the state, or in its place why it could not read it, such as a torn file or one the ownership check refuses. Every rank then fails at once, instead of the others waiting in the broadcast until the process-group timeout. Every rank calls this or none does. Raises: Exception: On rank 0, or without a process group, what reading the file raised. RuntimeError: On every other rank, naming rank 0's error. """ state: dict[str, Any] | None = None error: Exception | None = None if self._rank == 0 or not dist.is_initialized(): try: state = _load_train_state(path) except Exception as e: error = e if dist.is_initialized(): reason = None if error is None else f"{type(error).__name__}: {_error_text(error)}" outcome: list[tuple[dict[str, Any] | None, str | None]] = [(state, reason)] dist.broadcast_object_list(outcome, src=0) state, reason = outcome[0] if error is None and reason is not None: raise RuntimeError(f"Rank 0 could not read {path}: {reason}") if error is not None: raise error assert state is not None return state def _broadcast_metadata( self, ckpt_dir: Path, read: _MetadataOutcome | None = None ) -> _MetadataOutcome: """Return rank 0's read of the checkpoint's ``metadata.json`` on every rank: the JSON object it holds, or why rank 0 could not read one. Every rank calls this or none does. Rank 0 alone reads the file, or takes ``read``, the read ``_agreed_load_dir`` made for the same load, and broadcasts the outcome once, so every check of a load decides from the same record on every rank and none is left waiting on the broadcast. """ outcome: list[_MetadataOutcome] = [(None, None)] if self._rank == 0 or not dist.is_initialized(): outcome[0] = read if read is not None else _metadata_outcome(ckpt_dir) if dist.is_initialized(): dist.broadcast_object_list(outcome, src=0) return outcome[0] def _check_plugins( self, metadata: _MetadataOutcome, ckpt_dir: Path, expected: list[str] ) -> None: """Refuse a checkpoint saved with a ``plugins`` list other than ``expected``. A plugin can register a component the model is built from, so another list can build another model from the same TOML, and DCP loads a model whose parameter names are a subset of the saved ones without an error. The lists compare in order, each module counted once, since importing a module again does nothing. ``metadata`` is what ``_broadcast_metadata`` returned on every rank, so every rank raises or goes on together, and rank 0 alone warns. A checkpoint whose ``metadata.json`` records no list, or cannot be read, is not compared. Raises: ValueError: The lists differ and ``checkpoint.ignore_plugins_mismatch`` is off. """ meta, error = metadata saved = None if meta is None else meta.get("plugins") if not isinstance(saved, list) or not all(isinstance(p, str) for p in saved): if self._rank == 0: if meta is None: reason = error elif saved is None: reason = f"its {_METADATA_FILE} records no plugins list" else: reason = f"its {_METADATA_FILE} records plugins = {saved!r}" logger.warning( f"plugins = {list(expected)!r} is not compared with {ckpt_dir}: {reason}" ) return if list(dict.fromkeys(saved)) == list(dict.fromkeys(expected)): return message = ( f"{ckpt_dir} was saved with plugins = {saved!r}, but this run sets plugins = " f"{list(expected)!r}: a plugin can register a component the model is built from, " "and a model whose parameters are a subset of the saved ones loads without an error." ) if self.config.ignore_plugins_mismatch: if self._rank == 0: logger.warning( f"{message} Going on, since checkpoint.ignore_plugins_mismatch is set" ) return raise ValueError( f"{message} Set plugins as the checkpoint has them, or, if the plugins that differ " "build no part of the model, set checkpoint.ignore_plugins_mismatch = true." ) def _check_vlm_freeze( self, metadata: _MetadataOutcome, ckpt_dir: Path, expected: _FreezeExpectation, ) -> None: """Refuse a checkpoint whose recorded VLM freeze differs from the run's. ``metadata`` is what ``_broadcast_metadata`` returned on every rank, so every rank compares the same record and raises or goes on together, and rank 0 alone warns. ``expected`` is the run's canonical freeze metadata, or a function that gives it for a step, called with the step the record holds. Only the modules both freezes name are compared (see ``_intersect_freeze_meta_by_module``). A record that cannot be read, a checkpoint without one included, or that holds no step for ``expected`` to take, is not compared, with a warning; one that records no freeze is not compared. Raises: ValueError: The freezes differ and ``checkpoint.ignore_freeze_mismatch`` is off. """ meta, error = metadata saved = None if meta is None else meta.get("vlm_freeze") step = None if meta is None else _recorded_step(meta) if meta is not None and saved is not None and callable(expected) and step is None: error = f"its {_METADATA_FILE} records step={meta.get('step')!r}, which is not a step" if error is not None: if self._rank == 0: logger.warning(f"The VLM freeze is not compared with {ckpt_dir}: {error}") return if saved is None: return wanted = expected(cast(int, step)) if callable(expected) else expected saved_filt, expected_filt = _intersect_freeze_meta_by_module(saved, wanted) if saved_filt == expected_filt: return dropped_from_saved = sorted( {e["module"] for e in saved} - {e["module"] for e in saved_filt} ) dropped_from_expected = sorted( {e["module"] for e in wanted} - {e["module"] for e in expected_filt} ) cross_arch_note = "" if dropped_from_saved or dropped_from_expected: cross_arch_note = ( f" (cross-arch keys ignored: saved-only={dropped_from_saved}, " f"current-only={dropped_from_expected})" ) msg = ( f"VLM freeze mismatch at {ckpt_dir}: saved={saved_filt}, current={expected_filt}" f"{cross_arch_note}" ) if getattr(self.config, "ignore_freeze_mismatch", False): if self._rank == 0: logger.warning(msg + "; proceeding because checkpoint.ignore_freeze_mismatch=True") return raise ValueError(msg + " (set checkpoint.ignore_freeze_mismatch=true to override)") def _check_weight_decay_scope(self, metadata: _MetadataOutcome, ckpt_dir: Path) -> None: """Refuse a checkpoint saved under a weight-decay scope other than this manager's. ``metadata`` is what ``_broadcast_metadata`` returned on every rank, so every rank raises or proceeds together. A checkpoint without ``metadata.json``, as one whose save stopped before writing it or a copy that lost it, records no scope, so it is refused like one whose record cannot be read, never taken for the legacy scope. Raises: ValueError: The checkpoint's scope differs from this manager's, or it has no ``metadata.json`` holding a valid scope record. """ meta, error = metadata saved: str | None = None if meta is not None: try: saved = _recorded_weight_decay_scope(meta, ckpt_dir / _METADATA_FILE) except ValueError as e: error = str(e) if error is not None: raise ValueError( f"Cannot check the weight_decay_scope of {ckpt_dir}: {error}. A checkpoint's " f"{_METADATA_FILE} records the scope its optimizer state was saved under, which " f"decides the optimizer's param groups, so that state is not loaded without a " f"valid record. Restore the file as the save wrote it, or " f"{_fresh_optimizer_route(ckpt_dir)}" ) if saved != self._weight_decay_scope: raise ValueError( f"{ckpt_dir} was saved with optimizer.weight_decay_scope={saved!r}, but this " f"run uses {self._weight_decay_scope!r}. The scope decides the optimizer's " f"param groups, so the saved optimizer state cannot be loaded into this run's " f"groups. Resume with weight_decay_scope={saved!r}, or " f"{_fresh_optimizer_route(ckpt_dir)}" ) def _check_lr_multipliers( self, metadata: _MetadataOutcome, ckpt_dir: Path ) -> list[str | None] | None: """Refuse a checkpoint saved with LR multipliers, or patterns of their modules, other than this manager's. The multipliers and the patterns decide the optimizer's param groups and their learning rates, which the saved optimizer state and the scheduler state in ``train_state.pt`` are laid out for. ``metadata`` is what ``_broadcast_metadata`` returned on every rank, so every rank raises or proceeds together. A manager with multipliers refuses a ``metadata.json`` that cannot be read or holds an invalid record; one without refuses only a record of multipliers, and loads past any other with a warning, as from a checkpoint saved without them. Returns: The module each of the checkpoint's optimizer param groups names, None for a group of no listed module, as its save recorded them; None when it recorded none or this manager has no multipliers. Raises: ValueError: The checkpoint's multipliers or patterns differ from this manager's, or, for a manager with multipliers, its ``metadata.json`` does not hold a valid record. """ try: multipliers, patterns, group_modules = _lr_record( metadata, ckpt_dir, layout=bool(self._lr_multipliers) ) except ValueError as e: if self._lr_multipliers: raise ValueError(f"Cannot check the lr_multipliers of {ckpt_dir}: {e}") from e logger.warning( f"Cannot read the lr_multipliers record of {ckpt_dir} ({e}); this run has no " f"lr_multipliers, so it loads the checkpoint as one saved without them" ) return None if multipliers != self._lr_multipliers: change = ( f"optimizer.lr_multipliers={multipliers}, but this run uses {self._lr_multipliers}" ) elif patterns != self._lr_module_patterns: change = ( f"the module patterns {patterns} for its optimizer.lr_multipliers, but this run " f"has {self._lr_module_patterns}" ) else: return group_modules raise ValueError( f"{ckpt_dir} was saved with {change}. The multipliers and the patterns of their " f"modules decide the optimizer's param groups and their learning rates, and the " f"checkpoint's optimizer and scheduler state belong to the groups it was saved with. " f"Resume with the saved values, or start from its weights alone under the new ones: " f"checkpoint.load_path={str(ckpt_dir)!r} with " f'checkpoint.exclude_from_loading=["optimizer", "train_state"], which restarts the ' f"step, schedule and data position, and a checkpoint.dir that holds no checkpoint, " f"since training auto-resumes from a checkpoint there in place of load_path." ) @property def restored_extra(self) -> dict[str, Any]: """The extra keys the last ``load()`` restored from ``train_state.pt``. Empty before a load, and after one that restored no train state. """ return dict(self._restored_extra) @property def restored_optimizer(self) -> bool: """Whether the last ``load()`` restored this rank's optimizer state, its rates included. False before a load, and after one that left the optimizer out or found no optimizer state in the checkpoint, as one saved before the first update holds none. """ return self._restored_optimizer
[docs] def apply_dataloader_state(self, dataloader: Any) -> None: """Apply any dataloader state stashed during load(). Training loops call load() before constructing the dataloader (since the dataloader depends on phase/annealing state that load() restores). This method applies the stashed state once the loader exists. No-op if no state is pending, or if the loader does not support ``load_state_dict`` (e.g., a plain torch DataLoader). A ``StatefulDataLoader`` or ``StreamingDataLoader`` checks the position on every rank first (``check_state``), and the ranks share their verdicts before any rank applies it, since a rank's view of the data, such as a data file's size, can differ from another's: every rank applies the position, or none does. A position that some rank's loader cannot place raises ``DataPositionError`` on every rank on a resume; after a ``warm_start`` load, or an exact resume that ``checkpoint.ignore_rank_state_mismatch`` let onto a changed topology or past a checkpoint with no per-rank state, every rank starts the data at its first sample instead, with a warning that names the ranks that cannot place it and why. Whether the ranks share verdicts follows from the broadcast train state and the loader's type alone, so every rank reaches that collective or none does. On such a flag resume only these two loaders take the saved position, since they check that it fits the new layout; another loader's state may be rank 0's own, so it is dropped with a warning and the data starts at its first sample. A restored checkpoint that holds no data position, such as a streaming checkpoint saved before streaming positions were recorded, leaves a stateful loader at its first sample, with a warning. """ missing, self._pending_dataloader_missing = self._pending_dataloader_missing, False if self._pending_dataloader_state is None: if missing and dataloader is not None and hasattr(dataloader, "load_state_dict"): start = ( "the stream restarts at its first document" if isinstance(dataloader, StreamingDataLoader) else "the data starts at its first sample" ) logger.warning(f"The restored checkpoint holds no data position, so {start}") return state, self._pending_dataloader_state = self._pending_dataloader_state, None carried, self._pending_dataloader_carried = self._pending_dataloader_carried, False warm_start = self._pending_dataloader_warm_start if dataloader is None or not hasattr(dataloader, "load_state_dict"): return if not isinstance(dataloader, (StatefulDataLoader, StreamingDataLoader)): if carried: logger.warning( f"Dropping the saved data position on the changed topology: a " f"{type(dataloader).__name__} may keep one rank's own position, which does " f"not fit the other ranks, so the data starts at its first sample" ) return try: dataloader.load_state_dict(state) except DataPositionError as e: if not warm_start: raise logger.warning( f"The warm start's data position does not carry over to this run, so the " f"data starts at its first sample: {e}" ) return logger.info("Applied stashed dataloader state") return refusals, world = self._position_refusals(dataloader, state) if refusals: mine = refusals.get(self._rank) first = min(refusals) reason = mine if mine is not None else f"rank {first}: {refusals[first]}" where = "" if len(refusals) == world else f" on ranks {sorted(refusals)}" if warm_start: logger.warning( f"The warm start's data position does not carry over to this run{where}, so " f"the data starts at its first sample on every rank: {reason}" ) return if carried: logger.warning( f"The saved data position does not carry over to the changed topology" f"{where}, so the data starts at its first sample on every rank " f"(checkpoint.ignore_rank_state_mismatch=true): {reason}" ) return if mine is not None: raise DataPositionError(mine) raise DataPositionError(f"The saved data position cannot be resumed{where}: {reason}") dataloader.load_state_dict(state) logger.info("Applied stashed dataloader state")
def _position_refusals( self, dataloader: Any, state: dict[str, Any] ) -> tuple[dict[int, str], int]: """Why each rank's loader cannot place ``state``, gathered on every rank. Every rank checks the position against its own loader with ``check_state``, which changes nothing. A rank's view of the data, such as a data file's size, can differ from another's, so the ranks gather their verdicts before any rank applies a position. A check that fails some other way is gathered too, so every rank raises together. Collective on the dedicated gloo group; ``apply_dataloader_state`` calls it whenever a position is pending for one of the loaders that check it, which the broadcast train state and the configured loader decide alike on every rank. Returns: Global rank -> why its loader cannot place the position (empty when every rank's can), and the number of ranks that checked. Raises: Exception: On a rank whose check failed other than with ``DataPositionError``, that error; ``RuntimeError`` on every other rank. """ failure: Exception | None = None verdict: tuple[str, str] | None = None try: dataloader.check_state(state) except DataPositionError as e: verdict = ("refused", str(e)) except Exception as e: failure = e verdict = ("failed", f"{type(e).__name__}: {_error_text(e)}") verdicts: dict[int, tuple[str, str] | None] = {self._rank: verdict} if dist.is_initialized(): gathered: list[Any] = [None] * dist.get_world_size(self._sync_group) dist.all_gather_object(gathered, verdict, group=self._sync_group) verdicts = dict(enumerate(gathered)) if failure is not None: raise failure failed = {rank: v[1] for rank, v in verdicts.items() if v is not None and v[0] == "failed"} if failed: first = min(failed) raise RuntimeError( f"Checking the saved data position failed on ranks {sorted(failed)}: " f"rank {first}: {failed[first]}" ) refusals = {rank: v[1] for rank, v in verdicts.items() if v is not None} return refusals, len(verdicts) def _resolve_load_path(self, path: str | None = None) -> Path | None: """Resolve the checkpoint path to load from. Returns the raw resolution (explicit path, ``load_path``, or the ``latest`` symlink target). The DCP-durability fallback for an interrupted async flush is applied separately in ``load()``, scoped to the case where DCP state is actually being loaded — so it never interferes with DCP-excluded loads (e.g. fine-tuning). """ if path is not None: p = Path(path) return p if p.exists() else None if self.config.load_path: p = Path(self.config.load_path) return p if p.exists() else None latest = self._latest_link() if latest.exists(): return latest.resolve() return None def _agreed_load_dir( self, path: str | None, fall_back: bool ) -> tuple[Path | None, SavedLayout | None, _MetadataOutcome | None]: """Return the checkpoint rank 0 resolves for a load, and its layout, on every rank. Rank 0 resolves ``path`` (see ``_resolve_load_path``), following symlinks, and, with ``fall_back`` (an exact resume that reads DCP shards), takes the newest complete ``step_N`` beside it when that one is not a complete save (see ``_newest_saved_beside``). It then reads the chosen checkpoint's ``metadata.json``, and how the checkpoint lays out its DCP shards (see ``saved_layout``), None for one that holds no DCP index. It broadcasts the directory and the layout, or why it could not choose, so every rank loads the same directory as the same layout, or returns or raises together, whatever its own view of the filesystem. Every rank must call this. Returns: The directory and the layout, both None when no checkpoint resolves, and on rank 0 its read of ``metadata.json`` (see ``_broadcast_metadata``), None on every other rank, so the whole load decides from one read of the record. Raises: Exception: On rank 0, what resolving the checkpoint raised. RuntimeError: On every other rank, naming rank 0's error. """ outcome: list[dict[str, Any]] = [{"dir": None, "layout": None, "error": None}] read: _MetadataOutcome | None = None error: Exception | None = None if self._rank == 0 or not dist.is_initialized(): try: resolved = self._resolve_load_path(path) if resolved is not None: resolved = resolved.resolve() if resolved is not None and fall_back: resolved = self._newest_saved_beside(resolved, self._pp_size).resolve() layout = None if resolved is not None: read = _metadata_outcome(resolved) layout = saved_layout(resolved, read[0] or {}) outcome[0] = { "dir": None if resolved is None else str(resolved), "layout": layout, "error": None, } except Exception as e: error = e outcome[0] = { "dir": None, "layout": None, "error": f"{type(e).__name__}: {_error_text(e)}", } if dist.is_initialized(): dist.broadcast_object_list(outcome, src=0) if error is not None: raise error chosen, reason = outcome[0]["dir"], outcome[0]["error"] if reason is not None: raise RuntimeError(f"Rank 0 could not pick the checkpoint to load: {reason}") if chosen is None: return None, None, None return Path(chosen), outcome[0]["layout"], read @staticmethod def _newest_saved_beside(resolved: Path, num_stages: int | None = None) -> Path: """``resolved``, or the newest ``step_N`` beside it that is complete if it is not. A checkpoint is complete when ``is_complete_checkpoint`` accepts it with ``num_stages``, the run's pipeline degree, and with the train state an exact resume restores: the rule ``resolve_resume_path`` applies, so the two never disagree on a checkpoint. A switch is logged, so resume degrades to the last complete step instead of failing in ``dcp.load`` with "metadata is None" or on the missing train state; ``resolved`` comes back when no step beside it qualifies. """ reason = _incomplete_reason(resolved, num_stages) if reason is None: return resolved saved = { int(number): d for d in resolved.parent.iterdir() if d.name.startswith("step_") and (number := d.name.removeprefix("step_")).isdigit() and is_complete_checkpoint(d, num_stages) } if not saved: return resolved fallback = saved[max(saved)] logger.warning( f"{resolved} is not a complete save ({reason}), so the save that wrote it was " f"likely cut short, or it lost a file since. Resuming from {fallback} instead, the " f"newest checkpoint beside it whose save completed." ) return fallback def _optimizers_saved_in( self, dcp_dir: Path, keys: Collection[str] ) -> list[torch.optim.Optimizer]: """Return the optimizers saved in ``dcp_dir``; warn if the inner ones are missing. The inner ones are missing from a checkpoint saved before they were checkpointed, whose param groups are as many as the outer optimizer's and hold none of the inner ones' settings (see ``_saved_inner_groups``). """ inner = self.checkpointed_optimizers[1:] if ( not inner or _saved_optimizer_param_groups(keys) != len(self.optimizer.param_groups) or _saved_inner_groups(keys, self.optimizer, inner) ): return self.checkpointed_optimizers name = type(self.optimizer).__name__ n_params = sum(p.numel() for opt in inner for g in opt.param_groups for p in g["params"]) logger.warning( f"{dcp_dir} holds only {name}'s own optimizer state: it was saved before " f"{name}'s inner optimizer was checkpointed. Resuming {name}'s state alone; the " f"{n_params:,} parameters its inner optimizer updates start from fresh moments, " f"so this resume is not bit-exact. Checkpoints saved from now on include them." ) return self.checkpointed_optimizers[:1] def _cleanup(self) -> None: """Remove old checkpoints beyond the retention limit. Never removed regardless of retention: the current ``latest`` target, the directory the last ``save()`` writes into (``_inflight_dir``), whose async flush may still be running, a deferred async checkpoint (``_pending_finalize``), and any dynamic-window milestone (``CheckpointConfig.is_dynamic_milestone``), so the dense early-dynamics checkpoints survive even with a finite ``keep_last_n``. A save drains ``_pending_finalize``, which runs this cleanup, only after its own flush is dispatched, so ``_inflight_dir`` is what keeps a checkpoint that is not among the newest, as after a rewind, from being deleted while it is written. A directory that NFS briefly keeps non-empty is retried after 0.05, 0.1, 0.2 and 0.4 s, waits that all the removals of one cleanup share, so a cleanup requests at most 0.75 s of retry sleep. One that still cannot be removed is logged and left for the next cleanup. """ keep = self.config.keep_last_n if keep <= 0: return ckpt_dirs = sorted( (d for d in self.base_dir.iterdir() if d.is_dir() and d.name.startswith("step_")), key=lambda d: int(d.name.split("_")[1]), ) protected: set[Path] = set() latest = self._latest_link() if latest.exists(): protected.add(latest.resolve()) if self._pending_finalize is not None: protected.add(self._pending_finalize[1].resolve()) if self._inflight_dir is not None: protected.add(self._inflight_dir.resolve()) for d in ckpt_dirs: if self.config.is_dynamic_milestone(int(d.name.split("_")[1])): protected.add(d.resolve()) to_remove = ckpt_dirs[:-keep] if len(ckpt_dirs) > keep else [] delays = iter(_REMOVE_RETRY_DELAYS) for d in to_remove: if d.resolve() in protected: continue try: _remove_tree(d, self._sidecar_lock, delays) except OSError as e: logger.warning( f"Could not remove old checkpoint {d} ({e}); the next cleanup retries it" ) continue logger.info(f"Removed old checkpoint: {d}")