【问题标题】:RuntimeError: Error(s) in loading state_dict for BertModelRuntimeError:为 BertModel 加载 state_dict 时出错
【发布时间】:2023-03-12 00:10:01
【问题描述】:

我使用拥抱人脸转换器库对 BERT 模型进行微调,并在云端的 GPU 中对其进行训练。然后我保存模型和标记器,如下所示:

model.save_pretrained('/saved_model/')
torch.save(best_model.state_dict(), '/saved_model/model')
tokenizer.save_pretrained('/saved_model/')

我在我的电脑中下载了saved_model 目录。然后我在我的计算机中加载如下所示的模型/标记器

import torch
from transformers import *
tokenizer = BertTokenizer.from_pretrained('./saved_model/')
config = BertConfig('./saved_model/config.json')
model = BertModel(config)
model.load_state_dict(torch.load('./saved_model/pytorch_model.bin', map_location=torch.device('cpu')))
model.eval()

但是对于model.load_state_dict 行,它会抛出以下错误

RuntimeError: Error(s) in loading state_dict for BertModel:
    Missing key(s) in state_dict:

它列出了 state_dict 中明显缺失的一堆键。

我是 pytorch 的新手,不知道发生了什么。很可能我没有以正确的方式保存模型。

请提出建议。

【问题讨论】:

    标签: machine-learning deep-learning pytorch transfer-learning


    【解决方案1】:

    您可能知道,PyTorch 模块的state_dictOrderedDict。当您尝试从 state_dict 加载模块的权重时,它会抱怨缺少键,这意味着 state_dict 不包含这些键。在这种情况下,我建议采取以下措施。

    1. 检查state_dict 中存在哪些键。只保存密钥的子集听起来是不可能的。
    2. 另外,请确保加载了正确的配置。否则,如果您训练的 BertModel 和您要为其加载权重的新 BertModel 不同,那么您将收到此错误。
    3. 最后,如果您的代码通过上述两种情况,然后保存模型,请确保将所有层的参数保存在文件中。声明 torch.save(best_model.state_dict(), '/saved_model/model') 对我来说看起来不错,但请确保 best_model.state_dict() 包含所有预期的键。

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 2020-11-10
      • 2020-09-18
      • 1970-01-01
      • 2021-02-21
      • 2021-11-27
      • 2022-10-19
      • 1970-01-01
      • 2020-04-10
      相关资源
      最近更新 更多