File size: 5,033 Bytes
8652b04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/usr/bin/env python3
"""Run identical Lustify SDXL jobs concurrently on multiple GPUs."""

from __future__ import annotations

import argparse
import os
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parent
DEFAULT_SCRIPT = ROOT / "generate_lustify.py"
DEFAULT_PYTHON = Path(sys.executable)


def parse_args() -> tuple[argparse.Namespace, list[str]]:
    parser = argparse.ArgumentParser(
        description=(
            "Launch one identical Lustify generation job per GPU. "
            "Seeds are base_seed, base_seed-1, ..."
        )
    )
    parser.add_argument("--gpus", required=True, help="Comma-separated physical GPU IDs, e.g. 4,5,6,7")
    parser.add_argument("--seed", required=True, type=int, help="Seed for the first GPU")
    parser.add_argument("--output", default="outputs/lustify.png", help="Base output path")
    parser.add_argument("--log-dir", type=Path, default=ROOT / "logs")
    parser.add_argument("--script", type=Path, default=DEFAULT_SCRIPT, help=argparse.SUPPRESS)
    parser.add_argument("--python", type=Path, default=DEFAULT_PYTHON, help=argparse.SUPPRESS)
    parser.add_argument("--dry-run", action="store_true", help="Show GPU/seed/output mapping without launching")
    args, child_args = parser.parse_known_args()
    return args, child_args


def parse_gpus(value: str) -> list[int]:
    try:
        gpus = [int(item.strip()) for item in value.split(",") if item.strip()]
    except ValueError as error:
        raise SystemExit("--gpus must be a comma-separated list of integer GPU IDs") from error
    if not gpus:
        raise SystemExit("--gpus must contain at least one GPU ID")
    if len(set(gpus)) != len(gpus):
        raise SystemExit("--gpus must not contain duplicate GPU IDs")
    if any(gpu < 0 for gpu in gpus):
        raise SystemExit("GPU IDs must be non-negative")
    return gpus


def output_for(base: Path, seed: int) -> Path:
    suffix = base.suffix or ".png"
    return base.with_name(f"{base.stem}_seed{seed}{suffix}")


def terminate_all(processes: list[subprocess.Popen]) -> None:
    for process in processes:
        if process.poll() is None:
            process.terminate()
    for process in processes:
        if process.poll() is None:
            try:
                process.wait(timeout=10)
            except subprocess.TimeoutExpired:
                process.kill()


def main() -> None:
    args, child_args = parse_args()
    gpus = parse_gpus(args.gpus)
    if not args.script.is_file():
        raise SystemExit(f"Generation script does not exist: {args.script}")
    if not args.python.is_file():
        raise SystemExit(f"Python interpreter does not exist: {args.python}")
    if "--device" in child_args:
        raise SystemExit("Do not pass --device; each physical GPU is mapped to cuda:0 automatically")

    base_output = Path(args.output)
    jobs = []
    for index, gpu in enumerate(gpus):
        seed = args.seed - index
        output = output_for(base_output, seed)
        log = args.log_dir / f"{base_output.stem}_gpu{gpu}_seed{seed}.log"
        jobs.append((gpu, seed, output, log))
        print(f"GPU {gpu}: seed={seed}, output={output}, log={log}")

    if args.dry_run:
        return

    base_output.parent.mkdir(parents=True, exist_ok=True)
    args.log_dir.mkdir(parents=True, exist_ok=True)
    processes: list[subprocess.Popen] = []
    exit_codes: list[int] = []
    log_files = []
    try:
        for gpu, seed, output, log in jobs:
            env = os.environ.copy()
            env["CUDA_VISIBLE_DEVICES"] = str(gpu)
            env.setdefault("TOKENIZERS_PARALLELISM", "false")
            env.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
            command = [
                str(args.python),
                str(args.script),
                *child_args,
                "--seed",
                str(seed),
                "--output",
                str(output),
            ]
            log_file = log.open("w", encoding="utf-8")
            log_files.append(log_file)
            processes.append(
                subprocess.Popen(
                    command,
                    cwd=ROOT,
                    env=env,
                    stdout=log_file,
                    stderr=subprocess.STDOUT,
                )
            )

        exit_codes = [process.wait() for process in processes]
    except KeyboardInterrupt:
        print("Interrupted; terminating all child processes", file=sys.stderr)
        terminate_all(processes)
        raise SystemExit(130)
    finally:
        for log_file in log_files:
            log_file.close()

    failures = [(*jobs[index][:2], code, jobs[index][3]) for index, code in enumerate(exit_codes) if code]
    if failures:
        for gpu, seed, code, log in failures:
            print(f"FAILED GPU {gpu}, seed {seed}, exit={code}; see {log}", file=sys.stderr)
        raise SystemExit(1)
    print(f"Completed {len(jobs)} jobs successfully")


if __name__ == "__main__":
    main()