pytorch 细节 多GPU卡训练 一个可在windows单GPU独立运行的DDP

an vanilla example for DDP on lunix

# main.py
import torch
import torch.distributed as dist
import torch.multiprocessing as mp

mp.spawn(main_worker, nprocs=4, args=(4, myargs))
def main_worker(proc, nprocs, args):
   dist.init_process_group(backend='nccl', init_method='tcp://127.0.0.1:23456', world_size=4, rank=gpu)
   torch.cuda.set_device(args.local_rank)
   train_dataset = ...
   train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)

   train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=..., sampler=train_sampler)

   model = ...
   model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.local_rank])

   optimizer = optim.SGD(model.parameters())

   for epoch in range(100):
      for batch_idx, (data, target) in enumerate(train_loader):
          images = images.cuda(non_blocking=True)
          target = target.cuda(non_blocking=True)
          ...
          output = model(images)
          loss = criterion(output, target)
          ...
          optimizer.zero_grad()
          loss.backward()
          optimizer.step()

windows下的错误

1.‘CUDA_VISIBLE_DEVICES‘ 不是内部或外部命令

import os
os.environ["CUDA_VISIBLE_DEVICES"]='0'
# os.environ["CUDA_VISIBLE_DEVICES"]='0,1,2,3'

2.EOFError: Ran out of input
解决方案:torch.utils.data.DataLoader这个方法的地方,修改这个方法的一个参数即可:修改其中的num_workers = 0

# num_workers=0,
    train_loader = torch.utils.data.DataLoader(train_dataset,
                                               batch_size=args.batch_size,
                                               num_workers=0,
                                               pin_memory=False,
                                               sampler=train_sampler)

3.RuntimeError: cannot pin ‘torch.cuda.FloatTensor’ only dense CPU tensors can be pinned在本文末尾,单个GPU dataloader pin_memory=True报错

# pin_memory=False,
    train_loader = torch.utils.data.DataLoader(train_dataset,
                                               batch_size=args.batch_size,
                                               num_workers=0,
                                               pin_memory=False,
                                               sampler=train_sampler)
  1. windows不支持NCCL backend=‘gloo’。 这个报错还可以通过不启用ddp解决,但好像不适用于本问题。
    dist.init_process_group(backend='gloo',
                            init_method='tcp://127.0.0.1:23456',
                            world_size=args.nprocs,
                            rank=local_rank)

一个可在windows单GPU独立运行的DDP demo

