validate.py 6.5 KB
Newer Older
Y
yejianwu 已提交
1 2 3 4 5
import argparse
import sys
import os
import os.path
import numpy as np
L
liuqi 已提交
6
import re
Y
yejianwu 已提交
7
from scipy import spatial
8
from scipy import stats
Y
yejianwu 已提交
9 10 11

# Validation Flow:
# 1. Generate input data
12
# 2. Use mace_run to run model on phone.
Y
yejianwu 已提交
13 14
# 3. adb pull the result.
# 4. Compare output data of mace and tf
15
#    python validate.py --model_file tf_model_opt.pb \
Y
yejianwu 已提交
16
#        --input_file input_file \
17 18 19 20 21
#        --mace_out_file output_file \
#        --input_node input_node \
#        --output_node output_node \
#        --input_shape 1,64,64,3 \
#        --output_shape 1,64,64,2
Y
yejianwu 已提交
22 23 24 25 26 27 28

def load_data(file):
  if os.path.isfile(file):
    return np.fromfile(file=file, dtype=np.float32)
  else:
    return np.empty([0])

L
liuqi 已提交
29 30 31
def format_output_name(name):
  return re.sub('[^0-9a-zA-Z]+', '_', name)

L
liuqi 已提交
32
def compare_output(output_name, mace_out_value, out_value):
Y
yejianwu 已提交
33
  if mace_out_value.size != 0:
34 35 36 37
    out_value = out_value.reshape(-1)
    mace_out_value = mace_out_value.reshape(-1)
    assert len(out_value) == len(mace_out_value)
    similarity = (1 - spatial.distance.cosine(out_value, mace_out_value))
L
liuqi 已提交
38
    print output_name, 'MACE VS', FLAGS.platform.upper(), 'similarity: ', similarity
L
liuqi 已提交
39
    if (FLAGS.mace_runtime == "cpu" and similarity > 0.999) or \
Y
yejianwu 已提交
40
        (FLAGS.mace_runtime == "neon" and similarity > 0.999) or \
L
liuqi 已提交
41
        (FLAGS.mace_runtime == "gpu" and similarity > 0.995) or \
42
        (FLAGS.mace_runtime == "dsp" and similarity > 0.930):
Y
yejianwu 已提交
43 44 45
      print '=======================Similarity Test Passed======================'
    else:
      print '=======================Similarity Test Failed======================'
46
      sys.exit(-1)
Y
yejianwu 已提交
47 48
  else:
    print '=======================Skip empty node==================='
49
    sys.exit(-1)
Y
yejianwu 已提交
50 51


L
liuqi 已提交
52 53 54
def validate_tf_model(input_names, input_shapes, output_names):
  import tensorflow as tf
  if not os.path.isfile(FLAGS.model_file):
Y
yejianwu 已提交
55
    print("Input graph file '" + FLAGS.model_file + "' does not exist!")
56
    sys.exit(-1)
Y
yejianwu 已提交
57 58

  input_graph_def = tf.GraphDef()
L
liuqi 已提交
59
  with open(FLAGS.model_file, "rb") as f:
Y
yejianwu 已提交
60 61 62 63 64 65 66
    data = f.read()
    input_graph_def.ParseFromString(data)
    tf.import_graph_def(input_graph_def, name="")

    with tf.Session() as session:
      with session.graph.as_default() as graph:
        tf.import_graph_def(input_graph_def, name="")
L
liuqi 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80
        input_dict = {}
        for i in range(len(input_names)):
          input_value = load_data(FLAGS.input_file + "_" + input_names[i])
          input_value = input_value.reshape(input_shapes[i])
          input_node = graph.get_tensor_by_name(input_names[i] + ':0')
          input_dict[input_node] = input_value

        output_nodes = []
        for name in output_names:
          output_nodes.extend([graph.get_tensor_by_name(name + ':0')])
        output_values = session.run(output_nodes, feed_dict=input_dict)
        for i in range(len(output_names)):
          output_file_name = FLAGS.mace_out_file + "_" + format_output_name(output_names[i])
          mace_out_value = load_data(output_file_name)
L
liuqi 已提交
81
          compare_output(output_names[i], mace_out_value, output_values[i])
L
liuqi 已提交
82 83 84 85 86 87 88 89 90 91

