sh_commands.py 43.4 KB
Newer Older
Y
yejianwu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

Y
yejianwu 已提交
15 16
import falcon_cli
import filelock
Y
yejianwu 已提交
17
import glob
L
liuqi 已提交
18
import logging
Y
yejianwu 已提交
19
import os
20
import re
Y
yejianwu 已提交
21
import sh
Y
yejianwu 已提交
22
import subprocess
23
import sys
24
import time
W
wuchenghui 已提交
25
import urllib
26
from enum import Enum
27

L
liuqi 已提交
28
import common
L
Liangliang He 已提交
29

30 31 32 33 34 35 36
sys.path.insert(0, "mace/python/tools")
try:
    from encrypt_opencl_codegen import encrypt_opencl_codegen
    from opencl_codegen import opencl_codegen
    from binary_codegen import tuning_param_codegen
    from generate_data import generate_input_data
    from validate import validate
37
    from mace_engine_factory_codegen import gen_mace_engine_factory
Y
yejianwu 已提交
38 39
except Exception as e:
    print("Import error:\n%s" % e)
40 41
    exit(1)

42 43 44
################################
# common
################################
L
liuqi 已提交
45 46 47
logger = logging.getLogger('MACE')


48
def strip_invalid_utf8(str):
L
Liangliang He 已提交
49 50
    return sh.iconv(str, "-c", "-t", "UTF-8")

51

52 53 54 55 56 57
def split_stdout(stdout_str):
    stdout_str = strip_invalid_utf8(stdout_str)
    # Filter out last empty line
    return [l.strip() for l in stdout_str.split('\n') if len(l.strip()) > 0]


58
def make_output_processor(buff):
L
Liangliang He 已提交
59
    def process_output(line):
L
Liangliang He 已提交
60
        print(line.rstrip())
L
Liangliang He 已提交
61 62 63 64
        buff.append(line)

    return process_output

65

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
def device_lock_path(serialno):
    return "/tmp/device-lock-%s" % serialno


def device_lock(serialno, timeout=3600):
    return filelock.FileLock(device_lock_path(serialno), timeout=timeout)


def is_device_locked(serialno):
    try:
        with device_lock(serialno, timeout=0.000001):
            return False
    except filelock.Timeout:
        return True


82 83 84 85 86
class BuildType(object):
    proto = 'proto'
    code = 'code'


Y
yejianwu 已提交
87 88 89
################################
# clear data
################################
90 91 92 93 94
def clear_phone_data_dir(serialno, phone_data_dir):
    sh.adb("-s",
           serialno,
           "shell",
           "rm -rf %s" % phone_data_dir)
95 96 97


def clear_model_codegen(model_codegen_dir="mace/codegen/models"):
Y
yejianwu 已提交
98 99 100 101
    if os.path.exists(model_codegen_dir):
        sh.rm("-rf", model_codegen_dir)


102 103 104
################################
# adb commands
################################
W
wuchenghui 已提交
105 106
def adb_devices():
    serialnos = []
107
    p = re.compile(r'(\w+)\s+device')
108
    for line in split_stdout(sh.adb("devices")):
109 110
        m = p.match(line)
        if m:
W
wuchenghui 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
            serialnos.append(m.group(1))

    return serialnos


def get_soc_serialnos_map():
    serialnos = adb_devices()
    soc_serialnos_map = {}
    for serialno in serialnos:
        props = adb_getprop_by_serialno(serialno)
        soc_serialnos_map.setdefault(props["ro.board.platform"], [])\
            .append(serialno)

    return soc_serialnos_map


def get_target_socs_serialnos(target_socs=None):
    soc_serialnos_map = get_soc_serialnos_map()
    serialnos = []
    if target_socs is None:
        target_socs = soc_serialnos_map.keys()
    for target_soc in target_socs:
        serialnos.extend(soc_serialnos_map[target_soc])
    return serialnos
L
Liangliang He 已提交
135

136

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
def get_soc_serial_number_map():
    serial_numbers = adb_devices()
    soc_serial_number_map = {}
    for num in serial_numbers:
        props = adb_getprop_by_serialno(num)
        soc_serial_number_map[props["ro.board.platform"]] = num
    return soc_serial_number_map


def get_target_soc_serial_number(target_soc):
    soc_serial_number_map = get_soc_serial_number_map()
    serial_number = None
    if target_soc in soc_serial_number_map:
        serial_number = soc_serial_number_map[target_soc]
    return serial_number


154
def adb_getprop_by_serialno(serialno):
L
Liangliang He 已提交
155
    outputs = sh.adb("-s", serialno, "shell", "getprop")
156
    raw_props = split_stdout(outputs)
L
Liangliang He 已提交
157
    props = {}
158
    p = re.compile(r'\[(.+)\]: \[(.+)\]')
L
Liangliang He 已提交
159 160 161 162 163 164
    for raw_prop in raw_props:
        m = p.match(raw_prop)
        if m:
            props[m.group(1)] = m.group(2)
    return props

165

W
wuchenghui 已提交
166 167
def adb_get_device_name_by_serialno(serialno):
    props = adb_getprop_by_serialno(serialno)
L
liuqi 已提交
168
    return props.get("ro.product.model", "").replace(' ', '')
W
wuchenghui 已提交
169 170


171
def adb_supported_abis(serialno):
L
Liangliang He 已提交
172 173 174 175 176
    props = adb_getprop_by_serialno(serialno)
    abilist_str = props["ro.product.cpu.abilist"]
    abis = [abi.strip() for abi in abilist_str.split(',')]
    return abis

177

178
def adb_get_all_socs():
L
Liangliang He 已提交
179 180 181 182 183
    socs = []
    for d in adb_devices():
        props = adb_getprop_by_serialno(d)
        socs.append(props["ro.board.platform"])
    return set(socs)
184

L
Liangliang He 已提交
185

Y
yejianwu 已提交
186 187 188 189 190 191 192 193 194 195 196 197 198
def adb_push(src_path, dst_path, serialno):
    print("Push %s to %s" % (src_path, dst_path))
    sh.adb("-s", serialno, "push", src_path, dst_path)


def adb_pull(src_path, dst_path, serialno):
    print("Pull %s to %s" % (src_path, dst_path))
    try:
        sh.adb("-s", serialno, "pull", src_path, dst_path)
    except Exception as e:
        print("Error msg: %s" % e.stderr)


199 200
def adb_run(abi,
            serialno,
L
Liangliang He 已提交
201 202
            host_bin_path,
            bin_name,
203
            args="",
L
liuqi 已提交
204
            opencl_profiling=True,
205
            vlog_level=0,
206
            device_bin_path="/data/local/tmp/mace",
L
liuqi 已提交
207
            out_of_range_check=True,
208
            address_sanitizer=False):
