File size: 1,406 Bytes
76eb7b3 | 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 | """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)
|