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

15
import numpy as np
L
liuqi 已提交
16 17 18 19 20 21 22 23
import sys
import subprocess
import time
import sh
import yaml

import common
from common import *
24 25
from dana.dana_cli import DanaTrend
from dana.dana_util import DanaUtil
B
Bin Li 已提交
26
import layers_validate
L
liuqi 已提交
27 28 29 30 31 32 33 34 35 36 37 38
import sh_commands


class DeviceWrapper:
    allow_scheme = ('ssh', 'adb')

    def __init__(self, device_dict):
        """
        init device with device dict info
        :type device_dict: Device
        :param device_dict: a key-value dict that holds the device information,
                       which attribute has:
39 40
                       device_name, target_abis, target_socs, system,
                        address, username
L
liuqi 已提交
41
        """
42
        self._dana_util = DanaUtil()
L
liuqi 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
        diff = set(device_dict.keys()) - set(YAMLKeyword.__dict__.keys())
        if len(diff) > 0:
            six.print_('Wrong key detected: ')
            six.print_(diff)
            raise KeyError(str(diff))
        self.__dict__.update(device_dict)
        if self.system == SystemType.android:
            self.data_dir = PHONE_DATA_DIR
            self.interior_dir = self.data_dir + '/interior'
        elif self.system == SystemType.arm_linux:
            try:
                sh.ssh('-q', '{}@{}'.format(self.username, self.address),
                       'exit')
            except sh.ErrorReturnCode as e:
                six.print_('device connect failed, '
                           'please check your authentication')
                raise e
            self.data_dir = DEVICE_DATA_DIR
            self.interior_dir = self.data_dir + '/interior'
L
luxuhui 已提交
62 63 64
        elif self.system == SystemType.host:
            self.data_dir = DEVICE_DATA_DIR
            self.interior_dir = self.data_dir + '/interior'
L
liuqi 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

    ##################
    #  internal use  #
    ##################

    def exec_command(self, command, *args, **kwargs):
        if self.system == SystemType.android:
            sh.adb('-s', self.address, 'shell', command, *args, **kwargs)
        elif self.system == SystemType.arm_linux:
            sh.ssh('{}@{}'.format(self.username, self.address),
                   command, *args, **kwargs)

    #####################
    #  public interface #
    #####################

    def is_lock(self):
        return sh_commands.is_device_locked(self.address)

    def lock(self):
        return sh_commands.device_lock(self.address)

    def clear_data_dir(self):
        if self.system == SystemType.android:
            sh_commands.clear_phone_data_dir(self.address, PHONE_DATA_DIR)
        elif self.system == SystemType.arm_linux:
            self.exec_command('rm -rf {}'.format(self.data_dir))

    def pull_from_data_dir(self, filename, dst_path):
        if self.system == SystemType.android:
            self.pull(PHONE_DATA_DIR, filename, dst_path)
        elif self.system == SystemType.arm_linux:
            self.pull(DEVICE_DATA_DIR, filename, dst_path)

    def create_internal_storage_dir(self):
        internal_storage_dir = '{}/interior/'.format(self.data_dir)
        if self.system == SystemType.android:
            sh_commands.create_internal_storage_dir(self.address,
                                                    internal_storage_dir)
        elif self.system == SystemType.arm_linux:
            self.exec_command('mkdir -p {}'.format(internal_storage_dir))
        return internal_storage_dir

    def rm(self, file):
        if self.system == SystemType.android:
            sh.adb('-s', self.address, 'shell', 'rm', '-rf', file, _fg=True)
        elif self.system == SystemType.arm_linux:
            self.exec_command('rm -rf {}'.format(file), _fg=True)

    def push(self, src_path, dst_path):
        mace_check(os.path.exists(src_path), "Device",
                   '{} not found'.format(src_path))
117
        six.print_("Push %s to %s" % (src_path, dst_path))
L
liuqi 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        if self.system == SystemType.android:
            sh_commands.adb_push(src_path, dst_path, self.address)
        elif self.system == SystemType.arm_linux:
            try:
                sh.scp(src_path, '{}@{}:{}'.format(self.username,
                                                   self.address,
                                                   dst_path))
            except sh.ErrorReturnCode_1 as e:
                six.print_('Push Failed !', e, file=sys.stderr)
                raise e

    def pull(self, src_path, file_name, dst_path='.'):
        if not os.path.exists(dst_path):
            sh.mkdir("-p", dst_path)
        src_file = "%s/%s" % (src_path, file_name)
        dst_file = "%s/%s" % (dst_path, file_name)
        if os.path.exists(dst_file):
            sh.rm('-f', dst_file)
136
        six.print_("Pull %s to %s" % (src_file, dst_path))
L
liuqi 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        if self.system == SystemType.android:
            sh_commands.adb_pull(
                src_file, dst_file, self.address)
        elif self.system == SystemType.arm_linux:
            try:
                sh.scp('-r', '%s@%s:%s' % (self.username,
                                           self.address,
                                           src_file),
                       dst_file)
            except sh.ErrorReturnCode_1 as e:
                six.print_("Pull Failed !", file=sys.stderr)
                raise e

    def tuning_run(self,
                   abi,
                   target_dir,
                   target_name,
                   vlog_level,
                   embed_model_data,
                   model_output_dir,
                   input_nodes,
                   output_nodes,
                   input_shapes,
160
                   input_data_formats,
L
liuqi 已提交
161
                   output_shapes,
162
                   output_data_formats,
L
liuqi 已提交
163 164 165 166 167 168
                   mace_model_dir,
                   model_tag,
                   device_type,
                   running_round,
                   restart_round,
                   limit_opencl_kernel_time,
169
                   opencl_queue_window_size,
L
liuqi 已提交
170 171 172 173 174 175 176 177 178 179 180 181
                   tuning,
                   out_of_range_check,
                   model_graph_format,
                   opencl_binary_file,
                   opencl_parameter_file,
                   libmace_dynamic_library_path,
                   omp_num_threads=-1,
                   cpu_affinity_policy=1,
                   gpu_perf_hint=3,
                   gpu_priority_hint=3,
                   input_file_name='model_input',
                   output_file_name='model_out',
B
Bin Li 已提交
182 183
                   input_dir="",
                   output_dir="",
L
liuqi 已提交
184 185
                   runtime_failure_ratio=0.0,
                   address_sanitizer=False,
B
Bin Li 已提交
186 187
                   link_dynamic=False,
                   quantize_stat=False,
B
Bin Li 已提交
188
                   layers_validate_file="",
L
liyin 已提交
189
                   benchmark=False,
L
liuqi 已提交
190 191 192 193 194 195 196 197 198 199
                   ):
        six.print_("* Run '%s' with round=%s, restart_round=%s, tuning=%s, "
                   "out_of_range_check=%s, omp_num_threads=%s, "
                   "cpu_affinity_policy=%s, gpu_perf_hint=%s, "
                   "gpu_priority_hint=%s" %
                   (model_tag, running_round, restart_round, str(tuning),
                    str(out_of_range_check), omp_num_threads,
                    cpu_affinity_policy, gpu_perf_hint, gpu_priority_hint))
        mace_model_path = ""
        if model_graph_format == ModelFormat.file:
B
Bin Li 已提交
200 201
            mace_model_path = layers_validate_file if layers_validate_file \
                else "%s/%s.pb" % (mace_model_dir, model_tag)
202 203 204 205 206 207 208 209

        model_data_file = ""
        if not embed_model_data:
            if self.system == SystemType.host:
                model_data_file = "%s/%s.data" % (mace_model_dir, model_tag)
            else:
                model_data_file = "%s/%s.data" % (self.data_dir, model_tag)

L
liuqi 已提交
210 211 212 213 214 215
        if self.system == SystemType.host:
            libmace_dynamic_lib_path = \
                os.path.dirname(libmace_dynamic_library_path)
            p = subprocess.Popen(
                [
                    "env",
216
                    "ASAN_OPTIONS=detect_leaks=1",
L
liuqi 已提交
217 218 219
                    "LD_LIBRARY_PATH=%s" % libmace_dynamic_lib_path,
                    "MACE_CPP_MIN_VLOG_LEVEL=%s" % vlog_level,
                    "MACE_RUNTIME_FAILURE_RATIO=%f" % runtime_failure_ratio,
B
Bin Li 已提交
220
                    "MACE_LOG_TENSOR_RANGE=%d" % (1 if quantize_stat else 0),
L
liuqi 已提交
221 222 223 224 225 226
                    "%s/%s" % (target_dir, target_name),
                    "--model_name=%s" % model_tag,
                    "--input_node=%s" % ",".join(input_nodes),
                    "--output_node=%s" % ",".join(output_nodes),
                    "--input_shape=%s" % ":".join(input_shapes),
                    "--output_shape=%s" % ":".join(output_shapes),
227 228
                    "--input_data_format=%s" % ",".join(input_data_formats),
                    "--output_data_format=%s" % ",".join(output_data_formats),
L
liuqi 已提交
229 230 231 232
                    "--input_file=%s/%s" % (model_output_dir,
                                            input_file_name),
                    "--output_file=%s/%s" % (model_output_dir,
                                             output_file_name),
B
Bin Li 已提交
233 234
                    "--input_dir=%s" % input_dir,
                    "--output_dir=%s" % output_dir,
235
                    "--model_data_file=%s" % model_data_file,
L
liuqi 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248
                    "--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,
                    "--model_file=%s" % mace_model_path,
                ],
                stderr=subprocess.PIPE,
                stdout=subprocess.PIPE)
            out, err = p.communicate()
            self.stdout = err + out
249
            six.print_(self.stdout)
L
liuqi 已提交
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 276 277
            six.print_("Running finished!\n")
        elif self.system in [SystemType.android, SystemType.arm_linux]:
            self.rm(self.data_dir)
            self.exec_command('mkdir -p {}'.format(self.data_dir))
            internal_storage_dir = self.create_internal_storage_dir()

            for input_name in input_nodes:
                formatted_name = common.formatted_file_name(input_file_name,
                                                            input_name)
                self.push("%s/%s" % (model_output_dir, formatted_name),
                          self.data_dir)
            if self.system == SystemType.android and address_sanitizer:
                self.push(sh_commands.find_asan_rt_library(abi),
                          self.data_dir)

            if not embed_model_data:
                model_data_path = "%s/%s.data" % (mace_model_dir, model_tag)
                mace_check(os.path.exists(model_data_path), "Device",
                           'model data file not found,'
                           ' please convert model first')
                self.push(model_data_path, self.data_dir)

            if device_type == common.DeviceType.GPU:
                if os.path.exists(opencl_binary_file):
                    self.push(opencl_binary_file, self.data_dir)
                if os.path.exists(opencl_parameter_file):
                    self.push(opencl_parameter_file, self.data_dir)

B
Bin Li 已提交
278 279 280 281 282
            if self.system == SystemType.android \
                    and device_type == common.DeviceType.HEXAGON:
                self.push(
                    "third_party/nnlib/%s/libhexagon_controller.so" % abi,
                    self.data_dir)
L
liuqi 已提交
283

L
lichao18 已提交
284 285 286 287
            if device_type == common.DeviceType.APU:
                self.push("third_party/apu/libapu-frontend.so",
                          self.data_dir)

L
liuqi 已提交
288 289 290 291
            mace_model_phone_path = ""
            if model_graph_format == ModelFormat.file:
                mace_model_phone_path = "%s/%s.pb" % (self.data_dir,
                                                      model_tag)
292
                self.push(mace_model_path, mace_model_phone_path)
L
liuqi 已提交
293 294
            if link_dynamic:
                self.push(libmace_dynamic_library_path, self.data_dir)
295 296 297 298
                if self.system == SystemType.android:
                    sh_commands.push_depended_so_libs(
                        libmace_dynamic_library_path, abi, self.data_dir,
                        self.address)
L
liuqi 已提交
299 300 301 302 303 304 305 306 307 308 309 310
            self.push("%s/%s" % (target_dir, target_name), self.data_dir)

            stdout_buff = []
            process_output = sh_commands.make_output_processor(stdout_buff)
            cmd = [
                "LD_LIBRARY_PATH=%s" % self.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,
                "MACE_RUN_PARAMETER_PATH=%s/mace_run.config" % self.data_dir,
                "MACE_INTERNAL_STORAGE_PATH=%s" % internal_storage_dir,
                "MACE_LIMIT_OPENCL_KERNEL_TIME=%s" % limit_opencl_kernel_time,
311
                "MACE_OPENCL_QUEUE_WINDOW_SIZE=%s" % opencl_queue_window_size,
L
liuqi 已提交
312
                "MACE_RUNTIME_FAILURE_RATIO=%f" % runtime_failure_ratio,
B
Bin Li 已提交
313
                "MACE_LOG_TENSOR_RANGE=%d" % (1 if quantize_stat else 0),
L
liuqi 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327
            ]
            if self.system == SystemType.android and address_sanitizer:
                cmd.extend([
                    "LD_PRELOAD=%s/%s" %
                    (self.data_dir,
                     sh_commands.asan_rt_library_names(abi))
                ])
            cmd.extend([
                "%s/%s" % (self.data_dir, target_name),
                "--model_name=%s" % model_tag,
                "--input_node=%s" % ",".join(input_nodes),
                "--output_node=%s" % ",".join(output_nodes),
                "--input_shape=%s" % ":".join(input_shapes),
                "--output_shape=%s" % ":".join(output_shapes),
328 329
                "--input_data_format=%s" % ",".join(input_data_formats),
                "--output_data_format=%s" % ",".join(output_data_formats),
L
liuqi 已提交
330 331
                "--input_file=%s/%s" % (self.data_dir, input_file_name),
                "--output_file=%s/%s" % (self.data_dir, output_file_name),
B
Bin Li 已提交
332 333
                "--input_dir=%s" % input_dir,
                "--output_dir=%s" % output_dir,
334
                "--model_data_file=%s" % model_data_file,
L
liuqi 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347
                "--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,
                "--model_file=%s" % mace_model_phone_path,
                "--opencl_binary_file=%s/%s" %
                (self.data_dir, os.path.basename(opencl_binary_file)),
                "--opencl_parameter_file=%s/%s" %
                (self.data_dir, os.path.basename(opencl_parameter_file)),
            ])
L
liyin 已提交
348 349 350
            if benchmark:
                cmd.append("--benchmark=%s" % benchmark)

L
liuqi 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
            cmd = ' '.join(cmd)
            cmd_file_name = "%s-%s-%s" % ('cmd_file',
                                          model_tag,
                                          str(time.time()))
            cmd_file = "%s/%s" % (self.data_dir, cmd_file_name)
            tmp_cmd_file = "%s/%s" % ('/tmp', cmd_file_name)
            with open(tmp_cmd_file, 'w') as file:
                file.write(cmd)
            self.push(tmp_cmd_file, cmd_file)
            os.remove(tmp_cmd_file)
            self.exec_command('sh {}'.format(cmd_file),
                              _tty_in=True,
                              _out=process_output,
                              _err_to_out=True)
            self.stdout = "".join(stdout_buff)
            if not sh_commands.stdout_success(self.stdout):
                common.MaceLogger.error("Mace Run", "Mace run failed.")

            six.print_("Running finished!\n")
        else:
            six.print_('Unsupported system %s' % self.system, file=sys.stderr)
            raise Exception('Wrong device')

        return self.stdout

    def tuning(self, library_name, model_name, model_config,
               model_graph_format, model_data_format,
               target_abi, mace_lib_type):
        six.print_('* Tuning, it may take some time')
        build_tmp_binary_dir = get_build_binary_dir(library_name, target_abi)
        mace_run_name = MACE_RUN_STATIC_NAME
        link_dynamic = False
        if mace_lib_type == MACELibType.dynamic:
            mace_run_name = MACE_RUN_DYNAMIC_NAME
            link_dynamic = True
        embed_model_data = model_data_format == ModelFormat.code

        # build for specified soc
        # device_wrapper = DeviceWrapper(device)

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

        self.clear_data_dir()

        subgraphs = model_config[YAMLKeyword.subgraphs]
        # generate input data
