converter.py 69.5 KB
Newer Older
Y
yejianwu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright 2018 Xiaomi, Inc.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
14 15

import argparse
L
liuqi 已提交
16
import glob
17
import hashlib
18
import os
L
liuqi 已提交
19
import re
L
Liangliang He 已提交
20
import sh
21 22
import subprocess
import sys
23
import urllib
Y
yejianwu 已提交
24
import yaml
L
liuqi 已提交
25

26
from enum import Enum
27
import six
28

29
import sh_commands
30
from sh_commands import BuildType
31
from sh_commands import ModelFormat
L
Liangliang He 已提交
32

33
from common import CaffeEnvType
34
from common import DeviceType
35 36 37
from common import mace_check
from common import MaceLogger
from common import StringFormatter
38

Y
yejianwu 已提交
39 40 41 42
################################
# set environment
################################
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
A
Allen 已提交
43

44 45 46
################################
# common definitions
################################
A
Allen 已提交
47
BUILD_OUTPUT_DIR = 'builds'
B
Bin Li 已提交
48
BUILD_DOWNLOADS_DIR = BUILD_OUTPUT_DIR + '/downloads'
49
PHONE_DATA_DIR = "/data/local/tmp/mace_run"
50
MODEL_OUTPUT_DIR_NAME = 'model'
L
liuqi 已提交
51
MODEL_HEADER_DIR_PATH = 'include/mace/public'
52 53
BUILD_TMP_DIR_NAME = '_tmp'
BUILD_TMP_GENERAL_OUTPUT_DIR_NAME = 'general'
Y
yejianwu 已提交
54
OUTPUT_LIBRARY_DIR_NAME = 'lib'
55
OUTPUT_OPENCL_BINARY_DIR_NAME = 'opencl'
L
liuqi 已提交
56
OUTPUT_OPENCL_BINARY_FILE_NAME = 'compiled_opencl_kernel'
L
liuqi 已提交
57
OUTPUT_OPENCL_PARAMETER_FILE_NAME = 'tuned_opencl_parameter'
58
CL_COMPILED_BINARY_FILE_NAME = "mace_cl_compiled_program.bin"
L
liuqi 已提交
59
CL_TUNED_PARAMETER_FILE_NAME = "mace_run.config"
L
liuqi 已提交
60 61
CODEGEN_BASE_DIR = 'mace/codegen'
MODEL_CODEGEN_DIR = CODEGEN_BASE_DIR + '/models'
62 63
ENGINE_CODEGEN_DIR = CODEGEN_BASE_DIR + '/engine'
LIB_CODEGEN_DIR = CODEGEN_BASE_DIR + '/lib'
Y
yejianwu 已提交
64 65 66 67
LIBMACE_SO_TARGET = "//mace/libmace:libmace.so"
LIBMACE_STATIC_TARGET = "//mace/libmace:libmace_static"
LIBMACE_STATIC_PATH = "bazel-genfiles/mace/libmace/libmace.a"
LIBMACE_DYNAMIC_PATH = "bazel-bin/mace/libmace/libmace.so"
68
MODEL_LIB_TARGET = "//mace/codegen:generated_models"
Y
yejianwu 已提交
69
MODEL_LIB_PATH = "bazel-genfiles/mace/codegen/libgenerated_models.a"
L
liuqi 已提交
70
MACE_RUN_STATIC_NAME = "mace_run_static"
71
MACE_RUN_DYNAMIC_NAME = "mace_run_dynamic"
L
liuqi 已提交
72
MACE_RUN_STATIC_TARGET = "//mace/tools/validation:" + MACE_RUN_STATIC_NAME
73 74 75 76 77 78 79 80 81 82 83
MACE_RUN_DYNAMIC_TARGET = "//mace/tools/validation:" + MACE_RUN_DYNAMIC_NAME
EXAMPLE_STATIC_NAME = "example_static"
EXAMPLE_DYNAMIC_NAME = "example_dynamic"
EXAMPLE_STATIC_TARGET = "//mace/examples/cli:" + EXAMPLE_STATIC_NAME
EXAMPLE_DYNAMIC_TARGET = "//mace/examples/cli:" + EXAMPLE_DYNAMIC_NAME
BM_MODEL_STATIC_NAME = "benchmark_model_static"
BM_MODEL_DYNAMIC_NAME = "benchmark_model_dynamic"
BM_MODEL_STATIC_TARGET = "//mace/benchmark:" + BM_MODEL_STATIC_NAME
BM_MODEL_DYNAMIC_TARGET = "//mace/benchmark:" + BM_MODEL_DYNAMIC_NAME
DEVICE_INTERIOR_DIR = PHONE_DATA_DIR + "/interior"
BUILD_TMP_OPENCL_BIN_DIR = 'opencl_bin'
84
ALL_SOC_TAG = 'all'
85 86

ABITypeStrs = [
L
liuqi 已提交
87 88 89
    'armeabi-v7a',
    'arm64-v8a',
    'host',
90
]
L
liuqi 已提交
91 92 93 94 95 96


class ABIType(object):
    armeabi_v7a = 'armeabi-v7a'
    arm64_v8a = 'arm64-v8a'
    host = 'host'
97 98


99 100 101 102 103 104 105 106 107 108 109
ModelFormatStrs = [
    "file",
    "code",
]


class MACELibType(object):
    static = 0
    dynamic = 1


110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
PlatformTypeStrs = [
    "tensorflow",
    "caffe",
]
PlatformType = Enum('PlatformType', [(ele, ele) for ele in PlatformTypeStrs],
                    type=str)

RuntimeTypeStrs = [
    "cpu",
    "gpu",
    "dsp",
    "cpu+gpu"
]


class RuntimeType(object):
    cpu = 'cpu'
    gpu = 'gpu'
    dsp = 'dsp'
    cpu_gpu = 'cpu+gpu'


Y
yejianwu 已提交
132 133 134 135 136 137 138 139 140 141
InputDataTypeStrs = [
    "int32",
    "float32",
]

InputDataType = Enum('InputDataType',
                     [(ele, ele) for ele in InputDataTypeStrs],
                     type=str)


142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
CPUDataTypeStrs = [
    "fp32",
]

CPUDataType = Enum('CPUDataType', [(ele, ele) for ele in CPUDataTypeStrs],
                   type=str)

GPUDataTypeStrs = [
    "fp16_fp32",
    "fp32_fp32",
]

GPUDataType = Enum('GPUDataType', [(ele, ele) for ele in GPUDataTypeStrs],
                   type=str)

L
liuqi 已提交
157 158 159 160 161 162 163
DSPDataTypeStrs = [
    "uint8",
]

DSPDataType = Enum('DSPDataType', [(ele, ele) for ele in DSPDataTypeStrs],
                   type=str)

164 165
WinogradParameters = [0, 2, 4]

166 167 168 169 170 171 172 173 174 175
DataFormatStrs = [
    "NONE",
    "NHWC",
]


class DataFormat(object):
    NONE = "NONE"
    NHWC = "NHWC"

176 177

class DefaultValues(object):
178
    mace_lib_type = MACELibType.static
179 180 181 182 183 184 185 186 187 188
    omp_num_threads = -1,
    cpu_affinity_policy = 1,
    gpu_perf_hint = 3,
    gpu_priority_hint = 3,


class YAMLKeyword(object):
    library_name = 'library_name'
    target_abis = 'target_abis'
    target_socs = 'target_socs'
189 190
    model_graph_format = 'model_graph_format'
    model_data_format = 'model_data_format'
191 192 193 194 195 196 197 198 199
    models = 'models'
    platform = 'platform'
    model_file_path = 'model_file_path'
    model_sha256_checksum = 'model_sha256_checksum'
    weight_file_path = 'weight_file_path'
    weight_sha256_checksum = 'weight_sha256_checksum'
    subgraphs = 'subgraphs'
    input_tensors = 'input_tensors'
    input_shapes = 'input_shapes'
李寅 已提交
200
    input_ranges = 'input_ranges'
201 202
    output_tensors = 'output_tensors'
    output_shapes = 'output_shapes'
B
Bin Li 已提交
203 204
    check_tensors = 'check_tensors'
    check_shapes = 'check_shapes'
205 206
    runtime = 'runtime'
    data_type = 'data_type'
Y
yejianwu 已提交
207
    input_data_types = 'input_data_types'
208 209
    input_data_formats = 'input_data_formats'
    output_data_formats = 'output_data_formats'
210 211 212 213
    limit_opencl_kernel_time = 'limit_opencl_kernel_time'
    nnlib_graph_mode = 'nnlib_graph_mode'
    obfuscate = 'obfuscate'
    winograd = 'winograd'
李寅 已提交
214 215
    quantize = 'quantize'
    quantize_range_file = 'quantize_range_file'
216
    change_concat_ranges = 'change_concat_ranges'
217
    validation_inputs_data = 'validation_inputs_data'
218
    validation_threshold = 'validation_threshold'
李寅 已提交
219
    graph_optimize_options = 'graph_optimize_options'  # internal use for now
220
    cl_mem_type = 'cl_mem_type'
221 222 223 224 225


class ModuleName(object):
    YAML_CONFIG = 'YAML CONFIG'
    MODEL_CONVERTER = 'Model Converter'
L
liuqi 已提交
226 227
    RUN = 'RUN'
    BENCHMARK = 'Benchmark'
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249


CPP_KEYWORDS = [
    'alignas', 'alignof', 'and', 'and_eq', 'asm', 'atomic_cancel',
    'atomic_commit', 'atomic_noexcept', 'auto', 'bitand', 'bitor',
    'bool', 'break', 'case', 'catch', 'char', 'char16_t', 'char32_t',
    'class', 'compl', 'concept', 'const', 'constexpr', 'const_cast',
    'continue', 'co_await', 'co_return', 'co_yield', 'decltype', 'default',
    'delete', 'do', 'double', 'dynamic_cast', 'else', 'enum', 'explicit',
    'export', 'extern', 'false', 'float', 'for', 'friend', 'goto', 'if',
    'import', 'inline', 'int', 'long', 'module', 'mutable', 'namespace',
    'new', 'noexcept', 'not', 'not_eq', 'nullptr', 'operator', 'or', 'or_eq',
    'private', 'protected', 'public', 'register', 'reinterpret_cast',
    'requires', 'return', 'short', 'signed', 'sizeof', 'static',
    'static_assert', 'static_cast', 'struct', 'switch', 'synchronized',
    'template', 'this', 'thread_local', 'throw', 'true', 'try', 'typedef',
    'typeid', 'typename', 'union', 'unsigned', 'using', 'virtual', 'void',
    'volatile', 'wchar_t', 'while', 'xor', 'xor_eq', 'override', 'final',
    'transaction_safe', 'transaction_safe_dynamic', 'if', 'elif', 'else',
    'endif', 'defined', 'ifdef', 'ifndef', 'define', 'undef', 'include',
    'line', 'error', 'pragma',
]
Y
yejianwu 已提交
250

