Bert模型导出为onnx和pb格式

def export_bert_onnx():
    from transformers import AutoModel, AutoConfig, AutoTokenizer

    path = '../data_path/models/roberta_hf'
    bert_model = AutoModel.from_pretrained(path)
    config = AutoConfig.from_pretrained(path)
    tokenizer = AutoTokenizer.from_pretrained(path)

    from transformers.onnx.features import FeaturesManager

    onnx_config = FeaturesManager._SUPPORTED_MODEL_TYPE['bert']['sequence-classification'](config)

    dummy_inputs = onnx_config.generate_dummy_inputs(tokenizer, framework='pt')
    input_ids = dummy_inputs['input_ids']
    attention_masks = dummy_inputs['attention_mask']
    token_type_ids = dummy_inputs['token_type_ids']
    import torch

    input_names = ["input_ids", "attention_masks", "token_type_ids"]
    output_names = ["output"]
    torch.onnx.export(bert_model, (input_ids, attention_masks, token_type_ids), 'bert_model.onnx', verbose=True,
                      input_names=input_names,
                      output_names=output_names, opset_version=10)


def export_pb(onnx_path):
    from onnx_tf.backend import prepare
    import onnx
    import os

    target_path = os.path.dirname(onnx_path)

    print("加载模型:", onnx_path)
    model = onnx.load(onnx_path)

    print('导出pb模型:', target_path)
    tf_model = prepare(model)
    tf_model.export_graph(r'./pb/1')
    print("导出pb完成!")

if __name__ == '__main__':
    # export_bert_onnx()
    export_pb('bert_model.onnx')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值