【环境搭建:onnx模型部署】onnxruntime-gpu安装与测试(python)

1. onnxruntime 安装

onnx 模型在 CPU 上进行推理,在conda环境中直接使用pip安装即可

pip install onnxruntime

2. onnxruntime-gpu 安装

想要 onnx 模型在 GPU 上加速推理,需要安装 onnxruntime-gpu 。有两种思路:

  • 依赖于 本地主机 上已安装的 cuda 和 cudnn 版本
  • 不依赖于 本地主机 上已安装的 cuda 和 cudnn 版本

要注意:onnxruntime-gpu, cuda, cudnn三者的版本要对应,否则会报错 或 不能使用GPU推理。
onnxruntime-gpu, cuda, cudnn版本对应关系详见: 官网

2.1 方法一:onnxruntime-gpu依赖于本地主机上cuda和cudnn

  • 查看已安装 cuda 和 cudnn 版本

    # cuda version
    cat /usr/local/cuda/version.txt
    
    # cudnn version
    cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2
    
  • 根据 onnxruntime-gpu, cuda, cudnn 三者对应关系,安装相应的 onnxruntime-gpu 即可。

    ## cuda==10.2
    ## cudnn==8.0.3
    ## onnxruntime-gpu==1.5.0 or 1.6.0
    pip install onnxruntime-gpu==1.6.0
    

2.2 方法二:onnxruntime-gpu不依赖于本地主机上cuda和cudnn

在 conda 环境中安装,不依赖于 本地主机 上已安装的 cuda 和 cudnn 版本,灵活方便。这里,先说一下已经测试通过的组合:

  • python3.6, cudatoolkit10.2.89, cudnn7.6.5, onnxruntime-gpu1.4.0
  • python3.8, cudatoolkit11.3.1, cudnn8.2.1, onnxruntime-gpu1.14.1

如果需要其他的版本, 可以根据 onnxruntime-gpu, cuda, cudnn 三者对应关系自行组合测试。

下面,从创建conda环境,到实现在GPU上加速onnx模型推理进行举例。

2.2.1 举例:创建onnxruntime-gpu==1.14.1的conda环境

## 创建conda环境
conda create -n torch python=3.8

## 激活conda环境
source activate torch
conda install pytorch==1.10.0 torchvision==0.11.0 torchaudio==0.10.0 cudatoolkit=11.3 -c pytorch -c conda-forge
conda install cudnn==8.2.1
pip install onnxruntime-gpu==1.14.1
## pip install ... (根据需求,安装其他的包)

2.2.2 举例:实例测试

  • 打开终端,输入 watch -n 0.1 nvidia-smi, 实时查看gpu使用情况

  • 代码测试,摘取API

      import numpy as np
      import torch
      import onnxruntime
      
      MODEL_FILE = '.model.onnx'
      DEVICE_NAME = 'cuda' if torch.cuda.is_available() else 'cpu'
      DEVICE_INDEX = 0
      DEVICE=f'{DEVICE_NAME}:{DEVICE_INDEX}'
      
      # A simple model to calculate addition of two tensors
      def model():
          class Model(torch.nn.Module):
              def __init__(self):
                  super(Model, self).__init__()
      
              def forward(self, x, y):
                  return x.add(y)
      
          return Model()
      
      # Create an instance of the model and export it to ONNX graph format
      def create_model(type: torch.dtype = torch.float32):
          sample_x = torch.ones(3, dtype=type)
          sample_y = torch.zeros(3, dtype=type)
          torch.onnx.export(model(), (sample_x, sample_y), MODEL_FILE,
                            input_names=["x", "y"], output_names=["z"], 
                            dynamic_axes={"x":{0 : "array_length_x"}, "y":{0: "array_length_y"}})
       
      # Create an ONNX Runtime session with the provided model
      def create_session(model: str) -> onnxruntime.InferenceSession:
          providers = ['CPUExecutionProvider']
          if torch.cuda.is_available():
              providers.insert(0, 'CUDAExecutionProvider')
          return onnxruntime.InferenceSession(model, providers=providers)
      
      # Run the model on CPU consuming and producing numpy arrays 
      def run(x: np.array, y: np.array) -> np.array:
          session = create_session(MODEL_FILE)
          z = session.run(["z"], {"x": x, "y": y})
          return z[0]   
    
      # Run the model on device consuming and producing ORTValues
      def run_with_data_on_device(x: np.array, y: np.array) -> onnxruntime.OrtValue:
          session = create_session(MODEL_FILE)
      
          x_ortvalue = onnxruntime.OrtValue.ortvalue_from_numpy(x, DEVICE_NAME, DEVICE_INDEX)
          y_ortvalue = onnxruntime.OrtValue.ortvalue_from_numpy(y, DEVICE_NAME, DEVICE_INDEX)
      
          io_binding = session.io_binding()
          io_binding.bind_input(name='x', device_type=x_ortvalue.device_name(), device_id=0, element_type=x.dtype, shape=x_ortvalue.shape(), buffer_ptr=x_ortvalue.data_ptr())
          io_binding.bind_input(name='y', device_type=y_ortvalue.device_name(), device_id=0, element_type=y.dtype, shape=y_ortvalue.shape(), buffer_ptr=y_ortvalue.data_ptr())
          io_binding.bind_output(name='z', device_type=DEVICE_NAME, device_id=DEVICE_INDEX, element_type=x.dtype, shape=x_ortvalue.shape())
          session.run_with_iobinding(io_binding)
      
          z = io_binding.get_outputs()
      
          return z[0]
    
      def main():
          create_model()
          # print(run(x=np.float32([1.0, 2.0, 3.0]),y=np.float32([4.0, 5.0, 6.0])))
          
          t1 = time.time()
          print(run(x=np.float32([1.0, 2.0, 3.0]),y=np.float32([4.0, 5.0, 6.0])))
          # [array([5., 7., 9.], dtype=float32)]t1 = time.time()
          t2 = time.time()
      
          print(run_with_data_on_device(x=np.float32([1.0, 2.0, 3.0, 4.0, 5.0]), y=np.float32([1.0, 2.0, 3.0, 4.0, 5.0])).numpy())
          # [ 2.  4.  6.  8. 10.]
          t3 = time.time()
          
          print(f'Done. ({(1E3 * (t2 - t1)):.1f}ms) Inference.')
          print(f'Done. ({(1E3 * (t3 - t2)):.1f}ms) Inference.')
      
      if __name__ == "__main__":
          main()   
    
  • 14
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值