Source code for kempnerforge.resilience.signal_handler

"""Graceful shutdown via signal handling.

Handles SIGTERM (SLURM preemption / graceful shutdown) and SIGUSR1
(SLURM requeue) by setting a flag that the training loop checks after
each step. On signal, the loop saves an emergency checkpoint and exits.

Timeout protection ensures the process exits even if graceful shutdown
stalls (e.g., stuck in NCCL collective).
"""

from __future__ import annotations

import logging
import math
import os
import signal
import threading
import time
from collections import deque
from types import FrameType

logger = logging.getLogger(__name__)

_SHUTDOWN_SIGNALS = (signal.SIGTERM, signal.SIGUSR1)

SHUTDOWN_LEAD_ENV = "KEMPNERFORGE_SHUTDOWN_LEAD_SEC"
"""Seconds a launch script gives its ranks from the shutdown SIGTERM until they may be killed."""

SHUTDOWN_LEAD_FRACTION = 0.75
"""Share of that lead the forced-exit timer of a SIGTERM defaults to, so it fires first."""

DEFAULT_SHUTDOWN_TIMEOUT_SEC = 600.0
"""The forced-exit timeout when neither the config nor the launch script sets one."""

_EVERY_RANK = {"every_rank": True}


[docs] def resolve_shutdown_timeouts(configured: float | None) -> tuple[float, float]: """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. """ raw = os.environ.get(SHUTDOWN_LEAD_ENV, "").strip() lead: float | None = None if raw: try: lead = float(raw) except ValueError: lead = math.nan if not 0 < lead < math.inf: raise ValueError( f"{SHUTDOWN_LEAD_ENV} must be a positive number of seconds, got {raw!r}" ) if configured is None: sigterm = DEFAULT_SHUTDOWN_TIMEOUT_SEC if lead is None else SHUTDOWN_LEAD_FRACTION * lead return DEFAULT_SHUTDOWN_TIMEOUT_SEC, sigterm if lead is not None and configured >= lead: logger.warning( f"train.shutdown_timeout_sec={configured:g} is not below the {lead:g} s that " f"{SHUTDOWN_LEAD_ENV} gives the ranks from the shutdown SIGTERM until they may be " f"killed, so a rank whose emergency save hangs can be killed before its forced exit " f"fires and logs why; leave it unset for {SHUTDOWN_LEAD_FRACTION:g} of the lead" ) return configured, configured
[docs] def ignore_shutdown_signals_in_worker(worker_id: int) -> None: """``worker_init_fn`` that makes a DataLoader worker ignore shutdown signals. SLURM preemption and ``torchrun`` teardown signal the whole process group, not a single PID, so SIGTERM reaches every DataLoader worker as well as the rank's main process. Workers install no handler, take the default action and die at once. The main process — which handles the signal cooperatively, by setting a flag and finishing its step — then fails fetching its next micro-batch, and that failure escapes before the loop reaches its ``should_shutdown()`` check, so no emergency checkpoint is written. Ignoring the shutdown signals in the worker keeps it serving long enough for the step to finish, which puts the emergency save back on the loop's normal path rather than on an exception path. The cost: ``multiprocessing.Process.terminate()`` is itself SIGTERM, so a shielded worker cannot be reaped that way, and ``multiprocessing``'s exit hook, which terminates leftover workers and then joins them, would block on one forever. Workers are therefore shut down through the loader's sentinel path: ``StatefulDataLoader.close`` and ``StreamingDataLoader.close``, which the training loop calls on every exit path and a process calls at exit for every loader whose workers are still alive. Nothing closes a plain ``DataLoader`` at exit: its caller has to call ``shutdown_workers`` itself. Args: worker_id: Worker index, supplied by ``DataLoader``. Unused. """ for sig in _SHUTDOWN_SIGNALS: signal.signal(sig, signal.SIG_IGN)
[docs] class ShutdownHandler: """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() Args: 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. """
[docs] def __init__( self, timeout_sec: float | None = None, sigterm_timeout_sec: float | None = None ) -> None: if timeout_sec is None: timeout_sec, resolved_sigterm = resolve_shutdown_timeouts(None) if sigterm_timeout_sec is None: sigterm_timeout_sec = resolved_sigterm self._shutdown_requested = False self._signal_received: signal.Signals | None = None self._timeout_sec = timeout_sec self._sigterm_timeout_sec = ( timeout_sec if sigterm_timeout_sec is None else sigterm_timeout_sec ) self._timer: threading.Timer | None = None self._deadline = math.inf self._armed_sec = 0.0 self._changes: deque[tuple[float, float] | None] = deque() self._changing = threading.Lock() self._original_handlers: dict[signal.Signals, signal._HANDLER] = {}
@property def shutdown_requested(self) -> bool: """Whether a shutdown was requested, by a signal or by ``request()``.""" return self._shutdown_requested @property def signal_received(self) -> signal.Signals | None: """The signal that triggered shutdown, or None.""" return self._signal_received
[docs] def should_shutdown(self) -> bool: """Check if the training loop should exit. Call this after each training step. """ return self._shutdown_requested
[docs] def request(self) -> None: """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. """ self._shutdown_requested = True self._start_timer(self._timeout_sec)
[docs] def register(self) -> None: """Register signal handlers for SIGTERM and SIGUSR1. Must be called from the main thread. """ for sig in _SHUTDOWN_SIGNALS: self._original_handlers[sig] = signal.getsignal(sig) signal.signal(sig, self._handle_signal) logger.info("Shutdown handler registered (SIGTERM, SIGUSR1)")
[docs] def reinstall(self) -> None: """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. """ if threading.current_thread() is not threading.main_thread(): return for sig in self._original_handlers: signal.signal(sig, self._handle_signal)
[docs] def unregister(self) -> None: """Restore the original signal handlers; the forced-exit timer stays armed.""" for sig, handler in self._original_handlers.items(): signal.signal(sig, handler) self._original_handlers.clear()
[docs] def cancel_watchdog(self) -> None: """Cancel the forced-exit timer, leaving the signal handlers installed.""" self._cancel_timer()
[docs] def finish(self) -> None: """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. """ self.unregister() self.cancel_watchdog() if self._shutdown_requested: logger.info("Graceful shutdown complete")
def _handle_signal(self, signum: int, frame: FrameType | None) -> None: """Signal handler: sets the shutdown flag and starts the signal's timeout. Its log lines, like the timer's, go out on every rank, since the rank whose timer fires first may be the one whose exit ends the job. """ sig = signal.Signals(signum) self._shutdown_requested = True self._signal_received = sig logger.warning(f"Received {sig.name}; requesting graceful shutdown", extra=_EVERY_RANK) sigterm = sig == signal.SIGTERM self._start_timer(self._sigterm_timeout_sec if sigterm else self._timeout_sec) def _start_timer(self, timeout_sec: float) -> None: """Arm the forced exit ``timeout_sec`` from now, unless that is no earlier than one armed. A timeout of 0 arms nothing. A running timer due later is replaced, so the earliest deadline a shutdown has been given is the one that holds. """ if timeout_sec > 0: self._change((time.monotonic() + timeout_sec, timeout_sec)) def _change(self, change: tuple[float, float] | None) -> None: """Queue a change to the forced-exit timer, and apply the queue unless a call already is. ``change`` is ``(deadline, timeout_sec)`` to arm, or ``None`` to cancel. A signal handler runs on the main thread between two bytecodes of whatever it interrupts, which can be a call applying the queue, and a call from another thread can overlap one too. Such a call only queues its change, which the call applying the queue applies before it returns, in order. So no call builds, starts, cancels or replaces a timer that another is still setting up, and the lock is only ever tried, never waited on, so a handler cannot deadlock on it. A ``KeyboardInterrupt`` or ``SystemExit`` that another signal handler raises right after ``acquire()`` returns can leave the lock held, after which every change only queues, and one raised in ``_arm`` after the new timer starts can leave that timer running untracked. """ self._changes.append(change) while self._changes and self._changing.acquire(blocking=False): try: while self._changes: queued = self._changes.popleft() if queued is None: self._drop_timer() else: self._arm(*queued) finally: self._changing.release() def _arm(self, deadline: float, timeout_sec: float) -> None: """Replace the timer with one due at ``deadline``, unless the one armed is due no later.""" if deadline >= self._deadline: return timer = threading.Timer(max(0.0, deadline - time.monotonic()), self._force_exit) timer.daemon = True timer.start() if self._timer is not None: self._timer.cancel() self._timer, self._deadline, self._armed_sec = timer, deadline, timeout_sec logger.info(f"Forced exit in {timeout_sec:g}s if shutdown not complete", extra=_EVERY_RANK) def _drop_timer(self) -> None: """Cancel the timer, if one is armed.""" if self._timer is not None: self._timer.cancel() self._timer = None self._deadline = math.inf def _force_exit(self) -> None: """Force-exit the process if graceful shutdown takes too long.""" logger.error( f"Graceful shutdown timed out after {self._armed_sec:g}s; forcing exit", extra=_EVERY_RANK, ) os._exit(1) def _cancel_timer(self) -> None: """Cancel the forced-exit timer if active.""" self._change(None)