• Tutorials >
  • (optional) Exporting a Model from PyTorch to ONNX and Running it using ONNX Runtime
Shortcuts

(可选)将模型从PyTorch导出到ONNX并使用ONNX Runtime运行

创建于:2019年7月17日 | 最后更新:2024年7月17日 | 最后验证:2024年11月5日

注意

截至 PyTorch 2.1,有两个版本的 ONNX 导出器。

  • torch.onnx.dynamo_export 是基于 PyTorch 2.0 发布的 TorchDynamo 技术的最新(仍在测试阶段)导出器。

  • torch.onnx.export 基于 TorchScript 后端,自 PyTorch 1.2.0 起可用。

在本教程中,我们描述了如何使用TorchScript的torch.onnx.export ONNX导出器将PyTorch中定义的模型转换为ONNX格式。

导出的模型将使用ONNX Runtime执行。 ONNX Runtime是一个专注于性能的ONNX模型引擎, 它可以在多个平台和硬件(Windows、Linux、Mac以及CPU和GPU)上高效地进行推理。 ONNX Runtime已被证明可以显著提高多个模型的性能,如这里所述。

对于本教程,您需要安装ONNXONNX Runtime。您可以通过以下方式获取ONNX和ONNX Runtime的二进制构建:

%%bash
pip install onnx onnxruntime

ONNX Runtime 建议使用 PyTorch 的最新稳定运行时。

# Some standard imports
import numpy as np

from torch import nn
import torch.utils.model_zoo as model_zoo
import torch.onnx

超分辨率是一种提高图像、视频分辨率的方法,广泛应用于图像处理或视频编辑中。在本教程中,我们将使用一个小型的超分辨率模型。

首先,让我们在PyTorch中创建一个SuperResolution模型。 该模型使用了在“Real-Time Single Image and Video Super-Resolution Using an Efficient Sub-Pixel Convolutional Neural Network” - Shi et al中描述的高效子像素卷积层, 用于通过放大因子提高图像的分辨率。 该模型期望图像的YCbCr的Y分量作为输入, 并输出超分辨率下的放大Y分量。

The model 直接来自 PyTorch 的示例,未作修改:

# Super Resolution model definition in PyTorch
import torch.nn as nn
import torch.nn.init as init


class SuperResolutionNet(nn.Module):
    def __init__(self, upscale_factor, inplace=False):
        super(SuperResolutionNet, self).__init__()

        self.relu = nn.ReLU(inplace=inplace)
        self.conv1 = nn.Conv2d(1, 64, (5, 5), (1, 1), (2, 2))
        self.conv2 = nn.Conv2d(64, 64, (3, 3), (1, 1), (1, 1))
        self.conv3 = nn.Conv2d(64, 32, (3, 3), (1, 1), (1, 1))
        self.conv4 = nn.Conv2d(32, upscale_factor ** 2, (3, 3), (1, 1), (1, 1))
        self.pixel_shuffle = nn.PixelShuffle(upscale_factor)

        self._initialize_weights()

    def forward(self, x):
        x = self.relu(self.conv1(x))
        x = self.relu(self.conv2(x))
        x = self.relu(self.conv3(x))
        x = self.pixel_shuffle(self.conv4(x))
        return x

    def _initialize_weights(self):
        init.orthogonal_(self.conv1.weight, init.calculate_gain('relu'))
        init.orthogonal_(self.conv2.weight, init.calculate_gain('relu'))
        init.orthogonal_(self.conv3.weight, init.calculate_gain('relu'))
        init.orthogonal_(self.conv4.weight)

# Create the super-resolution model by using the above model definition.
torch_model = SuperResolutionNet(upscale_factor=3)

通常,你现在会训练这个模型;然而,对于本教程,我们将下载一些预训练的权重。请注意,这个模型并未完全训练以达到良好的准确性,此处仅用于演示目的。

在导出模型之前,调用torch_model.eval()torch_model.train(False)将模型切换到推理模式是很重要的。这是必要的,因为像dropout或batchnorm这样的操作符在推理和训练模式下的行为是不同的。

