原文链接:https://blog.csdn.net/qq_39129717/article/details/124613026
pytorch将模型加载到多gpu上的时候,会用到:

model = torch.nn.DataParallel(model).cuda()
#或者
model = torch.nn.DataParallel(model, device_ids=[1, 2, 3])

多GPU在直接保存模型的时候,如果直接:

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

加载后的模型参数每个都会带有 module

如果使用strict=False的加载方式,很有可能会使测试结果不同:

model.load_state_dict(weights_dict, strict=False)
解决方法1:

在保存模型的时候使用model.module保存:

torch.save(model.module.state_dict(), save_dict)

加载的时候可直接加载,比如:

checkpoint = torch.load('./weight/BigDtat_BLoss6_0.83.pth', map_location='cpu')
model.load_state_dict(checkpoint)
model.cuda()
解决方法2:

如果模型已经保存,将模型参数字典中的module替换为空字串进行加载:

checkpoint = torch.load(weight_pth, map_location='cpu')
model.load_state_dict({k.replace('module.', ''): v for k, v in checkpoint.items()})
model.load_state_dict(checkpoint)
model = model.cuda()

不要使用model.load_state_dict(weights_dict, strict=False)这种方式,会造成预测预测结果发生变换。

Logo

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

更多推荐