TVM Compiler中文教程:TVM编译ONNX模型并执行

た 入场券 2022-01-23 07:41 703阅读 0赞

文章目录

  • 编译ONNX模型
    • 加载预训练ONNX模型
    • 加载一张测试图像
    • 使用relay编译模型
    • 在TVM上执行
    • 显示结果

编译ONNX模型

下面描述使用Relay如何部署ONNX模型:

  1. #安装onnx,https://github.com/onnx/onnx
  2. pip install onnx --user

首先导入所需要的python包:

  1. import onnx
  2. import numpy as np
  3. import tvm
  4. import tvm.relay as relay
  5. from tvm.contrib.download import download_testdata

加载预训练ONNX模型

  1. model_url = ''.join(['https://gist.github.com/zhreshold/', 'bcda4716699ac97ea44f791c24310193/raw/','93672b029103648953c4e5ad3ac3aadf346a4cdc/','super_resolution_0.2.onnx'])
  2. model_path = download_testdata(model_url, 'super_resolution.onnx', module='onnx')
  3. #从硬盘加载supe_resolution.onnx
  4. onnx_model = onnx.load(model_path)

加载一张测试图像

  1. from PIL import Image
  2. img_url = 'https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true'
  3. img_path = download_testdata(img_url, 'cat.png', module='data')
  4. img = Image.open(img_path).resize((224,224))
  5. img_ycbcr = img.convert("YCbCr")
  6. img_y, img_cb, img_cr = img_ycbcr.split()
  7. x = np.array(img_y)[np.newaxis, np.newaxis, :, :]

使用relay编译模型

  1. target = 'llvm'
  2. input_name = '1'
  3. shape_dict = { input_name: x.shape}
  4. sym, params = relay.frontend.from_onnx(onnx_model, shape_dict)
  5. with relay.build_config(opt_level = 1):
  6. intrp = relay.build_module.create_executor('graph',sym, tvm.cpu(0), target)

在TVM上执行

  1. dtype = 'float32'
  2. tvm_output = intrp.evaluate(sym)(tvm.nd.array(x.astype(dtype)),**params).asnumpy()

显示结果

  1. from matplotlib import pyplot as plt
  2. out_y = Image.fromarray(np.uint8((tvm_output[0,0]).clip(0, 255)),model='L')
  3. out_cb = img_cb.resize(out_y.size, Image.BICUBIC)
  4. out_cr = img_cr.resize(out_y.size, Image.BICUBIC)
  5. result = Image.merge('YCbCr', [out_y, out_cb, out_cr]).convert('RGB')
  6. canvas = np.full((672,672*2,3),255)
  7. canvas[0:224, 0:224, :] = np.asarray(img)
  8. canvas[:, 672:, :] = np.asarray(result)
  9. plt.imshow(canvas.astype(np.uint8))
  10. plt.show()

发表评论

表情:
评论列表 (有 0 条评论,703人围观)

还没有评论,来说两句吧...

相关阅读