L
Liangliang He 已提交
209 210 211 212 213 214
    host_bin_full_path = "%s/%s" % (host_bin_path, bin_name)
    device_bin_full_path = "%s/%s" % (device_bin_path, bin_name)
    props = adb_getprop_by_serialno(serialno)
    print(
        "====================================================================="
    )
L
Liangliang He 已提交
215
    print("Trying to lock device %s" % serialno)
216 217 218 219
    with device_lock(serialno):
        print("Run on device: %s, %s, %s" %
              (serialno, props["ro.board.platform"],
               props["ro.product.model"]))
Y
yejianwu 已提交
220 221
        sh.adb("-s", serialno, "shell", "rm -rf %s" % device_bin_path)
        sh.adb("-s", serialno, "shell", "mkdir -p %s" % device_bin_path)
Y
yejianwu 已提交
222
        adb_push(host_bin_full_path, device_bin_full_path, serialno)
223 224 225 226 227
        ld_preload = ""
        if address_sanitizer:
            adb_push(find_asan_rt_library(abi), device_bin_path, serialno)
            ld_preload = "LD_PRELOAD=%s/%s" % (device_bin_path,
                                               asan_rt_library_names(abi)),
L
liuqi 已提交
228 229
        opencl_profiling = 1 if opencl_profiling else 0
        out_of_range_check = 1 if out_of_range_check else 0
Y
yejianwu 已提交
230
        print("Run %s" % device_bin_full_path)
231

Y
yejianwu 已提交
232 233
        stdout_buff = []
        process_output = make_output_processor(stdout_buff)
L
liuqi 已提交
234
        sh.adb(
Y
yejianwu 已提交
235 236 237
            "-s",
            serialno,
            "shell",
238 239 240 241
            ld_preload,
            "MACE_OUT_OF_RANGE_CHECK=%d" % out_of_range_check,
            "MACE_OPENCL_PROFILING=%d" % opencl_profiling,
            "MACE_CPP_MIN_VLOG_LEVEL=%d" % vlog_level,
242 243 244
            device_bin_full_path,
            args,
            _tty_in=True,
Y
yejianwu 已提交
245
            _out=process_output,
246
            _err_to_out=True)
Y
yejianwu 已提交
247
        return "".join(stdout_buff)
248 249


250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
################################
# Toolchain
################################
def asan_rt_library_names(abi):
    asan_rt_names = {
        "armeabi-v7a": "libclang_rt.asan-arm-android.so",
        "arm64-v8a": "libclang_rt.asan-aarch64-android.so",
    }
    return asan_rt_names[abi]


def find_asan_rt_library(abi, asan_rt_path=''):
    if not asan_rt_path:
        find_path = os.environ['ANDROID_NDK_HOME']
        candidates = split_stdout(sh.find(find_path, "-name",
                                          asan_rt_library_names(abi)))
        if len(candidates) == 0:
            common.MaceLogger.error(
                "Toolchain",
                "Can't find AddressSanitizer runtime library in % s" %
                find_path)
        elif len(candidates) > 1:
            common.MaceLogger.info(
                "More than one AddressSanitizer runtime library, use the 1st")
        return candidates[0]
    return "%s/%s" % (asan_rt_path, asan_rt_library_names(abi))
276 277


278 279 280
################################
# bazel commands
################################
Y
yejianwu 已提交
281 282 283
def bazel_build(target,
                abi="armeabi-v7a",
                hexagon_mode=False,
李寅 已提交
284
                enable_openmp=True,
285 286
                enable_neon=True,
                address_sanitizer=False):
Y
yejianwu 已提交
287 288
    print("* Build %s with ABI %s" % (target, abi))
    if abi == "host":
W
wuchenghui 已提交
289
        bazel_args = (
Y
yejianwu 已提交
290 291
            "build",
            "--define",
W
wuchenghui 已提交
292
            "openmp=%s" % str(enable_openmp).lower(),
293
            target,
W
wuchenghui 已提交
294
        )
Y
yejianwu 已提交
295 296 297 298
    else:
        bazel_args = (
            "build",
            target,
299 300
            "--config",
            "android",
Y
yejianwu 已提交
301 302
            "--cpu=%s" % abi,
            "--define",
李寅 已提交
303
            "neon=%s" % str(enable_neon).lower(),
Y
yejianwu 已提交
304
            "--define",
W
wuchenghui 已提交
305
            "openmp=%s" % str(enable_openmp).lower(),
Y
yejianwu 已提交
306 307
            "--define",
            "hexagon=%s" % str(hexagon_mode).lower())
308 309 310 311
    if address_sanitizer:
        bazel_args += ("--config", "asan")
    else:
        bazel_args += ("--config", "optimization")
L
liuqi 已提交
312 313
    sh.bazel(
        _fg=True,
314 315
        *bazel_args)
    print("Build done!\n")
Y
yejianwu 已提交
316 317 318


def bazel_build_common(target, build_args=""):
L
Liangliang He 已提交
319 320
    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
L
liuqi 已提交
321
    sh.bazel(
L
Liangliang He 已提交
322
        "build",
Y
yejianwu 已提交
323
        target + build_args,
324
        _tty_in=True,
L
Liangliang He 已提交
325
        _out=process_output,
326
        _err_to_out=True)
L
Liangliang He 已提交
327 328
    return "".join(stdout_buff)

329 330

def bazel_target_to_bin(target):
L
Liangliang He 已提交
331 332 333 334 335 336 337 338
    # change //mace/a/b:c to bazel-bin/mace/a/b/c
    prefix, bin_name = target.split(':')
    prefix = prefix.replace('//', '/')
    if prefix.startswith('/'):
        prefix = prefix[1:]
    host_bin_path = "bazel-bin/%s" % prefix
    return host_bin_path, bin_name

339 340 341 342 343

################################
# mace commands
################################
def gen_encrypted_opencl_source(codegen_path="mace/codegen"):
L
Liangliang He 已提交
344
    sh.mkdir("-p", "%s/opencl" % codegen_path)
345 346
    encrypt_opencl_codegen("./mace/kernels/opencl/cl/",
                           "mace/codegen/opencl/opencl_encrypt_program.cc")
L
Liangliang He 已提交
347

348

Y
yejianwu 已提交
349
def gen_mace_engine_factory_source(model_tags,
350
                                   model_load_type,
Y
yejianwu 已提交
351
                                   codegen_path="mace/codegen"):
352 353 354 355
    print("* Genearte mace engine creator source")
    codegen_tools_dir = "%s/engine" % codegen_path
    sh.rm("-rf", codegen_tools_dir)
    sh.mkdir("-p", codegen_tools_dir)
356
    gen_mace_engine_factory(
357 358
        model_tags,
        "mace/python/tools",
359
        model_load_type,
360 361 362 363 364 365 366
        codegen_tools_dir)
    print("Genearte mace engine creator source done!\n")


