如何从Pytorch中导出ONNX模型并使用它实现图像超分

前言

        在本教程中,我们将介绍如何将 PyTorch 中定义的模型转换为 ONNX 格式,然后使用 ONNX 运行时运行它。

        ONNX 运行时是面向 ONNX 模型的以性能为中心的引擎,可跨多个平台和硬件(Windows、Linux 和 Mac)以及 CPU 和 GPU 进行高效推理。ONNX 运行时已被证明可以显著提高多个模型的性能,如此处所述。

        对于本教程,您需要安装 ONNX 和 ONNX 运行时。可以使用 pip install onnx onnxruntime 获取 ONNX 和 ONNX 运行时的二进制生成。ONNX 运行时建议使用 PyTorch 的最新稳定运行时。

模型的创建、导出与使用方法

# Some standard imports
import io
import numpy as np

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

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

        首先,让我们在 PyTorch 中创建一个 SuperResolution 模型。该模型使用“使用高效的亚像素卷积神经网络的实时单图像和视频超分辨率”中描述的高效亚像素卷积层 - Shi等人通过高档因子提高图像的分辨率。该模型期望图像 YCbCr 的 Y 分量作为输入,并以超分辨率输出放大后的 Y 分量。

创建模型

        该模型直接来自 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 = 1    # 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 运行时是否计算相同的值。

        但在使用 ONNX 运行时验证模型的输出之前,我们将使用 ONNX API 检查 ONNX 模型。首先, onnx.load("super_resolution.onnx") 将加载保存的模型并输出 onnx.ModelProto 结构(用于捆绑 ML 模型的顶级文件/容器格式)。有关更多信息,请访问 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 运行时的 Python API 计算输出。这部分通常可以在单独的进程中或在另一台计算机上完成,但我们将继续相同的过程,以便我们可以验证 ONNX 运行时和 PyTorch 是否正在为网络计算相同的值。

        为了使用 ONNX 运行时运行模型,我们需要使用所选配置参数为模型创建推理会话(此处我们使用默认配置)。创建会话后,我们使用 run() API 评估模型。此调用的输出是一个列表,其中包含由 ONNX 运行时计算的模型的输出。

import onnxruntime

ort_session = onnxruntime.InferenceSession("super_resolution.onnx")

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 运行时运行的输出在数值上与给定的精度( rtol=1e-03 和 atol=1e-05 )匹配。作为旁注,如果它们不匹配,则 ONNX 导出器中存在问题。

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

示例代码

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

        首先,让我们加载图像,使用标准的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 运行时中运行超分辨率模型,如前所述。

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")

超分后的图像效果: 

总结

ONNX 运行时是一个跨平台引擎,您可以在多个平台以及 CPU 和 GPU 上运行它。

还可以将 ONNX 运行时部署到云,以便使用服务器机器学习服务进行模型推理。

猜你喜欢

转载自blog.csdn.net/qq_39312146/article/details/132074762
今日推荐