【问题标题】:How do I save my fine tuned bert for sequence classification model tokenizer and config?如何为序列分类模型标记器和配置保存微调的 bert?
【发布时间】:2021-02-04 18:28:35
【问题描述】:

我想在文件夹中像这样微调后保存所有训练好的模型:

config.json
added_token.json
special_tokens_map.json
tokenizer_config.json
vocab.txt
pytorch_model.bin

我只能保存 pytorch_model.bin,但我无法保存其他详细信息,如何保存模型的所有配置、标记器等?

我用过

tokenizer.save_pretrained('results/tokenizer/')

但出现错误

AttributeError: 'BertTokenizer' object has no attribute 'save_pretrained'

我通过以下代码保存了二进制模型文件

torch.save(model_to_save.state_dict(), output_model_file)

但是当我用它来保存分词器或配置文件时,我无法做到这一点,因为我不知道应该保存分词器的文件扩展名,而且我无法访问 cofig 文件, 有什么办法可以保存我模型的所有细节吗? 提前感谢

【问题讨论】:

    标签: model save bert-language-model


    【解决方案1】:

    我不知道您如何定义标记器以及将“标记器”变量分配给什么,但这可以解决您的问题:

    from transformers import AutoTokenizer
    
    tokenizer = AutoTokenizer.from_pretrained(...)
    tokenizer.save_pretrained('results/tokenizer/')
    

    这将保存有关标记器的所有内容,并使用 your_model.save_pretrained('results/tokenizer/') 你得到:

    config.json
    added_token.json
    special_tokens_map.json
    tokenizer_config.json
    vocab.txt
    pytorch_model.bin
    

    评论后更新:

    如果您使用的是from pytorch_pretrained_bert import BertForSequenceClassification,则该属性不可用(您可以从code 中看到)。

    你应该做的是使用transformers,它也集成了这个功能。

    例子:

    from transformers import BertForSequenceClassification
    
    model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
    model.save_pretrained('results/tokenizer/')
    

    另一种解决方案是使用AutoClasses

    【讨论】:

    • 我试过你的代码 your_model.save_pretrained('results/tokenizer/') 但出现这个错误 torch.nn.modules.module.ModuleAttributeError: 'BertForSequenceClassification' object has no attribute 'save_pretrained'
    • 是的,当然,现在我尝试更新我的答案,使其更完整,以便更好地解释
    • 我尝试了您更新的解决方案,但出现错误 torch.nn.modules.module.ModuleAttributeError: 'BertForSequenceClassification' object has no attribute 'save_pretrained'
    • 您没有使用我更新答案中的代码。您将继续使用pytorch_pretrained_bert 而不是transformers。请复制并粘贴我的最后三行,您会看到它有效。
    • 鉴于我对模型进行了微调,并且我想保存微调后的版本而不是导入的版本,我可以使用此代码保存模型的 .bin 文件 model_to_save = model.module if hasattr( model, 'module') else model # 只保存模型本身 output_model_file = os.path.join(args.output_dir, "pytorch_model_task.bin") 但我无法保存其他配置文件
    猜你喜欢
    • 2021-02-21
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2021-07-22
    • 2021-10-31
    • 1970-01-01
    • 2020-06-03
    • 2020-09-09
    相关资源
    最近更新 更多