sh_commands.py 45.5 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

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

29 30 31 32 33 34 35
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
36
    from mace_engine_factory_codegen import gen_mace_engine_factory
Y
yejianwu 已提交
37 38
except Exception as e:
    print("Import error:\n%s" % e)
39 40
    exit(1)

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


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

50 51

def make_output_processor(buff):
L
Liangliang He 已提交
52
    def process_output(line):
L
Liangliang He 已提交
53
        print(line.rstrip())
L
Liangliang He 已提交
54 55 56 57
        buff.append(line)

    return process_output

58

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
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


Y
yejianwu 已提交
75 76 77
################################
# clear data
################################
78 79 80 81 82
def clear_phone_data_dir(serialno, phone_data_dir):
    sh.adb("-s",
           serialno,
           "shell",
           "rm -rf %s" % phone_data_dir)
83 84 85


def clear_model_codegen(model_codegen_dir="mace/codegen/models"):
Y
yejianwu 已提交
86 87 88 89
    if os.path.exists(model_codegen_dir):
        sh.rm("-rf", model_codegen_dir)


90 91 92 93
################################
# adb commands
################################
def adb_split_stdout(stdout_str):
L
Liangliang He 已提交
94 95 96 97
    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]

98

W
wuchenghui 已提交
99 100
def adb_devices():
    serialnos = []
101 102 103 104
    p = re.compile(r'(\w+)\s+device')
    for line in adb_split_stdout(sh.adb("devices")):
        m = p.match(line)
        if m:
W
wuchenghui 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
            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 已提交
129

130 131

def adb_getprop_by_serialno(serialno):
L
Liangliang He 已提交
132 133 134
    outputs = sh.adb("-s", serialno, "shell", "getprop")
    raw_props = adb_split_stdout(outputs)
    props = {}
135
    p = re.compile(r'\[(.+)\]: \[(.+)\]')
L
Liangliang He 已提交
136 137 138 139 140 141
    for raw_prop in raw_props:
        m = p.match(raw_prop)
        if m:
            props[m.group(1)] = m.group(2)
    return props

142

W
wuchenghui 已提交
143 144 145 146 147
def adb_get_device_name_by_serialno(serialno):
    props = adb_getprop_by_serialno(serialno)
    return props.get("ro.product.model", "")


148
def adb_supported_abis(serialno):
L
Liangliang He 已提交
149 150 151 152 153
    props = adb_getprop_by_serialno(serialno)
    abilist_str = props["ro.product.cpu.abilist"]
    abis = [abi.strip() for abi in abilist_str.split(',')]
    return abis

154

155
def adb_get_all_socs():
L
Liangliang He 已提交
156 157 158 159 160
    socs = []
    for d in adb_devices():
        props = adb_getprop_by_serialno(d)
        socs.append(props["ro.board.platform"])
    return set(socs)
161

L
Liangliang He 已提交
162

Y
yejianwu 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175
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)


L
Liangliang He 已提交
176 177 178
def adb_run(serialno,
            host_bin_path,
            bin_name,
179 180 181
            args="",
            opencl_profiling=1,
            vlog_level=0,
182 183
            device_bin_path="/data/local/tmp/mace",
            out_of_range_check=1):
L
Liangliang He 已提交
184 185 186 187 188 189
    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 已提交
190
    print("Trying to lock device %s" % serialno)
191 192 193 194
    with device_lock(serialno):
        print("Run on device: %s, %s, %s" %
              (serialno, props["ro.board.platform"],
               props["ro.product.model"]))
Y
yejianwu 已提交
195 196
        sh.adb("-s", serialno, "shell", "rm -rf %s" % device_bin_path)
        sh.adb("-s", serialno, "shell", "mkdir -p %s" % device_bin_path)
Y
yejianwu 已提交
197
        adb_push(host_bin_full_path, device_bin_full_path, serialno)
Y
yejianwu 已提交
198 199 200 201 202 203 204 205 206 207
        print("Run %s" % device_bin_full_path)
        stdout_buff = []
        process_output = make_output_processor(stdout_buff)
        p = sh.adb(
            "-s",
            serialno,
            "shell",
            "MACE_OUT_OF_RANGE_CHECK=%d MACE_OPENCL_PROFILING=%d "
            "MACE_CPP_MIN_VLOG_LEVEL=%d %s %s" %
            (out_of_range_check, opencl_profiling, vlog_level,
208
             device_bin_full_path, args),
Y
yejianwu 已提交
209 210 211 212 213
            _out=process_output,
            _bg=True,
            _err_to_out=True)
        p.wait()
        return "".join(stdout_buff)
214 215


216 217 218
def adb_run_valgrind(serialno,
                     host_bin_path,
                     bin_name,
219
                     valgrind_path="/data/local/tmp/valgrind",
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
                     valgrind_args="",
                     args="",
                     opencl_profiling=1,
                     vlog_level=0,
                     device_bin_path="/data/local/tmp/mace",
                     out_of_range_check=1):
    valgrind_lib = valgrind_path + "/lib/valgrind"
    valgrind_bin = valgrind_path + "/bin/valgrind"
    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(
        "====================================================================="
    )
    print("Trying to lock device %s" % serialno)
    with device_lock(serialno):
        print("Run on device: %s, %s, %s" %
              (serialno, props["ro.board.platform"],
               props["ro.product.model"]))
        result = sh.adb("-s", serialno, "shell", "ls %s" % valgrind_path)
        if result.startswith("ls:"):
            print("Please install valgrind to %s manually." % valgrind_path)
            return result
        sh.adb("-s", serialno, "shell", "rm -rf %s" % device_bin_path)
        sh.adb("-s", serialno, "shell", "mkdir -p %s" % device_bin_path)
        adb_push(host_bin_full_path, device_bin_full_path, serialno)
        print("Run %s" % device_bin_full_path)
        stdout_buff = []
        process_output = make_output_processor(stdout_buff)
        p = sh.adb(
            "-s",
            serialno,
            "shell",
            "MACE_OUT_OF_RANGE_CHECK=%d MACE_OPENCL_PROFILING=%d "
            "MACE_CPP_MIN_VLOG_LEVEL=%d VALGRIND_LIB=%s %s %s %s %s " %
            (out_of_range_check, opencl_profiling, vlog_level,
             valgrind_lib, valgrind_bin, valgrind_args,
             device_bin_full_path, args),
            _out=process_output,
            _bg=True,
            _err_to_out=True)
        p.wait()
        return "".join(stdout_buff)


265 266 267
################################
# bazel commands
################################
Y
yejianwu 已提交
268 269 270 271 272
def bazel_build(target,
                strip="always",
                abi="armeabi-v7a",
                production_mode=False,
                hexagon_mode=False,
273
                disable_no_tuning_warning=False,
W
wuchenghui 已提交
274
                debug=False,
李寅 已提交
275 276
                enable_openmp=True,
                enable_neon=True):
Y
yejianwu 已提交
277 278 279 280
    print("* Build %s with ABI %s" % (target, abi))
    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
    if abi == "host":
W
wuchenghui 已提交
281
        bazel_args = (
Y
yejianwu 已提交
282 283 284 285 286 287 288 289 290 291 292
            "build",
            "-c",
            "opt",
            "--strip",
            strip,
            "--verbose_failures",
            target,
            "--copt=-std=c++11",
            "--copt=-D_GLIBCXX_USE_C99_MATH_TR1",
            "--copt=-O3",
            "--define",
W
wuchenghui 已提交
293
            "openmp=%s" % str(enable_openmp).lower(),
Y
yejianwu 已提交
294 295
            "--define",
            "production=%s" % str(production_mode).lower(),
W
wuchenghui 已提交
296 297 298
        )
        p = sh.bazel(
            *bazel_args,
Y
yejianwu 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
            _out=process_output,
            _bg=True,
            _err_to_out=True)
        p.wait()
    else:
        bazel_args = (
            "build",
            "-c",
            "opt",
            "--strip",
            strip,
            "--verbose_failures",
            target,
            "--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=-DMACE_OBFUSCATE_LITERALS",
            "--copt=-O3",
            "--define",
李寅 已提交
320
            "neon=%s" % str(enable_neon).lower(),
Y
yejianwu 已提交
321
            "--define",
W
wuchenghui 已提交
322
            "openmp=%s" % str(enable_openmp).lower(),
Y
yejianwu 已提交
323 324 325 326 327 328
            "--define",
            "production=%s" % str(production_mode).lower(),
            "--define",
            "hexagon=%s" % str(hexagon_mode).lower())
        if disable_no_tuning_warning:
            bazel_args += ("--copt=-DMACE_DISABLE_NO_TUNING_WARNING",)
329 330
        if debug:
            bazel_args += ("--copt=-g",)
Y
yejianwu 已提交
331 332 333 334 335 336 337 338 339 340 341
        p = sh.bazel(
            _out=process_output,
            _bg=True,
            _err_to_out=True,
            *bazel_args)
        p.wait()
    print("Building done!\n")
    return "".join(stdout_buff)


def bazel_build_common(target, build_args=""):
L
Liangliang He 已提交
342 343 344 345
    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
    p = sh.bazel(
        "build",
Y
yejianwu 已提交
346
        target + build_args,
L
Liangliang He 已提交
347 348 349 350 351 352
        _out=process_output,
        _bg=True,
        _err_to_out=True)
    p.wait()
    return "".join(stdout_buff)

353 354

def bazel_target_to_bin(target):
L
Liangliang He 已提交
355 356 357 358 359 360 361 362
    # 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

363 364 365 366 367

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

372

Y
yejianwu 已提交
373
def gen_mace_engine_factory_source(model_tags,
374
                                   model_load_type,
Y
yejianwu 已提交
375
                                   codegen_path="mace/codegen"):
376 377 378 379
    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)
380
    gen_mace_engine_factory(
381 382
        model_tags,
        "mace/python/tools",
383
        model_load_type,
384 385 386 387 388 389 390
        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):
391
    compiled_opencl_dir = "/data/local/tmp/mace_run/interior/"
392
    mace_run_param_file = "mace_run.config"
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
    if cl_bin_dirs:
Y
yejianwu 已提交
399 400 401 402 403
        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":
404 405 406 407
            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)
408
            adb_pull("/data/local/tmp/mace_run/%s" % mace_run_param_file,
Y
yejianwu 已提交
409 410 411
                     cl_bin_dir, serialno)


W
wuchenghui 已提交
412
def gen_opencl_binary_code(model_output_dirs,
413 414
                           cl_built_kernel_file_name,
                           cl_platform_info_file_name,
Y
yejianwu 已提交
415
                           codegen_path="mace/codegen"):
416
    opencl_codegen_file = "%s/opencl/opencl_compiled_program.cc" % codegen_path
Y
yejianwu 已提交
417 418 419 420 421

    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)
422 423 424 425
    opencl_codegen(opencl_codegen_file,
                   cl_bin_dirs_str,
                   cl_built_kernel_file_name,
                   cl_platform_info_file_name)
Y
yejianwu 已提交
426 427


W
wuchenghui 已提交
428
def gen_tuning_param_code(model_output_dirs,
Y
yejianwu 已提交
429
                          codegen_path="mace/codegen"):
430
    mace_run_param_file = "mace_run.config"
Y
yejianwu 已提交
431 432 433 434
    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)
435 436 437 438 439

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

440 441 442 443 444
    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 已提交
445 446


447
def gen_mace_version(codegen_path="mace/codegen"):
L
Liangliang He 已提交
448 449 450 451
    sh.mkdir("-p", "%s/version" % codegen_path)
    sh.bash("mace/tools/git/gen_version_source.sh",
            "%s/version/version.cc" % codegen_path)

452

L
liuqi 已提交
453
def gen_compiled_opencl_source(codegen_path="mace/codegen"):
454
    opencl_codegen_file = "%s/opencl/opencl_compiled_program.cc" % codegen_path
L
Liangliang He 已提交
455
    sh.mkdir("-p", "%s/opencl" % codegen_path)
456
    opencl_codegen(opencl_codegen_file)
L
Liangliang He 已提交
457

L
liuqi 已提交
458

Y
yejianwu 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471
def gen_model_code(model_codegen_dir,
                   platform,
                   model_file_path,
                   weight_file_path,
                   model_sha256_checksum,
                   input_nodes,
                   output_nodes,
                   runtime,
                   model_tag,
                   input_shapes,
                   dsp_mode,
                   embed_model_data,
                   fast_conv,
Y
yejianwu 已提交
472 473
                   obfuscate,
                   model_output_dir,
474
                   model_load_type,
475
                   gpu_data_type):
Y
yejianwu 已提交
476 477
    print("* Genearte model code")
    bazel_build_common("//mace/python/tools:converter")
Y
yejianwu 已提交
478

Y
yejianwu 已提交
479 480 481
    if os.path.exists(model_codegen_dir):
        sh.rm("-rf", model_codegen_dir)
    sh.mkdir("-p", model_codegen_dir)
Y
yejianwu 已提交
482

Y
yejianwu 已提交
483 484 485
    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
    p = sh.python("bazel-bin/mace/python/tools/converter",
Y
yejianwu 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
                  "-u",
                  "--platform=%s" % platform,
                  "--model_file=%s" % model_file_path,
                  "--weight_file=%s" % weight_file_path,
                  "--model_checksum=%s" % model_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,
Y
yejianwu 已提交
501 502 503
                  "--codegen_output=%s/model.cc" % model_codegen_dir,
                  "--pb_output=%s/%s.pb" % (model_output_dir, model_tag),
                  "--model_load_type=%s" % model_load_type,
504
                  "--gpu_data_type=%s" % gpu_data_type,
Y
yejianwu 已提交
505 506 507
                  _out=process_output,
                  _bg=True,
                  _err_to_out=True)
Y
yejianwu 已提交
508
    p.wait()
Y
yejianwu 已提交
509 510 511 512 513 514 515 516 517
    print("Model code gen done!\n")


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 已提交
518 519
        formatted_name = common.formatted_file_name(
            input_file_name, input_name)
520 521
        if os.path.exists("%s/%s" % (model_output_dir, formatted_name)):
            sh.rm("%s/%s" % (model_output_dir, formatted_name))
Y
yejianwu 已提交
522 523
    input_nodes_str = ",".join(input_nodes)
    input_shapes_str = ":".join(input_shapes)
524 525 526
    generate_input_data("%s/%s" % (model_output_dir, input_file_name),
                        input_nodes_str,
                        input_shapes_str)
Y
yejianwu 已提交
527 528 529 530 531 532 533 534

    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 已提交
535 536
        if isinstance(input_nodes, list):
            input_name_list.extend(input_nodes)
Y
yejianwu 已提交
537
        else:
W
wuchenghui 已提交
538
            input_name_list.append(input_nodes)
Y
yejianwu 已提交
539 540 541 542 543 544
        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 已提交
545 546
                        common.formatted_file_name(input_file_name,
                                                   input_name_list[i])
Y
yejianwu 已提交
547 548 549 550
                if input_file_list[i].startswith("http://") or \
                        input_file_list[i].startswith("https://"):
                    urllib.urlretrieve(input_file_list[i], dst_input_file)
                else:
551
                    sh.cp("-f", input_file_list[i], dst_input_file)
Y
yejianwu 已提交
552 553 554


def update_mace_run_lib(model_output_dir,
555
                        model_load_type,
Y
yejianwu 已提交
556
                        model_tag,
557
                        embed_model_data):
Y
yejianwu 已提交
558 559 560
    mace_run_filepath = model_output_dir + "/mace_run"
    if os.path.exists(mace_run_filepath):
        sh.rm("-rf", mace_run_filepath)
561
    sh.cp("-f", "bazel-bin/mace/tools/validation/mace_run", model_output_dir)
Y
yejianwu 已提交
562 563

    if embed_model_data == 0:
564
        sh.cp("-f", "mace/codegen/models/%s/%s.data" % (model_tag, model_tag),
Y
yejianwu 已提交
565 566
              model_output_dir)

567 568 569
    if model_load_type == "source":
        sh.cp("-f", "mace/codegen/models/%s/%s.h" % (model_tag, model_tag),
              model_output_dir)
Y
yejianwu 已提交
570 571


572 573 574 575
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
576 577


W
wuchenghui 已提交
578 579
def tuning_run(abi,
               serialno,
Y
yejianwu 已提交
580 581 582 583 584 585 586
               vlog_level,
               embed_model_data,
               model_output_dir,
               input_nodes,
               output_nodes,
               input_shapes,
               output_shapes,
Y
yejianwu 已提交
587
               mace_model_dir,
Y
yejianwu 已提交
588 589 590 591 592 593 594
               model_tag,
               device_type,
               running_round,
               restart_round,
               limit_opencl_kernel_time,
               tuning,
               out_of_range_check,
595
               phone_data_dir,
W
wuchenghui 已提交
596 597 598 599
               omp_num_threads=-1,
               cpu_affinity_policy=1,
               gpu_perf_hint=3,
               gpu_priority_hint=3,
李寅 已提交
600
               runtime_failure_ratio=0.0,
601 602 603
               valgrind=False,
               valgrind_path="/data/local/tmp/valgrind",
               valgrind_args="",
Y
yejianwu 已提交
604 605
               input_file_name="model_input",
               output_file_name="model_out"):
606
    print("* Run '%s' with round=%s, restart_round=%s, tuning=%s, "
W
wuchenghui 已提交
607 608
          "out_of_range_check=%s, omp_num_threads=%s, cpu_affinity_policy=%s, "
          "gpu_perf_hint=%s, gpu_priority_hint=%s" %
609
          (model_tag, running_round, restart_round, str(tuning),
W
wuchenghui 已提交
610 611
           str(out_of_range_check), omp_num_threads, cpu_affinity_policy,
           gpu_perf_hint, gpu_priority_hint))
Y
yejianwu 已提交
612
    if abi == "host":
Y
yejianwu 已提交
613 614 615 616
        if mace_model_dir:
            mace_model_path = "%s/%s.pb" % (mace_model_dir, model_tag)
        else:
            mace_model_path = ""