251

252 253 254
################################
# common functions
################################
255
def parse_device_type(runtime):
Y
yejianwu 已提交
256
    device_type = ""
257

258
    if runtime == RuntimeType.dsp:
259
        device_type = DeviceType.HEXAGON
260
    elif runtime == RuntimeType.gpu:
261
        device_type = DeviceType.GPU
262
    elif runtime == RuntimeType.cpu:
263
        device_type = DeviceType.CPU
264

265
    return device_type
266

Y
yejianwu 已提交
267 268

def get_hexagon_mode(configs):
L
Liangliang He 已提交
269
    runtime_list = []
L
liuqi 已提交
270 271 272 273
    for model_name in configs[YAMLKeyword.models]:
        model_runtime =\
            configs[YAMLKeyword.models][model_name].get(
                YAMLKeyword.runtime, "")
L
Liangliang He 已提交
274 275
        runtime_list.append(model_runtime.lower())

L
liuqi 已提交
276
    if RuntimeType.dsp in runtime_list:
Y
yejianwu 已提交
277 278 279 280
        return True
    return False


Y
yejianwu 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293
def get_opencl_mode(configs):
    runtime_list = []
    for model_name in configs[YAMLKeyword.models]:
        model_runtime =\
            configs[YAMLKeyword.models][model_name].get(
                YAMLKeyword.runtime, "")
        runtime_list.append(model_runtime.lower())

    if RuntimeType.gpu in runtime_list or RuntimeType.cpu_gpu in runtime_list:
        return True
    return False


294 295 296 297 298 299 300 301 302 303 304
def get_quantize_mode(configs):
    for model_name in configs[YAMLKeyword.models]:
        quantize =\
            configs[YAMLKeyword.models][model_name].get(
                YAMLKeyword.quantize, 0)
        if quantize == 1:
            return True

    return False


305 306
def md5sum(str):
    md5 = hashlib.md5()
307
    md5.update(str.encode('utf-8'))
308
    return md5.hexdigest()
309

Y
yejianwu 已提交
310

311 312 313 314 315 316
def sha256_checksum(fname):
    hash_func = hashlib.sha256()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_func.update(chunk)
    return hash_func.hexdigest()
Y
yejianwu 已提交
317

W
wuchenghui 已提交
318

319 320
def format_model_config(flags):
    with open(flags.config) as f:
321
        configs = yaml.load(f)
W
wuchenghui 已提交
322

323 324
    library_name = configs.get(YAMLKeyword.library_name, "")
    mace_check(len(library_name) > 0,
L
liuqi 已提交
325
               ModuleName.YAML_CONFIG, "library name should not be empty")
326

327 328 329 330
    if flags.target_abis:
        target_abis = flags.target_abis.split(',')
    else:
        target_abis = configs.get(YAMLKeyword.target_abis, [])
331 332
    mace_check((isinstance(target_abis, list) and len(target_abis) > 0),
               ModuleName.YAML_CONFIG, "target_abis list is needed")
333
    configs[YAMLKeyword.target_abis] = target_abis
334 335 336 337 338 339
    for abi in target_abis:
        mace_check(abi in ABITypeStrs,
                   ModuleName.YAML_CONFIG,
                   "target_abis must be in " + str(ABITypeStrs))

    target_socs = configs.get(YAMLKeyword.target_socs, "")
340 341 342 343
    if flags.target_socs:
        configs[YAMLKeyword.target_socs] = \
               [soc.lower() for soc in flags.target_socs.split(',')]
    elif not target_socs:
344 345 346 347
        configs[YAMLKeyword.target_socs] = []
    elif not isinstance(target_socs, list):
        configs[YAMLKeyword.target_socs] = [target_socs]

348 349 350
    configs[YAMLKeyword.target_socs] = \
        [soc.lower() for soc in configs[YAMLKeyword.target_socs]]

L
liuqi 已提交
351 352
    if ABIType.armeabi_v7a in target_abis \
            or ABIType.arm64_v8a in target_abis:
353
        available_socs = sh_commands.adb_get_all_socs()
354 355 356 357 358 359 360
        target_socs = configs[YAMLKeyword.target_socs]
        if ALL_SOC_TAG in target_socs:
            mace_check(available_socs,
                       ModuleName.YAML_CONFIG,
                       "Build for all SOCs plugged in computer, "
                       "you at least plug in one phone")
        else:
361 362 363 364 365 366
            for soc in target_socs:
                mace_check(soc in available_socs,
                           ModuleName.YAML_CONFIG,
                           "Build specified SOC library, "
                           "you must plug in a phone using the SOC")

367 368
    if flags.model_graph_format:
        model_graph_format = flags.model_graph_format
369
    else:
370 371 372 373 374 375 376 377
        model_graph_format = configs.get(YAMLKeyword.model_graph_format, "")
    mace_check(model_graph_format in ModelFormatStrs,
               ModuleName.YAML_CONFIG,
               'You must set model_graph_format and '
               "model_graph_format must be in " + str(ModelFormatStrs))
    configs[YAMLKeyword.model_graph_format] = model_graph_format
    if flags.model_data_format:
        model_data_format = flags.model_data_format
378
    else:
379 380 381 382 383 384 385 386 387 388 389 390
        model_data_format = configs.get(YAMLKeyword.model_data_format, "")
    configs[YAMLKeyword.model_data_format] = model_data_format
    mace_check(model_data_format in ModelFormatStrs,
               ModuleName.YAML_CONFIG,
               'You must set model_data_format and '
               "model_data_format must be in " + str(ModelFormatStrs))

    mace_check(not (model_graph_format == ModelFormat.file
                    and model_data_format == ModelFormat.code),
               ModuleName.YAML_CONFIG,
               "If model_graph format is 'file',"
               " the model_data_format must be 'file' too")
Y
yejianwu 已提交
391

392 393 394 395
    model_names = configs.get(YAMLKeyword.models, [])
    mace_check(len(model_names) > 0, ModuleName.YAML_CONFIG,
               "no model found in config file")

L
liuqi 已提交
396
    model_name_reg = re.compile(r'^[a-zA-Z0-9_]+$')
397 398 399 400 401 402 403 404
    for model_name in model_names:
        # check model_name legality
        mace_check(model_name not in CPP_KEYWORDS,
                   ModuleName.YAML_CONFIG,
                   "model name should not be c++ keyword.")
        mace_check((model_name[0] == '_' or model_name[0].isalpha())
                   and bool(model_name_reg.match(model_name)),
                   ModuleName.YAML_CONFIG,
L
liuqi 已提交
405
                   "model name should Meet the c++ naming convention"
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
                   " which start with '_' or alpha"
                   " and only contain alpha, number and '_'")

        model_config = configs[YAMLKeyword.models][model_name]
        platform = model_config.get(YAMLKeyword.platform, "")
        mace_check(platform in PlatformTypeStrs,
                   ModuleName.YAML_CONFIG,
                   "'platform' must be in " + str(PlatformTypeStrs))

        for key in [YAMLKeyword.model_file_path,
                    YAMLKeyword.model_sha256_checksum]:
            value = model_config.get(key, "")
            mace_check(value != "", ModuleName.YAML_CONFIG,
                       "'%s' is necessary" % key)

        weight_file_path = model_config.get(YAMLKeyword.weight_file_path, "")
        if weight_file_path:
            weight_checksum =\
                model_config.get(YAMLKeyword.weight_sha256_checksum, "")
            mace_check(weight_checksum != "", ModuleName.YAML_CONFIG,
                       "'%s' is necessary" %
                       YAMLKeyword.weight_sha256_checksum)
        else:
            model_config[YAMLKeyword.weight_sha256_checksum] = ""

        runtime = model_config.get(YAMLKeyword.runtime, "")
        mace_check(runtime in RuntimeTypeStrs,
                   ModuleName.YAML_CONFIG,
                   "'runtime' must be in " + str(RuntimeTypeStrs))
        if ABIType.host in target_abis:
            mace_check(runtime == RuntimeType.cpu,
                       ModuleName.YAML_CONFIG,
                       "host only support cpu runtime now.")

        data_type = model_config.get(YAMLKeyword.data_type, "")
        if runtime == RuntimeType.cpu_gpu and data_type not in GPUDataTypeStrs:
            model_config[YAMLKeyword.data_type] = \
                GPUDataType.fp16_fp32.value
        elif runtime == RuntimeType.cpu:
            if len(data_type) > 0:
                mace_check(data_type in CPUDataTypeStrs,
                           ModuleName.YAML_CONFIG,
                           "'data_type' must be in " + str(CPUDataTypeStrs)
                           + " for cpu runtime")
            else:
                model_config[YAMLKeyword.data_type] = \
                    CPUDataType.fp32.value
        elif runtime == RuntimeType.gpu:
            if len(data_type) > 0:
                mace_check(data_type in GPUDataTypeStrs,
                           ModuleName.YAML_CONFIG,
                           "'data_type' must be in " + str(GPUDataTypeStrs)
                           + " for gpu runtime")
            else:
                model_config[YAMLKeyword.data_type] =\
                    GPUDataType.fp16_fp32.value
L
liuqi 已提交
462 463 464 465 466 467 468 469 470
        elif runtime == RuntimeType.dsp:
            if len(data_type) > 0:
                mace_check(data_type in DSPDataTypeStrs,
                           ModuleName.YAML_CONFIG,
                           "'data_type' must be in " + str(DSPDataTypeStrs)
                           + " for dsp runtime")
            else:
                model_config[YAMLKeyword.data_type] = \
                    DSPDataType.uint8.value
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485

        subgraphs = model_config.get(YAMLKeyword.subgraphs, "")
        mace_check(len(subgraphs) > 0, ModuleName.YAML_CONFIG,
                   "at least one subgraph is needed")

        for subgraph in subgraphs:
            for key in [YAMLKeyword.input_tensors,
                        YAMLKeyword.input_shapes,
                        YAMLKeyword.output_tensors,
                        YAMLKeyword.output_shapes]:
                value = subgraph.get(key, "")
                mace_check(value != "", ModuleName.YAML_CONFIG,
                           "'%s' is necessary in subgraph" % key)
                if not isinstance(value, list):
                    subgraph[key] = [value]
