kempnerforge.resilience

Fault tolerance and resilience for KempnerForge.

class kempnerforge.resilience.NaNDetector[source]

Bases: object

Detects and tracks NaN/Inf values in loss and gradients.

Supports three responses to NaN:
  • "warn": Log a warning and return False.

  • "skip": The same; check_loss()’s warning also says the optimizer step is skipped.

  • "raise": Raise a RuntimeError.

The training loop skips the optimizer step whenever a check returns False, so there "warn" and "skip" behave the same; its action and max_consecutive come from train.nan_action and train.nan_max_consecutive.

Once the consecutive NaN count reaches max_consecutive, rollback_recommended turns True. Nothing rolls back on its own: the training loop stops on it, and a rollback to an earlier checkpoint is manual.

Parameters:
  • action – What to do when NaN is detected.

  • max_consecutive – Consecutive NaN steps before recommending rollback.

  • max_history – Number of NaN step indices to retain.

__init__(action='warn', max_consecutive=5, max_history=100)[source]
Parameters:
  • action (str)

  • max_consecutive (int)

  • max_history (int)

Return type:

None

check_loss(loss, step, grad_norm=None)[source]

Check a step’s loss, and its gradient norm when given, for NaN/Inf.

When running distributed, all-reduces a NaN flag so ALL ranks agree on whether to skip. Prevents rank desync where one rank sees NaN and skips its optimizer step while others proceed normally. The flag is on the current CUDA device, or on the CPU when CUDA is unavailable, so a gloo process group without CUDA reduces it as well.

A finite loss does not guarantee finite gradients: a micro-batch whose labels are all masked has an exact zero cross-entropy loss whatever its activations, so the caller passes the gradient norm as well. Each rank’s norm goes into the same reduced flag as the loss, so every rank skips the step together even when a non-finite gradient reaches only some ranks’ norms.

Parameters:
  • loss (float) – The scalar loss value to check.

  • step (int) – Current training step.

  • grad_norm (float | None) – The step’s gradient norm, or None to check the loss alone.

Returns:

True if the loss and the gradient norm are finite on ALL ranks, False if any rank has NaN/Inf in either.

Raises:

RuntimeError – If action is “raise” and NaN is detected.

Return type:

bool

check_gradients(model, step)[source]

Check model gradients for NaN/Inf before optimizer step.

Each rank checks the gradients it holds (the local shard of a DTensor). When running distributed, one all-reduce of a flag, as in check_loss(), gives every rank the same verdict, so this is a collective that every rank must call, and the ranks all skip the step or all take it. Unlike check_loss() it leaves state as it is.

Parameters:
  • model (torch.nn.Module) – The model to check, or this rank’s pipeline stage of it.

  • step (int) – Current training step.

Returns:

True if all gradients are finite on ALL ranks, False if any rank holds a NaN/Inf gradient.

Raises:

RuntimeError – If action is “raise” and any rank holds a NaN/Inf gradient.

Return type:

bool

Whether the consecutive NaN count has reached max_consecutive.

It recommends a rollback and does none: the training loop stops on it without a checkpoint, and the rollback to an earlier one is manual.

property should_rollback: bool

Deprecated alias of rollback_recommended.

Reading it emits a DeprecationWarning.

reset()[source]

Reset NaN tracking state (e.g., after a rollback).

Return type:

None

class kempnerforge.resilience.NaNState[source]

Bases: object

Tracks NaN/Inf occurrences across training steps.

consecutive_nans: int = 0
total_nans: int = 0
last_good_loss: float = inf
last_good_step: int = 0
nan_steps: list[int]
__init__(consecutive_nans=0, total_nans=0, last_good_loss=inf, last_good_step=0, nan_steps=<factory>)
Parameters:
  • consecutive_nans (int)

  • total_nans (int)

  • last_good_loss (float)

  • last_good_step (int)

  • nan_steps (list[int])

Return type:

None

class kempnerforge.resilience.SLURMInfo[source]

Bases: object

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 is_requeued: bool

Whether this job has been requeued (restart_count > 0).

__init__(job_id, job_name, node_list, num_nodes, ntasks_per_node, restart_count, partition, array_task_id)
Parameters:
  • 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)

Return type:

None

class kempnerforge.resilience.ShutdownHandler[source]

Bases: object

Cooperative shutdown handler for long-running training jobs.

Register this handler before the training loop. The training loop checks should_shutdown() after each step and takes appropriate action (save checkpoint, clean up, exit).

If the graceful shutdown exceeds its timeout, a forced exit is triggered via os._exit to avoid hanging on stuck collectives.

Usage:

handler = ShutdownHandler(timeout_sec=120)
handler.register()

for step in range(max_steps):
    train_step()
    handler.reinstall()
    if handler.should_shutdown():
        save_checkpoint()
        break
wait_for_checkpoint()
handler.finish()
Parameters:
  • timeout_sec – Seconds a shutdown that a SIGUSR1 or request() starts may take before the forced exit; 0 disables it. None resolves it, and sigterm_timeout_sec with it, as training does for an unset train.shutdown_timeout_sec (see resolve_shutdown_timeouts).

  • sigterm_timeout_sec – The same for a SIGTERM, which the launcher may follow with a kill; None takes timeout_sec, or the resolved value. A SIGTERM that arrives once a longer timer is running brings the forced exit forward to its own timeout.