400
        sh_commands.gen_input(
L
liuqi 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
            model_output_dir,
            subgraphs[0][YAMLKeyword.input_tensors],
            subgraphs[0][YAMLKeyword.input_shapes],
            subgraphs[0][YAMLKeyword.validation_inputs_data],
            input_ranges=subgraphs[0][YAMLKeyword.input_ranges],
            input_data_types=subgraphs[0][YAMLKeyword.input_data_types]
        )

        self.tuning_run(
            abi=target_abi,
            target_dir=build_tmp_binary_dir,
            target_name=mace_run_name,
            vlog_level=0,
            embed_model_data=embed_model_data,
            model_output_dir=model_output_dir,
            input_nodes=subgraphs[0][YAMLKeyword.input_tensors],
            output_nodes=subgraphs[0][YAMLKeyword.output_tensors],
            input_shapes=subgraphs[0][YAMLKeyword.input_shapes],
            output_shapes=subgraphs[0][YAMLKeyword.output_shapes],
420 421
            input_data_formats=subgraphs[0][YAMLKeyword.input_data_formats],
            output_data_formats=subgraphs[0][YAMLKeyword.output_data_formats],
L
liuqi 已提交
422 423 424 425 426 427 428
            mace_model_dir=mace_model_dir,
            model_tag=model_name,
            device_type=DeviceType.GPU,
            running_round=0,
            restart_round=1,
            limit_opencl_kernel_time=model_config[
                YAMLKeyword.limit_opencl_kernel_time],
429 430
            opencl_queue_window_size=model_config[
                YAMLKeyword.opencl_queue_window_size],
L
liuqi 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
            tuning=True,
            out_of_range_check=False,
            model_graph_format=model_graph_format,
            opencl_binary_file='',
            opencl_parameter_file='',
            libmace_dynamic_library_path=LIBMACE_DYNAMIC_PATH,
            link_dynamic=link_dynamic,
        )

        # pull opencl library
        self.pull(self.interior_dir, CL_COMPILED_BINARY_FILE_NAME,
                  '{}/{}'.format(model_output_dir,
                                 BUILD_TMP_OPENCL_BIN_DIR))

        # pull opencl parameter
        self.pull_from_data_dir(CL_TUNED_PARAMETER_FILE_NAME,
                                '{}/{}'.format(model_output_dir,
                                               BUILD_TMP_OPENCL_BIN_DIR))

        six.print_('Tuning done! \n')

B
Bin Li 已提交
452
    @staticmethod
B
Bin Li 已提交
453
    def get_layers(model_dir, model_name, layers):
B
Bin Li 已提交
454 455 456 457 458
        model_file = "%s/%s.pb" % (model_dir, model_name)
        output_dir = "%s/output_models/" % model_dir
        if os.path.exists(output_dir):
            sh.rm('-rf', output_dir)
        os.makedirs(output_dir)
B
Bin Li 已提交
459 460

        layers_validate.convert(model_file, output_dir, layers)
B
Bin Li 已提交
461 462 463 464 465 466 467 468

        output_configs_path = output_dir + "outputs.yml"
        with open(output_configs_path) as f:
            output_configs = yaml.load(f)
        output_configs = output_configs[YAMLKeyword.subgraphs]

        return output_configs

469 470
    def run_model(self, flags, configs, target_abi,
                  model_name, output_config, runtime, tuning):
L
liuqi 已提交
471 472 473 474 475
        library_name = configs[YAMLKeyword.library_name]
        embed_model_data = \
            configs[YAMLKeyword.model_data_format] == ModelFormat.code
        build_tmp_binary_dir = get_build_binary_dir(library_name, target_abi)
        # get target name for run
476
        mace_lib_type = flags.mace_lib_type
L
liyin 已提交
477 478
        if mace_lib_type == MACELibType.static:
            target_name = MACE_RUN_STATIC_NAME
L
liuqi 已提交
479
        else:
L
liyin 已提交
480
            target_name = MACE_RUN_DYNAMIC_NAME
