- 问题:unexpected key “module.encoder.embedding.weight” in state_dict
- 原因:保存模型用
nn.DataParallel
,使用该方法保存模型会用module
,但你加载模型时未用nn.DataParallel
- 解决方案:
方法1:用nn.DataParallel
方法载入模型
方法2:创建一个新的不包含module
前缀的ordered dict
载入模型
例子:
# original saved file with DataParallel
state_dict = torch.load('myfile.pth')
# create new OrderedDict that does not contain 'module'.
from collections import OrderedDict
new_state_dict = OrderDict()
for k, v in state_dict.items():
name = k[7:] # remove 'module'
new_state_dict[name] = v
# load params
model.load_state_dict(new_state_dict)