使用Huggingface变形金刚从磁盘加载预训练的模型

时间:2020-09-21 23:23:26

标签: huggingface-transformers

从文档for from_pretrained中,我了解到我不必每次都下载预训练的向量,我可以使用以下语法将其保存并从磁盘加载:

  - a path to a `directory` containing vocabulary files required by the tokenizer, for instance saved using the :func:`~transformers.PreTrainedTokenizer.save_pretrained` method, e.g.: ``./my_model_directory/``.
  - (not applicable to all derived classes, deprecated) a path or url to a single saved vocabulary file if and only if the tokenizer only requires a single vocabulary file (e.g. Bert, XLNet), e.g.: ``./my_model_directory/vocab.txt``.

所以,我去了模型中心:

我找到了想要的模型:

我从他们提供给该存储库的链接中下载了该文件:

使用屏蔽语言建模的英语预训练模型 (MLM)目标。它在本文中进行了介绍,并于2007年首次发布 该存储库。此模型区分大小写:有所作为 在英语和英语之间。

存储在以下位置:

  /my/local/models/cased_L-12_H-768_A-12/

其中包含:

 ./
 ../
 bert_config.json
 bert_model.ckpt.data-00000-of-00001
 bert_model.ckpt.index
 bert_model.ckpt.meta
 vocab.txt

所以,现在我有以下内容:

  PATH = '/my/local/models/cased_L-12_H-768_A-12/'
  tokenizer = BertTokenizer.from_pretrained(PATH, local_files_only=True)

我收到此错误:

>           raise EnvironmentError(msg)
E           OSError: Can't load config for '/my/local/models/cased_L-12_H-768_A-12/'. Make sure that:
E           
E           - '/my/local/models/cased_L-12_H-768_A-12/' is a correct model identifier listed on 'https://huggingface.co/models'
E           
E           - or '/my/local/models/cased_L-12_H-768_A-12/' is the correct path to a directory containing a config.json file

类似地,当我直接链接到config.json时:

  PATH = '/my/local/models/cased_L-12_H-768_A-12/bert_config.json'
  tokenizer = BertTokenizer.from_pretrained(PATH, local_files_only=True)

        if state_dict is None and not from_tf:
            try:
                state_dict = torch.load(resolved_archive_file, map_location="cpu")
            except Exception:
                raise OSError(
>                   "Unable to load weights from pytorch checkpoint file. "
                    "If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True. "
                )
E               OSError: Unable to load weights from pytorch checkpoint file. If you tried to load a PyTorch model from a TF 2.0 checkpoint, please set from_tf=True.

要使用我的本地预训练模型,我应该做些什么来改变拥抱面?

更新以处理评论

YOURPATH = '/somewhere/on/disk/'

name = 'transfo-xl-wt103'
tokenizer = TransfoXLTokenizerFast(name)
model = TransfoXLModel.from_pretrained(name)
tokenizer.save_pretrained(YOURPATH)
model.save_pretrained(YOURPATH)

>>> Please note you will not be able to load the save vocabulary in Rust-based TransfoXLTokenizerFast as they don't share the same structure.
('/somewhere/on/disk/vocab.bin', '/somewhere/on/disk/special_tokens_map.json', '/somewhere/on/disk/added_tokens.json')

因此所有内容都保存了,但是....

YOURPATH = '/somewhere/on/disk/'
TransfoXLTokenizerFast.from_pretrained('transfo-xl-wt103', cache_dir=YOURPATH, local_files_only=True)

    "Cannot find the requested files in the cached path and outgoing traffic has been"
ValueError: Cannot find the requested files in the cached path and outgoing traffic has been disabled. To enable model look-ups and downloads online, set 'local_files_only' to False.

3 个答案:

答案 0 :(得分:1)

文件相对于模型文件夹位于何处?我认为它必须是相对路径而不是绝对路径。因此,如果您要编写代码的文件位于'my/local/'中,那么您的代码应如下所示:

PATH = 'models/cased_L-12_H-768_A-12/'
tokenizer = BertTokenizer.from_pretrained(PATH, local_files_only=True)

您只需要指定所有文件所在的文件夹,而不是直接指定文件。我认为PATH绝对是一个问题。尝试更改“ /”和“ \”的斜线样式,它们在不同的操作系统中是不同的。也可以尝试使用“。”,例如./models/cased_L-12_H-768_A-12/等。

答案 1 :(得分:1)

我也有同样的需求,刚刚在我的 Linux 机器上使用 Tensorflow 实现了这个功能,所以我想分享一下。

我的代码环境的 requirements.txt 文件:

tensorflow==2.2.0
Keras==2.4.3
scikit-learn==0.23.1
scipy==1.4.1
numpy==1.18.1
opencv-python==4.5.1.48
seaborn==0.11.1
tensorflow-hub==0.12.0
nltk==3.6.2
tqdm==4.60.0
transformers==4.6.0
ipywidgets==7.6.3

我使用的是 Python 3.6。

我访问了 this 站点,该站点显示了我想要的特定拥抱脸模型的目录树。我碰巧想要 uncased 模型,但这些步骤对于您的 cased 版本应该是相似的。另请注意,我的链接指向此模型的一个非常具体的提交,只是为了可重复性 - 当有人阅读此内容时,很可能会有更新的版本。

我手动下载(或必须复制/粘贴到记事本++,因为在某些情况下,下载按钮会将我带到 txt/json 的原始版本......奇怪......)以下文件:

  • config.json
  • tf_model.h5
  • tokenizer_config.json
  • tokenizer.json
  • vocab.txt

注意:我再次使用的是 Tensorflow,所以我没有下载 Pytorch 权重。如果您使用 Pytorch,您可能需要下载这些权重而不是 tf_model.h5 文件。

然后我将这些文件放在我的 Linux 机器上的这个目录中:

/opt/word_embeddings/bert-base-uncased/

使用快速 ls -la 确保至少对所有这些文件都有读取权限可能是一个好主意(我对每个文件的权限是 -rw-r--r--)。我还拥有对父目录(上面列出的目录)的执行权限,因此人们可以 cd 到此目录。

从那里,我可以像这样加载模型:

分词器:

# python
from transformers import BertTokenizer
# tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
tokenizer = BertTokenizer.from_pretrained("/opt/word_embeddings/bert-base-uncased/")

层/模型权重:

# python
from transformers import TFAutoModel
# bert = TFAutoModel.from_pretrained("bert-base-uncased")
bert = TFAutoModel.from_pretrained("/opt/word_embeddings/bert-base-uncased/")

答案 2 :(得分:0)

您可以使用 simpletransformers 库。查看链接以获取更详细的说明。

    model = ClassificationModel(
    "bert", "dir/your_path"
)

这里我以分类模型为例。您可以将它用于许多其他任务以及问答等。