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