def pull_binaries(abi, serialno, model_output_dirs,
                  cl_built_kernel_file_name,
                  cl_platform_info_file_name):
367
    compiled_opencl_dir = "/data/local/tmp/mace_run/interior/"
368
    mace_run_param_file = "mace_run.config"
Y
yejianwu 已提交
369 370 371 372 373

    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)
374
    if cl_bin_dirs:
Y
yejianwu 已提交
375 376 377 378 379
        cl_bin_dir = cl_bin_dirs_str
        if os.path.exists(cl_bin_dir):
            sh.rm("-rf", cl_bin_dir)
        sh.mkdir("-p", cl_bin_dir)
        if abi != "host":
380 381 382 383
            adb_pull(compiled_opencl_dir + cl_built_kernel_file_name,
                     cl_bin_dir, serialno)
            adb_pull(compiled_opencl_dir + cl_platform_info_file_name,
                     cl_bin_dir, serialno)
384
            adb_pull("/data/local/tmp/mace_run/%s" % mace_run_param_file,
Y
yejianwu 已提交
385 386 387
                     cl_bin_dir, serialno)


W
wuchenghui 已提交
388
def gen_opencl_binary_code(model_output_dirs,
389 390
                           cl_built_kernel_file_name,
                           cl_platform_info_file_name,
Y
yejianwu 已提交
391
                           codegen_path="mace/codegen"):
392
    opencl_codegen_file = "%s/opencl/opencl_compiled_program.cc" % codegen_path
Y
yejianwu 已提交
393 394 395 396 397

    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)
398 399 400 401
    opencl_codegen(opencl_codegen_file,
                   cl_bin_dirs_str,
                   cl_built_kernel_file_name,
                   cl_platform_info_file_name)
Y
yejianwu 已提交
402 403


W
wuchenghui 已提交
404
def gen_tuning_param_code(model_output_dirs,
Y
yejianwu 已提交
405
                          codegen_path="mace/codegen"):
406
    mace_run_param_file = "mace_run.config"
Y
yejianwu 已提交
407 408 409 410
    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)
411 412 413 414 415

    tuning_codegen_dir = "%s/tuning/" % codegen_path
    if not os.path.exists(tuning_codegen_dir):
        sh.mkdir("-p", tuning_codegen_dir)

416 417 418 419 420
    tuning_param_variable_name = "kTuningParamsData"
    tuning_param_codegen(cl_bin_dirs_str,
                         mace_run_param_file,
                         "%s/tuning_params.cc" % tuning_codegen_dir,
                         tuning_param_variable_name)
Y
yejianwu 已提交
421 422


423
def gen_mace_version(codegen_path="mace/codegen"):
L
Liangliang He 已提交
424 425 426 427
    sh.mkdir("-p", "%s/version" % codegen_path)
    sh.bash("mace/tools/git/gen_version_source.sh",
            "%s/version/version.cc" % codegen_path)

428

L
liuqi 已提交
429
def gen_compiled_opencl_source(codegen_path="mace/codegen"):
430
    opencl_codegen_file = "%s/opencl/opencl_compiled_program.cc" % codegen_path
L
Liangliang He 已提交
431
    sh.mkdir("-p", "%s/opencl" % codegen_path)
432
    opencl_codegen(opencl_codegen_file)
L
Liangliang He 已提交
433

L
liuqi 已提交
434

Y
yejianwu 已提交
435 436 437 438 439
def gen_model_code(model_codegen_dir,
                   platform,
                   model_file_path,
                   weight_file_path,
                   model_sha256_checksum,
440
                   weight_sha256_checksum,
Y
yejianwu 已提交
441 442 443 444 445 446 447 448
                   input_nodes,
                   output_nodes,
                   runtime,
                   model_tag,
                   input_shapes,
                   dsp_mode,
                   embed_model_data,
                   fast_conv,
Y
yejianwu 已提交
449
                   obfuscate,
450 451
                   model_build_type,
                   data_type):
Y
yejianwu 已提交
452
    bazel_build_common("//mace/python/tools:converter")
Y
yejianwu 已提交
453

Y
yejianwu 已提交
454 455 456
    if os.path.exists(model_codegen_dir):
        sh.rm("-rf", model_codegen_dir)
    sh.mkdir("-p", model_codegen_dir)
Y
yejianwu 已提交
457

L
liuqi 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    sh.python("bazel-bin/mace/python/tools/converter",
              "-u",
              "--platform=%s" % platform,
              "--model_file=%s" % model_file_path,
              "--weight_file=%s" % weight_file_path,
              "--model_checksum=%s" % model_sha256_checksum,
              "--weight_checksum=%s" % weight_sha256_checksum,
              "--input_node=%s" % input_nodes,
              "--output_node=%s" % output_nodes,
              "--runtime=%s" % runtime,
              "--template=%s" % "mace/python/tools",
              "--model_tag=%s" % model_tag,
              "--input_shape=%s" % input_shapes,
              "--dsp_mode=%s" % dsp_mode,
              "--embed_model_data=%s" % embed_model_data,
              "--winograd=%s" % fast_conv,
              "--obfuscate=%s" % obfuscate,
              "--output_dir=%s" % model_codegen_dir,
              "--model_build_type=%s" % model_build_type,
              "--data_type=%s" % data_type,
              _fg=True)
Y
yejianwu 已提交
479 480 481 482 483 484 485 486


def gen_random_input(model_output_dir,
                     input_nodes,
                     input_shapes,
                     input_files,
                     input_file_name="model_input"):
    for input_name in input_nodes:
L
liuqi 已提交
487 488
        formatted_name = common.formatted_file_name(
            input_file_name, input_name)
489 490
        if os.path.exists("%s/%s" % (model_output_dir, formatted_name)):
            sh.rm("%s/%s" % (model_output_dir, formatted_name))
Y
yejianwu 已提交
491 492
    input_nodes_str = ",".join(input_nodes)
    input_shapes_str = ":".join(input_shapes)
493 494 495
    generate_input_data("%s/%s" % (model_output_dir, input_file_name),
                        input_nodes_str,
                        input_shapes_str)
Y
yejianwu 已提交
496 497 498 499 500 501 502 503

    input_file_list = []
    if isinstance(input_files, list):
        input_file_list.extend(input_files)
    else:
        input_file_list.append(input_files)
    if len(input_file_list) != 0:
        input_name_list = []
W
wuchenghui 已提交
504 505
        if isinstance(input_nodes, list):
            input_name_list.extend(input_nodes)
Y
yejianwu 已提交
506
        else:
W
wuchenghui 已提交
507
            input_name_list.append(input_nodes)
