PyTorch DDP快速上手附代码

[复制链接]
发表于 2025-10-8 03:41:56 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
如标题所示,博主有使命 想要快速上手DDP以测试RDMA参与下的耽误带宽.
环境准备:

验证PyTorch:
  1. python -c "import torch; print(torch.__version__, torch.cuda.device_count())"
复制代码
核心概念:

进程组:每个GPU对应一个独立进程
​AllReduce:跨卡聚合数据(如梯度)
​torchrun:官方保举启动工具

测试两卡all-reduce

看看博主的卡:
  1. import torch
  2. import torch.distributed as dist
  3. dist.init_process_group(backend='nccl')
  4. rank = dist.get_rank()
  5. world_size = dist.get_world_size()
  6. print(f'I am rank: {rank}  of world {world_size}')
  7. input_tensor = torch.rand([1024, 1024, 10], dtype=torch.float).to('cuda:%d' % rank)
  8. input_tensor.fill_(1.0)
  9. dist.all_reduce(input_tensor)
  10. print(input_tensor[0][0])
复制代码
效果:

还想进一步测试差别buffer size下的耽误和带宽环境:
  1. import os
  2. import torch
  3. import torch.distributed as dist
  4. import time
  5. os.environ['MASTER_ADDR'] = '127.0.0.1'
  6. os.environ['MASTER_PORT'] = '29500'
  7. dist.init_process_group(backend='nccl')
  8. rank = dist.get_rank()
  9. torch.cuda.set_device(rank)
  10. world_size = dist.get_world_size()
  11. buffer_sizes = [1, 1024, 2048, 4096, 8192,
  12.                 256 * 1024, 512 * 1024,
  13.                 1024 * 1024, 4 * 1024 * 1024,
  14.                 256 * 1024 * 1024]
  15. def benchmark(size):
  16.     input_tensor = torch.ones(size, dtype=torch.float32).to(f'cuda:{rank}')
  17.    
  18.     torch.cuda.synchronize()
  19.     start = time.time()
  20.    
  21.     dist.all_reduce(input_tensor)
  22.    
  23.     torch.cuda.synchronize()
  24.     elapsed = time.time() - start
  25.    
  26.     if rank == 0:
  27.         data_size = size * 4  # float32占4字节
  28.         bandwidth = (data_size / elapsed) / (1024**2)  # MB/s
  29.         print(f"Size: {size/1024:.1f} KB\tLatency: {elapsed*1000:.3f} ms\tBandwidth: {bandwidth:.2f} MB/s")
  30. if rank == 0:
  31.     print("Buffer Size (KB)\tLatency (ms)\tBandwidth (MB/s)")
  32.     print("------------------------------------------------")
  33. for size in buffer_sizes:
  34.     benchmark(size)
  35. dist.destroy_process_group()
复制代码
效果:

至此 单机两卡h20测试乐成 带宽耽误符合预期
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表