File size: 2,825 Bytes
12c2325 | 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 | #!/usr/bin/env python3
"""Minimal NCCL collective test intended to be launched with torchrun."""
from __future__ import annotations
import argparse
import json
import os
from datetime import timedelta
import torch
import torch.distributed as dist
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--timeout-seconds", type=int, default=120)
parser.add_argument("--tensor-elements", type=int, default=1_048_576)
parser.add_argument("--require-world-size", type=int)
return parser.parse_args()
def main() -> int:
args = parse_args()
if not torch.cuda.is_available():
raise RuntimeError("NCCL smoke test requires CUDA")
if not dist.is_available() or not dist.is_nccl_available():
raise RuntimeError("this PyTorch build does not provide NCCL")
local_rank = int(os.environ.get("LOCAL_RANK", "0"))
torch.cuda.set_device(local_rank)
dist.init_process_group(
backend="nccl",
timeout=timedelta(seconds=args.timeout_seconds),
device_id=torch.device("cuda", local_rank),
)
try:
rank = dist.get_rank()
world_size = dist.get_world_size()
if args.require_world_size is not None and world_size != args.require_world_size:
raise RuntimeError(
f"expected world size {args.require_world_size}, initialized {world_size}"
)
device = torch.device("cuda", local_rank)
value = torch.full(
(args.tensor_elements,),
float(rank + 1),
device=device,
dtype=torch.float32,
)
dist.all_reduce(value, op=dist.ReduceOp.SUM)
expected_sum = world_size * (world_size + 1) / 2
expected = torch.full_like(value, expected_sum)
torch.testing.assert_close(value, expected, rtol=0, atol=0)
broadcast = torch.tensor([rank], device=device, dtype=torch.int64)
dist.broadcast(broadcast, src=0)
if broadcast.item() != 0:
raise RuntimeError(f"broadcast returned {broadcast.item()}, expected 0")
dist.barrier(device_ids=[local_rank])
torch.cuda.synchronize(device)
if rank == 0:
print(
json.dumps(
{
"backend": dist.get_backend(),
"cuda_devices": torch.cuda.device_count(),
"status": "passed",
"tensor_elements_per_rank": args.tensor_elements,
"world_size": world_size,
},
sort_keys=True,
),
flush=True,
)
finally:
dist.destroy_process_group()
return 0
if __name__ == "__main__":
raise SystemExit(main())
|