from_onnx.py 3.79 KB
Newer Older
1
"""
Tianqi Chen committed
2 3
Compile ONNX Models
===================
4 5 6 7 8 9 10
**Author**: `Joshua Z. Zhang <https://zhreshold.github.io/>`_

This article is an introductory tutorial to deploy ONNX models with NNVM.

For us to begin with, onnx module is required to be installed.

A quick solution is to install protobuf compiler, and
11 12 13 14 15

.. code-block:: bash

    pip install onnx --user

16 17 18 19 20 21 22 23
or please refer to offical site.
https://github.com/onnx/onnx
"""
import nnvm
import tvm
import onnx
import numpy as np

24
def download(url, path, overwrite=False):
25 26 27
    import os
    if os.path.isfile(path) and not overwrite:
        print('File {} existed, skip.'.format(path))
28
        return
29 30 31 32 33 34 35
    print('Downloading from url {} to {}'.format(url, path))
    try:
        import urllib.request
        urllib.request.urlretrieve(url, path)
    except:
        import urllib
        urllib.urlretrieve(url, path)
36

37 38 39 40 41 42 43 44
######################################################################
# Load pretrained ONNX model
# ---------------------------------------------
# The example super resolution model used here is exactly the same model in onnx tutorial
# http://pytorch.org/tutorials/advanced/super_resolution_with_caffe2.html
# we skip the pytorch model construction part, and download the saved onnx model
model_url = ''.join(['https://gist.github.com/zhreshold/',
                     'bcda4716699ac97ea44f791c24310193/raw/',
45 46 47
                     '93672b029103648953c4e5ad3ac3aadf346a4cdc/',
                     'super_resolution_0.2.onnx'])
download(model_url, 'super_resolution.onnx', True)
48
# now you have super_resolution.onnx on disk
49
onnx_model = onnx.load_model('super_resolution.onnx')
50
# we can load the graph as NNVM compatible model
Wenhao Hu committed
51
sym, params = nnvm.frontend.from_onnx(onnx_model)
52 53 54 55 56

######################################################################
# Load a test image
# ---------------------------------------------
# A single cat dominates the examples!
57
from PIL import Image
58
img_url = 'https://github.com/dmlc/mxnet.js/blob/master/data/cat.png?raw=true'
59 60
download(img_url, 'cat.png')
img = Image.open('cat.png').resize((224, 224))
61 62 63
img_ycbcr = img.convert("YCbCr")  # convert to YCbCr
img_y, img_cb, img_cr = img_ycbcr.split()
x = np.array(img_y)[np.newaxis, np.newaxis, :, :]
64 65 66 67 68 69 70

######################################################################
# Compile the model on NNVM
# ---------------------------------------------
# We should be familiar with the process right now.
import nnvm.compiler
target = 'cuda'
71 72 73
# assume first input name is data
input_name = sym.list_input_names()[0]
shape_dict = {input_name: x.shape}
74 75
with nnvm.compiler.build_config(opt_level=3):
    graph, lib, params = nnvm.compiler.build(sym, target, shape_dict, params=params)
76 77 78 79 80 81 82 83 84 85

######################################################################
# Execute on TVM
# ---------------------------------------------
# The process is no different from other example
from tvm.contrib import graph_runtime
ctx = tvm.gpu(0)
dtype = 'float32'
m = graph_runtime.create(graph, lib, ctx)
# set inputs
86
m.set_input(input_name, tvm.nd.array(x.astype(dtype)))
87 88 89 90 91 92 93 94 95 96 97 98
m.set_input(**params)
# execute
m.run()
# get outputs
output_shape = (1, 1, 672, 672)
tvm_output = m.get_output(0, tvm.nd.empty(output_shape, dtype)).asnumpy()

######################################################################
# Display results
# ---------------------------------------------
# We put input and output image neck to neck
from matplotlib import pyplot as plt
99 100 101 102 103 104 105 106
out_y = Image.fromarray(np.uint8((tvm_output[0, 0]).clip(0, 255)), mode='L')
out_cb = img_cb.resize(out_y.size, Image.BICUBIC)
out_cr = img_cr.resize(out_y.size, Image.BICUBIC)
result = Image.merge('YCbCr', [out_y, out_cb, out_cr]).convert('RGB')
canvas = np.full((672, 672*2, 3), 255)
canvas[0:224, 0:224, :] = np.asarray(img)
canvas[:, 672:, :] = np.asarray(result)
plt.imshow(canvas.astype(np.uint8))
107
plt.show()