486
                subgraph[key] = [str(v) for v in subgraph[key]]
487

B
Bin Li 已提交
488 489 490 491 492 493 494 495 496 497
            for key in [YAMLKeyword.check_tensors,
                        YAMLKeyword.check_shapes]:
                value = subgraph.get(key, "")
                if value != "":
                    if not isinstance(value, list):
                        subgraph[key] = [value]
                    subgraph[key] = [str(v) for v in subgraph[key]]
                else:
                    subgraph[key] = []

Y
yejianwu 已提交
498 499 500 501
            input_data_types = subgraph.get(YAMLKeyword.input_data_types, "")
            if input_data_types:
                if not isinstance(input_data_types, list):
                    subgraph[YAMLKeyword.input_data_types] = [input_data_types]
502
                for input_data_type in subgraph[YAMLKeyword.input_data_types]:
Y
yejianwu 已提交
503 504 505 506 507 508 509
                    mace_check(input_data_type in InputDataTypeStrs,
                               ModuleName.YAML_CONFIG,
                               "'input_data_types' must be in "
                               + str(InputDataTypeStrs))
            else:
                subgraph[YAMLKeyword.input_data_types] = []

510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
            input_data_formats = subgraph.get(YAMLKeyword.input_data_formats,
                                              [])
            if input_data_formats:
                if not isinstance(input_data_formats, list):
                    subgraph[YAMLKeyword.input_data_formats] =\
                        [input_data_formats]
                else:
                    mace_check(len(input_data_formats)
                               == len(subgraph[YAMLKeyword.input_tensors]),
                               ModuleName.YAML_CONFIG,
                               "input_data_formats should match"
                               " the size of input")
                for input_data_format in\
                        subgraph[YAMLKeyword.input_data_formats]:
                    mace_check(input_data_format in DataFormatStrs,
                               ModuleName.YAML_CONFIG,
                               "'input_data_formats' must be in "
                               + str(DataFormatStrs) + ", but got "
                               + input_data_formats)
            else:
                subgraph[YAMLKeyword.input_data_formats] = [DataFormat.NHWC]

            output_data_formats = subgraph.get(YAMLKeyword.output_data_formats,
                                               [])
            if output_data_formats:
                if not isinstance(output_data_formats, list):
                    subgraph[YAMLKeyword.output_data_formats] = \
                        [output_data_formats]
                else:
                    mace_check(len(output_data_formats)
                               == len(subgraph[YAMLKeyword.output_tensors]),
                               ModuleName.YAML_CONFIG,
                               "output_data_formats should match"
                               " the size of output")
                for output_data_format in\
                        subgraph[YAMLKeyword.output_data_formats]:
                    mace_check(output_data_format in DataFormatStrs,
                               ModuleName.YAML_CONFIG,
                               "'input_data_formats' must be in "
                               + str(DataFormatStrs))
            else:
                subgraph[YAMLKeyword.output_data_formats] = [DataFormat.NHWC]

553 554 555 556 557 558 559 560 561 562
            validation_threshold = subgraph.get(
                YAMLKeyword.validation_threshold, {})
            if not isinstance(validation_threshold, dict):
                raise argparse.ArgumentTypeError(
                        'similarity threshold must be a dict.')

            threshold_dict = {
                    DeviceType.CPU: 0.999,
                    DeviceType.GPU: 0.995,
                    DeviceType.HEXAGON: 0.930,
李寅 已提交
563
                    DeviceType.CPU + "_QUANTIZE": 0.980,
564 565 566 567 568 569
                    }
            for k, v in six.iteritems(validation_threshold):
                if k.upper() == 'DSP':
                    k = DeviceType.HEXAGON
                if k.upper() not in (DeviceType.CPU,
                                     DeviceType.GPU,
李寅 已提交
570 571
                                     DeviceType.HEXAGON,
                                     DeviceType.CPU + "_QUANTIZE"):
572 573 574 575 576 577
                    raise argparse.ArgumentTypeError(
                            'Unsupported validation threshold runtime: %s' % k)
                threshold_dict[k.upper()] = v

            subgraph[YAMLKeyword.validation_threshold] = threshold_dict

L
liuqi 已提交
578 579 580 581 582 583 584 585
            validation_inputs_data = subgraph.get(
                YAMLKeyword.validation_inputs_data, [])
            if not isinstance(validation_inputs_data, list):
                subgraph[YAMLKeyword.validation_inputs_data] = [
                    validation_inputs_data]
            else:
                subgraph[YAMLKeyword.validation_inputs_data] = \
                    validation_inputs_data
586 587 588 589 590 591
            input_ranges = subgraph.get(
                YAMLKeyword.input_ranges, [])
            if not isinstance(input_ranges, list):
                subgraph[YAMLKeyword.input_ranges] = [input_ranges]
            else:
                subgraph[YAMLKeyword.input_ranges] = input_ranges
592 593
            subgraph[YAMLKeyword.input_ranges] =\
                [str(v) for v in subgraph[YAMLKeyword.input_ranges]]
W
wuchenghui 已提交
594

595 596 597
        for key in [YAMLKeyword.limit_opencl_kernel_time,
                    YAMLKeyword.nnlib_graph_mode,
                    YAMLKeyword.obfuscate,
李寅 已提交
598
                    YAMLKeyword.winograd,
599 600
                    YAMLKeyword.quantize,
                    YAMLKeyword.change_concat_ranges]:
601 602 603
            value = model_config.get(key, "")
            if value == "":
                model_config[key] = 0
L
Liangliang He 已提交
604

605 606 607 608 609 610
        mace_check(model_config[YAMLKeyword.winograd] in WinogradParameters,
                   ModuleName.YAML_CONFIG,
                   "'winograd' parameters must be in "
                   + str(WinogradParameters) +
                   ". 0 for disable winograd convolution")

L
liuqi 已提交
611 612
        weight_file_path = model_config.get(YAMLKeyword.weight_file_path, "")
        model_config[YAMLKeyword.weight_file_path] = weight_file_path
Y
yejianwu 已提交
613

614
    return configs
Y
yejianwu 已提交
615

W
wuchenghui 已提交
616

617
def get_build_binary_dir(library_name, target_abi):
618
    return "%s/%s/%s/%s" % (
619
        BUILD_OUTPUT_DIR, library_name, BUILD_TMP_DIR_NAME, target_abi)
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638


def get_build_model_dirs(library_name, model_name, target_abi, target_soc,
                         serial_num, model_file_path):
    model_path_digest = md5sum(model_file_path)
    model_output_base_dir = "%s/%s/%s/%s/%s" % (
        BUILD_OUTPUT_DIR, library_name, BUILD_TMP_DIR_NAME,
        model_name, model_path_digest)

    if target_abi == ABIType.host:
        model_output_dir = "%s/%s" % (model_output_base_dir, target_abi)
    elif not target_soc or not serial_num:
        model_output_dir = "%s/%s/%s" % (
            model_output_base_dir, BUILD_TMP_GENERAL_OUTPUT_DIR_NAME,
            target_abi)
    else:
        device_name = \
            sh_commands.adb_get_device_name_by_serialno(serial_num)
        model_output_dir = "%s/%s_%s/%s" % (
L
liuqi 已提交
639
            model_output_base_dir, device_name,
640
            target_soc, target_abi)
Y
yejianwu 已提交
641

642 643 644 645 646 647
    mace_model_dir = \
        '%s/%s/%s' % (BUILD_OUTPUT_DIR, library_name, MODEL_OUTPUT_DIR_NAME)

    return model_output_base_dir, model_output_dir, mace_model_dir


L
liuqi 已提交
648 649 650 651 652
def get_opencl_binary_output_path(library_name, target_abi,
                                  target_soc, serial_num):
    device_name = \
        sh_commands.adb_get_device_name_by_serialno(serial_num)
    return '%s/%s/%s/%s/%s_%s.%s.%s.bin' % \
653 654 655
           (BUILD_OUTPUT_DIR,
            library_name,
            OUTPUT_OPENCL_BINARY_DIR_NAME,
L
liuqi 已提交
656 657 658 659 660
            target_abi,
            library_name,
            OUTPUT_OPENCL_BINARY_FILE_NAME,
            device_name,
            target_soc)
661 662


L
liuqi 已提交
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
def get_opencl_parameter_output_path(library_name, target_abi,
                                     target_soc, serial_num):
    device_name = \
        sh_commands.adb_get_device_name_by_serialno(serial_num)
    return '%s/%s/%s/%s/%s_%s.%s.%s.bin' % \
           (BUILD_OUTPUT_DIR,
            library_name,
            OUTPUT_OPENCL_BINARY_DIR_NAME,
            target_abi,
            library_name,
            OUTPUT_OPENCL_PARAMETER_FILE_NAME,
            device_name,
            target_soc)


678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
def clear_build_dirs(library_name):
    # make build dir
    if not os.path.exists(BUILD_OUTPUT_DIR):
        os.makedirs(BUILD_OUTPUT_DIR)
    # clear temp build dir
    tmp_build_dir = os.path.join(BUILD_OUTPUT_DIR, library_name,
                                 BUILD_TMP_DIR_NAME)
    if os.path.exists(tmp_build_dir):
        sh.rm('-rf', tmp_build_dir)
    os.makedirs(tmp_build_dir)
    # clear lib dir
    lib_output_dir = os.path.join(
        BUILD_OUTPUT_DIR, library_name, OUTPUT_LIBRARY_DIR_NAME)
    if os.path.exists(lib_output_dir):
        sh.rm('-rf', lib_output_dir)


def check_model_converted(library_name, model_name,
L
liuqi 已提交
696 697
                          model_graph_format, model_data_format,
                          abi):
698 699 700 701 702
    model_output_dir = \
        '%s/%s/%s' % (BUILD_OUTPUT_DIR, library_name, MODEL_OUTPUT_DIR_NAME)
    if model_graph_format == ModelFormat.file:
        mace_check(os.path.exists("%s/%s.pb" % (model_output_dir, model_name)),
                   ModuleName.RUN,
L
liuqi 已提交
703
                   "You should convert model first.")
704
    else:
L
liuqi 已提交
705 706
        model_lib_path = get_model_lib_output_path(library_name, abi)
        mace_check(os.path.exists(model_lib_path),
707
                   ModuleName.RUN,
L
liuqi 已提交
708
                   "You should convert model first.")
709 710 711 712
    if model_data_format == ModelFormat.file:
        mace_check(os.path.exists("%s/%s.data" %
                                  (model_output_dir, model_name)),
                   ModuleName.RUN,
L
liuqi 已提交
713
                   "You should convert model first.")