Y
yejianwu 已提交
508 509 510 511 512 513
        if len(input_file_list) != len(input_name_list):
            raise Exception('If input_files set, the input files should '
                            'match the input names.')
        for i in range(len(input_file_list)):
            if input_file_list[i] is not None:
                dst_input_file = model_output_dir + '/' + \
L
liuqi 已提交
514 515
                        common.formatted_file_name(input_file_name,
                                                   input_name_list[i])
Y
yejianwu 已提交
516 517 518 519
                if input_file_list[i].startswith("http://") or \
                        input_file_list[i].startswith("https://"):
                    urllib.urlretrieve(input_file_list[i], dst_input_file)
                else:
520
                    sh.cp("-f", input_file_list[i], dst_input_file)
Y
yejianwu 已提交
521 522


523 524
def update_mace_run_lib(build_tmp_binary_dir):
    mace_run_filepath = build_tmp_binary_dir + "/mace_run"
Y
yejianwu 已提交
525 526
    if os.path.exists(mace_run_filepath):
        sh.rm("-rf", mace_run_filepath)
527 528 529 530 531 532 533 534 535 536
    sh.cp("-f", "bazel-bin/mace/tools/validation/mace_run",
          build_tmp_binary_dir)


def touch_tuned_file_flag(build_tmp_binary_dir):
    sh.touch(build_tmp_binary_dir + '/tuned')


def is_binary_tuned(build_tmp_binary_dir):
    return os.path.exists(build_tmp_binary_dir + '/tuned')
Y
yejianwu 已提交
537 538


539 540 541 542 543 544 545 546 547 548 549 550
def mv_model_file_to_output_dir(
        model_build_type,
        model_codegen_dir,
        model_name,
        output_dir):
    if model_build_type == BuildType.proto:
        sh.mv("-f",
              '%s/%s.pb' % (model_codegen_dir, model_name),
              output_dir)
    sh.mv("-f",
          '%s/%s.data' % (model_codegen_dir, model_name),
          output_dir)
Y
yejianwu 已提交
551 552


553 554 555 556
def create_internal_storage_dir(serialno, phone_data_dir):
    internal_storage_dir = "%s/interior/" % phone_data_dir
    sh.adb("-s", serialno, "shell", "mkdir", "-p", internal_storage_dir)
    return internal_storage_dir
557 558


W
wuchenghui 已提交
559 560
def tuning_run(abi,
               serialno,
561
               mace_run_dir,
Y
yejianwu 已提交
562 563 564 565 566 567 568
               vlog_level,
               embed_model_data,
               model_output_dir,
               input_nodes,
               output_nodes,
               input_shapes,
               output_shapes,
Y
yejianwu 已提交
569
               mace_model_dir,
Y
yejianwu 已提交
570 571 572 573 574 575 576
               model_tag,
               device_type,
               running_round,
               restart_round,
               limit_opencl_kernel_time,
               tuning,
               out_of_range_check,
577
               phone_data_dir,
578
               build_type,
W
wuchenghui 已提交
579 580 581 582
               omp_num_threads=-1,
               cpu_affinity_policy=1,
               gpu_perf_hint=3,
               gpu_priority_hint=3,
Y
yejianwu 已提交
583
               input_file_name="model_input",
584 585 586
               output_file_name="model_out",
               runtime_failure_ratio=0.0,
               address_sanitizer=False):
587
    print("* Run '%s' with round=%s, restart_round=%s, tuning=%s, "
W
wuchenghui 已提交
588 589
          "out_of_range_check=%s, omp_num_threads=%s, cpu_affinity_policy=%s, "
          "gpu_perf_hint=%s, gpu_priority_hint=%s" %
590
          (model_tag, running_round, restart_round, str(tuning),
W
wuchenghui 已提交
591 592
           str(out_of_range_check), omp_num_threads, cpu_affinity_policy,
           gpu_perf_hint, gpu_priority_hint))
593 594 595
    mace_model_path = ""
    if build_type == BuildType.proto:
        mace_model_path = "%s/%s.pb" % (mace_model_dir, model_tag)
Y
yejianwu 已提交
596
    if abi == "host":
W
wuchenghui 已提交
597 598
        p = subprocess.Popen(
            [
Y
yejianwu 已提交
599 600
                "env",
                "MACE_CPP_MIN_VLOG_LEVEL=%s" % vlog_level,
李寅 已提交
601
                "MACE_RUNTIME_FAILURE_RATIO=%f" % runtime_failure_ratio,
602
                "%s/mace_run" % mace_run_dir,
603
                "--model_name=%s" % model_tag,
Y
yejianwu 已提交
604 605 606 607 608 609
                "--input_node=%s" % ",".join(input_nodes),
                "--output_node=%s" % ",".join(output_nodes),
                "--input_shape=%s" % ":".join(input_shapes),
                "--output_shape=%s" % ":".join(output_shapes),
                "--input_file=%s/%s" % (model_output_dir, input_file_name),
                "--output_file=%s/%s" % (model_output_dir, output_file_name),
610
                "--model_data_file=%s/%s.data" % (mace_model_dir, model_tag),
Y
yejianwu 已提交
611 612 613
                "--device=%s" % device_type,
                "--round=%s" % running_round,
                "--restart_round=%s" % restart_round,
W
wuchenghui 已提交
614 615 616 617
                "--omp_num_threads=%s" % omp_num_threads,
                "--cpu_affinity_policy=%s" % cpu_affinity_policy,
                "--gpu_perf_hint=%s" % gpu_perf_hint,
                "--gpu_priority_hint=%s" % gpu_priority_hint,
Y
yejianwu 已提交
618
                "--model_file=%s" % mace_model_path,
W
wuchenghui 已提交
619 620 621
            ],
            stderr=subprocess.PIPE,
            stdout=subprocess.PIPE)
Y
yejianwu 已提交
622 623 624 625 626
        out, err = p.communicate()
        stdout = err + out
        print stdout
        print("Running finished!\n")
        return stdout
Y
yejianwu 已提交
627 628
    else:
        sh.adb("-s", serialno, "shell", "mkdir", "-p", phone_data_dir)
629 630
        internal_storage_dir = create_internal_storage_dir(
            serialno, phone_data_dir)
Y
yejianwu 已提交
631 632

        for input_name in input_nodes:
L
liuqi 已提交
633 634
            formatted_name = common.formatted_file_name(input_file_name,
                                                        input_name)
Y
yejianwu 已提交
635 636
            adb_push("%s/%s" % (model_output_dir, formatted_name),
                     phone_data_dir, serialno)
637 638 639
        if address_sanitizer:
            adb_push(find_asan_rt_library(abi), phone_data_dir, serialno)

Y
yejianwu 已提交
640
        if not embed_model_data:
641
            adb_push("%s/%s.data" % (mace_model_dir, model_tag),
Y
yejianwu 已提交
642
                     phone_data_dir, serialno)
643

