【ALBERT】TensorFlow 模型转 PyTorch 模型

任务简介:

由于目前 PyTorch 使用者非常多,BERT 源码又是 Google 用 TensorFlow 写的,Google 开源的 BERT 预训练模型都是 TensorFlow 生成的 ckpt 模型文件, PyTorch 使用者需要将 ckpt 文件转换为 PyTorch 的 bin 模型文件。

本文以 albert 模型为例,将 albert 的 TensorFlow 模型转 PyTorch 模型。


albert 模型转换代码:

"""
@Author  : ChenXin
@Date    : 2021/10/23 1:26
@Brief   : TensorFlow 的模型转为 PyTorch 模型
"""
import argparse
import logging
import torch
from transformers import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert

logging.basicConfig(level=logging.INFO)


def convert_tf_checkpoint_to_pytorch(tf_checkpoint_path, albert_config_file, pytorch_dump_path):
    # 初始化 PyTorch 模型
    config = AlbertConfig.from_json_file(albert_config_file)
    print("Building PyTorch model from configuration: {}".format(str(config)))
    model = AlbertForPreTraining(config)

    # 从 tf 的 checkpoint 文件中加载模型权重
    load_tf_weights_in_albert(model, config, tf_checkpoint_path)

    # 保存 PyTorch 模型
    print("Save PyTorch model to {}".format(pytorch_dump_path))
    torch.save(model.state_dict(), pytorch_dump_path)


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    # 参数设置
    parser.add_argument("--tf_checkpoint_path", default='./resources/albert_base_zh/model.ckpt-best', type=str,
                        required=False, help="Path to the TensorFlow checkpoint path.")
    parser.add_argument("--albert_config_file", default='./resources/albert_base_zh/albert_config.json', type=str,
                        required=False,
                        help="The config json file corresponding to the pre-trained ALBERT model. \n""This specifies the model architecture.", )
    parser.add_argument("--pytorch_dump_path", default='./resources/albert_base_zh/pytorch_model.bin', type=str, required=False,
                        help="Path to the output PyTorch model.")

    args = parser.parse_args()
    convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)

输出:

生成了 PyTorch 模型
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值