714 715


716 717 718 719
################################
# convert
################################
def print_configuration(configs):
720 721 722 723 724 725 726 727 728
    title = "Common Configuration"
    header = ["key", "value"]
    data = list()
    data.append([YAMLKeyword.library_name,
                 configs[YAMLKeyword.library_name]])
    data.append([YAMLKeyword.target_abis,
                 configs[YAMLKeyword.target_abis]])
    data.append([YAMLKeyword.target_socs,
                 configs[YAMLKeyword.target_socs]])
729 730 731 732
    data.append([YAMLKeyword.model_graph_format,
                 configs[YAMLKeyword.model_graph_format]])
    data.append([YAMLKeyword.model_data_format,
                 configs[YAMLKeyword.model_data_format]])
733
    MaceLogger.summary(StringFormatter.table(header, data, title))
L
Liangliang He 已提交
734

Y
yejianwu 已提交
735

736 737 738 739
def download_file(url, dst, num_retries=3):
    from six.moves import urllib

    try:
740
        urllib.request.urlretrieve(url, dst)
741
        MaceLogger.info('\nDownloaded successfully.')
L
liuqi 已提交
742 743
    except (urllib.error.ContentTooShortError, urllib.error.HTTPError,
            urllib.error.URLError) as e:
L
liuqi 已提交
744
        MaceLogger.warning('Download error:', e)
745 746 747 748 749 750 751
        if num_retries > 0:
            return download_file(url, dst, num_retries - 1)
        else:
            return False
    return True


B
Bin Li 已提交
752 753 754 755 756 757 758
def get_model_files(model_file_path,
                    model_sha256_checksum,
                    model_output_dir,
                    weight_file_path="",
                    weight_sha256_checksum=""):
    model_file = model_file_path
    weight_file = weight_file_path
759 760 761

    if model_file_path.startswith("http://") or \
            model_file_path.startswith("https://"):
B
Bin Li 已提交
762 763 764 765
        model_file = model_output_dir + "/" + md5sum(model_file_path) + ".pb"
        if not os.path.exists(model_file) or \
                sha256_checksum(model_file) != model_sha256_checksum:
            MaceLogger.info("Downloading model, please wait ...")
766 767 768
            if not download_file(model_file_path, model_file):
                MaceLogger.error(ModuleName.MODEL_CONVERTER,
                                 "Model download failed.")
B
Bin Li 已提交
769 770 771 772

    if sha256_checksum(model_file) != model_sha256_checksum:
        MaceLogger.error(ModuleName.MODEL_CONVERTER,
                         "model file sha256checksum not match")
L
Liangliang He 已提交
773 774 775

    if weight_file_path.startswith("http://") or \
            weight_file_path.startswith("https://"):
B
Bin Li 已提交
776 777 778 779 780
        weight_file = \
            model_output_dir + "/" + md5sum(weight_file_path) + ".caffemodel"
        if not os.path.exists(weight_file) or \
                sha256_checksum(weight_file) != weight_sha256_checksum:
            MaceLogger.info("Downloading model weight, please wait ...")
781 782 783
            if not download_file(weight_file_path, weight_file):
                MaceLogger.error(ModuleName.MODEL_CONVERTER,
                                 "Model download failed.")
B
Bin Li 已提交
784 785 786 787 788

    if weight_file:
        if sha256_checksum(weight_file) != weight_sha256_checksum:
            MaceLogger.error(ModuleName.MODEL_CONVERTER,
                             "weight file sha256checksum not match")
Y
yejianwu 已提交
789 790

    return model_file, weight_file
L
Liangliang He 已提交
791

L
liuqi 已提交
792

793
def convert_model(configs, cl_mem_type):
794 795 796 797
    # Remove previous output dirs
    library_name = configs[YAMLKeyword.library_name]
    if not os.path.exists(BUILD_OUTPUT_DIR):
        os.makedirs(BUILD_OUTPUT_DIR)
L
liuqi 已提交
798 799 800
    elif os.path.exists(os.path.join(BUILD_OUTPUT_DIR, library_name)):
        sh.rm("-rf", os.path.join(BUILD_OUTPUT_DIR, library_name))
    os.makedirs(os.path.join(BUILD_OUTPUT_DIR, library_name))
B
Bin Li 已提交
801 802
    if not os.path.exists(BUILD_DOWNLOADS_DIR):
        os.makedirs(BUILD_DOWNLOADS_DIR)
803 804 805

    model_output_dir = \
        '%s/%s/%s' % (BUILD_OUTPUT_DIR, library_name, MODEL_OUTPUT_DIR_NAME)
L
liuqi 已提交
806 807
    model_header_dir = \
        '%s/%s/%s' % (BUILD_OUTPUT_DIR, library_name, MODEL_HEADER_DIR_PATH)
808
    # clear output dir
809 810 811
    if os.path.exists(model_output_dir):
        sh.rm("-rf", model_output_dir)
    os.makedirs(model_output_dir)
L
liuqi 已提交
812 813
    if os.path.exists(model_header_dir):
        sh.rm("-rf", model_header_dir)
814 815 816 817 818 819 820 821 822 823 824 825 826 827

    embed_model_data = \
        configs[YAMLKeyword.model_data_format] == ModelFormat.code

    if os.path.exists(MODEL_CODEGEN_DIR):
        sh.rm("-rf", MODEL_CODEGEN_DIR)
    if os.path.exists(ENGINE_CODEGEN_DIR):
        sh.rm("-rf", ENGINE_CODEGEN_DIR)

    if configs[YAMLKeyword.model_graph_format] == ModelFormat.code:
        os.makedirs(model_header_dir)
        sh_commands.gen_mace_engine_factory_source(
            configs[YAMLKeyword.models].keys(),
            embed_model_data)
L
liuqi 已提交
828 829 830
        sh.cp("-f", glob.glob("mace/codegen/engine/*.h"),
              model_header_dir)

831 832 833 834 835
    for model_name in configs[YAMLKeyword.models]:
        MaceLogger.header(
            StringFormatter.block("Convert %s model" % model_name))
        model_config = configs[YAMLKeyword.models][model_name]
        runtime = model_config[YAMLKeyword.runtime]
836 837 838 839
        if cl_mem_type:
            model_config[YAMLKeyword.cl_mem_type] = cl_mem_type
        else:
            model_config[YAMLKeyword.cl_mem_type] = "image"
840

B
Bin Li 已提交
841
        model_file_path, weight_file_path = get_model_files(
842
            model_config[YAMLKeyword.model_file_path],
B
Bin Li 已提交
843 844 845 846
            model_config[YAMLKeyword.model_sha256_checksum],
            BUILD_DOWNLOADS_DIR,
            model_config[YAMLKeyword.weight_file_path],
            model_config[YAMLKeyword.weight_sha256_checksum])
847 848 849 850 851

        data_type = model_config[YAMLKeyword.data_type]
        # TODO(liuqi): support multiple subgraphs
        subgraphs = model_config[YAMLKeyword.subgraphs]

L
liuqi 已提交
852
        model_codegen_dir = "%s/%s" % (MODEL_CODEGEN_DIR, model_name)
853 854 855 856 857 858 859 860
        sh_commands.gen_model_code(
            model_codegen_dir,
            model_config[YAMLKeyword.platform],
            model_file_path,
            weight_file_path,
            model_config[YAMLKeyword.model_sha256_checksum],
            model_config[YAMLKeyword.weight_sha256_checksum],
            ",".join(subgraphs[0][YAMLKeyword.input_tensors]),
861
            ",".join(subgraphs[0][YAMLKeyword.input_data_formats]),
862
            ",".join(subgraphs[0][YAMLKeyword.output_tensors]),
863
            ",".join(subgraphs[0][YAMLKeyword.output_data_formats]),
B
Bin Li 已提交
864
            ",".join(subgraphs[0][YAMLKeyword.check_tensors]),
865 866 867
            runtime,
            model_name,
            ":".join(subgraphs[0][YAMLKeyword.input_shapes]),
李寅 已提交
868
            ":".join(subgraphs[0][YAMLKeyword.input_ranges]),
B
Bin Li 已提交
869 870
            ":".join(subgraphs[0][YAMLKeyword.output_shapes]),
            ":".join(subgraphs[0][YAMLKeyword.check_shapes]),
871 872 873
            model_config[YAMLKeyword.nnlib_graph_mode],
            embed_model_data,
            model_config[YAMLKeyword.winograd],
李寅 已提交
874 875
            model_config[YAMLKeyword.quantize],
            model_config.get(YAMLKeyword.quantize_range_file, ""),
876
            model_config[YAMLKeyword.change_concat_ranges],
877
            model_config[YAMLKeyword.obfuscate],
878
            configs[YAMLKeyword.model_graph_format],
李寅 已提交
879
            data_type,
880
            model_config[YAMLKeyword.cl_mem_type],
李寅 已提交
881
            ",".join(model_config.get(YAMLKeyword.graph_optimize_options, [])))
882

883
        if configs[YAMLKeyword.model_graph_format] == ModelFormat.file:
L
liuqi 已提交
884 885 886
            sh.mv("-f",
                  '%s/%s.pb' % (model_codegen_dir, model_name),
                  model_output_dir)
L
liuqi 已提交
887 888 889
            sh.mv("-f",
                  '%s/%s.data' % (model_codegen_dir, model_name),
                  model_output_dir)
L
liuqi 已提交
890 891
        else:
            if not embed_model_data:
L
liuqi 已提交
892
                sh.mv("-f",
L
liuqi 已提交
893
                      '%s/%s.data' % (model_codegen_dir, model_name),
L
liuqi 已提交
894
                      model_output_dir)
L
liuqi 已提交
895 896
            sh.cp("-f", glob.glob("mace/codegen/models/*/*.h"),
                  model_header_dir)
897

L
liuqi 已提交
898
        MaceLogger.summary(
899 900 901
            StringFormatter.block("Model %s converted" % model_name))


L
liuqi 已提交
902 903 904 905
def get_model_lib_output_path(library_name, abi):
    lib_output_path = os.path.join(BUILD_OUTPUT_DIR, library_name,
                                   MODEL_OUTPUT_DIR_NAME, abi,
                                   "%s.a" % library_name)
906
    return lib_output_path
907 908


909 910
def build_model_lib(configs, address_sanitizer):
    MaceLogger.header(StringFormatter.block("Building model library"))
911

912 913 914 915
    # create model library dir
    library_name = configs[YAMLKeyword.library_name]
    for target_abi in configs[YAMLKeyword.target_abis]:
        hexagon_mode = get_hexagon_mode(configs)
