【发布时间】:2020-12-18 05:59:06
【问题描述】:
我使用以下函数将预训练的 tf 模型转换为 pytorch。
def convert_tf_checkpoint_to_pytorch(*, tf_checkpoint_path, albert_config_file, pytorch_dump_path):
# Initialise PyTorch model
config = AlbertConfig.from_json_file(albert_config_file)
print("Building PyTorch model from configuration: {}".format(str(config)))
model = AlbertForPreTraining(config)
# Load weights from tf checkpoint
load_tf_weights_in_albert(model, config, tf_checkpoint_path)
# Save pytorch-model
print("Save PyTorch model to {}".format(pytorch_dump_path))
torch.save(model.state_dict(), pytorch_dump_path)
我正在通过以下方式加载转换后的模型和编码句子:
def vectorize_sentence(text):
albert_tokenizer = AlbertTokenizer.from_pretrained("albert-base-v2")
config = AlbertConfig.from_pretrained(config_path, output_hidden_states=True)
model = TFAlbertModel.from_pretrained(pytorch_dir, config=config, from_pt=True)
e = albert_tokenizer.encode(text, max_length=512)
model_input = tf.constant(e)[None, :] # Batch size 1
output = model(model_input)
v = [0] * 768
# generate sentence vectors by averaging the word vectors
for i in range(1, len(model_input[0]) - 1):
v = v + output[0][0][i].numpy()
vector = v/len(model_input[0])
return vector
但是在加载模型时,会出现警告:
PyTorch 模型 TFAlbertModel 的某些权重或缓冲区没有 从 TF 2.0 模型初始化并重新初始化: ['predictions.LayerNorm.bias', 'predictions.dense.weight', 'predictions.LayerNorm.weight','sop_classifier.classifier.bias', 'predictions.dense.bias','sop_classifier.classifier.weight', 'predictions.decoder.bias','predictions.bias', 'predictions.decoder.weight'] 你应该训练这个模型 一个下游任务,以便能够将其用于预测和推理。
谁能告诉我我做错了什么?警告是什么意思?我在 Transformers 的 github repo 上看到了 issue #5588。不知道我的问题是不是和这个一样。
【问题讨论】:
标签: python tensorflow machine-learning pytorch huggingface-transformers