from_tensorflow.py 7.19 KB
Newer Older
1 2 3
"""
Compile Tensorflow Models
=========================
4
This article is an introductory tutorial to deploy tensorflow models with TVM.
5

6
For us to begin with, tensorflow python module is required to be installed.
7

8
Please refer to https://www.tensorflow.org/install
9 10
"""

11
# tvm and nnvm
12 13
import nnvm
import tvm
14 15

# os and numpy
16 17 18 19 20 21 22 23 24
import numpy as np
import os.path

# Tensorflow imports
import tensorflow as tf
from tensorflow.core.framework import graph_pb2
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_util

25
# Tensorflow utility functions
26 27
import nnvm.testing.tf

28
# Base location for model related files.
29
repo_base = 'https://github.com/dmlc/web-data/raw/master/tensorflow/models/InceptionV1/'
30 31

# Test image
32 33
img_name = 'elephant-299.jpg'
image_url = os.path.join(repo_base, img_name)
34

35 36 37
######################################################################
# Tutorials
# ---------
38 39 40 41 42 43
# .. note::
#
#   protobuf should be exported with :any:`add_shapes=True` option.
#   Could use https://github.com/dmlc/web-data/tree/master/tensorflow/scripts/tf-to-nnvm.py
#   to add shapes for existing models.
#
44 45 46
# Please refer docs/frontend/tensorflow.md for more details for various models
# from tensorflow.

47 48
model_name = 'classify_image_graph_def-with_shapes.pb'
model_url = os.path.join(repo_base, model_name)
49 50

# Image label map
51 52
map_proto = 'imagenet_2012_challenge_label_map_proto.pbtxt'
map_proto_url = os.path.join(repo_base, map_proto)
53 54

# Human readable text for labels
55 56 57
lable_map = 'imagenet_synset_to_human_label_map.txt'
lable_map_url = os.path.join(repo_base, lable_map)

58 59 60 61 62 63 64 65 66 67
# Target settings
# Use these commented settings to build for cuda.
#target = 'cuda'
#target_host = 'llvm'
#layout = "NCHW"
#ctx = tvm.gpu(0)
target = 'llvm'
target_host = 'llvm'
layout = None
ctx = tvm.cpu(0)
68 69

######################################################################
70 71 72
# Download required files
# -----------------------
# Download files listed above.
73 74 75 76 77 78 79 80
from mxnet.gluon.utils import download

download(image_url, img_name)
download(model_url, model_name)
download(map_proto_url, map_proto)
download(lable_map_url, lable_map)

######################################################################
81 82 83
# Import model
# ------------
# Creates tensorflow graph definition from protobuf file.
84

85
with tf.gfile.FastGFile(os.path.join("./", model_name), 'rb') as f:
86 87 88 89 90
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    graph = tf.import_graph_def(graph_def, name='')
    # Call the utility to import the graph definition into default graph.
    graph_def = nnvm.testing.tf.ProcessGraphDefParam(graph_def)
91
    # Add shapes to the graph.
92 93
    with tf.Session() as sess:
        graph_def = nnvm.testing.tf.AddShapesToGraphDef(sess, 'softmax')
94 95 96 97

######################################################################
# Decode image
# ------------
98 99
# .. note::
#
100
#   tensorflow frontend import doesn't support preprocessing ops like JpegDecode.
101 102 103 104
#   JpegDecode is bypassed (just return source node).
#   Hence we supply decoded frame to TVM instead.
#

105 106 107
from PIL import Image
image = Image.open(img_name).resize((299, 299))

108
x = np.array(image)
109 110 111 112

######################################################################
# Import the graph to NNVM
# ------------------------
113 114 115 116 117
# Import tensorflow graph definition to nnvm.
#
# Results:
#   sym: nnvm graph for given tensorflow protobuf.
#   params: params converted from tensorflow params (tensor protobuf).
118
sym, params = nnvm.frontend.from_tensorflow(graph_def, layout=layout)
119

