pytorch:多GPU训练、保存加载参数、测试

一、指定使用单块gpu训练

os.environ["CUDA_VISIBLE_DEVICES"] = '1'

二、使用pytorch进行多GPU训练的需要添加的代码:

#设置使用哪些显卡,我这里用所有可用的
device_ids=range(torch.cuda.device_count())
model = Transformer().cuda()
model = nn.DataParallel(model, device_ids=device_ids)

三、保存和加载参数

#加载参数
model.load_state_dict(torch.load('模型参数/两条130数值的测试用的模型参数.pkl'))
#保存参数
torch.save(model.state_dict(), '模型参数/两条130数值的测试用的模型参数.pkl')

四、多GPU加载参数后测试:

# Test
enc_inputs = next(iter(loader))
greedy_dec_input = greedy_decoder(model, enc_inputs[0].view(1, -1).cuda(), start_value=enc_inputs[0][-1])
predict = model.module(enc_inputs[0].view(1, -1).cuda(), greedy_dec_input)
print(predict)

会有如下报错:
AttributeError: ‘DataParallel’ object has no attribute ‘encoder’

因为加载参数时,model = nn.DataParallel(model, device_ids=device_ids),model等于了nn.dataparallel,在操作原始模型的时候需要将model换为model.module

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值