重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

使用PyTorch怎么多GPU中对模型进行保存-创新互联

这篇文章将为大家详细讲解有关使用PyTorch怎么多GPU中对模型进行保存,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

成都创新互联公司提供高防服务器租用、云服务器、香港服务器、内江机房主机托管

多GPU下训练,创建模型代码通常如下:


os.environ['CUDA_VISIBLE_DEVICES'] = args.cuda
model = MyModel(args)
if torch.cuda.is_available() and args.use_gpu:
  model = torch.nn.DataParallel(model).cuda()

官方建议的模型保存方式,只保存参数:

torch.save(model.module.state_dict(), "model.pkl")

其实,这样很麻烦,我建议直接保存模型(参数+图):

torch.save(model, "model.pkl")

这样做很实用,特别是我们需要反复建模和调试的时候。这种情况下模型的加载很方便,因为模型的图已经和参数保存在一起,我们不需要根据不同的模型设置相应的超参,更换对应的网络结构,如下:

 if not (args.pretrained_model_path is None):
    print('load model from %s ...' % args.pretrained_model_path)
    model = torch.load(args.pretrained_model_path)
    print('success!')

但是需要注意,这种方式加载的是多GPU下模型。如果服务器环境变化不大,或者和训练时候是同一个GPU环境,就不会出现问题。

如果系统环境发生了变化,或者,我们只想加载模型参数,亦或是遇到下面的问题:

AttributeError: 'model' object has no attribute 'copy'

或者

AttributeError: 'DataParallel' object has no attribute 'copy'

或者

RuntimeError: module must have its parameters and buffers on device cuda:0 (device_ids[0]) but found

这时候我们可以用下面的方式载入模型,先建立模型,然后加载参数。

os.environ['CUDA_VISIBLE_DEVICES'] = args.cuda
# 建立模型
model = MyModel(args)

if torch.cuda.is_available() and args.use_gpu:
  model = torch.nn.DataParallel(model).cuda()

if not (args.pretrained_model_path is None):
  print('load model from %s ...' % args.pretrained_model_path)
  # 获得模型参数
  model_dict = torch.load(args.pretrained_model_path).module.state_dict()
  # 载入参数
  model.module.load_state_dict(model_dict)
  print('success!')

关于使用PyTorch怎么多GPU中对模型进行保存就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


当前题目:使用PyTorch怎么多GPU中对模型进行保存-创新互联
网页网址:http://cqcxhl.com/article/dpesgh.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP