sh_commands.py 29.2 KB
Newer Older
L
Liangliang He 已提交
1
# Copyright 2018 The MACE Authors. All Rights Reserved.
Y
yejianwu 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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.

import glob
L
liuqi 已提交
16
import logging
17
import numpy as np
Y
yejianwu 已提交
18
import os
L
liuqi 已提交
19
import random
20
import re
Y
yejianwu 已提交
21
import sh
22
import struct
23
import sys
L
liyin 已提交
24
import time
A
Allen 已提交
25
import platform
26

27 28
import six

L
liuqi 已提交
29
import common
L
liuqi 已提交
30
from common import abi_to_internal
L
Liangliang He 已提交
31

32 33 34
sys.path.insert(0, "mace/python/tools")
try:
    from encrypt_opencl_codegen import encrypt_opencl_codegen
35
    from opencl_binary_codegen import generate_opencl_code
36 37
    from generate_data import generate_input_data
    from validate import validate
38
    from mace_engine_factory_codegen import gen_mace_engine_factory
Y
yejianwu 已提交
39
except Exception as e:
40
    six.print_("Import error:\n%s" % e, file=sys.stderr)
41 42
    exit(1)

43

44 45 46
################################
# common
################################
L
liuqi 已提交
47 48


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

52

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


60
def make_output_processor(buff):
L
Liangliang He 已提交
61
    def process_output(line):
62
        six.print_(line.rstrip())
L
Liangliang He 已提交
63 64 65 66
        buff.append(line)

    return process_output

67

68 69 70 71
def device_lock_path(serialno):
    return "/tmp/device-lock-%s" % serialno


72
def device_lock(serialno, timeout=7200):
L
liuqi 已提交
73
    import filelock
74 75
    return filelock.FileLock(device_lock_path(serialno.replace("/", "")),
                             timeout=timeout)
76 77 78


def is_device_locked(serialno):
L
liuqi 已提交
79
    import filelock
80 81 82 83 84 85 86
    try:
        with device_lock(serialno, timeout=0.000001):
            return False
    except filelock.Timeout:
        return True


87 88 89 90 91
class BuildType(object):
    proto = 'proto'
    code = 'code'


92 93 94 95
def stdout_success(stdout):
    stdout_lines = stdout.split("\n")
    for line in stdout_lines:
        if "Aborted" in line or "FAILED" in line or \
96
                "Segmentation fault" in line:
97 98 99 100
            return False
    return True


L
liuqi 已提交
101 102 103 104
# select a random unlocked device support the ABI
def choose_a_random_device(target_devices, target_abi):
    eligible_devices = [dev for dev in target_devices
                        if target_abi in dev[common.YAMLKeyword.target_abis]]
105 106
    unlocked_devices = [dev for dev in eligible_devices if
                        not is_device_locked(dev[common.YAMLKeyword.address])]
L
liuqi 已提交
107 108 109 110 111 112 113
    if len(unlocked_devices) > 0:
        chosen_devices = [random.choice(unlocked_devices)]
    else:
        chosen_devices = [random.choice(eligible_devices)]
    return chosen_devices


Y
yejianwu 已提交
114 115 116
################################
# clear data
################################
117 118 119 120 121
def clear_phone_data_dir(serialno, phone_data_dir):
    sh.adb("-s",
           serialno,
           "shell",
           "rm -rf %s" % phone_data_dir)
122 123


124 125 126
################################
# adb commands
################################
W
wuchenghui 已提交
127 128
def adb_devices():
    serialnos = []
P
Paul Idstein 已提交
129
    p = re.compile(r'(\S+)\s+device')
130
    for line in split_stdout(sh.adb("devices")):
131 132
        m = p.match(line)
        if m:
W
wuchenghui 已提交
133 134 135 136 137 138 139 140 141 142
            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)
143
        soc_serialnos_map.setdefault(props["ro.board.platform"], []) \
W
wuchenghui 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156
            .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 已提交
157

158 159

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

170

W
wuchenghui 已提交
171 172
def adb_get_device_name_by_serialno(serialno):
    props = adb_getprop_by_serialno(serialno)
L
liuqi 已提交
173
    return props.get("ro.product.model", "").replace(' ', '')
W
wuchenghui 已提交
174 175


176
def adb_supported_abis(serialno):
L
Liangliang He 已提交
177 178 179 180 181
    props = adb_getprop_by_serialno(serialno)
    abilist_str = props["ro.product.cpu.abilist"]
    abis = [abi.strip() for abi in abilist_str.split(',')]
    return abis

182

183
def adb_get_all_socs():
L
Liangliang He 已提交
184 185 186 187 188
    socs = []
    for d in adb_devices():
        props = adb_getprop_by_serialno(d)
        socs.append(props["ro.board.platform"])
    return set(socs)
189

L
Liangliang He 已提交
190

Y
yejianwu 已提交
191 192 193 194 195 196 197 198
def adb_push(src_path, dst_path, serialno):
    sh.adb("-s", serialno, "push", src_path, dst_path)


def adb_pull(src_path, dst_path, serialno):
    try:
        sh.adb("-s", serialno, "pull", src_path, dst_path)
    except Exception as e:
L
liuqi 已提交
199
        six.print_("Error msg: %s" % e, file=sys.stderr)
Y
yejianwu 已提交
200 201


202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
################################
# 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",
L
liuqi 已提交
221
                "Can't find AddressSanitizer runtime library in %s" %
222 223 224 225 226 227
                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))
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
def simpleperf_abi_dir_names(abi):
    simpleperf_dir_names = {
        "armeabi-v7a": "arm",
        "arm64-v8a": "arm64",
    }
    return simpleperf_dir_names[abi]


def find_simpleperf_library(abi, simpleperf_path=''):
    if not simpleperf_path:
        find_path = os.environ['ANDROID_NDK_HOME']
        candidates = split_stdout(sh.find(find_path, "-name", "simpleperf"))
        if len(candidates) == 0:
            common.MaceLogger.error(
                "Toolchain",
                "Can't find Simpleperf runtime library in % s" %
                find_path)
        found = False
        for candidate in candidates:
            if candidate.find(simpleperf_abi_dir_names(abi) + "/") != -1:
                found = True
                return candidate
        if not found:
            common.MaceLogger.error(
                "Toolchain",
                "Can't find Simpleperf runtime library in % s" %
                find_path)

    return "%s/simpleperf" % simpleperf_path


261 262 263
################################
# bazel commands
################################
Y
yejianwu 已提交
264 265
def bazel_build(target,
                abi="armeabi-v7a",
L
liuqi 已提交
266
                toolchain='android',
B
Bin Li 已提交
267 268
                enable_hexagon=False,
                enable_hta=False,
L
lichao18 已提交
269
                enable_apu=False,
270
                enable_neon=True,
Y
yejianwu 已提交
271
                enable_opencl=True,
272
                enable_quantize=True,
L
luxuhui 已提交
273
                enable_bfloat16=False,
B
Bin Li 已提交
274
                enable_rpcmem=True,
L
liuqi 已提交
275
                address_sanitizer=False,
276
                symbol_hidden=True,
277
                debug_mode=False,
L
liuqi 已提交
278
                extra_args=""):
279
    six.print_("* Build %s with ABI %s" % (target, abi))
Y
yejianwu 已提交
280
    if abi == "host":
L
luxuhui 已提交
281
        toolchain = platform.system().lower()
W
wuchenghui 已提交
282
        bazel_args = (
Y
yejianwu 已提交
283
            "build",
L
Liangliang He 已提交
284
            "--config",
L
luxuhui 已提交
285
            toolchain,
Y
yejianwu 已提交
286
            "--define",
287
            "quantize=%s" % str(enable_quantize).lower(),
L
luxuhui 已提交
288 289
            "--define",
            "bfloat16=%s" % str(enable_bfloat16).lower(),
290
            target,
W
wuchenghui 已提交
291
        )
Y
yejianwu 已提交
292 293 294 295
    else:
        bazel_args = (
            "build",
            target,
296
            "--config",
L
liuqi 已提交
297 298
            toolchain,
            "--cpu=%s" % abi_to_internal(abi),
Y
yejianwu 已提交
299
            "--define",
李寅 已提交
300
            "neon=%s" % str(enable_neon).lower(),
Y
yejianwu 已提交
301
            "--define",
Y
yejianwu 已提交
302 303
            "opencl=%s" % str(enable_opencl).lower(),
            "--define",
304 305
            "quantize=%s" % str(enable_quantize).lower(),
            "--define",
L
luxuhui 已提交
306 307
            "bfloat16=%s" % str(enable_bfloat16).lower(),
            "--define",
B
Bin Li 已提交
308 309
            "rpcmem=%s" % str(enable_rpcmem).lower(),
            "--define",
B
Bin Li 已提交
310 311
            "hexagon=%s" % str(enable_hexagon).lower(),
            "--define",
L
lichao18 已提交
312 313 314
            "hta=%s" % str(enable_hta).lower(),
            "--define",
            "apu=%s" % str(enable_apu).lower())
315 316
    if address_sanitizer:
        bazel_args += ("--config", "asan")
317 318 319
    if debug_mode:
        bazel_args += ("--config", "debug")
    if not address_sanitizer and not debug_mode:
L
luxuhui 已提交
320 321 322 323
        if toolchain == "darwin" or toolchain == "ios":
            bazel_args += ("--config", "optimization_darwin")
        else:
            bazel_args += ("--config", "optimization")
324 325
        if symbol_hidden:
            bazel_args += ("--config", "symbol_hidden")
L
liuqi 已提交
326
    if extra_args:
327 328
        bazel_args += (extra_args,)
        six.print_(bazel_args)
L
liuqi 已提交
329 330
    sh.bazel(
        _fg=True,
331
        *bazel_args)
L
lichao18 已提交
332
    six.print_(bazel_args)
333
    six.print_("Build done!\n")
Y
yejianwu 已提交
334 335 336


def bazel_build_common(target, build_args=""):
L
Liangliang He 已提交
337 338
    stdout_buff = []
    process_output = make_output_processor(stdout_buff)
L
liuqi 已提交
339
    sh.bazel(
L
Liangliang He 已提交
340
        "build",
Y
yejianwu 已提交
341
        target + build_args,
342
        _tty_in=True,
L
Liangliang He 已提交
343
        _out=process_output,
344
        _err_to_out=True)
L
Liangliang He 已提交
345 346
    return "".join(stdout_buff)

347 348

def bazel_target_to_bin(target):
L
Liangliang He 已提交
349 350 351 352 353 354 355 356
    # 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

357 358 359 360 361

################################
# mace commands
################################
def gen_encrypted_opencl_source(codegen_path="mace/codegen"):
L
Liangliang He 已提交
362
    sh.mkdir("-p", "%s/opencl" % codegen_path)
363
    encrypt_opencl_codegen("./mace/ops/opencl/cl/",
364
                           "mace/codegen/opencl/opencl_encrypt_program.cc")
L
Liangliang He 已提交
365

366

Y
yejianwu 已提交
367
def gen_mace_engine_factory_source(model_tags,
B
Bin Li 已提交
368
                                   embed_model_data,
Y
yejianwu 已提交
369
                                   codegen_path="mace/codegen"):
370
    six.print_("* Generate mace engine creator source")
371 372 373
    codegen_tools_dir = "%s/engine" % codegen_path
    sh.rm("-rf", codegen_tools_dir)
    sh.mkdir("-p", codegen_tools_dir)
374
    gen_mace_engine_factory(
375
        model_tags,
B
Bin Li 已提交
376
        embed_model_data,
377
        codegen_tools_dir)
378
    six.print_("Generate mace engine creator source done!\n")
379 380


381 382 383 384
def merge_opencl_binaries(binaries_dirs,
                          cl_compiled_program_file_name,
                          output_file_path):
    platform_info_key = 'mace_opencl_precompiled_platform_info_key'
Y
yejianwu 已提交
385
    cl_bin_dirs = []
386
    for d in binaries_dirs:
Y
yejianwu 已提交
387
        cl_bin_dirs.append(os.path.join(d, "opencl_bin"))
388 389
    # create opencl binary output dir
    opencl_binary_dir = os.path.dirname(output_file_path)
L
liuqi 已提交
390 391
    if not os.path.exists(opencl_binary_dir):
        sh.mkdir("-p", opencl_binary_dir)
392 393 394 395 396 397
    kvs = {}
    for binary_dir in cl_bin_dirs:
        binary_path = os.path.join(binary_dir, cl_compiled_program_file_name)
        if not os.path.exists(binary_path):
            continue

398
        six.print_('generate opencl code from', binary_path)
399 400 401 402 403 404
        with open(binary_path, "rb") as f:
            binary_array = np.fromfile(f, dtype=np.uint8)

        idx = 0
        size, = struct.unpack("Q", binary_array[idx:idx + 8])
        idx += 8
405
        for _ in six.moves.range(size):
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
            key_size, = struct.unpack("i", binary_array[idx:idx + 4])
            idx += 4
            key, = struct.unpack(
                str(key_size) + "s", binary_array[idx:idx + key_size])
            idx += key_size
            value_size, = struct.unpack("i", binary_array[idx:idx + 4])
            idx += 4
            if key == platform_info_key and key in kvs:
                common.mace_check(
                    (kvs[key] == binary_array[idx:idx + value_size]).all(),
                    "",
                    "There exists more than one OpenCL version for models:"
                    " %s vs %s " %
                    (kvs[key], binary_array[idx:idx + value_size]))
            else:
                kvs[key] = binary_array[idx:idx + value_size]
            idx += value_size

    output_byte_array = bytearray()
    data_size = len(kvs)
    output_byte_array.extend(struct.pack("Q", data_size))
427
    for key, value in six.iteritems(kvs):
428 429 430 431 432 433 434 435
        key_size = len(key)
        output_byte_array.extend(struct.pack("i", key_size))
        output_byte_array.extend(struct.pack(str(key_size) + "s", key))
        value_size = len(value)
        output_byte_array.extend(struct.pack("i", value_size))
        output_byte_array.extend(value)

    np.array(output_byte_array).tofile(output_file_path)
Y
yejianwu 已提交
436 437


L
liuqi 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
def merge_opencl_parameters(binaries_dirs,
                            cl_parameter_file_name,
                            output_file_path):
    cl_bin_dirs = []
    for d in binaries_dirs:
        cl_bin_dirs.append(os.path.join(d, "opencl_bin"))
    # create opencl binary output dir
    opencl_binary_dir = os.path.dirname(output_file_path)
    if not os.path.exists(opencl_binary_dir):
        sh.mkdir("-p", opencl_binary_dir)
    kvs = {}
    for binary_dir in cl_bin_dirs:
        binary_path = os.path.join(binary_dir, cl_parameter_file_name)
        if not os.path.exists(binary_path):
            continue

454
        six.print_('generate opencl parameter from', binary_path)
L
liuqi 已提交
455 456 457 458 459 460
        with open(binary_path, "rb") as f:
            binary_array = np.fromfile(f, dtype=np.uint8)

        idx = 0
        size, = struct.unpack("Q", binary_array[idx:idx + 8])
        idx += 8
461
        for _ in six.moves.range(size):
L
liuqi 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474
            key_size, = struct.unpack("i", binary_array[idx:idx + 4])
            idx += 4
            key, = struct.unpack(
                str(key_size) + "s", binary_array[idx:idx + key_size])
            idx += key_size
            value_size, = struct.unpack("i", binary_array[idx:idx + 4])
            idx += 4
            kvs[key] = binary_array[idx:idx + value_size]
            idx += value_size

    output_byte_array = bytearray()
    data_size = len(kvs)
    output_byte_array.extend(struct.pack("Q", data_size))
475
    for key, value in six.iteritems(kvs):
L
liuqi 已提交
476 477 478 479 480 481 482 483 484 485
        key_size = len(key)
        output_byte_array.extend(struct.pack("i", key_size))
        output_byte_array.extend(struct.pack(str(key_size) + "s", key))
        value_size = len(value)
        output_byte_array.extend(struct.pack("i", value_size))
        output_byte_array.extend(value)

    np.array(output_byte_array).tofile(output_file_path)


486 487 488 489 490 491 492 493
def gen_input(model_output_dir,
              input_nodes,
              input_shapes,
              input_files=None,
              input_ranges=None,
              input_data_types=None,
              input_data_map=None,
              input_file_name="model_input"):
Y
yejianwu 已提交
494
    for input_name in input_nodes:
L
liuqi 已提交
495 496
        formatted_name = common.formatted_file_name(
            input_file_name, input_name)
497 498
        if os.path.exists("%s/%s" % (model_output_dir, formatted_name)):
            sh.rm("%s/%s" % (model_output_dir, formatted_name))
Y
yejianwu 已提交
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)
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    if input_data_map:
        for i in range(len(input_nodes)):
            dst_input_file = model_output_dir + '/' + \
                             common.formatted_file_name(input_file_name,
                                                        input_nodes[i])
            input_name = input_nodes[i]
            common.mace_check(input_name in input_data_map,
                              common.ModuleName.RUN,
                              "The preprocessor API in PrecisionValidator"
                              " script should return all inputs of model")
            if input_data_types[i] == 'float32':
                input_data = np.array(input_data_map[input_name],
                                      dtype=np.float32)
            elif input_data_types[i] == 'int32':
                input_data = np.array(input_data_map[input_name],
                                      dtype=np.int32)
            else:
                common.mace_check(
                    False,
                    common.ModuleName.RUN,
                    'Do not support input data type %s' % input_data_types[i])
            common.mace_check(
                list(map(int, common.split_shape(input_shapes[i])))
                == list(input_data.shape),
                common.ModuleName.RUN,
                "The shape return from preprocessor API of"
                " PrecisionValidator script is not same with"
                " model deployment file. %s vs %s"
                % (str(input_shapes[i]), str(input_data.shape)))
            input_data.tofile(dst_input_file)
    elif len(input_file_list) != 0:
Y
yejianwu 已提交
535
        input_name_list = []
W
wuchenghui 已提交
536 537
        if isinstance(input_nodes, list):
            input_name_list.extend(input_nodes)
Y
yejianwu 已提交
538
        else:
W
wuchenghui 已提交
539
            input_name_list.append(input_nodes)
540 541 542 543
        common.mace_check(len(input_file_list) == len(input_name_list),
                          common.ModuleName.RUN,
                          'If input_files set, the input files should '
                          'match the input names.')
Y
yejianwu 已提交
544 545 546
        for i in range(len(input_file_list)):
            if input_file_list[i] is not None:
                dst_input_file = model_output_dir + '/' + \
547 548
                                 common.formatted_file_name(input_file_name,
                                                            input_name_list[i])
Y
yejianwu 已提交
549 550
                if input_file_list[i].startswith("http://") or \
                        input_file_list[i].startswith("https://"):
551 552
                    six.moves.urllib.request.urlretrieve(input_file_list[i],
                                                         dst_input_file)
Y
yejianwu 已提交
553
                else:
554
                    sh.cp("-f", input_file_list[i], dst_input_file)
555 556 557 558 559 560 561 562 563 564 565
    else:
        # generate random input files
        input_nodes_str = ",".join(input_nodes)
        input_shapes_str = ":".join(input_shapes)
        input_ranges_str = ":".join(input_ranges)
        input_data_types_str = ",".join(input_data_types)
        generate_input_data("%s/%s" % (model_output_dir, input_file_name),
                            input_nodes_str,
                            input_shapes_str,
                            input_ranges_str,
                            input_data_types_str)
Y
yejianwu 已提交
566 567


568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
def gen_opencl_binary_cpps(opencl_bin_file_path,
                           opencl_param_file_path,
                           opencl_bin_cpp_path,
                           opencl_param_cpp_path):
    output_dir = os.path.dirname(opencl_bin_cpp_path)
    if not os.path.exists(output_dir):
        sh.mkdir("-p", output_dir)
    opencl_bin_load_func_name = 'LoadOpenCLBinary'
    opencl_bin_size_func_name = 'OpenCLBinarySize'
    opencl_param_load_func_name = 'LoadOpenCLParameter'
    opencl_param_size_func_name = 'OpenCLParameterSize'
    generate_opencl_code(opencl_bin_file_path, opencl_bin_load_func_name,
                         opencl_bin_size_func_name, opencl_bin_cpp_path)
    generate_opencl_code(opencl_param_file_path, opencl_param_load_func_name,
                         opencl_param_size_func_name, opencl_param_cpp_path)


585 586 587
def update_mace_run_binary(build_tmp_binary_dir, link_dynamic=False):
    if link_dynamic:
        mace_run_filepath = build_tmp_binary_dir + "/mace_run_dynamic"
Y
yejianwu 已提交
588
    else:
589
        mace_run_filepath = build_tmp_binary_dir + "/mace_run_static"
Y
yejianwu 已提交
590

Y
yejianwu 已提交
591 592
    if os.path.exists(mace_run_filepath):
        sh.rm("-rf", mace_run_filepath)
593
    if link_dynamic:
L
liyin 已提交
594
        sh.cp("-f", "bazel-bin/mace/tools/mace_run_dynamic",
Y
yejianwu 已提交
595 596
              build_tmp_binary_dir)
    else:
L
liyin 已提交
597
        sh.cp("-f", "bazel-bin/mace/tools/mace_run_static",
Y
yejianwu 已提交
598
              build_tmp_binary_dir)
599 600


601 602 603 604
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
605 606


Y
yejianwu 已提交
607 608
def push_depended_so_libs(libmace_dynamic_library_path,
                          abi, phone_data_dir, serialno):
B
Bin Li 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622
    src_file = "%s/sources/cxx-stl/llvm-libc++/libs/" \
               "%s/libc++_shared.so" \
               % (os.environ["ANDROID_NDK_HOME"], abi)
    try:
        dep_so_libs = sh.bash(os.environ["ANDROID_NDK_HOME"] + "/ndk-depends",
                              libmace_dynamic_library_path)
    except sh.ErrorReturnCode_127:
        print("Find no ndk-depends, use default libc++_shared.so")
    else:
        for dep in split_stdout(dep_so_libs):
            if dep == "libgnustl_shared.so":
                src_file = "%s/sources/cxx-stl/gnu-libstdc++/4.9/libs/" \
                           "%s/libgnustl_shared.so" \
                           % (os.environ["ANDROID_NDK_HOME"], abi)
623 624
    print("push %s to %s" % (src_file, phone_data_dir))
    adb_push(src_file, phone_data_dir, serialno)
Y
yejianwu 已提交
625 626


W
wuchenghui 已提交
627
def validate_model(abi,
L
liuqi 已提交
628
                   device,
Y
yejianwu 已提交
629 630
                   model_file_path,
                   weight_file_path,
L
lichao18 已提交
631
                   docker_image_tag,
632
                   dockerfile_path,
Y
yejianwu 已提交
633
                   platform,
634
                   device_type,
Y
yejianwu 已提交
635 636 637 638
                   input_nodes,
                   output_nodes,
                   input_shapes,
                   output_shapes,
639 640
                   input_data_formats,
                   output_data_formats,
Y
yejianwu 已提交
641
                   model_output_dir,
Y
yejianwu 已提交
642
                   input_data_types,
L
liuqi 已提交
643
                   caffe_env,
Y
yejianwu 已提交
644
                   input_file_name="model_input",
645
                   output_file_name="model_out",
L
liutuo 已提交
646
                   validation_threshold=0.9,
B
Bin Li 已提交
647
                   backend="tensorflow",
648 649 650 651 652 653
                   validation_outputs_data=[],
                   log_file=""):
    if not validation_outputs_data:
        six.print_("* Validate with %s" % platform)
    else:
        six.print_("* Validate with file: %s" % validation_outputs_data)
L
liuqi 已提交
654 655 656 657 658 659 660
    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))
L
liuqi 已提交
661
            device.pull_from_data_dir(formatted_name, model_output_dir)
Y
yejianwu 已提交
662

663
    if platform == "tensorflow" or platform == "onnx" or platform == "pytorch":
L
liutuo 已提交
664 665 666 667
        validate(platform, model_file_path, "",
                 "%s/%s" % (model_output_dir, input_file_name),
                 "%s/%s" % (model_output_dir, output_file_name), device_type,
                 ":".join(input_shapes), ":".join(output_shapes),
668
                 ",".join(input_data_formats), ",".join(output_data_formats),
L
liutuo 已提交
669
                 ",".join(input_nodes), ",".join(output_nodes),
B
Bin Li 已提交
670
                 validation_threshold, ",".join(input_data_types), backend,
671
                 validation_outputs_data,
B
Bin Li 已提交
672
                 log_file)
Y
yejianwu 已提交
673
    elif platform == "caffe":
L
lichao18 已提交
674 675
        image_name = "mace-caffe:" + docker_image_tag
        container_name = "mace_caffe_" + docker_image_tag + "_validator"
Y
yejianwu 已提交
676

L
liuqi 已提交
677 678
        if caffe_env == common.CaffeEnvType.LOCAL:
            try:
L
liuqi 已提交
679
                import caffe
L
liuqi 已提交
680
            except ImportError:
L
liuqi 已提交
681
                logging.error('There is no caffe python module.')
L
liuqi 已提交
682 683
            validate(platform, model_file_path, weight_file_path,
                     "%s/%s" % (model_output_dir, input_file_name),
684 685
                     "%s/%s" % (model_output_dir, output_file_name),
                     device_type,
L
liuqi 已提交
686
                     ":".join(input_shapes), ":".join(output_shapes),
687 688
                     ",".join(input_data_formats),
                     ",".join(output_data_formats),
689
                     ",".join(input_nodes), ",".join(output_nodes),
B
Bin Li 已提交
690
                     validation_threshold, ",".join(input_data_types), backend,
691
                     validation_outputs_data,
B
Bin Li 已提交
692
                     log_file)
L
liuqi 已提交
693 694 695
        elif caffe_env == common.CaffeEnvType.DOCKER:
            docker_image_id = sh.docker("images", "-q", image_name)
            if not docker_image_id:
696
                six.print_("Build caffe docker")
L
liuqi 已提交
697
                sh.docker("build", "-t", image_name,
698
                          dockerfile_path)
L
liuqi 已提交
699 700 701 702 703 704 705 706 707

            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:
708
                six.print_("Run caffe container")
L
liuqi 已提交
709
                sh.docker(
710 711 712 713 714 715 716
                    "run",
                    "-d",
                    "-it",
                    "--name",
                    container_name,
                    image_name,
                    "/bin/bash")
L
liuqi 已提交
717 718 719

            for input_name in input_nodes:
                formatted_input_name = common.formatted_file_name(
720
                    input_file_name, input_name)
L
liuqi 已提交
721
                sh.docker(
722 723 724
                    "cp",
                    "%s/%s" % (model_output_dir, formatted_input_name),
                    "%s:/mace" % container_name)
Y
yejianwu 已提交
725 726

            for output_name in output_nodes:
L
liuqi 已提交
727
                formatted_output_name = common.formatted_file_name(
728
                    output_file_name, output_name)
L
liuqi 已提交
729
                sh.docker(
730 731 732
                    "cp",
                    "%s/%s" % (model_output_dir, formatted_output_name),
                    "%s:/mace" % container_name)
L
liuqi 已提交
733 734
            model_file_name = os.path.basename(model_file_path)
            weight_file_name = os.path.basename(weight_file_path)
L
liuqi 已提交
735
            sh.docker("cp", "tools/common.py", "%s:/mace" % container_name)
L
liuqi 已提交
736 737 738 739
            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 已提交
740 741 742 743 744 745 746 747 748 749 750 751
            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,
L
luxuhui 已提交
752 753
                "--input_node=%s" % ",".join(input_nodes),
                "--output_node=%s" % ",".join(output_nodes),
L
liuqi 已提交
754 755
                "--input_shape=%s" % ":".join(input_shapes),
                "--output_shape=%s" % ":".join(output_shapes),
756 757
                "--input_data_format=%s" % ",".join(input_data_formats),
                "--output_data_format=%s" % ",".join(output_data_formats),
758
                "--validation_threshold=%f" % validation_threshold,
759
                "--input_data_type=%s" % ",".join(input_data_types),
760
                "--backend=%s" % backend,
761 762
                "--validation_outputs_data=%s" % ",".join(
                    validation_outputs_data),
L
lichao18 已提交
763
                "--log_file=%s" % log_file,
L
liuqi 已提交
764
                _fg=True)
765 766 767 768 769 770 771 772 773 774 775 776
    elif platform == "megengine":
        validate(platform, model_file_path, "",
                 "%s/%s" % (model_output_dir, input_file_name),
                 "%s/%s" % (model_output_dir, output_file_name),
                 device_type,
                 ":".join(input_shapes), ":".join(output_shapes),
                 ",".join(input_data_formats),
                 ",".join(output_data_formats),
                 ",".join(input_nodes), ",".join(output_nodes),
                 validation_threshold, ",".join(input_data_types), backend,
                 validation_outputs_data,
                 log_file)
Y
yejianwu 已提交
777

778
    six.print_("Validation done!\n")
Y
yejianwu 已提交
779 780


L
liuqi 已提交
781 782 783
################################
# library
################################
Y
yejianwu 已提交
784
def packaging_lib(libmace_output_dir, project_name):
785
    six.print_("* Package libs for %s" % project_name)
Y
yejianwu 已提交
786 787 788 789 790 791
    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)

792 793
    six.print_("Start packaging '%s' libs into %s" % (project_name,
                                                      tar_package_path))
A
Allen 已提交
794
    which_sys = platform.system()
795
    if which_sys == "Linux" or which_sys == "Darwin":
A
Allen 已提交
796
        sh.tar(
A
Allen 已提交
797 798 799 800 801 802
            "--exclude",
            "%s/_tmp" % project_dir,
            "-cvzf",
            "%s" % tar_package_path,
            glob.glob("%s/*" % project_dir),
            _fg=True)
803
    six.print_("Packaging Done!\n")
L
liuqi 已提交
804
    return tar_package_path