L
liuqi 已提交
481
        link_dynamic = mace_lib_type == MACELibType.dynamic
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 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 535 536

        if target_abi != ABIType.host:
            self.clear_data_dir()

        model_config = configs[YAMLKeyword.models][model_name]
        subgraphs = model_config[YAMLKeyword.subgraphs]

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

        model_opencl_output_bin_path = ''
        model_opencl_parameter_path = ''
        if tuning:
            model_opencl_output_bin_path = \
                '{}/{}/{}'.format(model_output_dir,
                                  BUILD_TMP_OPENCL_BIN_DIR,
                                  CL_COMPILED_BINARY_FILE_NAME)
            model_opencl_parameter_path = \
                '{}/{}/{}'.format(model_output_dir,
                                  BUILD_TMP_OPENCL_BIN_DIR,
                                  CL_TUNED_PARAMETER_FILE_NAME)
        elif target_abi != ABIType.host and self.target_socs:
            model_opencl_output_bin_path = get_opencl_binary_output_path(
                library_name, target_abi, self
            )
            model_opencl_parameter_path = get_opencl_parameter_output_path(
                library_name, target_abi, self
            )
        # run for specified soc
        device_type = parse_device_type(runtime)
        self.tuning_run(
            abi=target_abi,
            target_dir=build_tmp_binary_dir,
            target_name=target_name,
            vlog_level=flags.vlog_level,
            embed_model_data=embed_model_data,
            model_output_dir=model_output_dir,
            input_nodes=subgraphs[0][YAMLKeyword.input_tensors],
            output_nodes=output_config[
                YAMLKeyword.output_tensors],
            input_shapes=subgraphs[0][YAMLKeyword.input_shapes],
            output_shapes=output_config[YAMLKeyword.output_shapes],
            input_data_formats=subgraphs[0][
                YAMLKeyword.input_data_formats],
            output_data_formats=subgraphs[0][
                YAMLKeyword.output_data_formats],
            mace_model_dir=mace_model_dir,
            model_tag=model_name,
            device_type=device_type,
            running_round=flags.round,
            restart_round=flags.restart_round,
            limit_opencl_kernel_time=model_config[
                YAMLKeyword.limit_opencl_kernel_time],
537 538
            opencl_queue_window_size=model_config[
                YAMLKeyword.opencl_queue_window_size],
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
            tuning=False,
            out_of_range_check=flags.gpu_out_of_range_check,
            model_graph_format=configs[
                YAMLKeyword.model_graph_format],
            omp_num_threads=flags.omp_num_threads,
            cpu_affinity_policy=flags.cpu_affinity_policy,
            gpu_perf_hint=flags.gpu_perf_hint,
            gpu_priority_hint=flags.gpu_priority_hint,
            runtime_failure_ratio=flags.runtime_failure_ratio,
            address_sanitizer=flags.address_sanitizer,
            opencl_binary_file=model_opencl_output_bin_path,
            opencl_parameter_file=model_opencl_parameter_path,
            libmace_dynamic_library_path=LIBMACE_DYNAMIC_PATH,
            link_dynamic=link_dynamic,
            quantize_stat=flags.quantize_stat,
            input_dir=flags.input_dir,
            output_dir=flags.output_dir,
            layers_validate_file=output_config[
L
liyin 已提交
557 558
                YAMLKeyword.model_file_path],
            benchmark=flags.benchmark,
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
        )

    def get_output_map(self,
                       target_abi,
                       output_nodes,
                       output_shapes,
                       model_output_dir):
        output_map = {}
        for i in range(len(output_nodes)):
            output_name = output_nodes[i]
            formatted_name = common.formatted_file_name(
                "model_out", output_name)
            if target_abi != "host":
                if os.path.exists("%s/%s" % (model_output_dir,
                                             formatted_name)):
                    sh.rm("-rf", "%s/%s" % (model_output_dir,
                                            formatted_name))
                self.pull_from_data_dir(formatted_name,
                                        model_output_dir)
            output_file_path = os.path.join(model_output_dir,
                                            formatted_name)
            output_shape = [
                int(x) for x in common.split_shape(output_shapes[i])]
            output_map[output_name] = np.fromfile(
                output_file_path, dtype=np.float32).reshape(output_shape)
        return output_map

    def run_specify_abi(self, flags, configs, target_abi):
        if target_abi not in self.target_abis:
            six.print_('The device %s with soc %s do not support the abi %s' %
                       (self.device_name, self.target_socs, target_abi))
            return
        library_name = configs[YAMLKeyword.library_name]

L
liuqi 已提交
593 594 595 596 597 598 599
        model_output_dirs = []

        for model_name in configs[YAMLKeyword.models]:
            check_model_converted(library_name, model_name,
                                  configs[YAMLKeyword.model_graph_format],
                                  configs[YAMLKeyword.model_data_format],
                                  target_abi)
600
            if target_abi != ABIType.host:
L
liuqi 已提交
601 602 603
                self.clear_data_dir()
            MaceLogger.header(
                StringFormatter.block(
604
                    'Run model {} on {}'.format(model_name, self.device_name)))
L
liuqi 已提交
605 606 607 608 609

            model_config = configs[YAMLKeyword.models][model_name]
            model_runtime = model_config[YAMLKeyword.runtime]
            subgraphs = model_config[YAMLKeyword.subgraphs]

L
liuqi 已提交
610 611 612 613
            model_output_base_dir, model_output_dir, mace_model_dir = \
                get_build_model_dirs(
                    library_name, model_name, target_abi, self,
                    model_config[YAMLKeyword.model_file_path])
L
liuqi 已提交
614 615 616 617 618 619

            # clear temp model output dir
            if os.path.exists(model_output_dir):
                sh.rm('-rf', model_output_dir)
            os.makedirs(model_output_dir)

620
            tuning = False
L
liuqi 已提交
621 622
            if not flags.address_sanitizer \
                    and target_abi != ABIType.host \
L
liuqi 已提交
623 624
                    and (configs[YAMLKeyword.target_socs]
                         or flags.target_socs) \
L
liuqi 已提交
625 626 627 628 629 630 631
                    and self.target_socs \
                    and model_runtime in [RuntimeType.gpu,
                                          RuntimeType.cpu_gpu] \
                    and not flags.disable_tuning:
                self.tuning(library_name, model_name, model_config,
                            configs[YAMLKeyword.model_graph_format],
                            configs[YAMLKeyword.model_data_format],
632
                            target_abi, flags.mace_lib_type)