L
liuqi 已提交
916 917 918 919 920
        model_lib_output_path = get_model_lib_output_path(library_name,
                                                          target_abi)
        library_out_dir = os.path.dirname(model_lib_output_path)
        if not os.path.exists(library_out_dir):
            os.makedirs(library_out_dir)
921 922

        sh_commands.bazel_build(
923
            MODEL_LIB_TARGET,
924 925
            abi=target_abi,
            hexagon_mode=hexagon_mode,
Y
yejianwu 已提交
926
            enable_opencl=get_opencl_mode(configs),
927
            enable_quantize=get_quantize_mode(configs),
928 929
            address_sanitizer=address_sanitizer,
            symbol_hidden=True
930 931
        )

932
        sh.cp("-f", MODEL_LIB_PATH, model_lib_output_path)
933 934 935 936 937 938 939


def print_library_summary(configs):
    library_name = configs[YAMLKeyword.library_name]
    title = "Library"
    header = ["key", "value"]
    data = list()
940 941 942 943 944 945 946 947 948
    data.append(["MACE Model Path",
                 "%s/%s/%s"
                 % (BUILD_OUTPUT_DIR, library_name, MODEL_OUTPUT_DIR_NAME)])
    if configs[YAMLKeyword.model_graph_format] == ModelFormat.code:
        data.append(["MACE Model Header Path",
                     "%s/%s/%s"
                     % (BUILD_OUTPUT_DIR, library_name,
                        MODEL_HEADER_DIR_PATH)])

949 950 951
    MaceLogger.summary(StringFormatter.table(header, data, title))


952
def convert_func(flags):
953
    configs = format_model_config(flags)
954

955
    print_configuration(configs)
956

957
    convert_model(configs, flags.cl_mem_type)
958

959 960
    if configs[YAMLKeyword.model_graph_format] == ModelFormat.code:
        build_model_lib(configs, flags.address_sanitizer)
961 962 963 964 965 966 967 968 969 970 971 972

    print_library_summary(configs)


################################
# run
################################
def report_run_statistics(stdout,
                          abi,
                          serialno,
                          model_name,
                          device_type,
973 974
                          output_dir,
                          tuned):
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
    metrics = [0] * 3
    for line in stdout.split('\n'):
        line = line.strip()
        parts = line.split()
        if len(parts) == 4 and parts[0].startswith("time"):
            metrics[0] = str(float(parts[1]))
            metrics[1] = str(float(parts[2]))
            metrics[2] = str(float(parts[3]))
            break

    device_name = ""
    target_soc = ""
    if abi != "host":
        props = sh_commands.adb_getprop_by_serialno(serialno)
        device_name = props.get("ro.product.model", "")
        target_soc = props.get("ro.board.platform", "")

    report_filename = output_dir + "/report.csv"
    if not os.path.exists(report_filename):
        with open(report_filename, 'w') as f:
            f.write("model_name,device_name,soc,abi,runtime,"
996
                    "init(ms),warmup(ms),run_avg(ms),tuned\n")
997 998

    data_str = "{model_name},{device_name},{soc},{abi},{device_type}," \
999
               "{init},{warmup},{run_avg},{tuned}\n" \
1000 1001 1002 1003 1004 1005 1006
        .format(model_name=model_name,
                device_name=device_name,
                soc=target_soc,
                abi=abi,
                device_type=device_type,
                init=metrics[0],
                warmup=metrics[1],
1007
                run_avg=metrics[2],
1008
                tuned=tuned)
1009 1010 1011 1012
    with open(report_filename, 'a') as f:
        f.write(data_str)


1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
def build_mace_run(configs, target_abi, enable_openmp, address_sanitizer,
                   mace_lib_type):
    library_name = configs[YAMLKeyword.library_name]
    hexagon_mode = get_hexagon_mode(configs)

    build_tmp_binary_dir = get_build_binary_dir(library_name, target_abi)
    if os.path.exists(build_tmp_binary_dir):
        sh.rm("-rf", build_tmp_binary_dir)
    os.makedirs(build_tmp_binary_dir)

1023
    symbol_hidden = True
1024 1025
    mace_run_target = MACE_RUN_STATIC_TARGET
    if mace_lib_type == MACELibType.dynamic:
1026
        symbol_hidden = False
1027 1028 1029 1030 1031
        mace_run_target = MACE_RUN_DYNAMIC_TARGET
    build_arg = ""
    if configs[YAMLKeyword.model_graph_format] == ModelFormat.code:
        mace_check(os.path.exists(ENGINE_CODEGEN_DIR),
                   ModuleName.RUN,
L
liuqi 已提交
1032
                   "You should convert model first.")
1033 1034 1035 1036 1037 1038 1039
        build_arg = "--per_file_copt=mace/tools/validation/mace_run.cc@-DMODEL_GRAPH_FORMAT_CODE"  # noqa

    sh_commands.bazel_build(
        mace_run_target,
        abi=target_abi,
        hexagon_mode=hexagon_mode,
        enable_openmp=enable_openmp,
Y
yejianwu 已提交
1040
        enable_opencl=get_opencl_mode(configs),
1041
        enable_quantize=get_quantize_mode(configs),
1042
        address_sanitizer=address_sanitizer,
1043
        symbol_hidden=symbol_hidden,
1044 1045 1046 1047 1048 1049
        extra_args=build_arg
    )
    sh_commands.update_mace_run_binary(build_tmp_binary_dir,
                                       mace_lib_type == MACELibType.dynamic)


L
liuqi 已提交
1050 1051
def build_example(configs, target_abi, enable_openmp, address_sanitizer,
                  mace_lib_type):
1052 1053 1054 1055 1056 1057 1058 1059
    library_name = configs[YAMLKeyword.library_name]
    hexagon_mode = get_hexagon_mode(configs)

    build_tmp_binary_dir = get_build_binary_dir(library_name, target_abi)
    if os.path.exists(build_tmp_binary_dir):
        sh.rm("-rf", build_tmp_binary_dir)
    os.makedirs(build_tmp_binary_dir)

1060
    symbol_hidden = True
1061 1062
    libmace_target = LIBMACE_STATIC_TARGET
    if mace_lib_type == MACELibType.dynamic:
1063
        symbol_hidden = False
1064 1065 1066 1067 1068
        libmace_target = LIBMACE_SO_TARGET

    sh_commands.bazel_build(libmace_target,
                            abi=target_abi,
                            enable_openmp=enable_openmp,
Y
yejianwu 已提交
1069
                            enable_opencl=get_opencl_mode(configs),
1070
                            enable_quantize=get_quantize_mode(configs),
1071
                            hexagon_mode=hexagon_mode,
L
liuqi 已提交
1072
                            address_sanitizer=address_sanitizer,
1073
                            symbol_hidden=symbol_hidden)
1074 1075 1076 1077 1078 1079

    if os.path.exists(LIB_CODEGEN_DIR):
        sh.rm("-rf", LIB_CODEGEN_DIR)
    sh.mkdir("-p", LIB_CODEGEN_DIR)

    build_arg = ""
1080 1081 1082 1083 1084 1085 1086 1087 1088
    if configs[YAMLKeyword.model_graph_format] == ModelFormat.code:
        mace_check(os.path.exists(ENGINE_CODEGEN_DIR),
                   ModuleName.RUN,
                   "You should convert model first.")
        model_lib_path = get_model_lib_output_path(library_name,
                                                   target_abi)
        sh.cp("-f", model_lib_path, LIB_CODEGEN_DIR)
        build_arg = "--per_file_copt=mace/examples/cli/example.cc@-DMODEL_GRAPH_FORMAT_CODE"  # noqa

1089 1090 1091 1092 1093
    if mace_lib_type == MACELibType.dynamic:
        example_target = EXAMPLE_DYNAMIC_TARGET
        sh.cp("-f", LIBMACE_DYNAMIC_PATH, LIB_CODEGEN_DIR)
    else:
        example_target = EXAMPLE_STATIC_TARGET
1094
        sh.cp("-f", LIBMACE_STATIC_PATH, LIB_CODEGEN_DIR)
1095 1096 1097 1098

    sh_commands.bazel_build(example_target,
                            abi=target_abi,
                            enable_openmp=enable_openmp,
Y
yejianwu 已提交
1099
                            enable_opencl=get_opencl_mode(configs),
1100
                            enable_quantize=get_quantize_mode(configs),
1101
                            hexagon_mode=hexagon_mode,
L
liuqi 已提交
1102
                            address_sanitizer=address_sanitizer,
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
                            extra_args=build_arg)

    target_bin = "/".join(sh_commands.bazel_target_to_bin(example_target))
    sh.cp("-f", target_bin, build_tmp_binary_dir)
    if os.path.exists(LIB_CODEGEN_DIR):
        sh.rm("-rf", LIB_CODEGEN_DIR)


def tuning(library_name, model_name, model_config,
           model_graph_format, model_data_format,
           target_abi, target_soc, serial_num,
           mace_lib_type):
