如何将 HuggingFace 的 Seq2seq 模型转换为 onnx 格式

how to convert HuggingFace's Seq2seq models to onnx format

我正在尝试将 HuggingFace 的 t运行sformers 模型中的 Pegasus 新闻编辑室转换为 ONNX 格式。我遵循了 Huggingface 发布的 this 指南。安装先决条件后,我 运行 此代码:

!rm -rf onnx/
from pathlib import Path
from transformers.convert_graph_to_onnx import convert

convert(framework="pt", model="google/pegasus-newsroom", output=Path("onnx/google/pegasus-newsroom.onnx"), opset=11)

并得到这些错误:

ValueError                                Traceback (most recent call last)
<ipython-input-9-3b37ed1ceda5> in <module>()
      3 from transformers.convert_graph_to_onnx import convert
      4 
----> 5 convert(framework="pt", model="google/pegasus-newsroom", output=Path("onnx/google/pegasus-newsroom.onnx"), opset=11)
      6 
      7 

6 frames
/usr/local/lib/python3.6/dist-packages/transformers/models/pegasus/modeling_pegasus.py in forward(self, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, head_mask, encoder_head_mask, past_key_values, inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict)
    938             input_shape = inputs_embeds.size()[:-1]
    939         else:
--> 940             raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
    941 
    942         # past_key_values_length

ValueError: You have to specify either decoder_input_ids or decoder_inputs_embeds

我以前从未见过这个错误。有什么想法吗?

Pegasus 是 seq2seq model, you can't directly convert a seq2seq model (encoder-decoder model) using this method. The guide 用于 BERT 的编码器模型。任何only encoder或only decoder transformer模型都可以用这种方法转换。

要转换 seq2seq 模型(编码器-解码器),您必须将它们拆分并分别转换,将编码器转换为 onnx,将解码器转换为 onnx。你可以关注 this guide(这是为 T5 完成的,它也是 seq2seq 型号)

为什么会出现此错误?

正在转换 PyTorch to onnx

_ = torch.onnx._export(
                        model,
                        dummy_input,
                        ...
                       )

您需要为编码器和解码器提供一个虚拟变量 separately。默认情况下,使用此方法进行转换时,它会为编码器提供虚拟变量。由于这种转换方法不接受这个 seq2seq 模型的解码器,它不会给解码器一个虚拟变量,你会得到上面的错误。 ValueError: You have to specify either decoder_input_ids or decoder_inputs_embeds