Download proj2rep/dist.py from markjiang1/Proj2Rep-CTFM: direct link, hf CLI and curl.
- Browser
- Download file 1.41 kB
-
https://huggingface.co/markjiang1/Proj2Rep-CTFM/resolve/main/proj2rep/dist.py
- Command line
-
hf download hf://markjiang1/Proj2Rep-CTFM/proj2rep/dist.py
-
curl -L -o dist.py https://huggingface.co/markjiang1/Proj2Rep-CTFM/resolve/main/proj2rep/dist.py
1.41 kB
| """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) | |