#!/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()