bazel_adb_run.py 7.6 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
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
14 15 16 17 18

# Must run at root dir of libmace project.
# python tools/bazel_adb_run.py \
#     --target_abis=armeabi-v7a \
#     --target_socs=sdm845
L
Liangliang He 已提交
19
#     --target=//test/ccunit:mace_cc_test
20 21 22 23 24 25
#     --stdout_processor=stdout_processor

import argparse
import sys
import sh_commands

L
liuqi 已提交
26
from common import *
27 28
from dana.dana_util import DanaUtil
from dana.dana_cli import DanaTrend
L
liuqi 已提交
29
from device import DeviceWrapper, DeviceManager
L
Liangliang He 已提交
30

31 32
TABLE_NAME = 'Ops'

33

L
Liangliang He 已提交
34
def unittest_stdout_processor(stdout, device_properties, abi):
L
Liangliang He 已提交
35 36
    stdout_lines = stdout.split("\n")
    for line in stdout_lines:
L
Liangliang He 已提交
37 38
        if "Aborted" in line or "FAILED" in line or \
                "Segmentation fault" in line:
L
Liangliang He 已提交
39 40
            raise Exception("Command failed")

41

L
liuqi 已提交
42
def ops_benchmark_stdout_processor(stdout, dev, abi):
L
Liangliang He 已提交
43 44 45
    stdout_lines = stdout.split("\n")
    metrics = {}
    for line in stdout_lines:
L
Liangliang He 已提交
46
        if "Aborted" in line or "Segmentation fault" in line:
L
Liangliang He 已提交
47 48
            raise Exception("Command failed")

49

李寅 已提交
50 51 52 53 54 55 56 57 58 59 60
# TODO: after merge mace/python/tools and tools are merged,
# define str2bool as common util
def str2bool(v):
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')


61
def parse_args():
L
Liangliang He 已提交
62 63 64 65 66 67 68 69 70 71 72 73
    """Parses command line arguments."""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--target_abis",
        type=str,
        default="armeabi-v7a",
        help="Target ABIs, comma seperated list")
    parser.add_argument(
        "--target_socs",
        type=str,
        default="all",
        help="SoCs (ro.board.platform from getprop) to build, "
74
             "comma seperated list or all/random")
L
Liangliang He 已提交
75 76 77 78
    parser.add_argument(
        "--target", type=str, default="//...", help="Bazel target to build")
    parser.add_argument(
        "--run_target",
李寅 已提交
79
        type=str2bool,
L
Liangliang He 已提交
80 81 82 83 84 85
        default=False,
        help="Whether to run the target")
    parser.add_argument("--args", type=str, default="", help="Command args")
    parser.add_argument(
        "--stdout_processor",
        type=str,
86
        default="unittest_stdout_processor",
L
Liangliang He 已提交
87
        help="Stdout processing function, default: stdout_processor")
李寅 已提交
88 89 90 91 92
    parser.add_argument(
        "--enable_neon",
        type=str2bool,
        default=True,
        help="Whether to use neon optimization")
L
luxuhui 已提交
93
    parser.add_argument(
94
        "--enable_quantize",
L
luxuhui 已提交
95
        type=str2bool,
96 97
        default=True,
        help="Whether to use quantization ops")
98 99 100 101
    parser.add_argument(
        '--address_sanitizer',
        action="store_true",
        help="Whether to enable AddressSanitizer")
102 103 104 105
    parser.add_argument(
        '--debug_mode',
        action="store_true",
        help="Reserve debug symbols.")
李寅 已提交
106 107 108 109 110
    parser.add_argument(
        "--simpleperf",
        type=str2bool,
        default=False,
        help="Whether to use simpleperf stat")
L
liuqi 已提交
111 112 113 114
    parser.add_argument(
        '--device_yml',
        type=str,
        default='',
115 116
        help='embedded linux device config yml file')
    parser.add_argument('--vlog_level', type=int, default=0, help='vlog level')
L
Liangliang He 已提交
117 118
    return parser.parse_known_args()

119

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
def report_to_dana(dana_util, item_name, metric_name,
                   device, soc, abi, value, trend):
    serie_id = dana_util.create_serie_id_lite(
        TABLE_NAME, "%s_%s_%s_%s_%s" % (metric_name, device,
                                        soc, abi, item_name))
    dana_util.report_benchmark(serie_id=serie_id, value=value, trend=trend)