L
liuqi 已提交
633 634
                model_output_dirs.append(model_output_dir)
                self.clear_data_dir()
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
                tuning = True

            accuracy_validation_script = \
                subgraphs[0][YAMLKeyword.accuracy_validation_script]
            output_configs = []
            if not accuracy_validation_script and flags.layers != "-1":
                mace_check(configs[YAMLKeyword.model_graph_format] ==
                           ModelFormat.file and
                           configs[YAMLKeyword.model_data_format] ==
                           ModelFormat.file, "Device",
                           "'--layers' only supports model format 'file'.")
                output_configs = self.get_layers(mace_model_dir,
                                                 model_name,
                                                 flags.layers)
            # run for specified soc
            if not subgraphs[0][YAMLKeyword.check_tensors]:
                output_nodes = subgraphs[0][YAMLKeyword.output_tensors]
                output_shapes = subgraphs[0][YAMLKeyword.output_shapes]
            else:
                output_nodes = subgraphs[0][YAMLKeyword.check_tensors]
                output_shapes = subgraphs[0][YAMLKeyword.check_shapes]
            model_path = "%s/%s.pb" % (mace_model_dir, model_name)
            output_config = {YAMLKeyword.model_file_path: model_path,
                             YAMLKeyword.output_tensors: output_nodes,
                             YAMLKeyword.output_shapes: output_shapes}
            output_configs.append(output_config)

L
liuqi 已提交
662 663 664 665 666 667 668
            runtime_list = []
            if target_abi == ABIType.host:
                runtime_list.append(RuntimeType.cpu)
            elif model_runtime == RuntimeType.cpu_gpu:
                runtime_list.extend([RuntimeType.cpu, RuntimeType.gpu])
            else:
                runtime_list.append(model_runtime)
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
            if accuracy_validation_script:
                flags.validate = False
                flags.report = False

                import imp
                accuracy_val_module = imp.load_source(
                    'accuracy_val_module',
                    accuracy_validation_script)
                for runtime in runtime_list:
                    accuracy_validator = \
                        accuracy_val_module.AccuracyValidator()
                    sample_size = accuracy_validator.sample_size()
                    val_batch_size = accuracy_validator.batch_size()
                    for i in range(0, sample_size, val_batch_size):
                        inputs = accuracy_validator.preprocess(
                            i, i + val_batch_size)
                        sh_commands.gen_input(
                            model_output_dir,
                            subgraphs[0][YAMLKeyword.input_tensors],
                            subgraphs[0][YAMLKeyword.input_shapes],
                            input_data_types=subgraphs[0][YAMLKeyword.input_data_types],  # noqa
                            input_data_map=inputs)

                        self.run_model(flags, configs, target_abi, model_name,
                                       output_configs[-1], runtime, tuning)
                        accuracy_validator.postprocess(
                            i, i + val_batch_size,
                            self.get_output_map(
                                target_abi,
                                output_nodes,
                                subgraphs[0][YAMLKeyword.output_shapes],
                                model_output_dir))
                    accuracy_validator.result()
            else:
                sh_commands.gen_input(
                    model_output_dir,
                    subgraphs[0][YAMLKeyword.input_tensors],
                    subgraphs[0][YAMLKeyword.input_shapes],
                    subgraphs[0][YAMLKeyword.validation_inputs_data],
                    input_ranges=subgraphs[0][YAMLKeyword.input_ranges],
                    input_data_types=subgraphs[0][YAMLKeyword.input_data_types]
                )
                for runtime in runtime_list:
                    device_type = parse_device_type(runtime)
L
liutuo 已提交
713 714 715 716
                    log_dir = mace_model_dir + "/" + runtime
                    if os.path.exists(log_dir):
                        sh.rm('-rf', log_dir)
                    os.makedirs(log_dir)
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
                    for output_config in output_configs:
                        self.run_model(flags, configs, target_abi, model_name,
                                       output_config, runtime, tuning)
                        if flags.validate:
                            log_file = ""
                            if flags.layers != "-1":
                                log_file = log_dir + "/log.csv"
                            model_file_path, weight_file_path = \
                                get_model_files(
                                    model_config[YAMLKeyword.model_file_path],
                                    model_config[
                                        YAMLKeyword.model_sha256_checksum],
                                    BUILD_DOWNLOADS_DIR,
                                    model_config[YAMLKeyword.weight_file_path],
                                    model_config[
                                        YAMLKeyword.weight_sha256_checksum])
                            validate_type = device_type