__init__(timeout_sec=None, sigterm_timeout_sec=None)[source]
Parameters:
  • timeout_sec (float | None)

  • sigterm_timeout_sec (float | None)

Return type:

None

property shutdown_requested: bool

Whether a shutdown was requested, by a signal or by request().

property signal_received: Signals | None

The signal that triggered shutdown, or None.

should_shutdown()[source]

Check if the training loop should exit.

Call this after each training step.

Return type:

bool

request()[source]

Request a shutdown without a signal, as when another rank received one.

Sets the flag and starts the forced-exit timer with timeout_sec, as a SIGUSR1 does, so a rank that stops because another rank was signaled is bounded by its own timer too; its own SIGTERM, if one follows, brings the exit forward. Calling it again changes nothing.

Return type:

None

register()[source]

Register signal handlers for SIGTERM and SIGUSR1.

Must be called from the main thread.

Return type:

None

reinstall()[source]

Install the handlers again; a no-op unless registered, or off the main thread.

Native code can replace a handler below Python, where signal.getsignal cannot see it: the LLVM inside Triton does on its first in-process compile, after which SIGUSR1 does nothing. Only the main thread can install a handler, so on any other thread, such as a training loop run off the main thread, this does nothing.

Return type:

None

unregister()[source]

Restore the original signal handlers; the forced-exit timer stays armed.

Return type:

None

cancel_watchdog()[source]

Cancel the forced-exit timer, leaving the signal handlers installed.

Return type:

None

finish()[source]

Call once the emergency checkpoint is durable and teardown is done.

Restores the signal handlers and cancels the forced-exit timer, so it must come after the last step that a second signal or a hang could cut short: the checkpoint flush, and tearing down the process group.

Return type:

None

kempnerforge.resilience.check_gpu_health(device=0)[source]

Run basic GPU health checks.

Performs:
  1. CUDA availability check

  2. Small test computation on the device

  3. Memory allocation test

Returns:

Dict with health check results.

Parameters:

device (int)

Return type:

dict[str, bool | str]

kempnerforge.resilience.check_nccl_health(timeout_sec=10.0)[source]

Check NCCL communication health via a lightweight all-reduce.

The all-reduce runs with async_op=True so work.wait(timeout=...) enforces the caller’s bound rather than falling back to the process-group default timeout (nccl_timeout_sec, 1800s). Without that, this function would sit for 30 minutes on a single stuck peer regardless of the timeout_sec argument.

Parameters:

timeout_sec (float) – Per-operation timeout for the collective. Returns False if the all-reduce does not complete within this budget.

Returns:

True on success, False on timeout, error, or world-size mismatch.

Return type:

bool

kempnerforge.resilience.get_slurm_info()[source]

Read SLURM job information from environment variables.

Returns:

SLURMInfo if running under SLURM, None otherwise.

Return type:

SLURMInfo | None

kempnerforge.resilience.is_slurm_job()[source]

Check if we are running under SLURM.

Return type:

bool

kempnerforge.resilience.is_slurm_requeue()[source]

Check if this is a requeued SLURM job.

Uses SLURM_RESTART_COUNT (set by SLURM on requeue).

Return type:

bool

kempnerforge.resilience.log_job_info()[source]

Log SLURM job information (if running under SLURM).

Return type:

None

kempnerforge.resilience.resolve_resume_path(checkpoint_dir, num_stages=None, *, require_train_state=True)[source]

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.

Parameters:
  • checkpoint_dir (str) – Base checkpoint directory.

  • num_stages (int | None) – 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 (bool) – 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.

Return type:

Path | None

kempnerforge.resilience.resolve_shutdown_timeouts(configured)[source]

The forced-exit timeouts, in seconds, for train.shutdown_timeout_sec.

The launch scripts under scripts/slurm export KEMPNERFORGE_SHUTDOWN_LEAD_SEC, the seconds their ranks have from the shutdown SIGTERM until they may be killed: the --signal lead of the scripts that launch the ranks with srun, since at the time limit SLURM’s SIGTERM can make srun kill them at once, and the 30 s that torchrun gives its workers by default in singlenode.sh. Left unset, a SIGTERM gets three quarters of that lead, so a rank whose emergency save, flush or teardown hangs exits through the timer, which logs Graceful shutdown timed out, before the launcher kills it; without the variable it gets 600 s. A SIGUSR1, the manual stop, which no kill follows, and a shutdown another rank started get 600 s. 0 disables the timer. Any other value applies to both, with a warning when it is not below the lead, since the launcher can then kill the rank before the timer fires.

Returns:

(timeout_sec, sigterm_timeout_sec), as ShutdownHandler takes them.

Raises:

ValueError – KEMPNERFORGE_SHUTDOWN_LEAD_SEC is set to something other than a positive number of seconds.

Parameters:

configured (float | None)

Return type:

tuple[float, float]

Modules

elastic

SLURM job and auto-resume helpers.

health

GPU and NCCL health checks and NaN detection.

signal_handler

Graceful shutdown via signal handling.