# Load pretrained model weights
model_url = 'https://s3.amazonaws.com/pytorch/test_data/export/superres_epoch100-44c6958e.pth'
batch_size = 64    # just a random number

# Initialize model with the pretrained weights
map_location = lambda storage, loc: storage
if torch.cuda.is_available():
    map_location = None
torch_model.load_state_dict(model_zoo.load_url(model_url, map_location=map_location))

# set the model to inference mode
torch_model.eval()

在PyTorch中导出模型可以通过追踪或脚本化来实现。本教程将使用通过追踪导出的模型作为示例。要导出模型,我们调用torch.onnx.export()函数。这将执行模型,并记录用于计算输出的操作符的追踪。因为export会运行模型,所以我们需要提供一个输入张量x。只要类型和大小正确,其中的值可以是随机的。请注意,除非指定为动态轴,否则输入大小将在导出的ONNX图中固定为所有输入的维度。在这个例子中,我们导出了一个输入为batch_size 1的模型,但随后在torch.onnx.export()dynamic_axes参数中将第一个维度指定为动态。因此,导出的模型将接受大小为[batch_size, 1, 224, 224]的输入,其中batch_size可以是可变的。

要了解更多关于PyTorch导出接口的详细信息,请查看 torch.onnx 文档

# Input to the model
x = torch.randn(batch_size, 1, 224, 224, requires_grad=True)
torch_out = torch_model(x)

# Export the model
torch.onnx.export(torch_model,               # model being run
                  x,                         # model input (or a tuple for multiple inputs)
                  "super_resolution.onnx",   # where to save the model (can be a file or file-like object)
                  export_params=True,        # store the trained parameter weights inside the model file
                  opset_version=10,          # the ONNX version to export the model to
                  do_constant_folding=True,  # whether to execute constant folding for optimization
                  input_names = ['input'],   # the model's input names
                  output_names = ['output'], # the model's output names
                  dynamic_axes={'input' : {0 : 'batch_size'},    # variable length axes
                                'output' : {0 : 'batch_size'}})

我们还计算了torch_out,即模型的输出,我们将使用它来验证我们导出的模型在ONNX Runtime中运行时计算的值是否相同。

但在使用ONNX Runtime验证模型的输出之前,我们将使用ONNX API检查ONNX模型。 首先,onnx.load("super_resolution.onnx")将加载保存的模型并输出一个onnx.ModelProto结构(一种用于捆绑机器学习模型的顶级文件/容器格式。更多信息请参阅onnx.proto文档)。 然后,onnx.checker.check_model(onnx_model)将验证模型的结构并确认模型具有有效的模式。 通过检查模型的版本、图的结构以及节点及其输入和输出来验证ONNX图的有效性。

import onnx

onnx_model = onnx.load("super_resolution.onnx")
onnx.checker.check_model(onnx_model)

现在让我们使用ONNX Runtime的Python API来计算输出。 这部分通常可以在单独的进程或另一台机器上完成,但我们将继续在同一进程中,以便我们可以验证ONNX Runtime和PyTorch为网络计算的值是否相同。

为了使用ONNX Runtime运行模型,我们需要为模型创建一个推理会话,并选择配置参数(这里我们使用默认配置)。 一旦会话创建完成,我们使用run() API评估模型。 此调用的输出是一个列表,包含由ONNX Runtime计算的模型输出。

import onnxruntime

ort_session = onnxruntime.InferenceSession("super_resolution.onnx", providers=["CPUExecutionProvider"])

def to_numpy(tensor):
    return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()

# compute ONNX Runtime output prediction
ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}
ort_outs = ort_session.run(None, ort_inputs)

# compare ONNX Runtime and PyTorch results
np.testing.assert_allclose(to_numpy(torch_out), ort_outs[0], rtol=1e-03, atol=1e-05)

print("Exported model has been tested with ONNXRuntime, and the result looks good!")

