"""Multi-GPU helpers. Every entry point works under `torchrun --nproc_per_node N` and as a plain single process.""" import os from datetime import timedelta import torch import torch.distributed as dist # Steps that split cases across GPUs can leave ranks idle for a long time; keep collectives patient. TIMEOUT = timedelta(hours=12) def init(): """Start the process group when launched by torchrun. Returns (rank, world size, device).""" local = int(os.environ.get("LOCAL_RANK", "0")) if torch.cuda.is_available(): local %= torch.cuda.device_count() # more processes than GPUs: several share a GPU torch.cuda.set_device(local) if "RANK" in os.environ and not dist.is_initialized(): dist.init_process_group("nccl" if torch.cuda.is_available() else "gloo", timeout=TIMEOUT) rank, world = (dist.get_rank(), dist.get_world_size()) if dist.is_initialized() else (0, 1) return rank, world, torch.device(f"cuda:{local}" if torch.cuda.is_available() else "cpu") def broadcast(t, src=0): if dist.is_initialized(): dist.broadcast(t, src) return t def done(sync=True): """End the process group. sync=False for steps whose ranks work on independent cases.""" if dist.is_initialized(): if sync: dist.barrier() dist.destroy_process_group() def log(rank, *a): if rank == 0: print(*a, flush=True)