def report_run_statistics(stdouts, device, soc, abi, dana_util):
    if stdouts is None:
        print('report_run_statistics failed: stdouts is None.')
        return
    for line in stdouts.split('\n'):
        line = line.strip()
        parts = line.split()
        if len(parts) == 5 and parts[0].startswith('MACE'):
            item_name = str(parts[0])
            report_to_dana(dana_util, item_name, 'time-ns', device, soc,
                           abi, float(parts[1]), DanaTrend.SMALLER)
            report_to_dana(dana_util, item_name, 'iterations', device, soc,
                           abi, float(parts[2]), DanaTrend.HIGHER)
            input_mbs = float(parts[3])
            if input_mbs < sys.float_info.min:
                input_mbs = sys.float_info.min
            report_to_dana(dana_util, item_name, 'input-MBS', device, soc,
                           abi, input_mbs, DanaTrend.HIGHER)
            gmacps = float(parts[4])
            if gmacps < sys.float_info.min:
                gmacps = sys.float_info.min
            report_to_dana(dana_util, item_name, 'GMACPS', device, soc,
                           abi, gmacps, DanaTrend.HIGHER)


153
def main(unused_args):
L
Liangliang He 已提交
154 155 156
    target = FLAGS.target
    host_bin_path, bin_name = sh_commands.bazel_target_to_bin(target)
    target_abis = FLAGS.target_abis.split(',')
157
    dana_util = DanaUtil()
L
Liangliang He 已提交
158 159

    for target_abi in target_abis:
L
liuqi 已提交
160
        toolchain = infer_toolchain(target_abi)
161 162 163 164 165
        sh_commands.bazel_build(
            target,
            abi=target_abi,
            toolchain=toolchain,
            enable_neon=FLAGS.enable_neon,
166
            enable_quantize=FLAGS.enable_quantize,
167
            address_sanitizer=FLAGS.address_sanitizer,
L
liyin 已提交
168
            debug_mode=FLAGS.debug_mode)
L
Liangliang He 已提交
169
        if FLAGS.run_target:
L
liuqi 已提交
170
            target_devices = DeviceManager.list_devices(FLAGS.device_yml)
171
            if FLAGS.target_socs != TargetSOCTag.all and \
L
liuqi 已提交
172
                    FLAGS.target_socs != TargetSOCTag.random:
L
liuqi 已提交
173 174 175 176
                target_socs = set(FLAGS.target_socs.split(','))
                target_devices = \
                    [dev for dev in target_devices
                     if dev[YAMLKeyword.target_socs] in target_socs]
L
liuqi 已提交
177 178 179
            if FLAGS.target_socs == TargetSOCTag.random:
                target_devices = sh_commands.choose_a_random_device(
                    target_devices, target_abi)
L
liuqi 已提交
180

L
liuqi 已提交
181 182
            for dev in target_devices:
                if target_abi not in dev[YAMLKeyword.target_abis]:
L
Liangliang He 已提交
183
                    print("Skip device %s which does not support ABI %s" %
L
liuqi 已提交
184
                          (dev, target_abi))
L
Liangliang He 已提交
185
                    continue
L
liuqi 已提交
186 187
                device_wrapper = DeviceWrapper(dev)
                stdouts = device_wrapper.run(
188 189 190 191
                    target_abi,
                    host_bin_path,
                    bin_name,
                    args=FLAGS.args,
L
liuqi 已提交
192
                    opencl_profiling=True,
193
                    vlog_level=FLAGS.vlog_level,
L
liuqi 已提交
194
                    out_of_range_check=True,
李寅 已提交
195 196
                    address_sanitizer=FLAGS.address_sanitizer,
                    simpleperf=FLAGS.simpleperf)
197
                globals()[FLAGS.stdout_processor](stdouts, dev, target_abi)
L
luxuhui 已提交
198 199 200 201 202
                if dana_util.service_available():
                    report_run_statistics(stdouts=stdouts,
                                          device=dev['device_name'],
                                          soc=dev['target_socs'],
                                          abi=target_abi, dana_util=dana_util)
L
Liangliang He 已提交
203

204 205

if __name__ == "__main__":
L
Liangliang He 已提交
206 207
    FLAGS, unparsed = parse_args()
    main(unused_args=[sys.argv[0]] + unparsed)