Python 如何以正常的非并行方式运行Pytorch模型?

Python 如何以正常的非并行方式运行Pytorch模型?,python,machine-learning,pytorch,Python,Machine Learning,Pytorch,我正在浏览,这里有一个代码块,它考虑了两个选项,DataParallel和DistributedDataParallel: if not args.distributed: if args.arch.startswith('alexnet') or args.arch.startswith('vgg'): model.features = torch.nn.DataParallel(model.features) model.cuda() else

我正在浏览,这里有一个代码块,它考虑了两个选项,
DataParallel
DistributedDataParallel

if not args.distributed:
    if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):
        model.features = torch.nn.DataParallel(model.features)
        model.cuda()
    else:
        model = torch.nn.DataParallel(model).cuda()
else:
    model.cuda()
    model = torch.nn.parallel.DistributedDataParallel(model)
如果我不想要这两个选项中的任何一个,并且我想在没有
DataParallel
的情况下运行它,该怎么办。我该怎么做

如何定义我的模型,使其作为普通的
nn
运行,而不并行任何东西?

  • DataParallel
    是一个包装器对象,用于在同一台机器的多个GPU上并行计算,请参阅
  • DistributedDataParallel
    也是一个包装器对象,允许您在多个设备上分发数据,请参阅
如果不需要,只需移除包装器并按原样使用模型:

if not args.distributed:
    if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):
        model.features = model.features
        model.cuda()
    else:
        model = model.cuda()
else:
    model.cuda()
    model = model
这是为了尽量减少代码修改。当然,由于您对并行化不感兴趣,您可以将整个
if
语句删除为以下内容:

if args.arch.startswith('alexnet') or args.arch.startswith('vgg'):
    model.features = model.features
model = model.cuda()

请注意,此代码假定您正在GPU上运行。

谢谢您的帮助。这是有效的向所有
变量添加
.cuda()
非常重要。