Source code for kempnerforge.resilience.elastic

"""SLURM job and auto-resume helpers.

Despite the module name, nothing here is elastic training: there is no
elastic (torchelastic) rendezvous and no change of membership while a job
runs. The helpers read the SLURM job's environment and find the checkpoint
a restarted run resumes from:

- SLURM job info detection
- Requeue detection
- Auto-resume path resolution
"""

from __future__ import annotations

import logging
import os
from dataclasses import dataclass
from pathlib import Path

logger = logging.getLogger(__name__)


[docs] @dataclass class SLURMInfo: """Information about the current SLURM job.""" job_id: str job_name: str node_list: str num_nodes: int ntasks_per_node: int restart_count: int partition: str array_task_id: str | None @property def is_requeued(self) -> bool: """Whether this job has been requeued (restart_count > 0).""" return self.restart_count > 0
[docs] def get_slurm_info() -> SLURMInfo | None: """Read SLURM job information from environment variables. Returns: SLURMInfo if running under SLURM, None otherwise. """ job_id = os.environ.get("SLURM_JOB_ID") if job_id is None: return None return SLURMInfo( job_id=job_id, job_name=os.environ.get("SLURM_JOB_NAME", ""), node_list=os.environ.get("SLURM_JOB_NODELIST", ""), num_nodes=int(os.environ.get("SLURM_NNODES", "1")), ntasks_per_node=int(os.environ.get("SLURM_NTASKS_PER_NODE", "1")), restart_count=int(os.environ.get("SLURM_RESTART_COUNT", "0")), partition=os.environ.get("SLURM_JOB_PARTITION", ""), array_task_id=os.environ.get("SLURM_ARRAY_TASK_ID"), )
[docs] def is_slurm_job() -> bool: """Check if we are running under SLURM.""" return "SLURM_JOB_ID" in os.environ
[docs] def is_slurm_requeue() -> bool: """Check if this is a requeued SLURM job. Uses ``SLURM_RESTART_COUNT`` (set by SLURM on requeue). """ return int(os.environ.get("SLURM_RESTART_COUNT", "0")) > 0
[docs] def resolve_resume_path( checkpoint_dir: str, num_stages: int | None = None, *, require_train_state: bool = True ) -> Path | None: """Find the latest checkpoint for auto-resume. Checks: 1. ``{checkpoint_dir}/latest`` symlink 2. Most recent ``step_N`` directory *whose save completed* A checkpoint counts when ``is_complete_checkpoint`` accepts it, with the same ``num_stages`` and ``require_train_state``, so a reader of a run's checkpoints that calls that function counts the same steps as saved. An interrupted save leaves a ``step_N`` that exists but holds no ``.metadata``, and resuming into it fails in ``dcp.load`` with "metadata is None". A save that stopped after its DCP shards and before ``train_state.pt`` and ``metadata.json`` leaves optimizer state without the step, LR schedule and data position that go with it, which ``CheckpointManager.load`` refuses. Skipping both kinds turns an unrecoverable run into one that resumes from the last complete checkpoint, whatever left the partial directory behind. ``CheckpointManager`` points ``latest`` only at a complete save, but the save can lose files afterwards, so ``latest`` is checked like a ``step_N``: when it is not complete, a warning names it and why, and the scan below picks the checkpoint to resume. A ``latest`` whose shards are all there but that lost ``train_state.pt`` or ``metadata.json`` is still returned when no checkpoint is complete, after an error log, instead of the run starting over from step 0; the load then refuses one without ``train_state.pt``, and the optimizer state of one without ``metadata.json``, the only record of the weight-decay scope that state was saved under. Otherwise, when ``step_N`` directories exist but none is complete, a run that meant to resume starts over, so that is logged at ERROR. Args: checkpoint_dir: Base checkpoint directory. num_stages: The run's pipeline degree. With it, a ``step_N`` in the per-stage layout that records no degree counts only when ``pp0`` through ``pp{num_stages - 1}`` all hold ``.metadata``, including stages that never created their directory. When no step has every stage, the newest one that is otherwise complete is returned as before, after an error log, rather than the run starting over: a checkpoint saved with another pipeline degree before the degree was recorded looks the same. One that records its degree is complete at that degree, so a checkpoint of any layout is returned as it is, and loading it refuses what the run cannot load with an error that names both layouts. require_train_state: Skip a checkpoint whose shards hold optimizer state, or that has a ``train_state.pt``, unless it has both ``train_state.pt`` and ``metadata.json``. A caller that loads the weights alone, which such a checkpoint still holds in full, passes False to keep the newest one whose shards are complete. Returns: Path to the latest usable checkpoint, or None if none found. """ from kempnerforge.checkpoint.layout import _incomplete_reason base = Path(checkpoint_dir) if not base.exists(): return None latest = base / "latest" committed: tuple[Path, str] | None = None if latest.exists(): resolved = latest.resolve() reason = _incomplete_reason(resolved, num_stages, require_train_state) if reason is None: logger.info(f"Auto-resume: found latest checkpoint at {resolved}") return resolved if _incomplete_reason(resolved, num_stages, require_train_state=False) is None: committed = resolved, reason logger.warning( f"Auto-resume: skipping latest -> {resolved}: {reason}; looking for the newest " f"step_N whose save completed" ) step_dirs = sorted( ( d for d in base.iterdir() if d.is_dir() and d.name.startswith("step_") and d.name.split("_")[1].isdigit() ), key=lambda d: int(d.name.split("_")[1]), reverse=True, ) short_of_stages: Path | None = None for path in step_dirs: reason = _incomplete_reason(path, num_stages, require_train_state) if reason is None: logger.info(f"Auto-resume: found checkpoint at {path}") return path if num_stages is not None and num_stages > 1: otherwise = _incomplete_reason(path, None, require_train_state) if otherwise is None: short_of_stages = short_of_stages or path logger.warning( f"Auto-resume: skipping {path}: its stage directories are complete, but " f"this run has {num_stages} pipeline stages and not all of them are there" ) continue reason = otherwise logger.warning( f"Auto-resume: skipping {path}: {reason}, so the save that produced it did not " f"complete, or a file was lost since" ) if committed is not None: resolved, reason = committed logger.error( f"Auto-resume: no checkpoint under {base} is a complete save; resuming latest -> " f"{resolved}, whose DCP shards are all there ({reason}), instead of the run " f"starting over from step 0" ) return resolved if short_of_stages is not None: logger.error( f"Auto-resume: no complete checkpoint under {base} has all {num_stages} pipeline " f"stages; resuming {short_of_stages}, the newest that is otherwise complete. " f"Either a stage stopped before saving, or the checkpoint was saved with another " f"pipeline degree, which resume does not support" ) return short_of_stages if step_dirs: logger.error( f"Auto-resume: {len(step_dirs)} checkpoint directories under " f"{base} and none holds a complete save; starting from step 0, or from " f"checkpoint.load_path if one is set. Every saved step would have to be " f"re-trained." ) return None
[docs] def log_job_info() -> None: """Log SLURM job information (if running under SLURM).""" info = get_slurm_info() if info is None: logger.info("Not running under SLURM") return logger.info( f"SLURM job: id={info.job_id}, name={info.job_name}, " f"nodes={info.num_nodes}, tasks/node={info.ntasks_per_node}, " f"partition={info.partition}, restart_count={info.restart_count}" ) if info.is_requeued: logger.info(f"Job was requeued (restart #{info.restart_count}); will auto-resume")