【问题标题】:Loading a converted pytorch model in huggingface transformers properly在拥抱脸变压器中正确加载转换后的 pytorch 模型
【发布时间】: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


    【解决方案1】:

    我觉得你可以试试

    model = AlbertModel.from_pretrained
    

    而不是

    model = TFAlbertModel.from_pretrained
    

    在 VectorizeSentence 定义中。

    AlbertModel是pytorch格式模型的类名,TFAlbertModel是tensorflow格式模型的类名。

    我不确定load_tf_weights_in_albert() 究竟做了什么,但我认为一旦你完成了你的模型就是pytorch 格式。

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 2021-02-16
      • 2021-08-16
      • 2021-12-12
      • 2021-10-05
      • 2020-06-17
      • 2021-11-02
      • 2021-08-08
      • 2020-11-06
      相关资源
      最近更新 更多