kempnerforge.resilience¶
Fault tolerance and resilience for KempnerForge.
- class kempnerforge.resilience.NaNDetector[source]¶
Bases:
objectDetects 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 aRuntimeError.
The training loop skips the optimizer step whenever a check returns False, so there
"warn"and"skip"behave the same; its action andmax_consecutivecome fromtrain.nan_actionandtrain.nan_max_consecutive.Once the consecutive NaN count reaches
max_consecutive,rollback_recommendedturns 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.
- 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:
- 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:
- 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 incheck_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. Unlikecheck_loss()it leavesstateas 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:
- property rollback_recommended: 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.
- class kempnerforge.resilience.NaNState[source]¶
Bases:
objectTracks NaN/Inf occurrences across training steps.
- class kempnerforge.resilience.SLURMInfo[source]¶
Bases:
objectInformation about the current SLURM job.
- class kempnerforge.resilience.ShutdownHandler[source]¶
Bases:
objectCooperative 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._exitto 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
SIGUSR1orrequest()starts may take before the forced exit; 0 disables it.Noneresolves it, andsigterm_timeout_secwith it, as training does for an unsettrain.shutdown_timeout_sec(seeresolve_shutdown_timeouts).sigterm_timeout_sec – The same for a
SIGTERM, which the launcher may follow with a kill;Nonetakestimeout_sec, or the resolved value. ASIGTERMthat arrives once a longer timer is running brings the forced exit forward to its own timeout.
- should_shutdown()[source]¶
Check if the training loop should exit.
Call this after each training step.
- Return type:
- 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 aSIGUSR1does, so a rank that stops because another rank was signaled is bounded by its own timer too; its ownSIGTERM, 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.getsignalcannot 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:
CUDA availability check
Small test computation on the device
Memory allocation test
- 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=Truesowork.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 thetimeout_secargument.
- 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_requeue()[source]¶
Check if this is a requeued SLURM job.
Uses
SLURM_RESTART_COUNT(set by SLURM on requeue).- Return type:
- 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:
{checkpoint_dir}/latestsymlinkMost recent
step_Ndirectory whose save completed
A checkpoint counts when
is_complete_checkpointaccepts it, with the samenum_stagesandrequire_train_state, so a reader of a run’s checkpoints that calls that function counts the same steps as saved. An interrupted save leaves astep_Nthat exists but holds no.metadata, and resuming into it fails indcp.loadwith “metadata is None”. A save that stopped after its DCP shards and beforetrain_state.ptandmetadata.jsonleaves optimizer state without the step, LR schedule and data position that go with it, whichCheckpointManager.loadrefuses. Skipping both kinds turns an unrecoverable run into one that resumes from the last complete checkpoint, whatever left the partial directory behind.CheckpointManagerpointslatestonly at a complete save, but the save can lose files afterwards, solatestis checked like astep_N: when it is not complete, a warning names it and why, and the scan below picks the checkpoint to resume. Alatestwhose shards are all there but that losttrain_state.ptormetadata.jsonis 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 withouttrain_state.pt, and the optimizer state of one withoutmetadata.json, the only record of the weight-decay scope that state was saved under. Otherwise, whenstep_Ndirectories 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_Nin the per-stage layout that records no degree counts only whenpp0throughpp{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 bothtrain_state.ptandmetadata.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/slurmexportKEMPNERFORGE_SHUTDOWN_LEAD_SEC, the seconds their ranks have from the shutdownSIGTERMuntil they may be killed: the--signallead of the scripts that launch the ranks withsrun, since at the time limit SLURM’sSIGTERMcan makesrunkill them at once, and the 30 s thattorchrungives its workers by default insinglenode.sh. Left unset, aSIGTERMgets three quarters of that lead, so a rank whose emergency save, flush or teardown hangs exits through the timer, which logsGraceful shutdown timed out, before the launcher kills it; without the variable it gets 600 s. ASIGUSR1, the manual stop, which no kill follows, and a shutdown another rank started get 600 s.0disables 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), asShutdownHandlertakes them.- Raises:
ValueError –
KEMPNERFORGE_SHUTDOWN_LEAD_SECis set to something other than a positive number of seconds.- Parameters:
configured (float | None)
- Return type:
Modules
SLURM job and auto-resume helpers. |
|
GPU and NCCL health checks and NaN detection. |
|
Graceful shutdown via signal handling. |