huggingface/accelerate · #4573

Exit cleanly when using launcher

SunMarc · merged Nov 16, 20263 files · 151 + / 52 −
docs/source/package_reference/cli.md1 + / 1 −
@@ -128,7 +128,7 @@ accelerate launch [arguments] {training_script} --{training_script-argument-1} - * `-m`, `--module` (`bool`) -- Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'. * `--no_python` (`bool`) -- Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script. * `--debug` (`bool`) -- Whether to print out the torch.distributed stack trace when something fails.-* `-q`, `--quiet` (`bool`) -- Silence subprocess errors from the launch stack trace to only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations).+* `-q`, `--quiet` (`bool`) -- Show training errors without the launcher traceback, even with `--debug`. Applies to single-process, multi-GPU, and DeepSpeed launches.   The rest of these arguments are configured through `accelerate config` and are read in from the specified `--config_file` (or default configuration) for their 
src/accelerate/commands/launch.py100 + / 51 −
@@ -18,11 +18,16 @@ import importlib import logging import os+import signal import subprocess import sys+import threading from collections import deque+from contextlib import suppress from pathlib import Path +import psutil+ from accelerate.commands.config import default_config_file, load_config_from_file from accelerate.commands.config.config_args import SageMakerConfig from accelerate.commands.config.config_utils import DYNAMO_BACKENDS@@ -162,7 +167,7 @@ def launch_command_parser(subparsers=None):         "--quiet",         "-q",         action="store_true",-        help="Silence subprocess errors from the launch stack trace and only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations)",+        help="Show training errors without the launcher traceback, even with --debug. Applies to single-process, multi-GPU, and DeepSpeed launches.",     )     # Hardware selection arguments     hardware_args = parser.add_argument_group(@@ -981,19 +986,65 @@ def launch_command_parser(subparsers=None):     return parser  -def simple_launcher(args):-    cmd, current_env = prepare_simple_launcher_cmd_env(args)+def _terminate_process_tree(process):+    processes = [process]+    # Capture descendants before stopping their parent, including workers in separate sessions.+    with suppress(psutil.NoSuchProcess):+        processes.extend(process.children(recursive=True))+    alive = processes+    try:+        for child in processes:+            with suppress(psutil.NoSuchProcess):+                child.terminate()+        _, alive = psutil.wait_procs(processes, timeout=5)+    except (KeyboardInterrupt, SystemExit):+        pass+    finally:+        for child in alive:+            with suppress(psutil.NoSuchProcess):+                child.kill()+        psutil.wait_procs(alive, timeout=5)+        process.wait()+ +def _run_subprocess(cmd, current_env, quiet):     # Tee the child's stderr: write it through as it arrives so output stays live, and keep the tail for the error.-    process = subprocess.Popen(cmd, env=current_env, stderr=subprocess.PIPE)+    process = psutil.Popen(cmd, env=current_env, stderr=subprocess.PIPE)     tail = deque(maxlen=CHILD_STDERR_TAIL_CHUNKS)-    while chunk := process.stderr.read1(CHILD_STDERR_CHUNK_SIZE):-        sys.stderr.buffer.write(chunk)-        sys.stderr.flush()-        tail.append(chunk)-    process.wait()++    def copy_stderr():+        while chunk := process.stderr.read1(CHILD_STDERR_CHUNK_SIZE):+            sys.stderr.buffer.write(chunk)+            sys.stderr.flush()+            tail.append(chunk)++    def handle_sigterm(signum, frame):+        sys.exit(128 + signum)++    reader = None+    previous_sigterm = None+    try:+        if threading.current_thread() is threading.main_thread():+            previous_sigterm = signal.signal(signal.SIGTERM, handle_sigterm)+        copy_stderr()+        process.wait()+    except (KeyboardInterrupt, SystemExit) as error:+        # Keep draining during shutdown so the child's cleanup cannot block on a full pipe.+        reader = threading.Thread(target=copy_stderr, daemon=True)+        reader.start()+        _terminate_process_tree(process)+        reader.join(timeout=5)+        if isinstance(error, KeyboardInterrupt):+            sys.exit(130)+        raise+    finally:+        if previous_sigterm is not None:+            signal.signal(signal.SIGTERM, previous_sigterm)+        # A descendant can still hold the pipe open; do not block closing a pipe another thread is reading.+        if reader is None or not reader.is_alive():+            process.stderr.close()     if process.returncode != 0:-        if not args.quiet:+        if not quiet:             stderr = b"".join(tail).decode(errors="replace")             raise subprocess.CalledProcessError(                 returncode=process.returncode, cmd=cmd, stderr=stderr@@ -1002,9 +1053,44 @@ def simple_launcher(args):             sys.exit(1)  -def multi_gpu_launcher(args):+def simple_launcher(args):+    cmd, current_env = prepare_simple_launcher_cmd_env(args)+    _run_subprocess(cmd, current_env, args.quiet)+++def _run_torchrun(args):     import torch.distributed.run as distrib_run+    from torch.distributed.elastic.multiprocessing.api import SignalException+    from torch.distributed.elastic.multiprocessing.errors import ChildFailedError++    debug = getattr(args, "debug", False)+    quiet = getattr(args, "quiet", False)+    args = _filter_args(+        args,+        distrib_run.get_args_parser(),+        ["--training_script", args.training_script, "--training_script_args", args.training_script_args],+    )+    try:+        distrib_run.run(args)+    except KeyboardInterrupt:+        sys.exit(130)+    except SignalException as error:+        # The elastic agent has already shut down its workers before re-raising the signal.+        sys.exit(128 + error.sigval)+    except Exception as error:+        if isinstance(error, ChildFailedError) and quiet:+            print(error, file=sys.stderr)+            sys.exit(1)+        if is_rich_available() and debug and not quiet:+            console = get_console()+            console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")+            console.print_exception(suppress=[__file__], show_locals=False)+            sys.exit(1)+        else:+            raise+ +def multi_gpu_launcher(args):     current_env = prepare_multi_gpu_env(args)     if not check_cuda_p2p_ib_support():         message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled."@@ -1018,28 +1104,11 @@ def multi_gpu_launcher(args):         if warn:             logger.warning(message) -    debug = getattr(args, "debug", False)-    args = _filter_args(-        args,-        distrib_run.get_args_parser(),-        ["--training_script", args.training_script, "--training_script_args", args.training_script_args],-    )-     with patch_environment(**current_env):-        try:-            distrib_run.run(args)-        except Exception:-            if is_rich_available() and debug:-                console = get_console()-                console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")-                console.print_exception(suppress=[__file__], show_locals=False)-            else:-                raise+        _run_torchrun(args)   def deepspeed_launcher(args):-    import torch.distributed.run as distrib_run-     if not is_deepspeed_available():         raise ImportError("DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.")     else:@@ -1064,30 +1133,10 @@ def deepspeed_launcher(args):             if len(valid_env_items) > 1:                 f.writelines(valid_env_items) -        process = subprocess.Popen(cmd, env=current_env)-        process.wait()-        if process.returncode != 0:-            if not args.quiet:-                raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd)-            else:-                sys.exit(1)+        _run_subprocess(cmd, current_env, args.quiet)     else:-        debug = getattr(args, "debug", False)-        args = _filter_args(-            args,-            distrib_run.get_args_parser(),-            ["--training_script", args.training_script, "--training_script_args", args.training_script_args],-        )         with patch_environment(**current_env):-            try:-                distrib_run.run(args)-            except Exception:-                if is_rich_available() and debug:-                    console = get_console()-                    console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]")-                    console.print_exception(suppress=[__file__], show_locals=False)-                else:-                    raise+            _run_torchrun(args)   def tpu_launcher(args):
tests/test_launch.py50 + / 0 −
@@ -14,15 +14,19 @@  import argparse import os+import signal import subprocess import unittest+from unittest.mock import Mock  import pytest+from torch.distributed.elastic.multiprocessing.api import SignalException  from accelerate.commands.launch import (     CHILD_STDERR_CHUNK_SIZE,     CHILD_STDERR_TAIL_CHUNKS,     launch_command_parser,+    multi_gpu_launcher,     simple_launcher, ) from accelerate.launchers import notebook_launcher@@ -105,6 +109,30 @@ def _simple_launcher_args(script, quiet=False):   class TestSimpleLauncher:+    @pytest.mark.parametrize("sig", [signal.SIGINT, signal.SIGTERM])+    def test_interrupt_stops_children(self, monkeypatch, sig):+        process, worker = Mock(), Mock()+        process.stderr.read1.return_value = b""+        process.children.return_value = [worker]+        previous_sigterm = signal.getsignal(signal.SIGTERM)++        def interrupted_wait():+            process.wait.side_effect = None+            if sig == signal.SIGTERM:+                signal.getsignal(sig)(sig, None)+            raise KeyboardInterrupt++        process.wait.side_effect = interrupted_wait+        monkeypatch.setattr("accelerate.commands.launch.psutil.Popen", lambda *args, **kwargs: process)+        monkeypatch.setattr("accelerate.commands.launch.psutil.wait_procs", lambda processes, timeout: (processes, []))+        with pytest.raises(SystemExit) as exc_info:+            simple_launcher(_simple_launcher_args("train.py"))+        assert exc_info.value.code == 128 + sig+        process.terminate.assert_called_once()+        worker.terminate.assert_called_once()+        assert process.wait.call_count == 2+        assert signal.getsignal(signal.SIGTERM) == previous_sigterm+     def test_child_stderr_is_written_through_and_attached(self, tmp_path, capfd):         script = tmp_path / "child.py"         # Floods stderr before failing: the case that deadlocks a wait()-then-read launcher and buffers@@ -128,6 +156,28 @@ def test_child_stderr_is_written_through_and_attached(self, tmp_path, capfd):         assert "the real cause" in str(exc_info.value.__cause__)  +class TestMultiGpuLauncher:+    @pytest.mark.parametrize(+        "error, exit_code",+        [+            (KeyboardInterrupt(), 130),+            (SignalException("interrupted", signal.SIGINT), 130),+            (SignalException("terminated", signal.SIGTERM), 143),+        ],+    )+    def test_interrupt_exits_cleanly(self, monkeypatch, error, exit_code):+        def interrupted_run(args):+            raise error++        monkeypatch.setattr("accelerate.commands.launch.prepare_multi_gpu_env", lambda args: {})+        monkeypatch.setattr("accelerate.commands.launch.check_cuda_p2p_ib_support", lambda: True)+        monkeypatch.setattr("torch.distributed.run.run", interrupted_run)+        args = argparse.Namespace(training_script="train.py", training_script_args=[], debug=True)+        with pytest.raises(SystemExit) as exc_info:+            multi_gpu_launcher(args)+        assert exc_info.value.code == exit_code++ def test_notebook_launcher_sets_accelerate_mixed_precision(monkeypatch):     # notebook_launcher used to set a bare MIXED_PRECISION key, which nothing     # in accelerate reads; the workers read ACCELERATE_MIXED_PRECISION.