W
wuchenghui 已提交
617 618
        p = subprocess.Popen(
            [
Y
yejianwu 已提交
619 620
                "env",
                "MACE_CPP_MIN_VLOG_LEVEL=%s" % vlog_level,
李寅 已提交
621
                "MACE_RUNTIME_FAILURE_RATIO=%f" % runtime_failure_ratio,
Y
yejianwu 已提交
622
                "%s/mace_run" % model_output_dir,
623
                "--model_name=%s" % model_tag,
Y
yejianwu 已提交
624 625 626 627 628 629 630 631 632 633
                "--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),
                "--model_data_file=%s/%s.data" % (model_output_dir, model_tag),
                "--device=%s" % device_type,
                "--round=%s" % running_round,
                "--restart_round=%s" % restart_round,
W
wuchenghui 已提交
634 635 636 637
                "--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 已提交
638
                "--model_file=%s" % mace_model_path,
W
wuchenghui 已提交
639 640 641
            ],
            stderr=subprocess.PIPE,
            stdout=subprocess.PIPE)
Y
yejianwu 已提交
642 643 644 645 646
        out, err = p.communicate()
        stdout = err + out
        print stdout
        print("Running finished!\n")
        return stdout
Y
yejianwu 已提交
647 648
    else:
        sh.adb("-s", serialno, "shell", "mkdir", "-p", phone_data_dir)
649 650
        internal_storage_dir = create_internal_storage_dir(
            serialno, phone_data_dir)
Y
yejianwu 已提交
651 652

        for input_name in input_nodes:
L
liuqi 已提交
653 654
            formatted_name = common.formatted_file_name(input_file_name,
                                                        input_name)
Y
yejianwu 已提交
655 656 657 658 659 660 661
            adb_push("%s/%s" % (model_output_dir, formatted_name),
                     phone_data_dir, serialno)
        adb_push("%s/mace_run" % model_output_dir, phone_data_dir,
                 serialno)
        if not embed_model_data:
            adb_push("%s/%s.data" % (model_output_dir, model_tag),
                     phone_data_dir, serialno)
W
wuchenghui 已提交
662
        adb_push("third_party/nnlib/libhexagon_controller.so",
Y
yejianwu 已提交
663 664
                 phone_data_dir, serialno)

Y
yejianwu 已提交
665 666 667 668 669 670 671 672
        if mace_model_dir:
            mace_model_path = "%s/%s.pb" % (phone_data_dir, model_tag)
            adb_push("%s/%s.pb" % (mace_model_dir, model_tag),
                     mace_model_path,
                     serialno)
        else:
            mace_model_path = ""

Y
yejianwu 已提交
673 674
        stdout_buff = []
        process_output = make_output_processor(stdout_buff)
675
        adb_cmd = [
W
wuchenghui 已提交
676 677 678 679
            "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,
680
            "MACE_RUN_PARAMETER_PATH=%s/mace_run.config" % phone_data_dir,
681
            "MACE_INTERNAL_STORAGE_PATH=%s" % internal_storage_dir,
682
            "MACE_LIMIT_OPENCL_KERNEL_TIME=%s" % limit_opencl_kernel_time,
李寅 已提交
683
            "MACE_RUNTIME_FAILURE_RATIO=%f" % runtime_failure_ratio,
684 685 686 687 688 689 690 691
        ]
        if valgrind:
            adb_cmd.extend([
                "VALGRIND_LIB=%s" % valgrind_path + "/lib/valgrind",
                valgrind_path + "/bin/valgrind",
                valgrind_args
            ])
        adb_cmd.extend([
W
wuchenghui 已提交
692
            "%s/mace_run" % phone_data_dir,
693
            "--model_name=%s" % model_tag,
W
wuchenghui 已提交
694 695 696 697 698 699 700 701 702 703 704 705 706 707
            "--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,
Y
yejianwu 已提交
708
            "--model_file=%s" % mace_model_path,
709 710 711 712 713 714 715
        ])
        adb_cmd = ' '.join(adb_cmd)
        p = sh.adb(
            "-s",
            serialno,
            "shell",
            adb_cmd,
W
wuchenghui 已提交
716 717 718
            _out=process_output,
            _bg=True,
            _err_to_out=True)
Y
yejianwu 已提交
719
        p.wait()
Y
yejianwu 已提交
720 721
        print("Running finished!\n")
        return "".join(stdout_buff)
Y
yejianwu 已提交
722 723


W
wuchenghui 已提交
724 725
def validate_model(abi,
                   serialno,
Y
yejianwu 已提交
726 727 728
                   model_file_path,
                   weight_file_path,
                   platform,
729
                   device_type,
Y
yejianwu 已提交
730 731 732 733 734
                   input_nodes,
                   output_nodes,
                   input_shapes,
                   output_shapes,
                   model_output_dir,
735
                   phone_data_dir,
L
liuqi 已提交
736
                   caffe_env,
Y
yejianwu 已提交
737 738 739
                   input_file_name="model_input",
                   output_file_name="model_out"):
    print("* Validate with %s" % platform)
