AIACC-Inference(AIACC推理加速)支持优化基于可导出ONNX格式的框架搭建的模型,能显著提升推理性能。本文介绍如何手动安装AIACC-Inference(AIACC推理加速) ONNX版并测试demo。

前提条件

  • 已创建阿里云GPU实例:
    • 实例规格:配备NVIDIA P100、V100或T4 GPU
      说明 更多信息,请参见实例规格族
    • 实例镜像:Ubuntu 16.04 LTS或CentOS 7.x
  • GPU实例已安装:
    • Python 3.6
    • CUDA 10.0、10.2或者11.0
    • cuDNN 7.6或以上版本
    • TensorRT 7.0.0.11(CUDA 10.0)或者7.1.3.4(CUDA 10.2、11.0)
      说明 如需测试其它TensorRT版本,请联系我们

背景信息

ONNX是一种开放式的文件格式,用于存储训练好的模型。通过ONNX可以将不同框架的模型数据存储成统一的格式,便于在同一环境下测试不同框架的模型。

AIACC-Inference(AIACC推理加速) ONNX版通过对模型计算图进行切割、执行层间融合,以及高性能OP实现,大幅提升推理性能。通过AIACC-Inference(AIACC推理加速) ONNX版提供的ONNX模型优化软件接口,您可以对基于PyTorch、MXNet及其它支持导出ONNX模型框架开发的深度学习模型进行推理优化。

AIACC-Inference(AIACC推理加速) ONNX版提供了FP32和FP16两种精度的模型优化选项,其中FP16精度的模型可以利用NVIDIA Volta和Turing架构下的Tensor Core硬件,进一步提升在V100、T4 GPU上的推理性能。

操作步骤

本文示例中基于ResNet50模型执行推理任务,随机生成一张图像并分类,将推理耗时从6.4 ms降低至1.5 ms以内。

采用的环境配置如下:
  • 实例规格:配备T4 GPU的ecs.gn6i-c4g1.xlarge
  • 实例镜像:Ubuntu 16.04 64位
  • Python:3.6.12
  • CUDA:10.0.130
  • cuDNN:7.6.5
  • TensorRT:7.0.0.11
使用AIACC-Inference(AIACC推理加速) ONNX版的操作步骤如下:

步骤1:安装AIACC-Inference(AIACC推理加速) ONNX版软件包

  1. 远程连接实例
  2. 下载软件包。
    本文示例中使用的软件包名称为aiacc_inference_onnx_latest.zip
    wget https://ali-perseus-release.oss-cn-huhehaote.aliyuncs.com/AIACC-Inference/AIACC-Inference-ONNX/aiacc_inference_onnx_latest.zip
  3. 安装unzip工具并解压软件包。
    apt-get install unzip
    unzip aiacc_inference_onnx_latest.zip
  4. 安装软件包。
    pip3 install aiacc_inference_onnx_latest/cuda10.0-TensorRT-7.0.0.11/aiaccix-*-cp36-cp36m-linux_x86_64.whl
    如果安装报错Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-uihnmvc2/onnx/,请尝试更新setuptools和pip:
    pip3 install --upgrade setuptools
    python3 -m pip install --upgrade pip

步骤2:使用Python执行推理

  1. 准备ResNet50模型。
    1. 下载ResNet50模型文件包。
      wget https://github.com/onnx/models/raw/master/vision/classification/resnet/model/resnet50-v1-7.tar.gz
    2. 解压文件包并进入模型文件所在目录。
      tar -xvf resnet50-v1-7.tar.gz && cd resnet50v1/

      查看目录下的文件,resnet50-v1-7.onnx即为本文示例中使用模型文件。

  2. 新建文件test.py,并添加示例代码。
    import numpy as np
    import aiaccix as aix
    import time
    import os
    # %%init session
    sess = aix.InferenceSession("./resnet50-v1-7.onnx")
    input_name = sess.get_inputs()[0].name
    input_shape = sess.get_inputs()[0].shape
    print("input_name is %s, input_shape is %s"%(input_name,str(input_shape)))
    # %%test image, image size == [1,3,224,224]
    input_image = np.random.random((1,3,224,224)).astype(np.float32)
    
    #warmup
    for _ in range(10):
      pred_onnx = sess.run(None, {input_name: input_image})
    
    #test the inference time of input_image
    start = time.time()
    for _ in range(1000):
      pred_onnx = sess.run(None, {input_name: input_image})
    end = time.time()
    print('shape is ',input_image.shape,', delta time: ',end-start,' ms')
  3. 执行test.py完成推理。
    python3 test.py
  4. 查看推理结果。
    本次推理结果如下图所示,推理耗时约1.48 ms。python-onnx