W
wuchenghui 已提交
644
        adb_push("third_party/nnlib/libhexagon_controller.so",
Y
yejianwu 已提交
645 646
                 phone_data_dir, serialno)

647 648 649 650 651
        mace_model_phone_path = ""
        if build_type == BuildType.proto:
            mace_model_phone_path = "%s/%s.pb" % (phone_data_dir, model_tag)
            adb_push(mace_model_path,
                     mace_model_phone_path,
Y
yejianwu 已提交
652
                     serialno)
653 654 655

        adb_push("%s/mace_run" % mace_run_dir, phone_data_dir,
                 serialno)
Y
yejianwu 已提交
656

Y
yejianwu 已提交
657 658
        stdout_buff = []
        process_output = make_output_processor(stdout_buff)
659
        adb_cmd = [
W
wuchenghui 已提交
660 661 662 663
            "LD_LIBRARY_PATH=%s" % phone_data_dir,
            "MACE_TUNING=%s" % int(tuning),
            "MACE_OUT_OF_RANGE_CHECK=%s" % int(out_of_range_check),
            "MACE_CPP_MIN_VLOG_LEVEL=%s" % vlog_level,
664
            "MACE_RUN_PARAMETER_PATH=%s/mace_run.config" % phone_data_dir,
665
            "MACE_INTERNAL_STORAGE_PATH=%s" % internal_storage_dir,
666
            "MACE_LIMIT_OPENCL_KERNEL_TIME=%s" % limit_opencl_kernel_time,
李寅 已提交
667
            "MACE_RUNTIME_FAILURE_RATIO=%f" % runtime_failure_ratio,
668
        ]
669
        if address_sanitizer:
670
            adb_cmd.extend([
671 672
                "LD_PRELOAD=%s/%s" % (phone_data_dir,
                                      asan_rt_library_names(abi))
673 674
            ])
        adb_cmd.extend([
W
wuchenghui 已提交
675
            "%s/mace_run" % phone_data_dir,
676
            "--model_name=%s" % model_tag,
W
wuchenghui 已提交
677 678 679 680 681 682 683 684 685 686 687 688 689 690
            "--input_node=%s" % ",".join(input_nodes),
            "--output_node=%s" % ",".join(output_nodes),
            "--input_shape=%s" % ":".join(input_shapes),
            "--output_shape=%s" % ":".join(output_shapes),
            "--input_file=%s/%s" % (phone_data_dir, input_file_name),
            "--output_file=%s/%s" % (phone_data_dir, output_file_name),
            "--model_data_file=%s/%s.data" % (phone_data_dir, model_tag),
            "--device=%s" % device_type,
            "--round=%s" % running_round,
            "--restart_round=%s" % restart_round,
            "--omp_num_threads=%s" % omp_num_threads,
            "--cpu_affinity_policy=%s" % cpu_affinity_policy,
            "--gpu_perf_hint=%s" % gpu_perf_hint,
            "--gpu_priority_hint=%s" % gpu_priority_hint,
691
            "--model_file=%s" % mace_model_phone_path,
692 693
        ])
        adb_cmd = ' '.join(adb_cmd)
L
liuqi 已提交
694
        sh.adb(
695 696 697 698
            "-s",
            serialno,
            "shell",
            adb_cmd,
699
            _tty_in=True,
W
wuchenghui 已提交
700
            _out=process_output,
701
            _err_to_out=True)
Y
yejianwu 已提交
702 703
        print("Running finished!\n")
        return "".join(stdout_buff)
Y
yejianwu 已提交
704 705


W
wuchenghui 已提交
706 707
def validate_model(abi,
                   serialno,
Y
yejianwu 已提交
708 709 710
                   model_file_path,
                   weight_file_path,
                   platform,
711
                   device_type,
Y
yejianwu 已提交
712 713 714 715 716
                   input_nodes,
                   output_nodes,
                   input_shapes,
                   output_shapes,
                   model_output_dir,
717
                   phone_data_dir,
L
liuqi 已提交
718
                   caffe_env,
Y
yejianwu 已提交
719 720 721
                   input_file_name="model_input",
                   output_file_name="model_out"):
    print("* Validate with %s" % platform)
L
liuqi 已提交
722 723 724 725 726 727 728 729 730
    if abi != "host":
        for output_name in output_nodes:
            formatted_name = common.formatted_file_name(
                output_file_name, output_name)
            if os.path.exists("%s/%s" % (model_output_dir,
                                         formatted_name)):
                sh.rm("-rf", "%s/%s" % (model_output_dir, formatted_name))
            adb_pull("%s/%s" % (phone_data_dir, formatted_name),
                     model_output_dir, serialno)
Y
yejianwu 已提交
731 732

    if platform == "tensorflow":
733 734
        validate(platform, model_file_path, "",
                 "%s/%s" % (model_output_dir, input_file_name),
735
                 "%s/%s" % (model_output_dir, output_file_name), device_type,
736 737
                 ":".join(input_shapes), ":".join(output_shapes),
                 ",".join(input_nodes), ",".join(output_nodes))
Y
yejianwu 已提交
738 739 740 741
    elif platform == "caffe":
        image_name = "mace-caffe:latest"
        container_name = "mace_caffe_validator"

L
liuqi 已提交
742 743 744 745 746 747 748 749
        if caffe_env == common.CaffeEnvType.LOCAL:
            import imp
            try:
                imp.find_module('caffe')
            except ImportError:
                logger.error('There is no caffe python module.')
            validate(platform, model_file_path, weight_file_path,
                     "%s/%s" % (model_output_dir, input_file_name),
750 751
                     "%s/%s" % (model_output_dir, output_file_name),
                     device_type,
L
liuqi 已提交
752 753 754 755 756 757 758
                     ":".join(input_shapes), ":".join(output_shapes),
                     ",".join(input_nodes), ",".join(output_nodes))
        elif caffe_env == common.CaffeEnvType.DOCKER:
            docker_image_id = sh.docker("images", "-q", image_name)
            if not docker_image_id:
                print("Build caffe docker")
                sh.docker("build", "-t", image_name,
L
Liangliang He 已提交
759
                          "third_party/caffe")
L
liuqi 已提交
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785

            container_id = sh.docker("ps", "-qa", "-f",
                                     "name=%s" % container_name)
            if container_id and not sh.docker("ps", "-qa", "--filter",
                                              "status=running", "-f",
                                              "name=%s" % container_name):
                sh.docker("rm", "-f", container_name)
                container_id = ""
            if not container_id:
                print("Run caffe container")
                sh.docker(
                        "run",
                        "-d",
                        "-it",
                        "--name",
                        container_name,
                        image_name,
                        "/bin/bash")

            for input_name in input_nodes:
                formatted_input_name = common.formatted_file_name(
                        input_file_name, input_name)
                sh.docker(
                        "cp",
                        "%s/%s" % (model_output_dir, formatted_input_name),
                        "%s:/mace" % container_name)