1115
    six.print_('* Tuning, it may take some time...')
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140

    build_tmp_binary_dir = get_build_binary_dir(library_name, target_abi)
    mace_run_name = MACE_RUN_STATIC_NAME
    link_dynamic = False
    if mace_lib_type == MACELibType.dynamic:
        mace_run_name = MACE_RUN_DYNAMIC_NAME
        link_dynamic = True

    embed_model_data = model_data_format == ModelFormat.code

    model_output_base_dir, model_output_dir, mace_model_dir = \
        get_build_model_dirs(library_name, model_name, target_abi,
                             target_soc, serial_num,
                             model_config[YAMLKeyword.model_file_path])

    # build for specified soc
    sh_commands.clear_phone_data_dir(serial_num, PHONE_DATA_DIR)

    subgraphs = model_config[YAMLKeyword.subgraphs]
    # generate input data
    sh_commands.gen_random_input(
        model_output_dir,
        subgraphs[0][YAMLKeyword.input_tensors],
        subgraphs[0][YAMLKeyword.input_shapes],
        subgraphs[0][YAMLKeyword.validation_inputs_data],
Y
yejianwu 已提交
1141 1142
        input_ranges=subgraphs[0][YAMLKeyword.input_ranges],
        input_data_types=subgraphs[0][YAMLKeyword.input_data_types])
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

    sh_commands.tuning_run(
        abi=target_abi,
        serialno=serial_num,
        target_dir=build_tmp_binary_dir,
        target_name=mace_run_name,
        vlog_level=0,
        embed_model_data=embed_model_data,
        model_output_dir=model_output_dir,
        input_nodes=subgraphs[0][YAMLKeyword.input_tensors],
        output_nodes=subgraphs[0][YAMLKeyword.output_tensors],
        input_shapes=subgraphs[0][YAMLKeyword.input_shapes],
        output_shapes=subgraphs[0][YAMLKeyword.output_shapes],
        mace_model_dir=mace_model_dir,
        model_tag=model_name,
        device_type=DeviceType.GPU,
        running_round=0,
        restart_round=1,
        limit_opencl_kernel_time=model_config[YAMLKeyword.limit_opencl_kernel_time],  # noqa
        tuning=True,
        out_of_range_check=False,
        phone_data_dir=PHONE_DATA_DIR,
        model_graph_format=model_graph_format,
        opencl_binary_file="",
        opencl_parameter_file="",
        libmace_dynamic_library_path=LIBMACE_DYNAMIC_PATH,
        link_dynamic=link_dynamic,
    )
    # pull opencl binary
    sh_commands.pull_file_from_device(
        serial_num,
        DEVICE_INTERIOR_DIR,
        CL_COMPILED_BINARY_FILE_NAME,
        "%s/%s" % (model_output_dir, BUILD_TMP_OPENCL_BIN_DIR))

    # pull opencl parameter
    sh_commands.pull_file_from_device(
        serial_num,
        PHONE_DATA_DIR,
        CL_TUNED_PARAMETER_FILE_NAME,
        "%s/%s" % (model_output_dir, BUILD_TMP_OPENCL_BIN_DIR))

1185
    six.print_('Tuning done\n')
1186 1187


1188 1189 1190
def run_specific_target(flags, configs, target_abi,
                        target_soc, serial_num):
    library_name = configs[YAMLKeyword.library_name]
1191 1192 1193 1194
    mace_lib_type = flags.mace_lib_type
    embed_model_data = \
        configs[YAMLKeyword.model_data_format] == ModelFormat.code
    build_tmp_binary_dir = get_build_binary_dir(library_name, target_abi)
L
liuqi 已提交
1195

1196
    # get target name for run
L
liuqi 已提交
1197
    if flags.example:
1198
        if mace_lib_type == MACELibType.static:
L
liuqi 已提交
1199 1200
            target_name = EXAMPLE_STATIC_NAME
        else:
1201
            target_name = EXAMPLE_DYNAMIC_NAME
L
liuqi 已提交
1202
    else:
1203
        if mace_lib_type == MACELibType.static:
L
liuqi 已提交
1204 1205
            target_name = MACE_RUN_STATIC_NAME
        else:
1206 1207 1208 1209
            target_name = MACE_RUN_DYNAMIC_NAME

    link_dynamic = mace_lib_type == MACELibType.dynamic
    model_output_dirs = []
L
liuqi 已提交
1210

1211
    for model_name in configs[YAMLKeyword.models]:
1212 1213
        check_model_converted(library_name, model_name,
                              configs[YAMLKeyword.model_graph_format],
L
liuqi 已提交
1214 1215
                              configs[YAMLKeyword.model_data_format],
                              target_abi)
L
liuqi 已提交
1216 1217 1218
        if target_abi == ABIType.host:
            device_name = ABIType.host
        else:
1219
            device_name = \
L
liuqi 已提交
1220
                sh_commands.adb_get_device_name_by_serialno(serial_num)
1221 1222
            sh_commands.clear_phone_data_dir(serial_num, PHONE_DATA_DIR)

L
liuqi 已提交
1223 1224 1225
        MaceLogger.header(
            StringFormatter.block(
                "Run model %s on %s" % (model_name, device_name)))
1226

1227 1228 1229 1230
        model_config = configs[YAMLKeyword.models][model_name]
        model_runtime = model_config[YAMLKeyword.runtime]
        subgraphs = model_config[YAMLKeyword.subgraphs]

L
liuqi 已提交
1231
        if not configs[YAMLKeyword.target_socs] or target_abi == ABIType.host:
1232 1233 1234 1235 1236 1237 1238 1239 1240
            model_output_base_dir, model_output_dir, mace_model_dir = \
                get_build_model_dirs(library_name, model_name, target_abi,
                                     None, None,
                                     model_config[YAMLKeyword.model_file_path])
        else:
            model_output_base_dir, model_output_dir, mace_model_dir = \
                get_build_model_dirs(library_name, model_name, target_abi,
                                     target_soc, serial_num,
                                     model_config[YAMLKeyword.model_file_path])
L
liuqi 已提交
1241
        # clear temp model output dir
1242 1243 1244 1245
        if os.path.exists(model_output_dir):
            sh.rm("-rf", model_output_dir)
        os.makedirs(model_output_dir)

L
liuqi 已提交
1246 1247 1248
        is_tuned = False
        model_opencl_output_bin_path = ""
        model_opencl_parameter_path = ""
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        # tuning for specified soc
        if not flags.address_sanitizer \
                and not flags.example \
                and target_abi != ABIType.host \
                and configs[YAMLKeyword.target_socs] \
                and target_soc \
                and model_runtime in [RuntimeType.gpu, RuntimeType.cpu_gpu] \
                and not flags.disable_tuning:
            tuning(library_name, model_name, model_config,
                   configs[YAMLKeyword.model_graph_format],
                   configs[YAMLKeyword.model_data_format],
                   target_abi, target_soc, serial_num,
                   mace_lib_type)
            model_output_dirs.append(model_output_dir)
L
liuqi 已提交
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
            model_opencl_output_bin_path =\
                "%s/%s/%s" % (model_output_dir,
                              BUILD_TMP_OPENCL_BIN_DIR,
                              CL_COMPILED_BINARY_FILE_NAME)
            model_opencl_parameter_path = \
                "%s/%s/%s" % (model_output_dir,
                              BUILD_TMP_OPENCL_BIN_DIR,
                              CL_TUNED_PARAMETER_FILE_NAME)
            sh_commands.clear_phone_data_dir(serial_num, PHONE_DATA_DIR)
            is_tuned = True
        elif target_abi != ABIType.host and target_soc:
            model_opencl_output_bin_path = get_opencl_binary_output_path(
                library_name, target_abi, target_soc, serial_num
            )
            model_opencl_parameter_path = get_opencl_parameter_output_path(
                library_name, target_abi, target_soc, serial_num
            )
1280 1281 1282 1283 1284 1285

        # generate input data
        sh_commands.gen_random_input(
            model_output_dir,
            subgraphs[0][YAMLKeyword.input_tensors],
            subgraphs[0][YAMLKeyword.input_shapes],
李寅 已提交
1286
            subgraphs[0][YAMLKeyword.validation_inputs_data],
Y
yejianwu 已提交
1287 1288
            input_ranges=subgraphs[0][YAMLKeyword.input_ranges],
            input_data_types=subgraphs[0][YAMLKeyword.input_data_types])
1289

1290 1291 1292 1293 1294 1295 1296 1297 1298
        runtime_list = []
        if target_abi == ABIType.host:
            runtime_list.extend([RuntimeType.cpu])
        elif model_runtime == RuntimeType.cpu_gpu:
            runtime_list.extend([RuntimeType.cpu, RuntimeType.gpu])
        else:
            runtime_list.extend([model_runtime])
        for runtime in runtime_list:
            device_type = parse_device_type(runtime)
1299
            # run for specified soc
B
Bin Li 已提交
1300 1301 1302 1303 1304 1305
            if not subgraphs[0][YAMLKeyword.check_tensors]:
                output_nodes = subgraphs[0][YAMLKeyword.output_tensors]
                output_shapes = subgraphs[0][YAMLKeyword.output_shapes]
            else:
                output_nodes = subgraphs[0][YAMLKeyword.check_tensors]
                output_shapes = subgraphs[0][YAMLKeyword.check_shapes]
1306 1307 1308
            run_output = sh_commands.tuning_run(
                abi=target_abi,
                serialno=serial_num,
L
liuqi 已提交
1309 1310
                target_dir=build_tmp_binary_dir,
                target_name=target_name,
1311 1312 1313 1314
                vlog_level=flags.vlog_level,
                embed_model_data=embed_model_data,
                model_output_dir=model_output_dir,
                input_nodes=subgraphs[0][YAMLKeyword.input_tensors],
B
Bin Li 已提交
1315
                output_nodes=output_nodes,
1316
                input_shapes=subgraphs[0][YAMLKeyword.input_shapes],
B
Bin Li 已提交
1317
                output_shapes=output_shapes,
1318 1319 1320 1321 1322 1323 1324
                mace_model_dir=mace_model_dir,
                model_tag=model_name,
                device_type=device_type,
                running_round=flags.round,
                restart_round=flags.restart_round,
                limit_opencl_kernel_time=model_config[YAMLKeyword.limit_opencl_kernel_time],  # noqa
                tuning=False,
L
Liangliang He 已提交
1325
                out_of_range_check=flags.gpu_out_of_range_check,
1326
                phone_data_dir=PHONE_DATA_DIR,
1327
                model_graph_format=configs[YAMLKeyword.model_graph_format],
1328 1329 1330 1331
                omp_num_threads=flags.omp_num_threads,
                cpu_affinity_policy=flags.cpu_affinity_policy,
                gpu_perf_hint=flags.gpu_perf_hint,
                gpu_priority_hint=flags.gpu_priority_hint,
1332 1333
                input_dir=flags.input_dir,
                output_dir=flags.output_dir,
1334 1335
                runtime_failure_ratio=flags.runtime_failure_ratio,
                address_sanitizer=flags.address_sanitizer,
L
liuqi 已提交
1336 1337
                opencl_binary_file=model_opencl_output_bin_path,
                opencl_parameter_file=model_opencl_parameter_path,
1338 1339
                libmace_dynamic_library_path=LIBMACE_DYNAMIC_PATH,
                link_dynamic=link_dynamic,
1340
                quantize_stat=flags.quantize_stat,
1341 1342
            )
            if flags.validate:
B
Bin Li 已提交
1343
                model_file_path, weight_file_path = get_model_files(
L
liuqi 已提交
1344
                    model_config[YAMLKeyword.model_file_path],
B
Bin Li 已提交
1345 1346 1347 1348
                    model_config[YAMLKeyword.model_sha256_checksum],
                    BUILD_DOWNLOADS_DIR,
                    model_config[YAMLKeyword.weight_file_path],
                    model_config[YAMLKeyword.weight_sha256_checksum])
1349

李寅 已提交
1350
                validate_type = device_type
B
Bin Li 已提交
1351 1352
                if model_config[YAMLKeyword.quantize] == 1 \
                        and device_type == DeviceType.CPU:
李寅 已提交
1353 1354
                    validate_type = device_type + "_QUANTIZE"

1355 1356 1357 1358 1359 1360 1361 1362
                sh_commands.validate_model(
                    abi=target_abi,
                    serialno=serial_num,
                    model_file_path=model_file_path,
                    weight_file_path=weight_file_path,
                    platform=model_config[YAMLKeyword.platform],
                    device_type=device_type,
                    input_nodes=subgraphs[0][YAMLKeyword.input_tensors],
B
Bin Li 已提交
1363
                    output_nodes=output_nodes,
1364
                    input_shapes=subgraphs[0][YAMLKeyword.input_shapes],
B
Bin Li 已提交
1365
                    output_shapes=output_shapes,
1366 1367
                    model_output_dir=model_output_dir,
                    phone_data_dir=PHONE_DATA_DIR,
Y
yejianwu 已提交
1368
                    input_data_types=subgraphs[0][YAMLKeyword.input_data_types],  # noqa
1369
                    caffe_env=flags.caffe_env,
李寅 已提交
1370
                    validation_threshold=subgraphs[0][YAMLKeyword.validation_threshold][validate_type])  # noqa
1371
            if flags.report and flags.round > 0:
L
liuqi 已提交
1372
                tuned = is_tuned and device_type == DeviceType.GPU
1373 1374
                report_run_statistics(
                    run_output, target_abi, serial_num,
1375
                    model_name, device_type, flags.report_dir,
1376 1377 1378 1379 1380 1381 1382 1383 1384
                    tuned)

    if model_output_dirs:
        opencl_output_bin_path = get_opencl_binary_output_path(
            library_name, target_abi, target_soc, serial_num
        )
        opencl_parameter_bin_path = get_opencl_parameter_output_path(
            library_name, target_abi, target_soc, serial_num
        )
L
liuqi 已提交
1385 1386 1387 1388 1389 1390
        # clear opencl output dir
        if os.path.exists(opencl_output_bin_path):
            sh.rm('-rf', opencl_output_bin_path)
        if os.path.exists(opencl_parameter_bin_path):
            sh.rm('-rf', opencl_parameter_bin_path)

1391 1392 1393 1394 1395 1396 1397 1398
        # merge all models' OpenCL binaries together
        sh_commands.merge_opencl_binaries(
            model_output_dirs, CL_COMPILED_BINARY_FILE_NAME,
            opencl_output_bin_path)
        # merge all models' OpenCL parameters together
        sh_commands.merge_opencl_parameters(
            model_output_dirs, CL_TUNED_PARAMETER_FILE_NAME,
            opencl_parameter_bin_path)
1399 1400


L
liuqi 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
def print_package_summary(package_path):
    title = "Library"
    header = ["key", "value"]
    data = list()
    data.append(["MACE Model package Path",
                 package_path])

    MaceLogger.summary(StringFormatter.table(header, data, title))


1411
def run_mace(flags):
1412
    configs = format_model_config(flags)
1413 1414

    clear_build_dirs(configs[YAMLKeyword.library_name])
1415 1416

    target_socs = configs[YAMLKeyword.target_socs]
1417
    if not target_socs or ALL_SOC_TAG in target_socs:
1418 1419 1420
        target_socs = sh_commands.adb_get_all_socs()

    for target_abi in configs[YAMLKeyword.target_abis]:
1421 1422 1423 1424
        # build target
        if flags.example:
            build_example(configs, target_abi,
                          not flags.disable_openmp,
L
liuqi 已提交
1425
                          flags.address_sanitizer,
1426 1427 1428 1429 1430 1431 1432 1433
                          flags.mace_lib_type)
        else:
            build_mace_run(configs, target_abi,
                           not flags.disable_openmp,
                           flags.address_sanitizer,
                           flags.mace_lib_type)

        # run
1434 1435 1436 1437
        if target_abi == ABIType.host:
            run_specific_target(flags, configs, target_abi, None, None)
        else:
            for target_soc in target_socs:
L
liuqi 已提交
1438 1439 1440 1441 1442 1443 1444 1445 1446
                serial_nums = \
                    sh_commands.get_target_socs_serialnos([target_soc])
                mace_check(serial_nums,
                           ModuleName.RUN,
                           'There is no device with soc: ' + target_soc)
                for serial_num in serial_nums:
                    with sh_commands.device_lock(serial_num):
                        run_specific_target(flags, configs, target_abi,
                                            target_soc, serial_num)
1447

L
liuqi 已提交
1448 1449 1450 1451 1452
    # package the output files
    package_path = sh_commands.packaging_lib(BUILD_OUTPUT_DIR,
                                             configs[YAMLKeyword.library_name])
    print_package_summary(package_path)

1453 1454 1455 1456

################################
#  benchmark model
################################
1457 1458 1459 1460 1461 1462
def build_benchmark_model(configs, target_abi, enable_openmp, mace_lib_type):
    library_name = configs[YAMLKeyword.library_name]
    hexagon_mode = get_hexagon_mode(configs)

    link_dynamic = mace_lib_type == MACELibType.dynamic
    if link_dynamic:
Y
yejianwu 已提交
1463
        symbol_hidden = False
1464 1465
        benchmark_target = BM_MODEL_DYNAMIC_TARGET
    else:
Y
yejianwu 已提交
1466
        symbol_hidden = True
1467 1468 1469 1470 1471 1472
        benchmark_target = BM_MODEL_STATIC_TARGET

    build_arg = ""
    if configs[YAMLKeyword.model_graph_format] == ModelFormat.code:
        mace_check(os.path.exists(ENGINE_CODEGEN_DIR),
                   ModuleName.BENCHMARK,
L
liuqi 已提交
1473
                   "You should convert model first.")
1474 1475 1476 1477 1478
        build_arg = "--per_file_copt=mace/benchmark/benchmark_model.cc@-DMODEL_GRAPH_FORMAT_CODE"  # noqa

    sh_commands.bazel_build(benchmark_target,
                            abi=target_abi,
                            enable_openmp=enable_openmp,
Y
yejianwu 已提交
1479
                            enable_opencl=get_opencl_mode(configs),
1480
                            enable_quantize=get_quantize_mode(configs),
1481
                            hexagon_mode=hexagon_mode,
Y
yejianwu 已提交
1482
                            symbol_hidden=symbol_hidden,
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
                            extra_args=build_arg)
    # clear tmp binary dir
    build_tmp_binary_dir = get_build_binary_dir(library_name, target_abi)
    if os.path.exists(build_tmp_binary_dir):
        sh.rm("-rf", build_tmp_binary_dir)
    os.makedirs(build_tmp_binary_dir)

    target_bin = "/".join(sh_commands.bazel_target_to_bin(benchmark_target))
    sh.cp("-f", target_bin, build_tmp_binary_dir)


1494 1495
def bm_specific_target(flags, configs, target_abi, target_soc, serial_num):
    library_name = configs[YAMLKeyword.library_name]
1496 1497
    embed_model_data = \
        configs[YAMLKeyword.model_data_format] == ModelFormat.code
L
liuqi 已提交
1498
    opencl_output_bin_path = ""
L
liuqi 已提交
1499
    opencl_parameter_path = ""
1500 1501 1502 1503
    link_dynamic = flags.mace_lib_type == MACELibType.dynamic

    if link_dynamic:
        bm_model_binary_name = BM_MODEL_DYNAMIC_NAME
1504
    else:
1505 1506 1507 1508
        bm_model_binary_name = BM_MODEL_STATIC_NAME
    build_tmp_binary_dir = get_build_binary_dir(library_name, target_abi)

    if configs[YAMLKeyword.target_socs] and target_abi != ABIType.host:
L
liuqi 已提交
1509 1510 1511
        opencl_output_bin_path = get_opencl_binary_output_path(
            library_name, target_abi, target_soc, serial_num
        )
L
liuqi 已提交
1512 1513 1514
        opencl_parameter_path = get_opencl_parameter_output_path(
            library_name, target_abi, target_soc, serial_num
        )
1515 1516

    for model_name in configs[YAMLKeyword.models]:
1517 1518
        check_model_converted(library_name, model_name,
                              configs[YAMLKeyword.model_graph_format],
L
liuqi 已提交
1519 1520
                              configs[YAMLKeyword.model_data_format],
                              target_abi)
L
liuqi 已提交
1521 1522 1523 1524 1525 1526 1527 1528
        if target_abi == ABIType.host:
            device_name = ABIType.host
        else:
            device_name = \
                sh_commands.adb_get_device_name_by_serialno(serial_num)
        MaceLogger.header(
            StringFormatter.block(
                "Benchmark model %s on %s" % (model_name, device_name)))
1529 1530 1531 1532
        model_config = configs[YAMLKeyword.models][model_name]
        model_runtime = model_config[YAMLKeyword.runtime]
        subgraphs = model_config[YAMLKeyword.subgraphs]

L
liuqi 已提交
1533
        if not configs[YAMLKeyword.target_socs] or target_abi == ABIType.host:
1534 1535 1536 1537 1538 1539 1540 1541 1542
            model_output_base_dir, model_output_dir, mace_model_dir = \
                get_build_model_dirs(library_name, model_name, target_abi,
                                     None, None,
                                     model_config[YAMLKeyword.model_file_path])
        else:
            model_output_base_dir, model_output_dir, mace_model_dir = \
                get_build_model_dirs(library_name, model_name, target_abi,
                                     target_soc, serial_num,
                                     model_config[YAMLKeyword.model_file_path])
1543 1544 1545 1546
        if os.path.exists(model_output_dir):
            sh.rm("-rf", model_output_dir)
        os.makedirs(model_output_dir)