def validate_caffe_model(input_names, input_shapes, output_names, output_shapes):
  os.environ['GLOG_minloglevel'] = '1' # suprress Caffe verbose prints
  import caffe
  if not os.path.isfile(FLAGS.model_file):
    print("Input graph file '" + FLAGS.model_file + "' does not exist!")
    sys.exit(-1)
  if not os.path.isfile(FLAGS.weight_file):
    print("Input weight file '" + FLAGS.weight_file + "' does not exist!")
    sys.exit(-1)
Y
yejianwu 已提交
92

L
liuqi 已提交
93
  caffe.set_mode_cpu()
Y
yejianwu 已提交
94

L
liuqi 已提交
95 96 97 98 99
  net = caffe.Net(FLAGS.model_file, caffe.TEST, weights=FLAGS.weight_file)

  for i in range(len(input_names)):
    input_value = load_data(FLAGS.input_file + "_" + input_names[i])
    input_value = input_value.reshape(input_shapes[i]).transpose((0, 3, 1, 2))
100
    input_blob_name = input_names[i]
101 102 103 104 105
    try:
      if input_names[i] in net.top_names:
        input_blob_name = net.top_names[input_names[i]][0]
    except ValueError:
      pass
106
    net.blobs[input_blob_name].data[0] = input_value
L
liuqi 已提交
107 108

  net.forward()
Y
yejianwu 已提交
109

L
liuqi 已提交
110
  for i in range(len(output_names)):
111
    value = net.blobs[net.top_names[output_names[i]][0]].data
L
liuqi 已提交
112 113 114 115 116
    out_shape = output_shapes[i]
    out_shape[1], out_shape[2], out_shape[3] = out_shape[3], out_shape[1], out_shape[2]
    value = value.reshape(out_shape).transpose((0, 2, 3, 1))
    output_file_name = FLAGS.mace_out_file + "_" + format_output_name(output_names[i])
    mace_out_value = load_data(output_file_name)
L
liuqi 已提交
117
    compare_output(output_names[i], mace_out_value, value)
L
liuqi 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131

def main(unused_args):
  input_names = [name for name in FLAGS.input_node.split(',')]
  input_shape_strs = [shape for shape in FLAGS.input_shape.split(':')]
  input_shapes = [[int(x) for x in shape.split(',')] for shape in input_shape_strs]
  output_names = [name for name in FLAGS.output_node.split(',')]
  assert len(input_names) == len(input_shapes)

  if FLAGS.platform == 'tensorflow':
    validate_tf_model(input_names, input_shapes, output_names)
  elif FLAGS.platform == 'caffe':
    output_shape_strs = [shape for shape in FLAGS.output_shape.split(':')]
    output_shapes = [[int(x) for x in shape.split(',')] for shape in output_shape_strs]
    validate_caffe_model(input_names, input_shapes, output_names, output_shapes)
Y
yejianwu 已提交
132 133 134 135 136

def parse_args():
  """Parses command line arguments."""
  parser = argparse.ArgumentParser()
  parser.register("type", "bool", lambda v: v.lower() == "true")
L
liuqi 已提交
137 138 139 140 141
  parser.add_argument(
    "--platform",
    type=str,
    default="",
    help="Tensorflow or Caffe.")
Y
yejianwu 已提交
142 143 144 145
  parser.add_argument(
    "--model_file",
    type=str,
    default="",
L
liuqi 已提交
146 147 148 149 150 151
    help="TensorFlow or Caffe \'GraphDef\' file to load.")
  parser.add_argument(
    "--weight_file",
    type=str,
    default="",
    help="caffe model file to load.")
Y
yejianwu 已提交
152 153 154 155 156 157 158 159 160 161
  parser.add_argument(
    "--input_file",
    type=str,
    default="",
    help="input file.")
  parser.add_argument(
    "--mace_out_file",
    type=str,
    default="",
    help="mace output file to load.")
162 163 164 165 166
  parser.add_argument(
    "--mace_runtime",
    type=str,
    default="gpu",
    help="mace runtime device.")
Y
yejianwu 已提交
167 168 169
  parser.add_argument(
    "--input_shape",
    type=str,
170
    default="1,64,64,3",
Y
yejianwu 已提交
171 172 173 174
    help="input shape.")
  parser.add_argument(
    "--output_shape",
    type=str,
175
    default="1,64,64,2",
Y
yejianwu 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
    help="output shape.")
  parser.add_argument(
    "--input_node",
    type=str,
    default="input_node",
    help="input node")
  parser.add_argument(
    "--output_node",
    type=str,
    default="output_node",
    help="output node")

  return parser.parse_known_args()


if __name__ == '__main__':
  FLAGS, unparsed = parse_args()
  main(unused_args=[sys.argv[0]] + unparsed)