Y
yejianwu 已提交
786 787

            for output_name in output_nodes:
L
liuqi 已提交
788 789 790 791 792 793 794 795
                formatted_output_name = common.formatted_file_name(
                        output_file_name, output_name)
                sh.docker(
                        "cp",
                        "%s/%s" % (model_output_dir, formatted_output_name),
                        "%s:/mace" % container_name)
            model_file_name = os.path.basename(model_file_path)
            weight_file_name = os.path.basename(weight_file_path)
L
liuqi 已提交
796
            sh.docker("cp", "tools/common.py", "%s:/mace" % container_name)
L
liuqi 已提交
797 798 799 800
            sh.docker("cp", "tools/validate.py", "%s:/mace" % container_name)
            sh.docker("cp", model_file_path, "%s:/mace" % container_name)
            sh.docker("cp", weight_file_path, "%s:/mace" % container_name)

L
liuqi 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
            sh.docker(
                "exec",
                container_name,
                "python",
                "-u",
                "/mace/validate.py",
                "--platform=caffe",
                "--model_file=/mace/%s" % model_file_name,
                "--weight_file=/mace/%s" % weight_file_name,
                "--input_file=/mace/%s" % input_file_name,
                "--mace_out_file=/mace/%s" % output_file_name,
                "--device_type=%s" % device_type,
                "--input_node=%s" % ",".join(input_nodes),
                "--output_node=%s" % ",".join(output_nodes),
                "--input_shape=%s" % ":".join(input_shapes),
                "--output_shape=%s" % ":".join(output_shapes),
                _fg=True)
Y
yejianwu 已提交
818 819 820 821

    print("Validation done!\n")


822 823 824
def build_host_libraries(model_build_type, abi):
    bazel_build("@com_google_protobuf//:protobuf_lite", abi=abi)
    bazel_build("//mace/proto:mace_cc", abi=abi)
Y
yejianwu 已提交
825 826
    bazel_build("//mace/codegen:generated_opencl", abi=abi)
    bazel_build("//mace/codegen:generated_tuning_params", abi=abi)
827 828 829 830 831 832 833 834 835
    bazel_build("//mace/codegen:generated_version", abi=abi)
    bazel_build("//mace/utils:utils", abi=abi)
    bazel_build("//mace/core:core", abi=abi)
    bazel_build("//mace/kernels:kernels", abi=abi)
    bazel_build("//mace/ops:ops", abi=abi)
    if model_build_type == BuildType.code:
        bazel_build(
            "//mace/codegen:generated_models",
            abi=abi)
Y
yejianwu 已提交
836 837 838


def merge_libs(target_soc,
L
liuqi 已提交
839
               serial_num,
Y
yejianwu 已提交
840 841
               abi,
               project_name,
842 843 844 845
               build_output_dir,
               library_output_dir,
               model_build_type,
               hexagon_mode):
Y
yejianwu 已提交
846
    print("* Merge mace lib")
847
    project_output_dir = "%s/%s" % (build_output_dir, project_name)
Y
yejianwu 已提交
848
    model_header_dir = "%s/include/mace/public" % project_output_dir
L
Liangliang He 已提交
849
    hexagon_lib_file = "third_party/nnlib/libhexagon_controller.so"
L
liuqi 已提交
850 851
    library_dir = "%s/%s" % (project_output_dir, library_output_dir)
    model_bin_dir = "%s/%s/" % (library_dir, abi)
852 853 854 855 856 857 858 859

    if os.path.exists(model_bin_dir):
        sh.rm("-rf", model_bin_dir)
    sh.mkdir("-p", model_bin_dir)
    if os.path.exists(model_header_dir):
        sh.rm("-rf", model_header_dir)
    sh.mkdir("-p", model_header_dir)
    # copy header files
860
    sh.cp("-f", glob.glob("mace/public/*.h"), model_header_dir)
Y
yejianwu 已提交
861
    if hexagon_mode:
L
liuqi 已提交
862
        sh.cp("-f", hexagon_lib_file, library_dir)
Y
yejianwu 已提交
863

864
    if model_build_type == BuildType.code:
Y
yejianwu 已提交
865
        sh.cp("-f", glob.glob("mace/codegen/engine/*.h"), model_header_dir)
866
        sh.cp("-f", glob.glob("mace/codegen/models/*/*.h"), model_header_dir)
Y
yejianwu 已提交
867

868
    # make static library
Y
yejianwu 已提交
869 870
    mri_stream = ""
    if abi == "host":
871 872
        mri_stream += "create %s/libmace_%s.a\n" % \
                      (model_bin_dir, project_name)
