在本地下载预训练的句子转换器模型

neh*_*ore 15 word-embedding bert-language-model huggingface-tokenizers sentence-transformers

我正在使用 SentenceTransformers 库(此处: https: //pypi.org/project/sentence-transformers/#pretrained-models)使用预训练模型 bert-base-nli-mean-tokens 创建句子嵌入。我有一个应用程序将部署到无法访问互联网的设备。到这里,已经回答了,如何保存模型下载预训练的BERT模型到本地。然而我一直坚持从本地保存的路径加载保存的模型。

当我尝试使用上述技术保存模型时,这些是输出文件:

('/bert-base-nli-mean-tokens/tokenizer_config.json',
 '/bert-base-nli-mean-tokens/special_tokens_map.json',
 '/bert-base-nli-mean-tokens/vocab.txt',
 '/bert-base-nli-mean-tokens/added_tokens.json')
Run Code Online (Sandbox Code Playgroud)

当我尝试将其加载到内存中时,使用

tokenizer = AutoTokenizer.from_pretrained(to_save_path)
Run Code Online (Sandbox Code Playgroud)

我越来越

Can't load config for '/bert-base-nli-mean-tokens'. Make sure that:

- '/bert-base-nli-mean-tokens' is a correct model identifier listed on 'https://huggingface.co/models'

- or '/bert-base-nli-mean-tokens' is the correct path to a directory containing a config.json 
Run Code Online (Sandbox Code Playgroud)

小智 28

您可以像这样下载并加载模型

from sentence_transformers import SentenceTransformer
modelPath = "local/path/to/model

model = SentenceTransformer('bert-base-nli-stsb-mean-tokens')
model.save(modelPath)
model = SentenceTransformer(modelPath)
Run Code Online (Sandbox Code Playgroud)

这对我有用。您可以查看 SBERT 文档以获取 SentenceTransformer 类的模型详细信息 [此处][1]

[1]: https: //www.sbert.net/docs/package_reference/SentenceTransformer.html# :~:text=class,可选%5Bstr%5D%20%3D%20None )


小智 3

有很多方法可以解决这个问题:

  • 假设您已经在本地(colab/notebook)训练了 BERT 基本模型,为了将其与Huggingface AutoClass一起使用,则该模型(以及分词器、vocab.txt、配置、特殊标记和 tf/pytorch 权重)必须上传至 Huggingface。此处提到了执行此操作的步骤。上传后,将使用您的用户名创建一个存储库,然后可以按如下方式访问模型:
from transformers import AutoTokenizer
from transformers import pipeline

tokenizer = AutoTokenizer.from_pretrained("<username>/<model-name>")
Run Code Online (Sandbox Code Playgroud)
  • 第二种方法是在本地使用经过训练的模型,这可以通过使用pipelines来完成。以下是如何在本地为您的用例使用经过训练(和保存)的模型的示例(给出了我本地训练的 QA 模型的示例):
from transformers import AutoModelForQuestionAnswering,AutoTokenizer,pipeline
nlp_QA=pipeline('question-answering',model='./abhilash1910/distilbert-squadv1',tokenizer='./abhilash1910/distilbert-squadv1')
QA_inp={
    'question': 'What is the fund price of Huggingface in NYSE?',
    'context': 'Huggingface Co. has a total fund price of $19.6 million dollars'
}
result=nlp_QA(QA_inp)
result
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以解决此问题,但这些可能会有所帮助。此外,这个预训练模型列表可能会有所帮助