问题

gpu训练的模型,使用cpu测试时遇到:

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='cpu' to map your storages to the CPU.

解决

此时改为:

torch.load("0.9472_0048.weights",map_location='cpu')

就可以解决问题了。

方便查阅,整理:

假设我们只保存了模型的参数(model.state_dict())到文件名为modelparameters.pth, model = Net()

  1. cpu -> cpu或者gpu -> gpu:
checkpoint = torch.load('modelparameters.pth')

model.load_state_dict(checkpoint)
  1. cpu -> gpu 1
torch.load('modelparameters.pth', map_location=lambda storage, loc: storage.cuda(1))
  1. gpu 1 -> gpu 0
torch.load('modelparameters.pth', map_location={'cuda:1':'cuda:0'})
  1. gpu -> cpu
torch.load('modelparameters.pth', map_location=lambda storage, loc: storage)
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