一、问题
调用torch.load()
加载模型时,出现以下错误
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU.
问题反馈是未获取到当前环境下的 cuda,分两种情况:
- 情况一、CPU
在只有 CPU 环境下运行的话,加上map_location=torch.device('cpu')
就可以。
eg:
model = torch.load('model/pytorch_resnet50.pth',map_location ='cpu')
- 情况二、GPU
当前环境有 GPU 和 CUDA 。先确定一下CUDA 版本 与 torch 版本是否一致
如果当前版本是一致的,解决办法如下。
二、解决办法
import torch
print(torch.cuda.is_available())
torch.cuda.current_device()
torch.cuda._initialized = True