我们应该看到PyTorch和ONNX Runtime运行的输出在给定的精度下(rtol=1e-03atol=1e-05)在数值上是匹配的。 顺便说一下,如果它们不匹配,那么ONNX导出器中存在问题,所以在这种情况下请与我们联系。

模型之间的时间比较

由于ONNX模型优化了推理速度,因此在ONNX模型上运行相同数据而不是在原生pytorch模型上运行,应该可以提高最多2倍的速度。批量大小越大,改进越明显。

import time

x = torch.randn(batch_size, 1, 224, 224, requires_grad=True)

start = time.time()
torch_out = torch_model(x)
end = time.time()
print(f"Inference of Pytorch model used {end - start} seconds")

ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(x)}
start = time.time()
ort_outs = ort_session.run(None, ort_inputs)
end = time.time()
print(f"Inference of ONNX model used {end - start} seconds")

使用ONNX Runtime在图像上运行模型

到目前为止,我们已经从PyTorch导出了一个模型,并展示了如何使用虚拟张量作为输入在ONNX Runtime中加载和运行它。

在本教程中,我们将使用一张广泛使用的著名猫图片,如下所示

cat

首先,让我们加载图像,使用标准的PIL Python库对其进行预处理。请注意,这种预处理是训练/测试神经网络时处理数据的标准做法。

我们首先调整图像大小以适应模型输入的大小(224x224)。 然后我们将图像分解为其Y、Cb和Cr分量。 这些分量代表灰度图像(Y),以及 蓝色差异(Cb)和红色差异(Cr)色度分量。 由于Y分量对人眼更敏感,我们 对这个分量感兴趣,我们将对其进行转换。 提取Y分量后,我们将其转换为张量, 这将是我们模型的输入。

from PIL import Image
import torchvision.transforms as transforms

img = Image.open("./_static/img/cat.jpg")

resize = transforms.Resize([224, 224])
img = resize(img)

img_ycbcr = img.convert('YCbCr')
img_y, img_cb, img_cr = img_ycbcr.split()

to_tensor = transforms.ToTensor()
img_y = to_tensor(img_y)
img_y.unsqueeze_(0)

现在,作为下一步,让我们获取表示灰度调整大小的猫图像的张量,并按照之前的解释在ONNX Runtime中运行超分辨率模型。

ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(img_y)}
ort_outs = ort_session.run(None, ort_inputs)
img_out_y = ort_outs[0]

此时,模型的输出是一个张量。 现在,我们将处理模型的输出,从输出张量中重建最终的输出图像,并保存图像。 后处理步骤已从PyTorch的超分辨率模型实现中采用 这里

img_out_y = Image.fromarray(np.uint8((img_out_y[0] * 255.0).clip(0, 255)[0]), mode='L')

# get the output image follow post-processing step from PyTorch implementation
final_img = Image.merge(
    "YCbCr", [
        img_out_y,
        img_cb.resize(img_out_y.size, Image.BICUBIC),
        img_cr.resize(img_out_y.size, Image.BICUBIC),
    ]).convert("RGB")

# Save the image, we will compare this with the output image from mobile device
final_img.save("./_static/img/cat_superres_with_ort.jpg")

# Save resized original image (without super-resolution)
img = transforms.Resize([img_out_y.size[0], img_out_y.size[1]])(img)
img.save("cat_resized.jpg")

这是两张图片之间的比较:

../_images/cat_resized.jpg

低分辨率图像

../_images/cat_superres_with_ort.jpg

超分辨率后的图像

ONNX Runtime 作为一个跨平台引擎,您可以在多个平台上运行它,并且可以在 CPU 和 GPU 上运行。

ONNX Runtime 也可以部署到云端,使用 Azure 机器学习服务进行模型推理。更多信息 here

有关ONNX Runtime性能的更多信息这里

有关ONNX Runtime的更多信息,请点击这里

脚本总运行时间: ( 0 分钟 0.000 秒)

Gallery generated by Sphinx-Gallery