问题描述
我正在使用 SentenceTransformers 库(此处:https://pypi.org/project/sentence-transformers/#pretrained-models)使用预训练模型 bert-base-nli-mean-tokens 创建句子嵌入。我有一个应用程序将部署到无法访问 Internet 的设备上。在这里,已经回答了,如何保存模型Download pre-trained BERT model locally。但是我一直坚持从本地保存的路径加载保存的模型。
('/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')
当我尝试将其加载到内存中时,使用
tokenizer = AutoTokenizer.from_pretrained(to_save_path)
我要了
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
解决方法
有很多方法可以解决这个问题:
- 假设您已经在本地(colab/notebook)训练了您的 BERT 基础模型,以便将其与 Huggingface AutoClass 一起使用,然后是模型(以及分词器、vocab.txt、配置、特殊标记和 tf /pytorch weights) 必须上传到 Huggingface。 here 提到了执行此操作的步骤。上传后,将使用您的用户名创建一个存储库,然后可以按如下方式访问模型:
from transformers import AutoTokenizer
from transformers import pipeline
tokenizer = AutoTokenizer.from_pretrained("<username>/<model-name>")
- 第二种方法是在本地使用经过训练的模型,这可以通过使用 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
- 第三种方法是直接使用 Huggingface 模型存储库中的 Sentence Transformers。
还有其他方法可以解决此问题,但这些方法可能会有所帮助。此外,此预训练模型列表可能help。