1547 1548 1549 1550 1551 1552 1553
        if target_abi != ABIType.host:
            sh_commands.clear_phone_data_dir(serial_num, PHONE_DATA_DIR)

        sh_commands.gen_random_input(
            model_output_dir,
            subgraphs[0][YAMLKeyword.input_tensors],
            subgraphs[0][YAMLKeyword.input_shapes],
李寅 已提交
1554
            subgraphs[0][YAMLKeyword.validation_inputs_data],
Y
yejianwu 已提交
1555 1556
            input_ranges=subgraphs[0][YAMLKeyword.input_ranges],
            input_data_types=subgraphs[0][YAMLKeyword.input_data_types])
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
        runtime_list = []
        if target_abi == ABIType.host:
            runtime_list.extend([RuntimeType.cpu])
        elif model_runtime == RuntimeType.cpu_gpu:
            runtime_list.extend([RuntimeType.cpu, RuntimeType.gpu])
        else:
            runtime_list.extend([model_runtime])
        for runtime in runtime_list:
            device_type = parse_device_type(runtime)
            sh_commands.benchmark_model(
                abi=target_abi,
                serialno=serial_num,
                benchmark_binary_dir=build_tmp_binary_dir,
1570
                benchmark_binary_name=bm_model_binary_name,
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
                vlog_level=0,
                embed_model_data=embed_model_data,
                model_output_dir=model_output_dir,
                input_nodes=subgraphs[0][YAMLKeyword.input_tensors],
                output_nodes=subgraphs[0][YAMLKeyword.output_tensors],
                input_shapes=subgraphs[0][YAMLKeyword.input_shapes],
                output_shapes=subgraphs[0][YAMLKeyword.output_shapes],
                mace_model_dir=mace_model_dir,
                model_tag=model_name,
                device_type=device_type,
                phone_data_dir=PHONE_DATA_DIR,
1582
                model_graph_format=configs[YAMLKeyword.model_graph_format],
1583 1584 1585
                omp_num_threads=flags.omp_num_threads,
                cpu_affinity_policy=flags.cpu_affinity_policy,
                gpu_perf_hint=flags.gpu_perf_hint,
1586
                gpu_priority_hint=flags.gpu_priority_hint,
Y
yejianwu 已提交
1587
                opencl_binary_file=opencl_output_bin_path,
L
liuqi 已提交
1588
                opencl_parameter_file=opencl_parameter_path,
1589 1590
                libmace_dynamic_library_path=LIBMACE_DYNAMIC_PATH,
                link_dynamic=link_dynamic)
1591 1592 1593


def benchmark_model(flags):
1594
    configs = format_model_config(flags)
1595 1596

    clear_build_dirs(configs[YAMLKeyword.library_name])
1597 1598

    target_socs = configs[YAMLKeyword.target_socs]
1599
    if not target_socs or ALL_SOC_TAG in target_socs:
1600 1601 1602
        target_socs = sh_commands.adb_get_all_socs()

    for target_abi in configs[YAMLKeyword.target_abis]:
1603 1604 1605 1606 1607
        # build benchmark_model binary
        build_benchmark_model(configs, target_abi,
                              not flags.disable_openmp,
                              flags.mace_lib_type)

L
liuqi 已提交
1608
        if target_abi == ABIType.host:
1609 1610 1611
            bm_specific_target(flags, configs, target_abi, None, None)
        else:
            for target_soc in target_socs:
L
liuqi 已提交
1612 1613 1614 1615 1616 1617 1618 1619 1620
                serial_nums = \
                    sh_commands.get_target_socs_serialnos([target_soc])
                mace_check(serial_nums,
                           ModuleName.BENCHMARK,
                           'There is no device with soc: ' + target_soc)
                for serial_num in serial_nums:
                    with sh_commands.device_lock(serial_num):
                        bm_specific_target(flags, configs, target_abi,
                                           target_soc, serial_num)
L
liuqi 已提交
1621

1622

L
liuqi 已提交
1623
################################
Y
yejianwu 已提交
1624
# parsing arguments
L
liuqi 已提交
1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
################################
def str2bool(v):
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')


def str_to_caffe_env_type(v):
    if v.lower() == 'docker':
1637
        return CaffeEnvType.DOCKER
L
liuqi 已提交
1638
    elif v.lower() == 'local':
1639
        return CaffeEnvType.LOCAL
L
liuqi 已提交
1640 1641 1642 1643
    else:
        raise argparse.ArgumentTypeError('[docker | local] expected.')


1644 1645 1646 1647 1648 1649 1650 1651 1652
def str_to_mace_lib_type(v):
    if v.lower() == 'dynamic':
        return MACELibType.dynamic
    elif v.lower() == 'static':
        return MACELibType.static
    else:
        raise argparse.ArgumentTypeError('[dynamic| static] expected.')


1653
def parse_args():
L
Liangliang He 已提交
1654
    """Parses command line arguments."""
1655 1656 1657
    all_type_parent_parser = argparse.ArgumentParser(add_help=False)
    all_type_parent_parser.add_argument(
        '--config',
L
Liangliang He 已提交
1658
        type=str,
1659
        default="",
L
liuqi 已提交
1660
        required=True,
1661
        help="the path of model yaml configuration file.")
1662
    all_type_parent_parser.add_argument(
1663
        "--model_graph_format",
1664 1665
        type=str,
        default="",
1666 1667 1668 1669 1670 1671
        help="[file, code], MACE Model graph format.")
    all_type_parent_parser.add_argument(
        "--model_data_format",
        type=str,
        default="",
        help="['file', 'code'], MACE Model data format.")
1672 1673 1674 1675 1676
    all_type_parent_parser.add_argument(
        "--target_abis",
        type=str,
        default="",
        help="Target ABIs, comma seperated list.")
1677 1678 1679 1680 1681
    all_type_parent_parser.add_argument(
        "--target_socs",
        type=str,
        default="",
        help="Target SOCs, comma seperated list.")
1682 1683
    convert_run_parent_parser = argparse.ArgumentParser(add_help=False)
    convert_run_parent_parser.add_argument(
1684 1685
        '--address_sanitizer',
        action="store_true",
L
liuqi 已提交
1686
        help="Whether to use address sanitizer to check memory error")
1687
    run_bm_parent_parser = argparse.ArgumentParser(add_help=False)
1688 1689 1690 1691 1692 1693 1694 1695 1696
    run_bm_parent_parser.add_argument(
        "--mace_lib_type",
        type=str_to_mace_lib_type,
        default=DefaultValues.mace_lib_type,
        help="[static | dynamic], Which type MACE library to use.")
    run_bm_parent_parser.add_argument(
        "--disable_openmp",
        action="store_true",
        help="Disable openmp for multiple thread.")
1697
    run_bm_parent_parser.add_argument(
W
wuchenghui 已提交
1698 1699
        "--omp_num_threads",
        type=int,
1700
        default=DefaultValues.omp_num_threads,
W
wuchenghui 已提交
1701
        help="num of openmp threads")
1702
    run_bm_parent_parser.add_argument(
W
wuchenghui 已提交
1703 1704
        "--cpu_affinity_policy",
        type=int,
1705
        default=DefaultValues.cpu_affinity_policy,
W
wuchenghui 已提交
1706
        help="0:AFFINITY_NONE/1:AFFINITY_BIG_ONLY/2:AFFINITY_LITTLE_ONLY")
1707
    run_bm_parent_parser.add_argument(
W
wuchenghui 已提交
1708 1709
        "--gpu_perf_hint",
        type=int,
1710
        default=DefaultValues.gpu_perf_hint,
W
wuchenghui 已提交
1711
        help="0:DEFAULT/1:LOW/2:NORMAL/3:HIGH")
1712
    run_bm_parent_parser.add_argument(
W
wuchenghui 已提交
1713 1714
        "--gpu_priority_hint",
        type=int,
1715
        default=DefaultValues.gpu_priority_hint,
W
wuchenghui 已提交
1716
        help="0:DEFAULT/1:LOW/2:NORMAL/3:HIGH")
1717 1718 1719

    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()
1720 1721 1722 1723
    convert = subparsers.add_parser(
        'convert',
        parents=[all_type_parent_parser, convert_run_parent_parser],
        help='convert to mace model (file or code)')
1724 1725 1726 1727 1728
    convert.add_argument(
        "--cl_mem_type",
        type=str,
        default=None,
        help="Which type of OpenCL memory type to use [image | buffer].")
1729
    convert.set_defaults(func=convert_func)
1730 1731 1732
    run = subparsers.add_parser(
        'run',
        parents=[all_type_parent_parser, run_bm_parent_parser,
1733
                 convert_run_parent_parser],
1734 1735
        help='run model in command line')
    run.set_defaults(func=run_mace)
1736 1737 1738 1739
    run.add_argument(
        "--disable_tuning",
        action="store_true",
        help="Disable tuning for specific thread.")
1740 1741
    run.add_argument(
        "--round",
L
Liangliang He 已提交
1742
        type=int,
1743 1744 1745 1746 1747
        default=1,
        help="The model running round.")
    run.add_argument(
        "--validate",
        action="store_true",
1748 1749
        help="whether to verify the results are consistent with "
             "the frameworks.")
1750
    run.add_argument(
L
liuqi 已提交
1751 1752 1753
        "--caffe_env",
        type=str_to_caffe_env_type,
        default='docker',
1754 1755
        help="[docker | local] you can specific caffe environment for"
             " validation. local environment or caffe docker image.")
1756 1757 1758 1759
    run.add_argument(
        "--vlog_level",
        type=int,
        default=0,
1760
        help="[1~5]. Verbose log level for debug.")
1761
    run.add_argument(
L
Liangliang He 已提交
1762
        "--gpu_out_of_range_check",
1763 1764 1765 1766 1767 1768
        action="store_true",
        help="Enable out of memory check for gpu.")
    run.add_argument(
        "--restart_round",
        type=int,
        default=1,
1769
        help="restart round between run.")
1770 1771 1772 1773 1774 1775
    run.add_argument(
        "--report",
        action="store_true",
        help="print run statistics report.")
    run.add_argument(
        "--report_dir",
1776 1777
        type=str,
        default="",
1778 1779
        help="print run statistics report.")
    run.add_argument(
李寅 已提交
1780 1781 1782 1783
        "--runtime_failure_ratio",
        type=float,
        default=0.0,
        help="[mock runtime failure ratio].")
L
liuqi 已提交
1784 1785 1786 1787
    run.add_argument(
        "--example",
        action="store_true",
        help="whether to run example.")
李寅 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796
    run.add_argument(
        "--quantize_stat",
        action="store_true",
        help="whether to stat quantization range.")
    run.add_argument(
        "--input_dir",
        type=str,
        default="",
        help="quantize stat input dir.")
1797 1798 1799 1800 1801
    run.add_argument(
        "--output_dir",
        type=str,
        default="",
        help="quantize stat output dir.")
1802 1803
    benchmark = subparsers.add_parser(
        'benchmark',
1804
        parents=[all_type_parent_parser, run_bm_parent_parser],
1805 1806
        help='benchmark model for detail information')
    benchmark.set_defaults(func=benchmark_model)
L
Liangliang He 已提交
1807 1808
    return parser.parse_known_args()

1809

Y
yejianwu 已提交
1810
if __name__ == "__main__":
1811 1812
    flags, unparsed = parse_args()
    flags.func(flags)