L
liuqi 已提交
740 741 742 743 744 745 746 747 748
    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 已提交
749 750

    if platform == "tensorflow":
751 752
        validate(platform, model_file_path, "",
                 "%s/%s" % (model_output_dir, input_file_name),
753
                 "%s/%s" % (model_output_dir, output_file_name), device_type,
754 755
                 ":".join(input_shapes), ":".join(output_shapes),
                 ",".join(input_nodes), ",".join(output_nodes))
Y
yejianwu 已提交
756 757 758 759 760
    elif platform == "caffe":
        image_name = "mace-caffe:latest"
        container_name = "mace_caffe_validator"
        res_file = "validation.result"

L
liuqi 已提交
761 762 763 764 765 766 767 768
        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),
769 770
                     "%s/%s" % (model_output_dir, output_file_name),
                     device_type,
L
liuqi 已提交
771 772 773 774 775 776 777
                     ":".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 已提交
778
                          "third_party/caffe")
L
liuqi 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804

            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 已提交
805 806

            for output_name in output_nodes:
L
liuqi 已提交
807 808 809 810 811 812 813 814
                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 已提交
815
            sh.docker("cp", "tools/common.py", "%s:/mace" % container_name)
L
liuqi 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
            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)

            stdout_buff = []
            process_output = make_output_processor(stdout_buff)
            p = 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,
833
                    "--device_type=%s" % device_type,
L
liuqi 已提交
834 835 836 837 838 839 840 841
                    "--input_node=%s" % ",".join(input_nodes),
                    "--output_node=%s" % ",".join(output_nodes),
                    "--input_shape=%s" % ":".join(input_shapes),
                    "--output_shape=%s" % ":".join(output_shapes),
                    _out=process_output,
                    _bg=True,
                    _err_to_out=True)
            p.wait()
Y
yejianwu 已提交
842 843 844 845

    print("Validation done!\n")


846
def build_production_code(model_load_type, abi):
Y
yejianwu 已提交
847 848
    bazel_build("//mace/codegen:generated_opencl", abi=abi)
    bazel_build("//mace/codegen:generated_tuning_params", abi=abi)
L
liuqi 已提交
849
    if abi == 'host':
850 851 852 853 854 855 856
        if model_load_type == "source":
            bazel_build(
                "//mace/codegen:generated_models",
                abi=abi)
        else:
            bazel_build("//mace/core:core", abi=abi)
            bazel_build("//mace/ops:ops", abi=abi)
Y
yejianwu 已提交
857 858 859 860 861 862 863


def merge_libs(target_soc,
               abi,
               project_name,
               libmace_output_dir,
               model_output_dirs,
Y
yejianwu 已提交
864
               mace_model_dirs_kv,
865
               model_load_type,
Y
yejianwu 已提交
866 867 868 869 870 871
               hexagon_mode,
               embed_model_data):
    print("* Merge mace lib")
    project_output_dir = "%s/%s" % (libmace_output_dir, project_name)
    model_header_dir = "%s/include/mace/public" % project_output_dir
    model_data_dir = "%s/data" % project_output_dir
L
Liangliang He 已提交
872
    hexagon_lib_file = "third_party/nnlib/libhexagon_controller.so"
Y
yejianwu 已提交
873 874 875 876 877 878
    model_bin_dir = "%s/%s/" % (project_output_dir, abi)

    if not os.path.exists(model_bin_dir):
        sh.mkdir("-p", model_bin_dir)
    if not os.path.exists(model_header_dir):
        sh.mkdir("-p", model_header_dir)
879
    sh.cp("-f", glob.glob("mace/public/*.h"), model_header_dir)
Y
yejianwu 已提交
880 881 882
    if not os.path.exists(model_data_dir):
        sh.mkdir("-p", model_data_dir)
    if hexagon_mode:
883
        sh.cp("-f", hexagon_lib_file, model_bin_dir)
Y
yejianwu 已提交
884

Y
yejianwu 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
    if model_load_type == "source":
        sh.cp("-f", glob.glob("mace/codegen/engine/*.h"), model_header_dir)

    for model_output_dir in model_output_dirs:
        if not embed_model_data:
            sh.cp("-f", glob.glob("%s/*.data" % model_output_dir),
                  model_data_dir)
        if model_load_type == "source":
            sh.cp("-f", glob.glob("%s/*.h" % model_output_dir),
                  model_header_dir)

    for model_name in mace_model_dirs_kv:
        sh.cp("-f", "%s/%s.pb" % (mace_model_dirs_kv[model_name], model_name),
              model_data_dir)

