如何检查 tokenizer/model 是否已保存
How do I check if a tokenizer/model is already saved
我正在将 HuggingFace Transformers 与 PyTorch 结合使用。我的做法是下载一个预训练好的模型,保存在本地项目文件夹中。
这样做的时候,我看到本地保存了.bin文件,代表型号。但是,我还下载并保存了一个分词器,但我看不到任何关联文件。
那么,如何在下载前检查分词器是否保存在本地?其次,除了通常的 os.path.isfile(...)
检查之外,有没有其他更好的方法可以在下载之前优先考虑从给定位置使用本地副本?
我过去曾为此目的使用过此代码。您可以根据自己的设置进行调整。
from tokenizers import BertWordPieceTokenizer
import urllib
from transformers import AutoTokenizer
def download_vocab_files_for_tokenizer(tokenizer, model_type, output_path, vocab_exist_bool=False):
vocab_files_map = tokenizer.pretrained_vocab_files_map
vocab_files = {}
for resource in vocab_files_map.keys():
download_location = vocab_files_map[resource][model_type]
f_path = os.path.join(output_path, os.path.basename(download_location))
if vocab_exist_bool != True:
urllib.request.urlretrieve(download_location, f_path)
vocab_files[resource] = f_path
return vocab_files
model_type = 'bert-base-uncased'
#initialized tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_type)
#will do this part later
#retrieve vocab file if it's not there
output_path = os.getcwd()+'/vocab_files/'
vocab_file_name = 'bert-base-uncased-vocab.txt'
vocab_exist_bool = os.path.exists(output_path + vocab_file_name)
#get vocab files
vocab_files = download_vocab_files_for_tokenizer(tokenizer, model_type, output_path, vocab_exist_bool=vocab_exist_bool)
我正在将 HuggingFace Transformers 与 PyTorch 结合使用。我的做法是下载一个预训练好的模型,保存在本地项目文件夹中。
这样做的时候,我看到本地保存了.bin文件,代表型号。但是,我还下载并保存了一个分词器,但我看不到任何关联文件。
那么,如何在下载前检查分词器是否保存在本地?其次,除了通常的 os.path.isfile(...)
检查之外,有没有其他更好的方法可以在下载之前优先考虑从给定位置使用本地副本?
我过去曾为此目的使用过此代码。您可以根据自己的设置进行调整。
from tokenizers import BertWordPieceTokenizer
import urllib
from transformers import AutoTokenizer
def download_vocab_files_for_tokenizer(tokenizer, model_type, output_path, vocab_exist_bool=False):
vocab_files_map = tokenizer.pretrained_vocab_files_map
vocab_files = {}
for resource in vocab_files_map.keys():
download_location = vocab_files_map[resource][model_type]
f_path = os.path.join(output_path, os.path.basename(download_location))
if vocab_exist_bool != True:
urllib.request.urlretrieve(download_location, f_path)
vocab_files[resource] = f_path
return vocab_files
model_type = 'bert-base-uncased'
#initialized tokenizer
tokenizer = AutoTokenizer.from_pretrained(model_type)
#will do this part later
#retrieve vocab file if it's not there
output_path = os.getcwd()+'/vocab_files/'
vocab_file_name = 'bert-base-uncased-vocab.txt'
vocab_exist_bool = os.path.exists(output_path + vocab_file_name)
#get vocab files
vocab_files = download_vocab_files_for_tokenizer(tokenizer, model_type, output_path, vocab_exist_bool=vocab_exist_bool)