Y
yejianwu 已提交
873
        mri_stream += (
874 875
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_opencl.pic.a\n")
Y
yejianwu 已提交
876
        mri_stream += (
877 878
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_tuning_params.pic.a\n")
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
        mri_stream += (
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_version.pic.a\n")
        mri_stream += (
            "addlib "
            "bazel-bin/mace/core/libcore.pic.a\n")
        mri_stream += (
            "addlib "
            "bazel-bin/mace/kernels/libkernels.pic.a\n")
        mri_stream += (
            "addlib "
            "bazel-bin/mace/utils/libutils.pic.a\n")
        mri_stream += (
            "addlib "
            "bazel-bin/mace/proto/libmace_cc.pic.a\n")
        mri_stream += (
            "addlib "
            "bazel-bin/external/com_google_protobuf/libprotobuf_lite.pic.a\n")
        mri_stream += (
            "addlib "
            "bazel-bin/mace/ops/libops.pic.lo\n")
        if model_build_type == BuildType.code:
901 902 903
            mri_stream += (
                "addlib "
                "bazel-bin/mace/codegen/libgenerated_models.pic.a\n")
Y
yejianwu 已提交
904
    else:
905 906 907 908
        if not target_soc:
            mri_stream += "create %s/libmace_%s.a\n" % \
                          (model_bin_dir, project_name)
        else:
L
liuqi 已提交
909 910 911 912
            device_name = adb_get_device_name_by_serialno(serial_num)
            mri_stream += "create %s/libmace_%s.%s.%s.a\n" % \
                          (model_bin_dir, project_name,
                           device_name, target_soc)
913
        if model_build_type == BuildType.code:
914 915 916
            mri_stream += (
                "addlib "
                "bazel-bin/mace/codegen/libgenerated_models.a\n")
Y
yejianwu 已提交
917
        mri_stream += (
918 919
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_opencl.a\n")
Y
yejianwu 已提交
920
        mri_stream += (
921 922
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_tuning_params.a\n")
Y
yejianwu 已提交
923
        mri_stream += (
924 925
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_version.a\n")
Y
yejianwu 已提交
926
        mri_stream += (
927 928
            "addlib "
            "bazel-bin/mace/core/libcore.a\n")
Y
yejianwu 已提交
929
        mri_stream += (
930 931
            "addlib "
            "bazel-bin/mace/kernels/libkernels.a\n")
Y
yejianwu 已提交
932
        mri_stream += (
933 934
            "addlib "
            "bazel-bin/mace/utils/libutils.a\n")
935 936 937 938 939 940
        mri_stream += (
            "addlib "
            "bazel-bin/mace/proto/libmace_cc.a\n")
        mri_stream += (
            "addlib "
            "bazel-bin/external/com_google_protobuf/libprotobuf_lite.a\n")
Y
yejianwu 已提交
941
        mri_stream += (
942 943
            "addlib "
            "bazel-bin/mace/ops/libops.lo\n")
Y
yejianwu 已提交
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966

    mri_stream += "save\n"
    mri_stream += "end\n"

    cmd = sh.Command("%s/toolchains/" % os.environ["ANDROID_NDK_HOME"] +
                     "aarch64-linux-android-4.9/prebuilt/linux-x86_64/" +
                     "bin/aarch64-linux-android-ar")

    cmd("-M", _in=mri_stream)

    print("Libs merged!\n")


def packaging_lib(libmace_output_dir, project_name):
    print("* Package libs for %s" % project_name)
    tar_package_name = "libmace_%s.tar.gz" % project_name
    project_dir = "%s/%s" % (libmace_output_dir, project_name)
    tar_package_path = "%s/%s" % (project_dir, tar_package_name)
    if os.path.exists(tar_package_path):
        sh.rm("-rf", tar_package_path)

    print("Start packaging '%s' libs into %s" % (project_name,
                                                 tar_package_path))
L
liuqi 已提交
967 968 969 970 971 972 973
    sh.tar(
        "cvzf",
        "%s" % tar_package_path,
        glob.glob("%s/*" % project_dir),
        "--exclude",
        "%s/_tmp" % project_dir,
        _fg=True)
Y
yejianwu 已提交
974 975 976
    print("Packaging Done!\n")


977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
def build_benchmark_model(abi,
                          model_output_dir,
                          hexagon_mode):
    benchmark_binary_file = "%s/benchmark_model" % model_output_dir
    if os.path.exists(benchmark_binary_file):
        sh.rm("-rf", benchmark_binary_file)

    benchmark_target = "//mace/benchmark:benchmark_model"
    bazel_build(benchmark_target,
                abi=abi,
                hexagon_mode=hexagon_mode)

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


W
wuchenghui 已提交
993 994
def benchmark_model(abi,
                    serialno,
995
                    benchmark_binary_dir,
Y
yejianwu 已提交
996 997 998
                    vlog_level,
                    embed_model_data,
                    model_output_dir,
Y
yejianwu 已提交
999
                    mace_model_dir,
Y
yejianwu 已提交
1000 1001 1002 1003 1004 1005
                    input_nodes,
                    output_nodes,
                    input_shapes,
                    output_shapes,
                    model_tag,
                    device_type,
1006
                    phone_data_dir,
1007
                    build_type,
W
wuchenghui 已提交
1008 1009 1010 1011
                    omp_num_threads=-1,
                    cpu_affinity_policy=1,
                    gpu_perf_hint=3,
                    gpu_priority_hint=3,
1012
                    input_file_name="model_input"):
Y
yejianwu 已提交
1013 1014
    print("* Benchmark for %s" % model_tag)

1015 1016 1017
    mace_model_path = ""
    if build_type == BuildType.proto:
        mace_model_path = "%s/%s.pb" % (mace_model_dir, model_tag)
Y
yejianwu 已提交
1018
    if abi == "host":
W
wuchenghui 已提交
1019 1020
        p = subprocess.Popen(
            [
Y
yejianwu 已提交
1021 1022
                "env",
                "MACE_CPP_MIN_VLOG_LEVEL=%s" % vlog_level,
1023
                "%s/benchmark_model" % benchmark_binary_dir,
1024
                "--model_name=%s" % model_tag,
Y
yejianwu 已提交
1025 1026 1027 1028 1029
                "--input_node=%s" % ",".join(input_nodes),
                "--output_node=%s" % ",".join(output_nodes),
                "--input_shape=%s" % ":".join(input_shapes),
                "--output_shape=%s" % ":".join(output_shapes),
                "--input_file=%s/%s" % (model_output_dir, input_file_name),
1030
                "--model_data_file=%s/%s.data" % (mace_model_dir, model_tag),
Y
yejianwu 已提交
1031
                "--device=%s" % device_type,
W
wuchenghui 已提交
1032 1033 1034 1035
                "--omp_num_threads=%s" % omp_num_threads,
                "--cpu_affinity_policy=%s" % cpu_affinity_policy,
                "--gpu_perf_hint=%s" % gpu_perf_hint,
                "--gpu_priority_hint=%s" % gpu_priority_hint,
Y
yejianwu 已提交
1036
                "--model_file=%s" % mace_model_path,
W
wuchenghui 已提交
1037
            ])
Y
yejianwu 已提交
1038 1039 1040
        p.wait()
    else:
        sh.adb("-s", serialno, "shell", "mkdir", "-p", phone_data_dir)
1041 1042
        internal_storage_dir = create_internal_storage_dir(
            serialno, phone_data_dir)
Y
yejianwu 已提交
1043 1044

        for input_name in input_nodes:
L
liuqi 已提交
1045 1046
            formatted_name = common.formatted_file_name(input_file_name,
                                                        input_name)
Y
yejianwu 已提交
1047 1048 1049
            adb_push("%s/%s" % (model_output_dir, formatted_name),
                     phone_data_dir, serialno)
        if not embed_model_data:
1050
            adb_push("%s/%s.data" % (mace_model_dir, model_tag),
Y
yejianwu 已提交
1051
                     phone_data_dir, serialno)
1052 1053 1054 1055 1056
        mace_model_phone_path = ""
        if build_type == BuildType.proto:
            mace_model_phone_path = "%s/%s.pb" % (phone_data_dir, model_tag)
            adb_push(mace_model_path,
                     mace_model_phone_path,
Y
yejianwu 已提交
1057
                     serialno)
1058 1059
        adb_push("%s/benchmark_model" % benchmark_binary_dir, phone_data_dir,
                 serialno)
Y
yejianwu 已提交
1060

L
liuqi 已提交
1061
        sh.adb(
W
wuchenghui 已提交
1062 1063 1064 1065 1066 1067 1068
            "-s",
            serialno,
            "shell",
            "LD_LIBRARY_PATH=%s" % phone_data_dir,
            "MACE_CPP_MIN_VLOG_LEVEL=%s" % vlog_level,
            "MACE_RUN_PARAMETER_PATH=%s/mace_run.config" %
            phone_data_dir,
1069
            "MACE_INTERNAL_STORAGE_PATH=%s" % internal_storage_dir,
W
wuchenghui 已提交
1070 1071
            "MACE_OPENCL_PROFILING=1",
            "%s/benchmark_model" % phone_data_dir,
1072
            "--model_name=%s" % model_tag,
W
wuchenghui 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
            "--input_node=%s" % ",".join(input_nodes),
            "--output_node=%s" % ",".join(output_nodes),
            "--input_shape=%s" % ":".join(input_shapes),
            "--output_shape=%s" % ":".join(output_shapes),
            "--input_file=%s/%s" % (phone_data_dir, input_file_name),
            "--model_data_file=%s/%s.data" % (phone_data_dir, model_tag),
            "--device=%s" % device_type,
            "--omp_num_threads=%s" % omp_num_threads,
            "--cpu_affinity_policy=%s" % cpu_affinity_policy,
            "--gpu_perf_hint=%s" % gpu_perf_hint,
            "--gpu_priority_hint=%s" % gpu_priority_hint,
1084
            "--model_file=%s" % mace_model_phone_path,
L
liuqi 已提交
1085
            _fg=True)
Y
yejianwu 已提交
1086 1087 1088 1089

    print("Benchmark done!\n")


W
wuchenghui 已提交
1090 1091
def build_run_throughput_test(abi,
                              serialno,
Y
yejianwu 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
                              vlog_level,
                              run_seconds,
                              merged_lib_file,
                              model_input_dir,
                              embed_model_data,
                              input_nodes,
                              output_nodes,
                              input_shapes,
                              output_shapes,
                              cpu_model_tag,
                              gpu_model_tag,
                              dsp_model_tag,
1104
                              phone_data_dir,
Y
yejianwu 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
                              strip="always",
                              input_file_name="model_input"):
    print("* Build and run throughput_test")

    model_tag_build_flag = ""
    if cpu_model_tag:
        model_tag_build_flag += "--copt=-DMACE_CPU_MODEL_TAG=%s " % \
                                cpu_model_tag
    if gpu_model_tag:
        model_tag_build_flag += "--copt=-DMACE_GPU_MODEL_TAG=%s " % \
                                gpu_model_tag
    if dsp_model_tag:
        model_tag_build_flag += "--copt=-DMACE_DSP_MODEL_TAG=%s " % \
                                dsp_model_tag

1120
    sh.cp("-f", merged_lib_file, "mace/benchmark/libmace_merged.a")
L
liuqi 已提交
1121
    sh.bazel(
Y
yejianwu 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
        "build",
        "-c",
        "opt",
        "--strip",
        strip,
        "--verbose_failures",
        "//mace/benchmark:model_throughput_test",
        "--crosstool_top=//external:android/crosstool",
        "--host_crosstool_top=@bazel_tools//tools/cpp:toolchain",
        "--cpu=%s" % abi,
        "--copt=-std=c++11",
        "--copt=-D_GLIBCXX_USE_C99_MATH_TR1",
        "--copt=-Werror=return-type",
        "--copt=-O3",
        "--define",
        "neon=true",
        "--define",
        "openmp=true",
        model_tag_build_flag,
L
liuqi 已提交
1141
        _fg=True)
Y
yejianwu 已提交
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166

    sh.rm("mace/benchmark/libmace_merged.a")
    sh.adb("-s",
           serialno,
           "shell",
           "mkdir",
           "-p",
           phone_data_dir)
    adb_push("%s/%s_%s" % (model_input_dir, input_file_name,
                           ",".join(input_nodes)),
             phone_data_dir,
             serialno)
    adb_push("bazel-bin/mace/benchmark/model_throughput_test",
             phone_data_dir,
             serialno)
    if not embed_model_data:
        adb_push("codegen/models/%s/%s.data" % cpu_model_tag,
                 phone_data_dir,
                 serialno)
        adb_push("codegen/models/%s/%s.data" % gpu_model_tag,
                 phone_data_dir,
                 serialno)
        adb_push("codegen/models/%s/%s.data" % dsp_model_tag,
                 phone_data_dir,
                 serialno)
L
Liangliang He 已提交
1167
    adb_push("third_party/nnlib/libhexagon_controller.so",
Y
yejianwu 已提交
1168 1169 1170
             phone_data_dir,
             serialno)

L
liuqi 已提交
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
    sh.adb(
        "-s",
        serialno,
        "shell",
        "LD_LIBRARY_PATH=%s" % phone_data_dir,
        "MACE_CPP_MIN_VLOG_LEVEL=%s" % vlog_level,
        "MACE_RUN_PARAMETER_PATH=%s/mace_run.config" %
        phone_data_dir,
        "%s/model_throughput_test" % phone_data_dir,
        "--input_node=%s" % ",".join(input_nodes),
        "--output_node=%s" % ",".join(output_nodes),
        "--input_shape=%s" % ":".join(input_shapes),
        "--output_shape=%s" % ":".join(output_shapes),
        "--input_file=%s/%s" % (phone_data_dir, input_file_name),
        "--cpu_model_data_file=%s/%s.data" % (phone_data_dir,
                                              cpu_model_tag),
        "--gpu_model_data_file=%s/%s.data" % (phone_data_dir,
                                              gpu_model_tag),
        "--dsp_model_data_file=%s/%s.data" % (phone_data_dir,
                                              dsp_model_tag),
        "--run_seconds=%s" % run_seconds,
        _fg=True)
Y
yejianwu 已提交
1193 1194 1195 1196

    print("throughput_test done!\n")


1197 1198 1199
################################
# falcon
################################
L
Liangliang He 已提交
1200
def falcon_tags(tags_dict):
L
Liangliang He 已提交
1201 1202 1203 1204 1205 1206 1207
    tags = ""
    for k, v in tags_dict.iteritems():
        if tags == "":
            tags = "%s=%s" % (k, v)
        else:
            tags = tags + ",%s=%s" % (k, v)
    return tags
L
Liangliang He 已提交
1208

1209

L
Liangliang He 已提交
1210 1211
def falcon_push_metrics(server, metrics, endpoint="mace_dev", tags={}):
    cli = falcon_cli.FalconCli.connect(server=server, port=8433, debug=False)
L
Liangliang He 已提交
1212 1213 1214 1215 1216 1217 1218
    ts = int(time.time())
    falcon_metrics = [{
        "endpoint": endpoint,
        "metric": key,
        "tags": falcon_tags(tags),
        "timestamp": ts,
        "value": value,
L
Liangliang He 已提交
1219
        "step": 600,
L
Liangliang He 已提交
1220 1221 1222
        "counterType": "GAUGE"
    } for key, value in metrics.iteritems()]
    cli.update(falcon_metrics)