Y
yejianwu 已提交
900 901
    mri_stream = ""
    if abi == "host":
902 903
        mri_stream += "create %s/libmace_%s.a\n" % \
                      (model_bin_dir, project_name)
Y
yejianwu 已提交
904
        mri_stream += (
905 906
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_opencl.pic.a\n")
Y
yejianwu 已提交
907
        mri_stream += (
908 909
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_tuning_params.pic.a\n")
910 911 912 913 914 915 916 917 918 919 920
        if model_load_type == "source":
            mri_stream += (
                "addlib "
                "bazel-bin/mace/codegen/libgenerated_models.pic.a\n")
        else:
            mri_stream += (
                "addlib "
                "bazel-bin/mace/core/libcore.pic.a\n")
            mri_stream += (
                "addlib "
                "bazel-bin/mace/ops/libops.pic.lo\n")
Y
yejianwu 已提交
921
    else:
922 923
        mri_stream += "create %s/libmace_%s.%s.a\n" % \
                      (model_bin_dir, project_name, target_soc)
924 925 926 927
        if model_load_type == "source":
            mri_stream += (
                "addlib "
                "bazel-bin/mace/codegen/libgenerated_models.a\n")
Y
yejianwu 已提交
928
        mri_stream += (
929 930
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_opencl.a\n")
Y
yejianwu 已提交
931
        mri_stream += (
932 933
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_tuning_params.a\n")
Y
yejianwu 已提交
934
        mri_stream += (
935 936
            "addlib "
            "bazel-bin/mace/codegen/libgenerated_version.a\n")
Y
yejianwu 已提交
937
        mri_stream += (
938 939
            "addlib "
            "bazel-bin/mace/core/libcore.a\n")
Y
yejianwu 已提交
940
        mri_stream += (
941 942
            "addlib "
            "bazel-bin/mace/kernels/libkernels.a\n")
Y
yejianwu 已提交
943
        mri_stream += (
944 945
            "addlib "
            "bazel-bin/mace/utils/libutils.a\n")
Y
yejianwu 已提交
946
        mri_stream += (
947 948
            "addlib "
            "bazel-bin/mace/utils/libutils_prod.a\n")
949 950 951 952 953 954
        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 已提交
955
        mri_stream += (
956 957
            "addlib "
            "bazel-bin/mace/ops/libops.lo\n")
Y
yejianwu 已提交
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980

    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))
Y
yejianwu 已提交
981 982 983
    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
    p = sh.tar(
Y
yejianwu 已提交
984 985
            "cvzf",
            "%s" % tar_package_path,
Y
yejianwu 已提交
986 987 988 989 990 991 992
            glob.glob("%s/*" % project_dir),
            "--exclude",
            "%s/build" % project_dir,
            _out=process_output,
            _bg=True,
            _err_to_out=True)
    p.wait()
Y
yejianwu 已提交
993 994 995
    print("Packaging Done!\n")


996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
def build_benchmark_model(abi,
                          embed_model_data,
                          model_output_dir,
                          model_tag,
                          hexagon_mode):
    benchmark_binary_file = "%s/benchmark_model" % model_output_dir
    if os.path.exists(benchmark_binary_file):
        sh.rm("-rf", benchmark_binary_file)
    if not embed_model_data:
        sh.cp("-f", "mace/codegen/models/%s/%s.data" % (model_tag, model_tag),
              model_output_dir)

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

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


W
wuchenghui 已提交
1018 1019
def benchmark_model(abi,
                    serialno,
Y
yejianwu 已提交
1020 1021 1022
                    vlog_level,
                    embed_model_data,
                    model_output_dir,
Y
yejianwu 已提交
1023
                    mace_model_dir,
Y
yejianwu 已提交
1024 1025 1026 1027 1028 1029
                    input_nodes,
                    output_nodes,
                    input_shapes,
                    output_shapes,
                    model_tag,
                    device_type,
1030
                    phone_data_dir,
W
wuchenghui 已提交
1031 1032 1033 1034
                    omp_num_threads=-1,
                    cpu_affinity_policy=1,
                    gpu_perf_hint=3,
                    gpu_priority_hint=3,
1035
                    input_file_name="model_input"):
Y
yejianwu 已提交
1036 1037 1038 1039 1040
    print("* Benchmark for %s" % model_tag)

    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
    if abi == "host":
Y
yejianwu 已提交
1041 1042 1043 1044
        if mace_model_dir:
            mace_model_path = "%s/%s.pb" % (mace_model_dir, model_tag)
        else:
            mace_model_path = ""
W
wuchenghui 已提交
1045 1046
        p = subprocess.Popen(
            [
Y
yejianwu 已提交
1047 1048 1049
                "env",
                "MACE_CPP_MIN_VLOG_LEVEL=%s" % vlog_level,
                "%s/benchmark_model" % model_output_dir,
1050
                "--model_name=%s" % model_tag,
Y
yejianwu 已提交
1051 1052 1053 1054 1055 1056 1057
                "--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),
                "--model_data_file=%s/%s.data" % (model_output_dir, model_tag),
                "--device=%s" % device_type,
W
wuchenghui 已提交
1058 1059 1060 1061
                "--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 已提交
1062
                "--model_file=%s" % mace_model_path,
W
wuchenghui 已提交
1063
            ])
Y
yejianwu 已提交
1064 1065 1066
        p.wait()
    else:
        sh.adb("-s", serialno, "shell", "mkdir", "-p", phone_data_dir)
1067 1068
        internal_storage_dir = create_internal_storage_dir(
            serialno, phone_data_dir)
Y
yejianwu 已提交
1069 1070

        for input_name in input_nodes:
L
liuqi 已提交
1071 1072
            formatted_name = common.formatted_file_name(input_file_name,
                                                        input_name)
Y
yejianwu 已提交
1073 1074 1075 1076 1077 1078 1079
            adb_push("%s/%s" % (model_output_dir, formatted_name),
                     phone_data_dir, serialno)
        adb_push("%s/benchmark_model" % model_output_dir, phone_data_dir,
                 serialno)
        if not embed_model_data:
            adb_push("%s/%s.data" % (model_output_dir, model_tag),
                     phone_data_dir, serialno)
Y
yejianwu 已提交
1080 1081 1082 1083 1084 1085 1086 1087
        if mace_model_dir:
            mace_model_path = "%s/%s.pb" % (phone_data_dir, model_tag)
            adb_push("%s/%s.pb" % (mace_model_dir, model_tag),
                     mace_model_path,
                     serialno)
        else:
            mace_model_path = ""

Y
yejianwu 已提交
1088
        p = sh.adb(
W
wuchenghui 已提交
1089 1090 1091 1092 1093 1094 1095
            "-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,
1096
            "MACE_INTERNAL_STORAGE_PATH=%s" % internal_storage_dir,
W
wuchenghui 已提交
1097 1098
            "MACE_OPENCL_PROFILING=1",
            "%s/benchmark_model" % phone_data_dir,
1099
            "--model_name=%s" % model_tag,
W
wuchenghui 已提交
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
            "--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,
Y
yejianwu 已提交
1111
            "--model_file=%s" % mace_model_path,
W
wuchenghui 已提交
1112 1113 1114
            _out=process_output,
            _bg=True,
            _err_to_out=True)
Y
yejianwu 已提交
1115 1116 1117 1118 1119 1120
        p.wait()

    print("Benchmark done!\n")
    return "".join(stdout_buff)


W
wuchenghui 已提交
1121 1122
def build_run_throughput_test(abi,
                              serialno,
Y
yejianwu 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
                              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,
1135
                              phone_data_dir,
Y
yejianwu 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
                              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

1151
    sh.cp("-f", merged_lib_file, "mace/benchmark/libmace_merged.a")
Y
yejianwu 已提交
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 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
    p = sh.bazel(
        "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,
        _out=process_output,
        _bg=True,
        _err_to_out=True)
    p.wait()

    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 已提交
1203
    adb_push("third_party/nnlib/libhexagon_controller.so",
Y
yejianwu 已提交
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
             phone_data_dir,
             serialno)

    p = 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,
            _out=process_output,
            _bg=True,
            _err_to_out=True)
    p.wait()

    print("throughput_test done!\n")


1236 1237 1238
################################
# falcon
################################
L
Liangliang He 已提交
1239
def falcon_tags(tags_dict):
L
Liangliang He 已提交
1240 1241 1242 1243 1244 1245 1246
    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 已提交
1247

1248

L
Liangliang He 已提交
1249 1250
def falcon_push_metrics(server, metrics, endpoint="mace_dev", tags={}):
    cli = falcon_cli.FalconCli.connect(server=server, port=8433, debug=False)
L
Liangliang He 已提交
1251 1252 1253 1254 1255 1256 1257
    ts = int(time.time())
    falcon_metrics = [{
        "endpoint": endpoint,
        "metric": key,
        "tags": falcon_tags(tags),
        "timestamp": ts,
        "value": value,
L
Liangliang He 已提交
1258
        "step": 600,
L
Liangliang He 已提交
1259 1260 1261
        "counterType": "GAUGE"
    } for key, value in metrics.iteritems()]
    cli.update(falcon_metrics)