Skip to content

armgit / Soup

Public Imported from GitHub
0

Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.

fix(train): on Windows, wait for the launcher and exit with its code for --gpus N (#1688)

Alpamys Makazhan1c079d4a57c9
diff --git a/changelog.d/0.75.1/1688.fixed.md b/changelog.d/0.75.1/1688.fixed.md
new file mode 100644
index 00000000..7091ee0b
--- /dev/null
+++ b/changelog.d/0.75.1/1688.fixed.md
@@ -0,0 +1,10 @@
+- `soup train --gpus N` on Windows waits for the `accelerate launch` it hands the run to and
+ exits with the launcher's exit code. The hand-over used `os.execvp` on every platform. On
+ Linux and macOS that replaces the process, so the launcher's status is the command's; on
+ Windows it starts the launcher as a new process and ends the calling one with status 0 at
+ once, so the shell got its prompt back while the run was still going and `soup train
+ --gpus 2 && next-step` ran `next-step` whatever the launcher returned later. Windows now
+ runs the launcher as a child (list argv, no shell), looked up in the `PATH` directories
+ only, and Ctrl+C waits for the launcher's own shutdown. Linux and macOS are unchanged; an
+ end-to-end test with a stand-in `accelerate` now checks the exit code on whichever
+ platform the suite runs on (#1688).
diff --git a/src/soup_cli/commands/train.py b/src/soup_cli/commands/train.py
index 46a1e374..5602d884 100644
--- a/src/soup_cli/commands/train.py
+++ b/src/soup_cli/commands/train.py
@@ -1236,14 +1236,16 @@ def train(
format_advice,
hint_argv_from_reexec,
is_in_distributed,
+ run_launcher,
)
num_processes = num_gpus * nodes
if not is_in_distributed():
# v0.33.0 #37 — auto-reexec under accelerate launch unless
- # --no-reexec was passed. Reexec uses os.execvp so the new
- # accelerate process replaces this process; no leftover PID
- # tree, stdio passes through unchanged.
+ # --no-reexec was passed. On POSIX the accelerate process
+ # replaces this one (os.execvp): no leftover PID tree, stdio
+ # passes through unchanged. Windows cannot do that, so there
+ # this process waits for the launcher (see run_launcher).
# #372 — one argv builder for both the re-exec and the printed
# hint, so they cannot drift. collect_reexec_passthrough is the
# only list of "flags the user typed" that survive a launch.
@@ -1333,15 +1335,19 @@ def train(
f"({num_processes} GPUs, {topo['interconnect']})[/]"
)
console.print(f"[dim]argv: {markup_escape(' '.join(argv))}[/]")
- # execvp replaces this process; the child carries --no-reexec.
+ # The launcher takes over; the child carries --no-reexec. On
+ # POSIX run_launcher execs and never returns. On Windows,
+ # where exec would return 0 at once and leave the launcher
+ # running, it waits and returns the launcher's exit code.
try:
- os.execvp(argv[0], argv)
+ launcher_code = run_launcher(argv)
except OSError as exc:
console.print(
f"[red]accelerate launch failed:[/] {markup_escape(str(exc))}\n"
"Use [bold]--no-reexec[/] to print the launch command."
)
raise typer.Exit(1) from exc
+ raise typer.Exit(launcher_code)
elif not dry_run:
# Already a launched rank — announce + apply NCCL hints. (The
# dry_run branch above intentionally does neither.)
diff --git a/src/soup_cli/utils/launcher.py b/src/soup_cli/utils/launcher.py
index b5e82d91..dc3083ad 100644
--- a/src/soup_cli/utils/launcher.py
+++ b/src/soup_cli/utils/launcher.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import errno
import ipaddress
import os
import re
@@ -14,6 +15,8 @@ MAX_NUM_MACHINES = 256 # sanity cap, consistent with --gpus MAX_GPU_COUNT=128
DEFAULT_MAIN_PROCESS_PORT = 29500
MAX_HOSTNAME_LEN = 253 # RFC 1035: 255 wire octets less the leading length and root bytes
_HOSTNAME_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?")
+# Windows cannot replace a process image; see run_launcher.
+_IS_WINDOWS = os.name == "nt"
def _is_hostname_or_ip(value: object) -> bool:
@@ -287,8 +290,8 @@ def build_train_reexec_argv(
) -> list[str]:
"""Argv soup would pass through ``accelerate launch`` on auto-reexec.
- This is the single source for "what the user typed" (#372). Both
- ``os.execvp`` and the ``--no-reexec`` printed hint derive from this list, so
+ This is the single source for "what the user typed" (#372). Both the
+ hand-over (``run_launcher``) and the ``--no-reexec`` printed hint derive from this list, so
they cannot drift. ``--no-reexec`` is always present because the child is
already under a launcher and must not re-exec again.
"""
@@ -307,6 +310,67 @@ def build_train_reexec_argv(
]
+def run_launcher(argv: Sequence[str]) -> int:
+ """Hand the run over to the launcher ``argv`` and report ITS exit code.
+
+ POSIX: ``os.execvp`` replaces this process with the launcher, so the
+ launcher's exit status is the command's and this function does not return.
+
+ Windows has no exec. ``os.execvp`` there starts the launcher as a NEW
+ process and ends the calling one with status 0 at once: the shell gets its
+ prompt back while the run is still going, and ``soup train --gpus N &&
+ next-step`` runs ``next-step`` straight away, whatever the launcher returns
+ later. So on Windows the launcher runs as a child (list argv, no shell,
+ inherited stdio and environment), this process waits for it, and its exit
+ code is returned for the caller to exit with.
+
+ Raises ``OSError`` when the launcher cannot be started.
+ """
+ args = list(argv)
+ if not args:
+ raise ValueError("launcher argv must not be empty")
+ if _IS_WINDOWS:
+ import subprocess
+
+ resolved = _find_on_path(args[0])
+ if resolved is None:
+ raise FileNotFoundError(errno.ENOENT, "launcher not found on PATH", args[0])
+ process = subprocess.Popen([resolved, *args[1:]])
+ while True:
+ try:
+ return process.wait()
+ except KeyboardInterrupt:
+ # The console delivers Ctrl+C to the launcher as well. Wait for
+ # it to finish its own shutdown and report the code it ends with.
+ continue
+ os.execvp(args[0], args)
+
+
+def _find_on_path(name: str) -> str | None:
+ """Full path of the program ``name`` in a ``PATH`` directory, or ``None``.
+
+ Tries the ``PATHEXT`` suffixes, so ``accelerate`` finds ``accelerate.exe``.
+ ``PATH`` directories only: ``shutil.which`` on Windows also looks in the
+ current directory first, which would run a file named like the launcher
+ out of the project directory. ``os.execvp`` never searched it either.
+ """
+ if os.path.dirname(name):
+ return name if os.path.isfile(name) else None
+ if os.path.splitext(name)[1]:
+ candidates = [name]
+ else:
+ suffixes = os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(";")
+ candidates = [name + suffix for suffix in suffixes if suffix]
+ for directory in os.get_exec_path():
+ if not directory:
+ continue
+ for candidate in candidates:
+ full = os.path.join(directory, candidate)
+ if os.path.isfile(full):
+ return full
+ return None
+
+
def hint_argv_from_reexec(script_args: Sequence[str]) -> list[str]:
"""``soup train ...`` form of a re-exec argv, for the ``--no-reexec`` hint.
diff --git a/tests/test_multi_gpu.py b/tests/test_multi_gpu.py
index 5a3f42fe..9af58625 100644
--- a/tests/test_multi_gpu.py
+++ b/tests/test_multi_gpu.py
@@ -377,13 +377,13 @@ class TestMultiNodeLauncher:
monkeypatch.setattr(train_cmd, "load_dataset", loader)
captured = []
- def fake_execvp(file, argv):
- captured.append((file, list(argv), {
+ def fake_run_launcher(argv):
+ captured.append((argv[0], list(argv), {
key: value for key, value in os.environ.items() if key.startswith("NCCL_")
}))
raise SystemExit(99)
- monkeypatch.setattr(os, "execvp", fake_execvp)
+ monkeypatch.setattr("soup_cli.utils.launcher.run_launcher", fake_run_launcher)
def invoke(args):
return CliRunner().invoke(
diff --git a/tests/test_part_b.py b/tests/test_part_b.py
index eb075bf7..16f9213a 100644
--- a/tests/test_part_b.py
+++ b/tests/test_part_b.py
@@ -195,8 +195,8 @@ class TestAutoReexec:
assert "accelerate" in result.output
def test_reexec_calls_execvp_with_accelerate_argv(self, tmp_path, monkeypatch):
- """With --gpus 2 and no --no-reexec, the train command should call
- os.execvp with an argv starting with 'accelerate'."""
+ """With --gpus 2 and no --no-reexec, the train command should run
+ the launcher with an argv starting with 'accelerate'."""
from typer.testing import CliRunner
from soup_cli.cli import app
@@ -244,13 +244,13 @@ class TestAutoReexec:
captured: dict = {}
- def _fake_execvp(file, argv):
- captured["file"] = file
+ def _fake_run_launcher(argv):
+ captured["file"] = argv[0]
captured["argv"] = list(argv)
# Raise SystemExit so Typer treats it as a clean exit.
raise SystemExit(99)
- monkeypatch.setattr("os.execvp", _fake_execvp)
+ monkeypatch.setattr("soup_cli.utils.launcher.run_launcher", _fake_run_launcher)
runner = CliRunner()
runner.invoke(
@@ -265,7 +265,7 @@ class TestAutoReexec:
# Force assertion — a bypass would have left captured empty and we'd
# silently accept a regression.
assert captured.get("file") == "accelerate", (
- f"os.execvp was not called with 'accelerate'; captured={captured!r}"
+ f"the launcher was not run with 'accelerate'; captured={captured!r}"
)
assert "launch" in captured["argv"]
assert "--num_processes" in captured["argv"]
diff --git a/tests/test_review_fixes_v07133.py b/tests/test_review_fixes_v07133.py
index 535388df..bd83b609 100644
--- a/tests/test_review_fixes_v07133.py
+++ b/tests/test_review_fixes_v07133.py
@@ -263,17 +263,17 @@ class TestDryRunNoReexec:
called = {"execvp": False}
- def _fake_execvp(file, argv):
+ def _fake_run_launcher(argv):
called["execvp"] = True
raise SystemExit(99)
- monkeypatch.setattr("os.execvp", _fake_execvp)
+ monkeypatch.setattr("soup_cli.utils.launcher.run_launcher", _fake_run_launcher)
CliRunner().invoke(
app, ["train", "--config", "soup.yaml", "--gpus", "2", "--dry-run"]
)
assert called["execvp"] is False, (
- "os.execvp was called on a --dry-run multi-GPU invocation"
+ "the launcher was run on a --dry-run multi-GPU invocation"
)
@@ -287,11 +287,11 @@ class TestReexecForwardsFlags:
captured: dict = {}
- def _fake_execvp(file, argv):
+ def _fake_run_launcher(argv):
captured["argv"] = list(argv)
raise SystemExit(99)
- monkeypatch.setattr("os.execvp", _fake_execvp)
+ monkeypatch.setattr("soup_cli.utils.launcher.run_launcher", _fake_run_launcher)
CliRunner().invoke(
app,
diff --git a/tests/test_train_gpus_exit_code.py b/tests/test_train_gpus_exit_code.py
new file mode 100644
index 00000000..6987ba86
--- /dev/null
+++ b/tests/test_train_gpus_exit_code.py
@@ -0,0 +1,363 @@
+"""``soup train --gpus N`` ends with the exit code of the launcher it hands over to.
+
+With ``--gpus N`` (N > 1) the command re-runs itself under ``accelerate
+launch``. It did that with ``os.execvp`` on every platform:
+
+* on POSIX ``execvp`` replaces the process, so the launcher's exit status is
+ the command's. Nothing to change; the end-to-end test below pins it.
+* Windows has no exec. ``os.execvp`` there starts the launcher as a NEW
+ process and ends the calling one with status 0 at once. The shell got its
+ prompt back while the run was still going, and ``soup train --gpus 2 &&
+ next-step`` ran ``next-step`` straight away, whatever the launcher returned
+ later.
+
+``soup_cli.utils.launcher.run_launcher`` now owns the hand-over: exec on POSIX,
+run-and-wait on Windows, and the command exits with the code it reports.
+
+The end-to-end test puts a fake ``accelerate`` that exits 7 on ``PATH`` and
+runs the real command line in a subprocess, on whatever platform the suite
+runs on. The unit tests drive both branches on every platform through the
+module's ``_IS_WINDOWS`` switch.
+"""
+
+from __future__ import annotations
+
+import os
+import stat
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+import soup_cli
+from soup_cli.cli import app
+from soup_cli.utils import launcher, topology
+from tests.conftest import strip_ansi
+
+_DISTRIBUTED_ENV = (
+ "RANK",
+ "WORLD_SIZE",
+ "LOCAL_RANK",
+ "ACCELERATE_MIXED_PRECISION",
+ "ACCELERATE_USE_DEEPSPEED",
+ "ACCELERATE_USE_FSDP",
+)
+
+_CONFIG = (
+ "base: test/model\n"
+ "task: sft\n"
+ "data: {train: data.jsonl, format: alpaca}\n"
+ "training: {epochs: 1, lr: 1e-4, batch_size: 1}\n"
+)
+
+
+def _plain(text: str) -> str:
+ """ANSI-stripped, whitespace-collapsed CLI output, safe to substring-match."""
+ return " ".join(strip_ansi(text).split())
+
+
+def _exit_with(code: int) -> list[str]:
+ return [sys.executable, "-c", f"import sys; sys.exit({code})"]
+
+
+# ---------------------------------------------------------------------------
+# run_launcher: the run-and-wait branch (what Windows uses)
+# ---------------------------------------------------------------------------
+
+
+class TestRunAndWait:
+ @pytest.fixture(autouse=True)
+ def _wait_branch(self, monkeypatch):
+ monkeypatch.setattr(launcher, "_IS_WINDOWS", True)
+
+ @pytest.mark.parametrize("code", [0, 1, 2, 7, 113])
+ def test_the_launcher_exit_code_is_returned(self, code):
+ assert launcher.run_launcher(_exit_with(code)) == code
+
+ def test_it_waits_for_the_launcher_to_finish(self, tmp_path):
+ marker = tmp_path / "finished.txt"
+ script = (
+ "import sys, time\n"
+ "time.sleep(0.6)\n"
+ f"open({str(marker)!r}, 'w').write('done')\n"
+ "sys.exit(7)\n"
+ )
+
+ code = launcher.run_launcher([sys.executable, "-c", script])
+
+ # Returned only after the child wrote its marker, and with its code.
+ assert marker.read_text() == "done"
+ assert code == 7
+
+ def test_the_launcher_inherits_the_environment(self, tmp_path, monkeypatch):
+ # The multi-node path exports NCCL_* with os.environ.setdefault just
+ # before the hand-over; the launcher must see them.
+ monkeypatch.setenv("NCCL_SOUP_TEST", "from-parent")
+ seen = "os.environ.get('NCCL_SOUP_TEST') == 'from-parent'"
+ script = f"import os, sys; sys.exit(5 if {seen} else 6)"
+
+ assert launcher.run_launcher([sys.executable, "-c", script]) == 5
+
+ def test_a_launcher_that_is_not_on_path_raises_oserror_naming_it(self):
+ with pytest.raises(OSError, match="no-such-launcher-soup-test"):
+ launcher.run_launcher(["no-such-launcher-soup-test", "launch"])
+
+ def test_no_shell_is_involved(self, tmp_path, monkeypatch):
+ # An argument that a shell would split or expand arrives as one argument.
+ monkeypatch.chdir(tmp_path)
+ out = tmp_path / "argv.txt"
+ script = f"import sys; open({str(out)!r}, 'w').write('|'.join(sys.argv[1:]))"
+ tricky = "a b & echo x > y"
+
+ assert launcher.run_launcher([sys.executable, "-c", script, tricky, "$HOME"]) == 0
+ assert out.read_text() == f"{tricky}|$HOME"
+ assert not (tmp_path / "y").exists()
+
+ def test_ctrl_c_keeps_waiting_for_the_launcher(self, monkeypatch):
+ # The console delivers Ctrl+C to the launcher too; the parent must not
+ # return before it, or the shell is told a code the run did not produce.
+ waits: list[str] = []
+
+ class _Process:
+ def __init__(self, argv):
+ self.argv = argv
+
+ def wait(self):
+ waits.append("wait")
+ if len(waits) < 3:
+ raise KeyboardInterrupt
+ return 130
+
+ def kill(self): # pragma: no cover - must not be called
+ raise AssertionError("the launcher was killed instead of awaited")
+
+ monkeypatch.setattr(subprocess, "Popen", _Process)
+
+ assert launcher.run_launcher(_exit_with(0)) == 130
+ assert waits == ["wait", "wait", "wait"]
+
+ def test_an_empty_argv_is_refused(self):
+ with pytest.raises(ValueError, match="launcher argv must not be empty"):
+ launcher.run_launcher([])
+
+
+class TestTheLauncherIsLookedUpOnPathOnly:
+ """``PATH`` directories and ``PATHEXT`` suffixes; never the current directory."""
+
+ @pytest.fixture
+ def dirs(self, tmp_path, monkeypatch):
+ first, second, cwd = tmp_path / "first", tmp_path / "second", tmp_path / "project"
+ for directory in (first, second, cwd):
+ directory.mkdir()
+ monkeypatch.setenv("PATH", os.pathsep.join([str(first), str(second)]))
+ monkeypatch.setenv("PATHEXT", ".exe;.cmd")
+ # Windows' own switch for "do not search the current directory". Some
+ # shells export it; without it a lookup that honours the Windows
+ # default would find the file in the project directory.
+ monkeypatch.delenv("NoDefaultCurrentDirectoryInExePath", raising=False)
+ monkeypatch.chdir(cwd)
+ return first, second, cwd
+
+ @pytest.mark.parametrize("suffix", [".exe", ".cmd"])
+ def test_a_pathext_suffix_is_tried_in_each_path_directory(self, dirs, suffix):
+ _first, second, _cwd = dirs
+ (second / f"soup-fake-launcher{suffix}").write_text("", encoding="utf-8")
+
+ found = launcher._find_on_path("soup-fake-launcher")
+
+ assert found is not None
+ assert os.path.samefile(found, second / f"soup-fake-launcher{suffix}")
+
+ def test_the_first_path_directory_wins(self, dirs):
+ first, second, _cwd = dirs
+ (first / "soup-fake-launcher.cmd").write_text("", encoding="utf-8")
+ (second / "soup-fake-launcher.exe").write_text("", encoding="utf-8")
+
+ found = launcher._find_on_path("soup-fake-launcher")
+
+ assert found is not None
+ assert os.path.samefile(found, first / "soup-fake-launcher.cmd")
+
+ def test_a_file_in_the_current_directory_is_not_the_launcher(self, dirs, monkeypatch):
+ _first, _second, cwd = dirs
+ (cwd / "soup-fake-launcher.exe").write_text("", encoding="utf-8")
+ (cwd / "soup-fake-launcher.cmd").write_text("", encoding="utf-8")
+
+ assert launcher._find_on_path("soup-fake-launcher") is None
+ monkeypatch.setattr(launcher, "_IS_WINDOWS", True)
+ with pytest.raises(OSError, match="launcher not found on PATH"):
+ launcher.run_launcher(["soup-fake-launcher", "launch"])
+
+ def test_an_empty_path_entry_does_not_mean_the_current_directory(self, dirs, monkeypatch):
+ first, second, cwd = dirs
+ monkeypatch.setenv("PATH", os.pathsep.join([str(first), "", str(second)]))
+ (cwd / "soup-fake-launcher.exe").write_text("", encoding="utf-8")
+
+ assert launcher._find_on_path("soup-fake-launcher") is None
+
+ def test_a_name_that_already_has_a_suffix_is_used_as_it_is(self, dirs):
+ first, _second, _cwd = dirs
+ (first / "soup-fake-launcher.cmd").write_text("", encoding="utf-8")
+
+ found = launcher._find_on_path("soup-fake-launcher.cmd")
+
+ assert found is not None
+ assert os.path.samefile(found, first / "soup-fake-launcher.cmd")
+ assert launcher._find_on_path("soup-fake-launcher.bat") is None
+
+ def test_an_explicit_path_is_not_searched_for(self, dirs):
+ assert launcher._find_on_path(sys.executable) == sys.executable
+ assert launcher._find_on_path(os.path.join("missing-dir", "tool.exe")) is None
+
+
+# ---------------------------------------------------------------------------
+# run_launcher: the exec branch (POSIX)
+# ---------------------------------------------------------------------------
+
+
+class TestExec:
+ def test_posix_replaces_the_process_with_the_launcher(self, monkeypatch):
+ monkeypatch.setattr(launcher, "_IS_WINDOWS", False)
+ calls: list[tuple] = []
+
+ def _execvp(file, argv):
+ calls.append((file, list(argv)))
+ raise SystemExit(99) # a real execvp never returns
+
+ monkeypatch.setattr(os, "execvp", _execvp)
+ monkeypatch.setattr(
+ subprocess, "Popen", lambda *a, **k: pytest.fail("POSIX must exec, not spawn")
+ )
+
+ with pytest.raises(SystemExit):
+ launcher.run_launcher(["accelerate", "launch", "--num_processes", "2"])
+
+ assert calls == [("accelerate", ["accelerate", "launch", "--num_processes", "2"])]
+
+ def test_the_switch_follows_the_platform(self):
+ assert launcher._IS_WINDOWS is (os.name == "nt")
+
+
+# ---------------------------------------------------------------------------
+# soup train --gpus N: the command exits with what run_launcher reports
+# ---------------------------------------------------------------------------
+
+
+def two_gpu_run(tmp_path, monkeypatch):
+ for var in _DISTRIBUTED_ENV:
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("COLUMNS", "200")
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "soup.yaml").write_text(_CONFIG, encoding="utf-8")
+ monkeypatch.setattr(launcher, "is_in_distributed", lambda: False)
+ # Keep the in-process runs off the real GPU probe; the end-to-end test uses it.
+ monkeypatch.setattr(
+ topology, "detect_topology", lambda: {"gpu_count": 2, "interconnect": "pcie"}
+ )
+
+ def invoke(*extra: str):
+ return CliRunner().invoke(
+ app, ["train", "--config", "soup.yaml", "--gpus", "2", "--yes", *extra]
+ )
+
+ return invoke
+
+
+class TestTrainExitsWithTheLauncherCode:
+ @pytest.mark.parametrize("code", [0, 1, 7, 113])
+ def test_exit_code_is_the_launcher_code(self, two_gpu_run, monkeypatch, code):
+ seen: list[list[str]] = []
+
+ def _run(argv):
+ seen.append(list(argv))
+ return code
+
+ monkeypatch.setattr(launcher, "run_launcher", _run)
+
+ result = two_gpu_run()
+
+ assert result.exit_code == code, (result.output, repr(result.exception))
+ assert len(seen) == 1
+ assert seen[0][:4] == ["accelerate", "launch", "--num_processes", "2"]
+ assert "--no-reexec" in seen[0]
+
+ def test_a_launcher_that_cannot_start_exits_1_with_the_hint(self, two_gpu_run, monkeypatch):
+ def _run(argv):
+ raise FileNotFoundError(2, "launcher not found on PATH", argv[0])
+
+ monkeypatch.setattr(launcher, "run_launcher", _run)
+
+ result = two_gpu_run()
+
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ out = _plain(result.output)
+ assert "accelerate launch failed:" in out
+ assert "launcher not found on PATH" in out
+ assert "Use --no-reexec to print the launch command." in out
+
+ def test_no_reexec_prints_the_command_and_does_not_launch(self, two_gpu_run, monkeypatch):
+ monkeypatch.setattr(
+ launcher, "run_launcher", lambda argv: pytest.fail("must not launch")
+ )
+
+ result = two_gpu_run("--no-reexec")
+
+ assert result.exit_code == 1, (result.output, repr(result.exception))
+ assert "Multi-GPU launch required" in _plain(result.output)
+
+
+# ---------------------------------------------------------------------------
+# End to end: a fake `accelerate` on PATH that exits 7
+# ---------------------------------------------------------------------------
+
+
+def _fake_accelerate(bin_dir: Path, marker: Path, code: int) -> None:
+ """A launcher named ``accelerate`` that records its arguments and exits ``code``."""
+ bin_dir.mkdir()
+ if os.name == "nt":
+ script = bin_dir / "accelerate.cmd"
+ script.write_text(
+ f'@echo %*> "{marker}"\r\n@exit {code}\r\n', encoding="utf-8", newline=""
+ )
+ else:
+ script = bin_dir / "accelerate"
+ script.write_text(
+ f'#!/bin/sh\nprintf \'%s \' "$@" > "{marker}"\nexit {code}\n',
+ encoding="utf-8",
+ newline="",
+ )
+ script.chmod(script.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
+
+
[email protected]("code", [7, 0])
+def test_soup_train_gpus_returns_the_exit_code_of_accelerate(tmp_path, code):
+ """The real command line, in a real process, on this platform's hand-over path."""
+ marker = tmp_path / "launched.txt"
+ _fake_accelerate(tmp_path / "bin", marker, code)
+ (tmp_path / "soup.yaml").write_text(_CONFIG, encoding="utf-8")
+
+ env = {key: value for key, value in os.environ.items() if key not in _DISTRIBUTED_ENV}
+ env["PATH"] = str(tmp_path / "bin") + os.pathsep + env.get("PATH", "")
+ # The child must import the tree under test, not another installed copy.
+ env["PYTHONPATH"] = str(Path(soup_cli.__file__).resolve().parents[1])
+ env["CUDA_VISIBLE_DEVICES"] = "-1"
+ env["HF_HUB_OFFLINE"] = "1"
+ env["NO_COLOR"] = "1"
+
+ proc = subprocess.run(
+ [sys.executable, "-m", "soup_cli.cli", "train", "--config", "soup.yaml",
+ "--gpus", "2", "--yes"],
+ cwd=tmp_path, env=env, capture_output=True, text=True, timeout=300, check=False,
+ encoding="utf-8", errors="replace",
+ )
+
+ # The launcher ran, with the launch argv, before the command returned ...
+ assert marker.is_file(), (proc.returncode, proc.stdout[-2000:], proc.stderr[-2000:])
+ launched = marker.read_text(encoding="utf-8", errors="replace")
+ assert "launch --num_processes 2" in launched
+ assert "--no-reexec" in launched
+ # ... and its exit code is the command's.
+ assert proc.returncode == code, (proc.stdout[-2000:], proc.stderr[-2000:])