B
Bin Li 已提交
734 735 736 737 738
                            if device_type in [DeviceType.CPU,
                                               DeviceType.GPU] and \
                                    (model_config[YAMLKeyword.quantize] == 1 or
                                     model_config[YAMLKeyword.quantize_large_weights] == 1):  # noqa
                                validate_type = DeviceType.QUANTIZE
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783

                            dockerfile_path, docker_image_tag = \
                                get_dockerfile_info(
                                    model_config.get(
                                        YAMLKeyword.dockerfile_path),
                                    model_config.get(
                                        YAMLKeyword.dockerfile_sha256_checksum),  # noqa
                                    model_config.get(
                                        YAMLKeyword.docker_image_tag)
                                ) if YAMLKeyword.dockerfile_path \
                                     in model_config \
                                    else ("third_party/caffe", "lastest")
                            sh_commands.validate_model(
                                abi=target_abi,
                                device=self,
                                model_file_path=model_file_path,
                                weight_file_path=weight_file_path,
                                docker_image_tag=docker_image_tag,
                                dockerfile_path=dockerfile_path,
                                platform=model_config[YAMLKeyword.platform],
                                device_type=device_type,
                                input_nodes=subgraphs[0][
                                    YAMLKeyword.input_tensors],
                                output_nodes=output_config[
                                    YAMLKeyword.output_tensors],
                                input_shapes=subgraphs[0][
                                    YAMLKeyword.input_shapes],
                                output_shapes=output_config[
                                    YAMLKeyword.output_shapes],
                                input_data_formats=subgraphs[0][
                                    YAMLKeyword.input_data_formats],
                                output_data_formats=subgraphs[0][
                                    YAMLKeyword.output_data_formats],
                                model_output_dir=model_output_dir,
                                input_data_types=subgraphs[0][
                                    YAMLKeyword.input_data_types],
                                caffe_env=flags.caffe_env,
                                validation_threshold=subgraphs[0][
                                    YAMLKeyword.validation_threshold][
                                    validate_type],
                                backend=subgraphs[0][YAMLKeyword.backend],
                                validation_outputs_data=subgraphs[0][
                                    YAMLKeyword.validation_outputs_data],
                                log_file=log_file,
                            )
784
                        if flags.round > 0:
785 786 787 788 789
                            tuned = tuning and device_type == DeviceType.GPU
                            self.report_run_statistics(
                                target_abi=target_abi,
                                model_name=model_name,
                                device_type=device_type,
790
                                flags=flags,
791 792
                                tuned=tuned)

L
liuqi 已提交
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816
        if model_output_dirs:
            opencl_output_bin_path = get_opencl_binary_output_path(
                library_name, target_abi, self
            )
            opencl_parameter_bin_path = get_opencl_parameter_output_path(
                library_name, target_abi, self
            )

            # clear opencl output dir
            if os.path.exists(opencl_output_bin_path):
                sh.rm('-rf', opencl_output_bin_path)
            if os.path.exists(opencl_parameter_bin_path):
                sh.rm('-rf', opencl_parameter_bin_path)

            # merge all model's opencl binaries together
            sh_commands.merge_opencl_binaries(
                model_output_dirs, CL_COMPILED_BINARY_FILE_NAME,
                opencl_output_bin_path
            )
            # merge all model's opencl parameter together
            sh_commands.merge_opencl_parameters(
                model_output_dirs, CL_TUNED_PARAMETER_FILE_NAME,
                opencl_parameter_bin_path
            )
817 818 819 820 821
            sh_commands.gen_opencl_binary_cpps(
                opencl_output_bin_path,
                opencl_parameter_bin_path,
                opencl_output_bin_path + '.cc',
                opencl_parameter_bin_path + '.cc')
L
liuqi 已提交
822 823 824 825 826

    def report_run_statistics(self,
                              target_abi,
                              model_name,
                              device_type,
827
                              flags,
L
liuqi 已提交
828 829 830 831 832
                              tuned):
        metrics = [0] * 3
        for line in self.stdout.split('\n'):
            line = line.strip()
            parts = line.split()
L
liuqi 已提交
833 834 835 836
            if len(parts) == 5 and parts[0].startswith('time'):
                metrics[0] = str(float(parts[2]))
                metrics[1] = str(float(parts[3]))
                metrics[2] = str(float(parts[4]))
L
liuqi 已提交
837
                break
838 839 840 841 842 843 844 845 846 847
        if flags.report:
            report_filename = flags.report_dir + '/report.csv'
            if not os.path.exists(report_filename):
                with open(report_filename, 'w') as f:
                    f.write('model_name,device_name,soc,abi,runtime,'
                            'init(ms),warmup(ms),run_avg(ms),tuned\n')

            data_str = \
                '{model_name},{device_name},{soc},{abi},{device_type},' \
                '{init},{warmup},{run_avg},{tuned}\n'.format(
L
liuqi 已提交
848
                    model_name=model_name,
849
                    device_name=self.device_name,
L
liuqi 已提交
850 851 852 853 854 855 856
                    soc=self.target_socs,
                    abi=target_abi,
                    device_type=device_type,
                    init=metrics[0],
                    warmup=metrics[1],
                    run_avg=metrics[2],
                    tuned=tuned)
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875
            with open(report_filename, 'a') as f:
                f.write(data_str)
        self.report_to_dana(model_name, target_abi, device_type,
                            {
                                'init': metrics[0],
                                'warmup': metrics[1],
                                'run-avg': metrics[2]
                            })

    def report_to_dana(self, model_name, target_abi, device_type, metrics):
        if not self._dana_util.service_available():
            return
        for (key, value) in metrics.items():
            value = float(value)
            self._dana_util.fast_report_benchmark(
                table_name="Models", base_name="%s_%s" % (key, model_name),
                device_name=self.device_name, soc=self.target_socs,
                target_abi=target_abi, runtime=device_type,
                value=value, trend=DanaTrend.SMALLER)
L
liuqi 已提交
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894

    def run(self,
            abi,
            host_bin_path,
            bin_name,
            args='',
            opencl_profiling=True,
            vlog_level=0,
            out_of_range_check=True,
            address_sanitizer=False,
            simpleperf=False):
        host_bin_full_path = '%s/%s' % (host_bin_path, bin_name)
        device_bin_full_path = '%s/%s' % (self.data_dir, bin_name)
        print(
            '================================================================'
        )
        print('Trying to lock device %s' % self.address)
        with self.lock():
            print('Run on device: %s, %s, %s' %
895
                  (self.address, self.target_socs, self.device_name))
