File size: 12,399 Bytes
f614769 | 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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | #!/usr/bin/env python
"""
Multi-GPU launcher for MD simulations.
Launches multiple experiment_runner.py processes across multiple GPUs,
each with a different index and proper logging.
"""
import argparse
import os
import subprocess
import time
from pathlib import Path
def launch_experiment(
gpu_id: int,
index: int,
model_name: str,
input_dir: str,
log_dir: Path,
runner_script: str = "experiment_runner.py",
extra_args: list = None,
):
"""
Launch a single experiment on a specific GPU.
Args:
gpu_id: GPU device ID (0-7)
index: Experiment index
model_name: Model name (e.g., 'mace_pyg')
input_dir: Input directory path
log_dir: Directory for log files
runner_script: Script to run (experiment_runner.py or elastic_tensor_runner.py)
extra_args: Additional arguments to pass to the runner script
"""
log_file = log_dir / f"gpu{gpu_id}_index{index}.log"
# Build command
cmd = [
"python",
f"md_simulation/{runner_script}",
"--model_name", model_name,
"--input_dir", input_dir,
"--index", str(index),
"--device", "cuda",
]
# Add any extra arguments
if extra_args:
cmd.extend(extra_args)
# Set environment with specific GPU
env = os.environ.copy()
env["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
# Launch process with logging
print(f"[GPU {gpu_id}] Launching index {index} -> {log_file}")
with open(log_file, "w") as f:
f.write(f"=== Experiment Index {index} on GPU {gpu_id} ===\n")
f.write(f"Command: {' '.join(cmd)}\n")
f.write(f"CUDA_VISIBLE_DEVICES={gpu_id}\n")
f.write("=" * 80 + "\n\n")
f.flush()
process = subprocess.Popen(
cmd,
env=env,
stdout=f,
stderr=subprocess.STDOUT,
text=True,
)
# wait for 5 seconds to avoid overwhelming the system
time.sleep(5) # wait for 5 seconds to avoid overwhelming the system
return process, log_file
def main():
parser = argparse.ArgumentParser(
description="Launch multiple MD simulations across multiple GPUs"
)
parser.add_argument(
"--model_name",
type=str,
required=True,
help="Model name (e.g., mace_pyg, orb, mattersim)",
)
parser.add_argument(
"--input_dir",
type=str,
required=True,
help="Input directory containing structures",
)
parser.add_argument(
"--start_index",
type=int,
default=0,
help="Starting index (default: 0)",
)
parser.add_argument(
"--end_index",
type=int,
default=100,
help="Ending index (exclusive, default: 100)",
)
parser.add_argument(
"--num_gpus",
type=int,
default=8,
help="Number of GPUs to use (default: 8)",
)
parser.add_argument(
"--gpu_offset",
type=int,
default=0,
help="GPU ID offset (default: 0, uses GPUs 0-7). Set to 4 to use GPUs 4-11.",
)
parser.add_argument(
"--log_dir",
type=str,
default=None,
help="Directory for log files (default: auto-generated based on input_dir, e.g., ./logs_minxhtp/)",
)
parser.add_argument(
"--mode",
type=str,
choices=["batch", "rolling"],
default="batch",
help="Launch mode: 'batch' waits for all GPUs to finish before next batch, "
"'rolling' launches new job as soon as any GPU is free (default: batch)",
)
parser.add_argument(
"--runner",
type=str,
choices=["experiment_runner.py", "elastic_tensor_runner.py"],
default="experiment_runner.py",
help="Runner script to use (default: experiment_runner.py for MD simulations)",
)
parser.add_argument(
"--extra_args",
type=str,
default="",
help="Extra arguments to pass to the runner script (e.g., '--runsteps 1000 --timestep 0.5')",
)
args = parser.parse_args()
# Auto-generate log directory based on input_dir if not specified
if args.log_dir is None:
# Extract dataset name from input_dir
dataset_name = Path(args.input_dir).name.lower()
args.log_dir = f"./logs_{dataset_name}"
# Create log directory
log_dir = Path(args.log_dir)
log_dir.mkdir(parents=True, exist_ok=True)
# Parse extra arguments
extra_args = args.extra_args.split() if args.extra_args else []
# Add dataset-specific output directory to extra args if not already specified
dataset_name = Path(args.input_dir).name.lower()
if not any('--log_dir_base' in arg for arg in extra_args):
if args.runner == "experiment_runner.py":
output_dir = f"./results_{dataset_name}"
else: # elastic_tensor_runner.py
output_dir = f"./elastic_{dataset_name}"
extra_args.extend(["--log_dir_base", output_dir])
# Create list of all indices to process
indices = list(range(args.start_index, args.end_index))
total_jobs = len(indices)
# Extract output directory from extra_args for display
output_dir = None
for i, arg in enumerate(extra_args):
if arg == "--log_dir_base" and i + 1 < len(extra_args):
output_dir = extra_args[i + 1]
break
print("=" * 80)
print(f"Multi-GPU Launcher Configuration")
print("=" * 80)
print(f"Runner script: {args.runner}")
print(f"Model: {args.model_name}")
print(f"Input directory: {args.input_dir}")
print(f"Indices: {args.start_index} to {args.end_index-1} ({total_jobs} total)")
print(f"GPUs: {args.num_gpus} (IDs {args.gpu_offset} to {args.gpu_offset + args.num_gpus - 1})")
print(f"Mode: {args.mode}")
if args.mode == "batch":
print(f" - Launches {args.num_gpus} jobs, waits for all to complete, then next batch")
else:
print(f" - Launches new job as soon as any GPU becomes free")
print(f"Launch logs: {log_dir}")
if output_dir:
print(f"Results output: {output_dir}")
if extra_args and not (len(extra_args) == 2 and extra_args[0] == "--log_dir_base"):
# Only show extra args if there are more than just log_dir_base
print(f"Extra arguments: {' '.join(extra_args)}")
print("=" * 80)
print()
# Track progress
completed = 0
failed = 0
current_idx = 0
# Main loop
try:
if args.mode == "batch":
# Batch mode: Launch full batch, wait for all to complete, repeat
batch_num = 1
while current_idx < total_jobs:
batch_start = current_idx
batch_end = min(current_idx + args.num_gpus, total_jobs)
batch_size = batch_end - batch_start
print("=" * 80)
print(f"Batch {batch_num}: Launching indices {indices[batch_start]} to {indices[batch_end-1]}")
print("=" * 80)
# Launch batch
active_processes = {}
for i in range(batch_size):
gpu_id = args.gpu_offset + i
index = indices[current_idx]
process, log_file = launch_experiment(
gpu_id=gpu_id,
index=index,
model_name=args.model_name,
input_dir=args.input_dir,
log_dir=log_dir,
runner_script=args.runner,
extra_args=extra_args,
)
active_processes[process] = (gpu_id, index, log_file)
current_idx += 1
time.sleep(0.5)
print(f"\nBatch {batch_num} launched ({batch_size} jobs). Waiting for completion...\n")
# Wait for all jobs in batch to complete
while active_processes:
completed_processes = []
for process, (gpu_id, index, log_file) in active_processes.items():
poll = process.poll()
if poll is not None:
completed_processes.append(process)
if poll == 0:
print(f"[GPU {gpu_id}] ✓ Index {index} completed successfully")
completed += 1
else:
print(f"[GPU {gpu_id}] ✗ Index {index} failed with exit code {poll}")
print(f" Check log: {log_file}")
failed += 1
for process in completed_processes:
del active_processes[process]
if active_processes:
time.sleep(2)
print(f"\nBatch {batch_num} completed!")
print(f"Progress: {completed} completed, {failed} failed, {total_jobs - current_idx} remaining\n")
batch_num += 1
else:
# Rolling mode: Launch new job as soon as any GPU is free
active_processes = {}
while current_idx < total_jobs or active_processes:
# Launch new jobs if slots available
while current_idx < total_jobs and len(active_processes) < args.num_gpus:
gpu_id = args.gpu_offset + (current_idx % args.num_gpus)
index = indices[current_idx]
process, log_file = launch_experiment(
gpu_id=gpu_id,
index=index,
model_name=args.model_name,
input_dir=args.input_dir,
log_dir=log_dir,
runner_script=args.runner,
extra_args=extra_args,
)
active_processes[process] = (gpu_id, index, log_file)
current_idx += 1
time.sleep(0.5)
# Check for completed processes
completed_processes = []
for process, (gpu_id, index, log_file) in active_processes.items():
poll = process.poll()
if poll is not None:
completed_processes.append(process)
if poll == 0:
print(f"[GPU {gpu_id}] ✓ Index {index} completed successfully")
completed += 1
else:
print(f"[GPU {gpu_id}] ✗ Index {index} failed with exit code {poll}")
print(f" Check log: {log_file}")
failed += 1
for process in completed_processes:
del active_processes[process]
# Progress update
print(f"\nProgress: {completed} completed, {failed} failed, "
f"{len(active_processes)} running, "
f"{total_jobs - current_idx} pending\n")
time.sleep(5)
except KeyboardInterrupt:
print("\n\nInterrupted by user. Terminating active processes...")
if 'active_processes' in locals():
for process in active_processes:
process.terminate()
for process in active_processes:
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
print("All processes terminated.")
return
print("\n" + "=" * 80)
print("All jobs completed!")
print(f"Successful: {completed}/{total_jobs}")
print(f"Failed: {failed}/{total_jobs}")
print(f"Launch logs: {log_dir}")
if output_dir:
print(f"Results: {output_dir}")
print("=" * 80)
if __name__ == "__main__":
main()
|