注:本例因为只有单GPU,使用args.nprocs = torch.cuda.device_count() 得到的int 数值1决定了init_process_group的world_size 即执行训练的所有的节点数
[init_process_group的参数意义](https://blog.csdn.net/m0_37400316/article/details/107225030)
import torch.multiprocessing as mp
import torch.utils.data.distributed

import argparse
import os
os.environ["CUDA_VISIBLE_DEVICES"]='0'
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models

import numpy as np
import os, imageio
xb = torch.randn(65536, 2).cuda()
yb = torch.randn(65536, 3).cuda()

from torch.utils.data.dataset import Dataset
class MyDataSet(Dataset):
    def __init__(self, data, label):#传入参数是我们的数据集(data)和标签集(label)
        self.data = data
        self.label = label
        self.length = data.shape[0]
    def __getitem__(self, mask):# 获取返回数据的方法,传入参数是一个index,也被叫做mask,就是我们对数据集的选择索引。在调用DataLoader时就会自己生成index,所以我们只需要写好方法即可。
        label = self.label[mask]
        data = self.data[mask]
        return data, label # 注意返回的顺序也重要
    def __len__(self):
        return self.length

class MLP(nn.Module):
    def __init__(self,depth=4,mapping_size=2,hidden_size=256):
        super().__init__()
        layers = []
        layers.append(nn.Linear(mapping_size,hidden_size))
        layers.append(nn.ReLU(inplace=True))
        for _ in range(depth-2):
            layers.append(nn.Linear(hidden_size,hidden_size))
            layers.append(nn.ReLU(inplace=True))
        layers.append(nn.Linear(hidden_size,3))
        self.layers = nn.Sequential(*layers)
    def forward(self,x):
        return torch.sigmoid(self.layers(x))



model_names = sorted(name for name in models.__dict__
                     if name.islower() and not name.startswith("__")
                     and callable(models.__dict__[name]))

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--data',metavar='DIR',default='/home/zhangzhi/Data/exports/ImageNet2012',help='path to dataset')
parser.add_argument('-a','--arch',metavar='ARCH',default='resnet18',choices=model_names,help='model architecture: ' + ' | '.join(model_names) +
' (default: resnet18)')
parser.add_argument('-j','--workers',default=4,type=int,metavar='N',help='number of data loading workers (default: 4)')
parser.add_argument('--epochs',default=90,type=int,metavar='N',help='number of total epochs to run')
parser.add_argument('--start-epoch',default=0,type=int,metavar='N',help='manual epoch number (useful on restarts)')
parser.add_argument('-b','--batch-size',default=3200,type=int,metavar='N',help='mini-batch size (default: 256), this is the total '
                    'batch size of all GPUs on the current node when '
                    'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--lr','--learning-rate',default=0.1,type=float,metavar='LR',help='initial learning rate',dest='lr')
parser.add_argument('--momentum',default=0.9,type=float,metavar='M',help='momentum')
parser.add_argument('--wd','--weight-decay',default=1e-4,type=float,metavar='W',help='weight decay (default: 1e-4)',dest='weight_decay')
parser.add_argument('-p','--print-freq',default=10,type=int,metavar='N',help='print frequency (default: 10)')
parser.add_argument('-e','--evaluate',dest='evaluate',action='store_true',help='evaluate model on validation set')
parser.add_argument('--pretrained',dest='pretrained',action='store_true',help='use pre-trained model')
parser.add_argument('--seed',default=None,type=int,help='seed for initializing training. ')


def reduce_mean(tensor, nprocs):
    rt = tensor.clone()
    dist.all_reduce(rt, op=dist.ReduceOp.SUM)
    rt /= nprocs
    return rt


def main():
    args = parser.parse_args()
    args.nprocs = torch.cuda.device_count()
    mp.spawn(main_worker, nprocs=args.nprocs, args=(args.nprocs, args))


def main_worker(local_rank, nprocs, args):
    args.local_rank = local_rank

    if args.seed is not None:
        random.seed(args.seed)
        torch.manual_seed(args.seed)
        cudnn.deterministic = True
        warnings.warn('You have chosen to seed training. '
                      'This will turn on the CUDNN deterministic setting, '
                      'which can slow down your training considerably! '
                      'You may see unexpected behavior when restarting '
                      'from checkpoints.')

    best_acc1 = .0
    # dist.init_process_group(backend='nccl',
    #                         init_method='tcp://127.0.0.1:23456',
    #                         world_size=args.nprocs,
    #                         rank=local_rank)
    dist.init_process_group(backend='gloo',
                            init_method='tcp://127.0.0.1:23456',
                            world_size=args.nprocs,
                            rank=local_rank)
    # create model
    model = MLP()
    torch.cuda.set_device(local_rank)
    model.cuda(local_rank)
    # When using a single GPU per process and per DistributedDataParallel,
    # we need to divide the batch size ourselves based on the total number of GPUs we have
    args.batch_size = 1204
    model = torch.nn.parallel.DistributedDataParallel(model,
                                                      device_ids=[local_rank])

    # define loss function (criterion) and optimizer
    criterion = nn.CrossEntropyLoss().cuda(local_rank)
    optimizer = torch.optim.SGD(model.parameters(),
                                args.lr,
                                momentum=args.momentum,
                                weight_decay=args.weight_decay)

    cudnn.benchmark = True

    train_dataset =  MyDataSet(xb,yb)
    train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
    train_loader = torch.utils.data.DataLoader(train_dataset,
                                               batch_size=args.batch_size,
                                               num_workers=0,
                                               pin_memory=False,
                                               sampler=train_sampler)

    for epoch in range(args.start_epoch, args.epochs):

        train_sampler.set_epoch(epoch)
        adjust_learning_rate(optimizer, epoch, args)
        # train for one epoch
        train(train_loader, model, criterion, optimizer, epoch, local_rank,
              args)

def train(train_loader, model, criterion, optimizer, epoch, local_rank, args):
    batch_time = AverageMeter('Time', ':6.3f')
    data_time = AverageMeter('Data', ':6.3f')
    losses = AverageMeter('Loss', ':.4e')
    top1 = AverageMeter('Acc@1', ':6.2f')
    top5 = AverageMeter('Acc@5', ':6.2f')
    progress = ProgressMeter(len(train_loader),
                             [batch_time, data_time, losses, top1, top5],
                             prefix="Epoch: [{}]".format(epoch))

    # switch to train mode
    model.train()

    end = time.time()
    for i, (images, target) in enumerate(train_loader):
        # measure data loading time
        data_time.update(time.time() - end)

        images = images.cuda(local_rank, non_blocking=True)
        target = target.cuda(local_rank, non_blocking=True)

        # compute output
        output = model(images)
        loss = criterion(output, target)
        print(loss)

        # compute gradient and do SGD step
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()



class AverageMeter(object):
    """Computes and stores the average and current value"""
    def __init__(self, name, fmt=':f'):
        self.name = name
        self.fmt = fmt
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

    def __str__(self):
        fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
        return fmtstr.format(**self.__dict__)


class ProgressMeter(object):
    def __init__(self, num_batches, meters, prefix=""):
        self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
        self.meters = meters
        self.prefix = prefix

    def display(self, batch):
        entries = [self.prefix + self.batch_fmtstr.format(batch)]
        entries += [str(meter) for meter in self.meters]
        print('\t'.join(entries))

    def _get_batch_fmtstr(self, num_batches):
        num_digits = len(str(num_batches // 1))
        fmt = '{:' + str(num_digits) + 'd}'
        return '[' + fmt + '/' + fmt.format(num_batches) + ']'


def adjust_learning_rate(optimizer, epoch, args):
    """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
    lr = args.lr * (0.1**(epoch // 30))
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr



if __name__ == '__main__':
    main()

参考

DDP教程:https://github.com/rentainhe/pytorch-distributed-training
DDP模式
pytorch分布式系列3——分布式训练时,torch.utils.data.distributed.DistributedSampler做了什么?
https://zhuanlan.zhihu.com/p/98535650

在lunix运行时的警告

计算交叉熵是出现异常提示:RuntimeError: multi-target not supported at /opt/conda/conda-bld/pytorch_1549635019666/work/aten/src/THNN/generic/ClassNLLCriterion.c:21

亚马逊云科技:多GPU训练

lunix 上修改一点就能运行

import torch.multiprocessing as mp
import torch.utils.data.distributed

import argparse
import os
os.environ["CUDA_VISIBLE_DEVICES"]='0,1'
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torchvision.models as models

import numpy as np
import os, imageio

xb = torch.randn(65536, 2).cuda()
yb = torch.randn(65536, 3).cuda()

from torch.utils.data.dataset import Dataset
class MyDataSet(Dataset):
    def __init__(self, data, label):#传入参数是我们的数据集(data)和标签集(label)
        self.data = data
        self.label = label
        self.length = data.shape[0]
    def __getitem__(self, mask):# 获取返回数据的方法,传入参数是一个index,也被叫做mask,就是我们对数据集的选择索引。在调用DataLoader时就会自己生成index,所以我们只需要写好方法即可。
        label = self.label[mask]
        data = self.data[mask]
        return data, label # 注意返回的顺序也重要
    def __len__(self):
        return self.length

class MLP(nn.Module):
    def __init__(self,depth=4,mapping_size=2,hidden_size=256):
        super().__init__()
        layers = []
        layers.append(nn.Linear(mapping_size,hidden_size))
        layers.append(nn.ReLU(inplace=True))
        for _ in range(depth-2):
            layers.append(nn.Linear(hidden_size,hidden_size))
            layers.append(nn.ReLU(inplace=True))
        layers.append(nn.Linear(hidden_size,3))
        self.layers = nn.Sequential(*layers)
    def forward(self,x):
        return torch.sigmoid(self.layers(x))



model_names = sorted(name for name in models.__dict__
                     if name.islower() and not name.startswith("__")
                     and callable(models.__dict__[name]))

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('--data',metavar='DIR',default='/home/zhangzhi/Data/exports/ImageNet2012',help='path to dataset')
parser.add_argument('-a','--arch',metavar='ARCH',default='resnet18',choices=model_names,help='model architecture: ' + ' | '.join(model_names) +
' (default: resnet18)')
parser.add_argument('-j','--workers',default=4,type=int,metavar='N',help='number of data loading workers (default: 4)')
parser.add_argument('--epochs',default=90,type=int,metavar='N',help='number of total epochs to run')
parser.add_argument('--start-epoch',default=0,type=int,metavar='N',help='manual epoch number (useful on restarts)')
parser.add_argument('-b','--batch-size',default=3200,type=int,metavar='N',help='mini-batch size (default: 256), this is the total '
                    'batch size of all GPUs on the current node when '
                    'using Data Parallel or Distributed Data Parallel')
parser.add_argument('--lr','--learning-rate',default=0.1,type=float,metavar='LR',help='initial learning rate',dest='lr')
parser.add_argument('--momentum',default=0.9,type=float,metavar='M',help='momentum')
parser.add_argument('--wd','--weight-decay',default=1e-4,type=float,metavar='W',help='weight decay (default: 1e-4)',dest='weight_decay')
parser.add_argument('-p','--print-freq',default=10,type=int,metavar='N',help='print frequency (default: 10)')
parser.add_argument('-e','--evaluate',dest='evaluate',action='store_true',help='evaluate model on validation set')
parser.add_argument('--pretrained',dest='pretrained',action='store_true',help='use pre-trained model')
parser.add_argument('--seed',default=None,type=int,help='seed for initializing training. ')


def reduce_mean(tensor, nprocs):
    rt = tensor.clone()
    dist.all_reduce(rt, op=dist.ReduceOp.SUM)
    rt /= nprocs
    return rt


def main():
    args = parser.parse_args()
    args.nprocs = torch.cuda.device_count()
    mp.spawn(main_worker, nprocs=args.nprocs, args=(args.nprocs, args))


def main_worker(local_rank, nprocs, args):
    args.local_rank = local_rank

    if args.seed is not None:
        random.seed(args.seed)
        torch.manual_seed(args.seed)
        cudnn.deterministic = True
        warnings.warn('You have chosen to seed training. '
                      'This will turn on the CUDNN deterministic setting, '
                      'which can slow down your training considerably! '
                      'You may see unexpected behavior when restarting '
                      'from checkpoints.')

    best_acc1 = .0
    dist.init_process_group(backend='nccl',
                            init_method='tcp://127.0.0.1:23456',
                            world_size=args.nprocs,
                            rank=local_rank)

    # create model
    model = MLP()
    torch.cuda.set_device(local_rank)
    model.cuda(local_rank)
    # When using a single GPU per process and per DistributedDataParallel,
    # we need to divide the batch size ourselves based on the total number of GPUs we have
    args.batch_size = 1204
    model = torch.nn.parallel.DistributedDataParallel(model,
                                                      device_ids=[local_rank])

    # define loss function (criterion) and optimizer
    criterion = nn.CrossEntropyLoss().cuda(local_rank)
    criterion = nn.MSELoss().cuda(local_rank)
    optimizer = torch.optim.SGD(model.parameters(),
                                args.lr,
                                momentum=args.momentum,
                                weight_decay=args.weight_decay)

    cudnn.benchmark = True

    train_dataset =  MyDataSet(xb,yb)
    train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
    train_loader = torch.utils.data.DataLoader(train_dataset,
                                               batch_size=args.batch_size,
                                               num_workers=0,
                                               pin_memory=False,
                                               sampler=train_sampler)

    for epoch in range(args.start_epoch, args.epochs):

        train_sampler.set_epoch(epoch)
        adjust_learning_rate(optimizer, epoch, args)
        # train for one epoch
        train(train_loader, model, criterion, optimizer, epoch, local_rank,
              args)

def train(train_loader, model, criterion, optimizer, epoch, local_rank, args):
    batch_time = AverageMeter('Time', ':6.3f')
    data_time = AverageMeter('Data', ':6.3f')
    losses = AverageMeter('Loss', ':.4e')
    top1 = AverageMeter('Acc@1', ':6.2f')
    top5 = AverageMeter('Acc@5', ':6.2f')
    progress = ProgressMeter(len(train_loader),
                             [batch_time, data_time, losses, top1, top5],
                             prefix="Epoch: [{}]".format(epoch))

    # switch to train mode
    model.train()

    end = time.time()
    for i, (images, target) in enumerate(train_loader):
        # measure data loading time
        data_time.update(time.time() - end)

        images = images.cuda(local_rank, non_blocking=True)
        target = target.cuda(local_rank, non_blocking=True)

        # compute output
        output = model(images)
        loss = criterion(output, target)
        print(loss)

        # compute gradient and do SGD step
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()



class AverageMeter(object):
    """Computes and stores the average and current value"""
    def __init__(self, name, fmt=':f'):
        self.name = name
        self.fmt = fmt
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

    def __str__(self):
        fmtstr = '{name} {val' + self.fmt + '} ({avg' + self.fmt + '})'
        return fmtstr.format(**self.__dict__)


class ProgressMeter(object):
    def __init__(self, num_batches, meters, prefix=""):
        self.batch_fmtstr = self._get_batch_fmtstr(num_batches)
        self.meters = meters
        self.prefix = prefix

    def display(self, batch):
        entries = [self.prefix + self.batch_fmtstr.format(batch)]
        entries += [str(meter) for meter in self.meters]
        print('\t'.join(entries))

    def _get_batch_fmtstr(self, num_batches):
        num_digits = len(str(num_batches // 1))
        fmt = '{:' + str(num_digits) + 'd}'
        return '[' + fmt + '/' + fmt.format(num_batches) + ']'


def adjust_learning_rate(optimizer, epoch, args):
    """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
    lr = args.lr * (0.1**(epoch // 30))
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr



if __name__ == '__main__':
    main()

你可能感兴趣的:(语言学习笔记,科技,pytorch,算法)