mace_tools.py 8.8 KB
Newer Older
1 2
#!/usr/bin/env python

3
# Must run at root dir of libmace project.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
# python tools/mace_tools.py \
#     --global_config=models/config \
#     --round=100 \
#     --mode=all

import argparse
import os
import shutil
import subprocess
import sys

from ConfigParser import ConfigParser

tf_model_file_dir_key = "TF_MODEL_FILE_DIR"


def run_command(command):
  print("Run command: {}".format(command))
  result = subprocess.Popen(
      command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  out, err = result.communicate()

  if out:
    print("Stdout msg:\n{}".format(out))
  if err:
    print("Stderr msg:\n{}".format(err))

  if result.returncode != 0:
    raise Exception("Exit not 0 from bash with code: {}, command: {}".format(
        result.returncode, command))


def get_libs(configs):
37 38 39
  global_target_abi = ""
  global_runtime = ""
  runtime_list = []
40
  for config in configs:
41 42 43 44 45
    if global_target_abi == "":
      global_target_abi = config["TARGET_ABI"]
    elif global_target_abi != config["TARGET_ABI"]:
      raise Exception("Multiple TARGET_ABI found in config files!")
    runtime_list.append(config["RUNTIME"])
46

47 48 49 50 51 52 53 54 55 56
  if "dsp" in runtime_list:
    global_runtime = "dsp"
  elif "gpu" in runtime_list:
    global_runtime = "gpu"
  elif "cpu" in runtime_list:
    global_runtime = "cpu"
  else:
    raise Exception("Not found available RUNTIME in config files!")

  libmace_name = "libmace-{}-{}".format(global_target_abi, global_runtime)
57 58 59 60

  command = "bash tools/download_and_link_lib.sh " + libmace_name
  run_command(command)

61 62
  return libmace_name

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80

def clear_env():
  command = "bash tools/clear_env.sh"
  run_command(command)


def generate_random_input(model_output_dir):
  generate_data_or_not = True
  command = "bash tools/validate_tools.sh {} {}".format(
      model_output_dir, int(generate_data_or_not))
  run_command(command)


def generate_model_code():
  command = "bash tools/generate_model_code.sh"
  run_command(command)


81 82 83
def build_mace_run(production_mode, model_output_dir, hexagon_mode):
  command = "bash tools/build_mace_run.sh {} {} {}".format(
      int(production_mode), model_output_dir, int(hexagon_mode))
84 85 86 87 88 89 90 91
  run_command(command)


def tuning_run(model_output_dir, running_round, tuning, production_mode):
  command = "bash tools/tuning_run.sh {} {} {} {}".format(
      model_output_dir, running_round, int(tuning), int(production_mode))
  run_command(command)

92 93 94
def benchmark_model(model_output_dir):
  command = "bash tools/benchmark.sh {}".format(model_output_dir)
  run_command(command)
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

def run_model(model_output_dir, running_round):
  tuning_run(model_output_dir, running_round, False, False)


def generate_production_code(model_output_dirs, pull_or_not):
  cl_bin_dirs = []
  for d in model_output_dirs:
    cl_bin_dirs.append(os.path.join(d, "opencl_bin"))
  cl_bin_dirs_str = ",".join(cl_bin_dirs)
  command = "bash tools/generate_production_code.sh {} {}".format(
      cl_bin_dirs_str, int(pull_or_not))
  run_command(command)


110 111 112 113 114 115
def build_mace_run_prod(model_output_dir, tuning, libmace_name):
  if "dsp" in libmace_name:
    hexagon_mode = True
  else:
    hexagon_mode = False

116
  production_or_not = False
117
  build_mace_run(production_or_not, model_output_dir, hexagon_mode)
118 119 120 121 122 123 124 125 126
  tuning_run(
      model_output_dir,
      running_round=0,
      tuning=tuning,
      production_mode=production_or_not)

  production_or_not = True
  pull_or_not = True
  generate_production_code([model_output_dir], pull_or_not)
127
  build_mace_run(production_or_not, model_output_dir, hexagon_mode)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168


def validate_model(model_output_dir):
  generate_data_or_not = False
  command = "bash tools/validate_tools.sh {} {}".format(
      model_output_dir, int(generate_data_or_not))
  run_command(command)


def build_production_code():
  command = "bash tools/build_production_code.sh"
  run_command(command)


def merge_libs_and_tuning_results(output_dir, model_output_dirs):
  pull_or_not = False
  generate_production_code(model_output_dirs, pull_or_not)
  build_production_code()

  model_output_dirs_str = ",".join(model_output_dirs)
  command = "bash tools/merge_libs.sh {} {}".format(output_dir,
                                                    model_output_dirs_str)
  run_command(command)


def parse_sub_model_configs(model_dirs, global_configs):
  model_configs = []
  for model_dir in model_dirs:
    model_config = {}

    model_config_path = os.path.join(model_dir, "config")
    if os.path.exists(model_config_path):
      cf = ConfigParser()
      # Preserve character case
      cf.optionxform = str
      cf.read(model_config_path)
      if "configs" in cf.sections():
        config_list = cf.items("configs")
        for config_map in config_list:
          model_config[config_map[0]] = config_map[1]
      else:
Y
yejianwu 已提交
169 170 171
        raise Exception("No config msg found in {}".format(model_config_path))
    else:
      raise Exception("Config file '{}' not found".format(model_config_path))
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196

    model_config[tf_model_file_dir_key] = model_dir

    for config_map in global_configs:
      model_config[config_map[0]] = config_map[1]

    model_configs.append(model_config)

  return model_configs


def parse_model_configs():
  config_parser = ConfigParser()
  # Preserve character case
  config_parser.optionxform = str

  global_config_dir = os.path.dirname(FLAGS.global_config)

  try:
    config_parser.read(FLAGS.global_config)
    config_sections = config_parser.sections()

    model_dirs = []
    model_output_map = {}
    if ("models" in config_sections) and (config_parser.items("models")):
197
      model_dirs_str = config_parser.get(
198
          "models", "DIRECTORIES")
199
      model_dirs_str = model_dirs_str.rstrip(
200 201 202
          ",")

      # Remove repetition element
203 204
      model_dirs = list(
          set(model_dirs_str.split(",")))
205

206
      for model_dir in model_dirs:
207
        # Create output dirs
208
        model_output_dir = FLAGS.output_dir + "/" + model_dir
209 210 211 212 213 214

        model_output_map[model_dir] = model_output_dir
    else:
      model_dirs = [global_config_dir]

      # Create output dirs
215
      model_output_dir = FLAGS.output_dir + "/" + global_config_dir
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
      model_output_map[global_config_dir] = model_output_dir
  except Exception as e:
    print("Error in read model path msg. Exception: {}".format(e))
    return

  global_configs = []
  if "configs" in config_sections:
    global_configs = config_parser.items("configs")

  return parse_sub_model_configs(model_dirs, global_configs), model_output_map


def parse_args():
  """Parses command line arguments."""
  parser = argparse.ArgumentParser()
  parser.register("type", "bool", lambda v: v.lower() == "true")
  parser.add_argument(
      "--global_config",
      type=str,
      default="./tool/config",
      help="The global config file of models.")
  parser.add_argument(
      "--output_dir", type=str, default="./build/", help="The output dir.")
  parser.add_argument(
      "--round", type=int, default=1, help="The model running round.")
  parser.add_argument(
      "--tuning", type="bool", default="true", help="Tune opencl params.")
  parser.add_argument(
244
      "--mode", type=str, default="all", help="[build|run|validate|merge|all].")
245 246 247 248 249 250 251 252 253 254 255 256 257
  return parser.parse_known_args()


def main(unused_args):
  configs, model_output_map = parse_model_configs()

  if FLAGS.mode == "build" or FLAGS.mode == "all":
    # Remove previous output dirs
    if not os.path.exists(FLAGS.output_dir):
      os.makedirs(FLAGS.output_dir)
    elif os.path.exists(os.path.join(FLAGS.output_dir, "libmace")):
      shutil.rmtree(os.path.join(FLAGS.output_dir, "libmace"))

258 259 260
  if FLAGS.mode == "validate":
    FLAGS.round = 1

261
  libmace_name = get_libs(configs)
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276

  model_output_dirs = []
  for config in configs:
    # Transfer params by environment
    for key in config:
      os.environ[key] = config[key]
    model_output_dir = model_output_map[config[tf_model_file_dir_key]]
    model_output_dirs.append(model_output_dir)

    if FLAGS.mode == "build" or FLAGS.mode == "all":
      if os.path.exists(model_output_dir):
        shutil.rmtree(model_output_dir)
      os.makedirs(model_output_dir)
      clear_env()

277
    if FLAGS.mode == "build" or FLAGS.mode == "run" or FLAGS.mode == "validate" or FLAGS.mode == "all":
278 279 280 281
      generate_random_input(model_output_dir)

    if FLAGS.mode == "build" or FLAGS.mode == "all":
      generate_model_code()
282
      build_mace_run_prod(model_output_dir, FLAGS.tuning, libmace_name)
283

284
    if FLAGS.mode == "run" or FLAGS.mode == "validate" or FLAGS.mode == "all":
285 286
      run_model(model_output_dir, FLAGS.round)

287 288 289
    if FLAGS.mode == "benchmark":
      benchmark_model(model_output_dir)

290
    if FLAGS.mode == "validate" or FLAGS.mode == "all":
291 292 293 294 295 296 297 298 299
      validate_model(model_output_dir)

  if FLAGS.mode == "build" or FLAGS.mode == "merge" or FLAGS.mode == "all":
    merge_libs_and_tuning_results(FLAGS.output_dir, model_output_dirs)


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