120
print ("Tensorflow protobuf imported as nnvm graph")
121
######################################################################
122 123 124 125 126 127 128 129 130
# NNVM Compilation
# ----------------
# Compile the graph to llvm target with given input specification.
#
# Results:
#   graph: Final graph after compilation.
#   params: final params after compilation.
#   lib: target library which can be deployed on target with tvm runtime.

131 132 133
import nnvm.compiler
shape_dict = {'DecodeJpeg/contents': x.shape}
dtype_dict = {'DecodeJpeg/contents': 'uint8'}
134
graph, lib, params = nnvm.compiler.build(sym, shape=shape_dict, target=target, target_host=target_host, dtype=dtype_dict, params=params)
135 136 137 138

######################################################################
# Execute the portable graph on TVM
# ---------------------------------
139
# Now we can try deploying the NNVM compiled model on target.
140

141 142 143 144 145 146 147 148 149 150 151 152
from tvm.contrib import graph_runtime
dtype = 'uint8'
m = graph_runtime.create(graph, lib, ctx)
# set inputs
m.set_input('DecodeJpeg/contents', tvm.nd.array(x.astype(dtype)))
m.set_input(**params)
# execute
m.run()
# get outputs
tvm_output = m.get_output(0, tvm.nd.empty(((1, 1008)), 'float32'))

######################################################################
153 154 155
# Process the output
# ------------------
# Process the model output to human readable text for InceptionV1.
156 157 158 159 160 161 162
predictions = tvm_output.asnumpy()
predictions = np.squeeze(predictions)

# Creates node ID --> English string lookup.
node_lookup = nnvm.testing.tf.NodeLookup(label_lookup_path=os.path.join("./", map_proto),
                                         uid_lookup_path=os.path.join("./", lable_map))

163
# Print top 5 predictions from TVM output.
164 165 166 167 168 169 170
top_k = predictions.argsort()[-5:][::-1]
for node_id in top_k:
    human_string = node_lookup.id_to_string(node_id)
    score = predictions[node_id]
    print('%s (score = %.5f)' % (human_string, score))

######################################################################
171 172 173
# Inference on tensorflow
# -----------------------
# Run the corresponding model on tensorflow
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

def create_graph():
    """Creates a graph from saved GraphDef file and returns a saver."""
    # Creates graph from saved graph_def.pb.
    with tf.gfile.FastGFile(model_name, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        graph = tf.import_graph_def(graph_def, name='')
        # Call the utility to import the graph definition into default graph.
        graph_def = nnvm.testing.tf.ProcessGraphDefParam(graph_def)

def run_inference_on_image(image):
    """Runs inference on an image.

    Parameters
    ----------
    image: String
        Image file name.

    Returns
    -------
        Nothing
    """
    if not tf.gfile.Exists(image):
        tf.logging.fatal('File does not exist %s', image)
    image_data = tf.gfile.FastGFile(image, 'rb').read()

    # Creates graph from saved GraphDef.
    create_graph()

    with tf.Session() as sess:
        softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
        predictions = sess.run(softmax_tensor,
                               {'DecodeJpeg/contents:0': image_data})

        predictions = np.squeeze(predictions)

        # Creates node ID --> English string lookup.
        node_lookup = nnvm.testing.tf.NodeLookup(label_lookup_path=os.path.join("./", map_proto),
                                                 uid_lookup_path=os.path.join("./", lable_map))

215
        # Print top 5 predictions from tensorflow.
216 217 218 219 220 221 222 223
        top_k = predictions.argsort()[-5:][::-1]
        print ("===== TENSORFLOW RESULTS =======")
        for node_id in top_k:
            human_string = node_lookup.id_to_string(node_id)
            score = predictions[node_id]
            print('%s (score = %.5f)' % (human_string, score))

run_inference_on_image (img_name)