Huggingface 节省标记器

Posted

技术标签:

【中文标题】Huggingface 节省标记器【英文标题】:Huggingface saving tokenizer 【发布时间】:2021-02-09 11:59:33 【问题描述】:

我正在尝试将标记器保存在 huggingface 中,以便以后可以从不需要访问互联网的容器中加载它。

BASE_MODEL = "distilbert-base-multilingual-cased"
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
tokenizer.save_vocabulary("./models/tokenizer/")
tokenizer2 = AutoTokenizer.from_pretrained("./models/tokenizer/")

但是,最后一行给出了错误:

OSError: Can't load config for './models/tokenizer3/'. Make sure that:

- './models/tokenizer3/' is a correct model identifier listed on 'https://huggingface.co/models'

- or './models/tokenizer3/' is the correct path to a directory containing a config.json file

变形金刚版本:3.1.0

How to load the saved tokenizer from pretrained model in Pytorch 很遗憾没有帮助。

编辑 1

感谢@ashwin 在下面的回答,我尝试了save_pretrained,但出现以下错误:

OSError: Can't load config for './models/tokenizer/'. Make sure that:

- './models/tokenizer/' is a correct model identifier listed on 'https://huggingface.co/models'

- or './models/tokenizer/' is the correct path to a directory containing a config.json file

tokenizer 文件夹的内容如下:

我尝试将tokenizer_config.json 重命名为config.json,然后出现错误:

ValueError: Unrecognized model in ./models/tokenizer/. Should have a `model_type` key in its config.json, or contain one of the following strings in its name: retribert, t5, mobilebert, distilbert, albert, camembert, xlm-roberta, pegasus, marian, mbart, bart, reformer, longformer, roberta, flaubert, bert, openai-gpt, gpt2, transfo-xl, xlnet, xlm, ctrl, electra, encoder-decoder

【问题讨论】:

【参考方案1】:

save_vocabulary(),仅保存分词器的词汇文件(BPE 令牌列表)。

要保存整个分词器,您应该使用save_pretrained()

因此,如下:

BASE_MODEL = "distilbert-base-multilingual-cased"
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
tokenizer.save_pretrained("./models/tokenizer/")
tokenizer2 = DistilBertTokenizer.from_pretrained("./models/tokenizer/")

编辑:

不知为何: 而不是

tokenizer2 = AutoTokenizer.from_pretrained("./models/tokenizer/")

使用

tokenizer2 = DistilBertTokenizer.from_pretrained("./models/tokenizer/")

有效。

【讨论】:

试过调查它。这似乎是一个错误。正如您所知道的那样,它保存了 tokenizer_config.json 并期望 config.json。 作为一种解决方法,由于您没有修改分词器,因此您使用from_pretrained 获取模型,然后保存模型。您还可以从保存的模型中加载分词器。这应该是一个暂定的解决方法。 请检查修改。 @sachinruk:以防万一您必须使用 AutoTokenizers,您必须保存相应的配置,如 here 所示。 @cronoik,我在另一篇文章中检查了你的答案。但是,我很想知道 github 上是否有任何提出的问题?我找不到与此问题有关的任何问题。【参考方案2】:

将“tokenizer_config.json”文件(由 save_pretrained() 函数创建的文件)重命名为“config.json”在我的环境中解决了同样的问题。

【讨论】:

【参考方案3】:

您需要将模型和分词器保存在同一目录中。 HuggingFace 实际上是在寻找模型的 config.json 文件,因此重命名 tokenizer_config.json 并不能解决问题

【讨论】:

以上是关于Huggingface 节省标记器的主要内容,如果未能解决你的问题,请参考以下文章

Huggingface AutoTokenizer 无法从本地路径加载

BERT HuggingFace 给出 NaN 损失

如何为拥抱脸重新下载标记器?

AutoTokenizer.from_pretrained 无法加载本地保存的预训练标记器 (PyTorch)

EncoderDecoderModel 转换解码器的分类器层

在 Huggingface BERT 模型之上添加密集层