torch gpu改cpu

本文介绍了如何在PyTorch中设置和切换设备(如GPU和CPU),包括模型的保存和加载过程。提供了详细的代码示例,帮助读者理解如何根据实际硬件情况选择最优设备。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、

torch在训练前一般会加以下代码:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

有cuda[gpu] 就使用,没有就用cpu

之后代码中进行修改:

model=xxx.cuda

一律改为

model=xxx.to(device) 

这种方法:如果电脑有gpu可用,调用的还是gpu

二、

(1) 模型在GPU上保存,运行在CPU上

torch.save(model.state_dict(), PATH)

device = torch.device("cpu")
model = xxxxxxx(*args, **kwargs)
model.load_state_dict(torch.load(PATH, map_location=device))
or

torch.load(xxxxxxxxxxxx) 同上

model.load_state_dict(没有map_location 参数)会报错

(2)模型在cpu,运行在gpu:

device = torch.device("cuda")
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH, map_location="cuda:0"))
model.to(device)

如果想控制使用哪个gpu:

torch.load('modelparameters.pth', map_location={'cuda:1':'cuda:0'}) 




ps:

import torch
print(torch.cuda.device_count())  # 可用gpu数量
print(torch.cuda.is_available())  # 是否可用gpu
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值