在CentOS上如何进行PyTorch的分布式训练

centos系统上执行pytorch分布式训练时,请按照以下流程操作:

  1. 安装PyTorch:首先确认已安装PyTorch。可以从PyTorch官方网站(https://www.php.cn/link/419e4410da152c74d727270283cb94ce

  2. 配置环境变量:若要利用多块GPU进行分布式训练,需设置特定的环境变量。比如,若有4块GPU,可按如下方式设置:

     export MASTER_ADDR='localhost'  export MASTER_PORT='12345'  export WORLD_SIZE=4

    MASTER_ADDR 是主节点的IP地址,MASTER_PORT 是选定的端口号,WORLD_SIZE 表示参与训练的GPU总数。

  3. 构建分布式训练脚本:PyTorch内置了torch.distributed模块用于分布式训练。需对现有训练脚本做出相应改动使其兼容分布式训练。以下为一简易实例:

     import torch  import torch.distributed as dist  from torch.nn.parallel import DistributedDataParallel as DDP   def main():      # 初始化分布式架构      dist.init_process_group(backend='nccl', init_method='tcp://localhost:12345', world_size=4, rank=0)       # 定义模型并迁移至GPU      model = ... # 构建您的模型      model.cuda()       # 利用DistributedDataParallel封装模型      model = DDP(model, device_ids=[torch.cuda.current_device()])       # 设置损失函数与优化器      criterion = torch.nn.CrossEntropyLoss().cuda()      optimizer = torch.optim.SGD(model.parameters(), lr=0.01)       # 载入数据      dataset = ... # 创建数据集      sampler = torch.utils.data.distributed.DistributedSampler(dataset)      dataloader = torch.utils.data.DataLoader(dataset, batch_size=..., sampler=sampler)       # 开始模型训练      for epoch in range(...):          sampler.set_epoch(epoch)          for inputs, targets in dataloader:              inputs, targets = inputs.cuda(), targets.cuda()              optimizer.zero_grad()              outputs = model(inputs)              loss = criterion(outputs, targets)              loss.backward()              optimizer.step()       # 结束分布式架构      dist.destroy_process_group()   if __name__ == "__main__":      main()

    请依据实际情形调整模型、数据集、损失函数、优化器及训练逻辑。

  4. 运行分布式训练:可以借助mpirun或torch.distributed.launch来发起分布式训练任务。例如:

     mpirun -np 4 python your_training_script.py

    或者采用torch.distributed.launch:

     python -m torch.distributed.launch --nproc_per_node=4 your_training_script.py

    其中的-np 4和–nproc_per_node=4指示每个节点所用GPU的数量。

  5. 关键点提示

    • 确保各节点间可通过网络互相通信。
    • 核实所有节点的PyTorch版本与CUDA版本保持一致。
    • 若在多台设备上实施分布式训练,务必把MASTER_ADDR设为主机IP,并保证所有节点能通过此IP相互通信。

上述过程构成了一个基础模板,具体应用时可能还需进一步定制化调整。开始分布式训练前,推荐深入研读PyTorch官方文档中有关分布式训练的部分。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享