L
liuqi 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
            self.rm(self.data_dir)
            self.exec_command('mkdir -p %s' % self.data_dir)
            self.push(host_bin_full_path, device_bin_full_path)
            ld_preload = ''
            if address_sanitizer:
                self.push(sh_commands.find_asan_rt_library(abi),
                          self.data_dir)
                ld_preload = 'LD_PRELOAD=%s/%s' % \
                             (self.data_dir,
                              sh_commands.asan_rt_library_names(abi))
            opencl_profiling = 1 if opencl_profiling else 0
            out_of_range_check = 1 if out_of_range_check else 0
            print('Run %s' % device_bin_full_path)
            stdout_buf = []
            process_output = sh_commands.make_output_processor(stdout_buf)

912 913
            internal_storage_dir = self.create_internal_storage_dir()

L
liuqi 已提交
914 915 916 917 918 919 920 921
            if simpleperf and self.system == SystemType.android:
                self.push(sh_commands.find_simpleperf_library(abi),
                          self.data_dir)
                simpleperf_cmd = '%s/simpleperf' % self.data_dir
                exec_cmd = [
                    ld_preload,
                    'MACE_OUT_OF_RANGE_CHECK=%s' % out_of_range_check,
                    'MACE_OPENCL_PROFILING=%d' % opencl_profiling,
922
                    'MACE_INTERNAL_STORAGE_PATH=%s' % internal_storage_dir,
L
liuqi 已提交
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
                    'MACE_CPP_MIN_VLOG_LEVEL=%d' % vlog_level,
                    simpleperf_cmd,
                    'stat',
                    '--group',
                    'raw-l1-dcache,raw-l1-dcache-refill',
                    '--group',
                    'raw-l2-dcache,raw-l2-dcache-refill',
                    '--group',
                    'raw-l1-dtlb,raw-l1-dtlb-refill',
                    '--group',
                    'raw-l2-dtlb,raw-l2-dtlb-refill',
                    device_bin_full_path,
                    args,
                ]
            else:
                exec_cmd = [
                    ld_preload,
                    'MACE_OUT_OF_RANGE_CHECK=%d' % out_of_range_check,
                    'MACE_OPENCL_PROFILNG=%d' % opencl_profiling,
942
                    'MACE_INTERNAL_STORAGE_PATH=%s' % internal_storage_dir,
L
liuqi 已提交
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
                    'MACE_CPP_MIN_VLOG_LEVEL=%d' % vlog_level,
                    device_bin_full_path,
                    args
                ]
            exec_cmd = ' '.join(exec_cmd)
            self.exec_command(exec_cmd, _tty_in=True,
                              _out=process_output, _err_to_out=True)
            return ''.join(stdout_buf)


class DeviceManager:
    @classmethod
    def list_adb_device(cls):
        adb_list = sh.adb('devices').stdout.decode('utf-8'). \
                       strip().split('\n')[1:]
        adb_list = [tuple(pair.split('\t')) for pair in adb_list]
        devices = []
        for adb in adb_list:
B
Bin Li 已提交
961 962
            if adb[1].startswith("no permissions"):
                continue
L
liuqi 已提交
963 964
            prop = sh_commands.adb_getprop_by_serialno(adb[0])
            android = {
965 966
                YAMLKeyword.device_name:
                    prop['ro.product.model'].replace(' ', ''),
L
liuqi 已提交
967 968 969 970 971 972 973
                YAMLKeyword.target_abis:
                    prop['ro.product.cpu.abilist'].split(','),
                YAMLKeyword.target_socs: prop['ro.board.platform'],
                YAMLKeyword.system: SystemType.android,
                YAMLKeyword.address: adb[0],
                YAMLKeyword.username: '',
            }
B
Bin Li 已提交
974 975
            if android not in devices:
                devices.append(android)
L
liuqi 已提交
976 977 978 979 980 981 982 983 984
        return devices

    @classmethod
    def list_ssh_device(cls, yml):
        with open(yml) as f:
            devices = yaml.load(f.read())
        devices = devices['devices']
        device_list = []
        for name, dev in six.iteritems(devices):
985 986
            dev[YAMLKeyword.device_name] = \
                dev[YAMLKeyword.models].replace(' ', '')
L
liuqi 已提交
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
            dev[YAMLKeyword.system] = SystemType.arm_linux
            device_list.append(dev)
        return device_list

    @classmethod
    def list_devices(cls, yml):
        devices_list = []
        devices_list.extend(cls.list_adb_device())
        if not yml:
            if os.path.exists('devices.yml'):
                devices_list.extend(cls.list_ssh_device('devices.yml'))
        else:
            if os.path.exists(yml):
                devices_list.extend(cls.list_ssh_device(yml))
            else:
                MaceLogger.error(ModuleName.RUN,
                                 'no ARM linux device config file found')
        host = {
            YAMLKeyword.device_name: SystemType.host,
            YAMLKeyword.target_abis: [ABIType.host],
            YAMLKeyword.target_socs: '',
            YAMLKeyword.system: SystemType.host,
1009
            YAMLKeyword.address: SystemType.host,
L
liuqi 已提交
1010 1011 1012 1013 1014 1015 1016 1017

        }
        devices_list.append(host)
        return devices_list


if __name__ == '__main__':
    pass