File size: 4,418 Bytes
f789875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Multi-worker launcher for benchmark_2000.py.

Splits the sampled indices across N workers, runs them concurrently on the same
GPU (or multiple GPUs), then merges per-worker summaries into a single
summary.json. Useful when a single image only utilises ~15% of a 4090.

Usage:
    # Run 4 workers concurrently on the same GPU
    python scripts/run_benchmark_workers.py --n 2000 --attack v15 --workers 4

    # Use a different number of workers
    python scripts/run_benchmark_workers.py --n 2000 --attack v15 --workers 6 --budget 25
"""

from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
import time
from pathlib import Path
from typing import Any

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from benchmark_2000 import summarize  # type: ignore


def merge_summaries(output_dir: Path, attack_name: str, workers: int) -> dict | None:
    """Read all per-image JSON files and merge them into one summary.json."""
    online_dir = output_dir / attack_name
    records: list[dict] = []
    for json_path in sorted(online_dir.glob("[0-9][0-9][0-9][0-9][0-9][0-9][0-9].json")):
        records.append(json.loads(json_path.read_text()))

    if not records:
        print(f"[warn] no per-image records found in {online_dir}")
        return None

    summary = summarize(records)
    summary.update({"attack": attack_name, "mode": "online", "workers": workers})
    summary_path = online_dir / "summary.json"
    summary_path.write_text(json.dumps(summary, indent=2))
    return summary


def main() -> None:
    parser = argparse.ArgumentParser(description="Launch multi-worker Perturb benchmark")
    parser.add_argument("--n", type=int, default=2000, help="Number of images to sample")
    parser.add_argument("--seed", type=int, default=20260819, help="Random seed for sampling")
    parser.add_argument("--attack", type=str, default="v15", help="Attack version")
    parser.add_argument("--budget", type=float, default=25.0, help="Attack time budget in seconds")
    parser.add_argument("--output-dir", type=Path, default=Path("benchmark_2000"), help="Output directory")
    parser.add_argument("--workers", type=int, default=4, help="Number of parallel workers")
    parser.add_argument("--force", action="store_true", help="Overwrite existing per-image JSONs")
    args = parser.parse_args()

    args.output_dir.mkdir(parents=True, exist_ok=True)
    log_dir = args.output_dir.parent / f"{args.output_dir.name}_logs"
    log_dir.mkdir(parents=True, exist_ok=True)

    script = Path(__file__).resolve().parents[1] / "scripts" / "benchmark_2000.py"
    base_cmd = [
        sys.executable,
        str(script),
        "--n", str(args.n),
        "--seed", str(args.seed),
        "--attack", args.attack,
        "--budget", str(args.budget),
        "--output-dir", str(args.output_dir),
        "--workers", str(args.workers),
    ]
    if args.force:
        base_cmd.append("--force")

    print(f"[info] launching {args.workers} workers for {args.n} images")
    print(f"[info] output dir: {args.output_dir}")
    print(f"[info] logs: {log_dir}")

    processes: list[subprocess.Popen] = []
    pids: list[int] = []
    for worker_id in range(args.workers):
        cmd = base_cmd + ["--worker-id", str(worker_id)]
        log_path = log_dir / f"worker{worker_id}.log"
        log_file = open(log_path, "w")
        proc = subprocess.Popen(cmd, stdout=log_file, stderr=subprocess.STDOUT)
        processes.append(proc)
        pids.append(proc.pid)
        print(f"[info] worker {worker_id} PID={proc.pid} log={log_path}")

    # Save all worker PIDs for monitoring tools.
    (log_dir / "pids.txt").write_text("\n".join(str(p) for p in pids) + "\n")

    start = time.time()
    try:
        for proc in processes:
            proc.wait()
    except KeyboardInterrupt:
        print("\n[warn] interrupted; terminating workers...")
        for proc in processes:
            proc.terminate()
        for proc in processes:
            proc.wait(timeout=10)
        raise

    elapsed = time.time() - start
    print(f"\n[info] all workers finished in {elapsed/3600:.2f}h")

    summary = merge_summaries(args.output_dir, args.attack, args.workers)
    if summary:
        print("\n" + "=" * 64)
        print("MERGED SUMMARY")
        print("=" * 64)
        print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()