common.py 17.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 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 enum
L
liuqi 已提交
16
import hashlib
B
Bin Li 已提交
17
import inspect
L
liuqi 已提交
18
import re
L
liuqi 已提交
19
import os
L
liyin 已提交
20

21 22
import six

L
liuqi 已提交
23 24 25 26

################################
# log
################################
27 28 29 30 31 32 33 34 35
class CMDColors:
    PURPLE = '\033[95m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
L
liuqi 已提交
36

37

B
Bin Li 已提交
38 39 40 41 42 43
def get_frame_info(level=2):
    caller_frame = inspect.stack()[level]
    info = inspect.getframeinfo(caller_frame[0])
    return info.filename + ':' + str(info.lineno) + ': '


44 45 46
class MaceLogger:
    @staticmethod
    def header(message):
47
        six.print_(CMDColors.PURPLE + message + CMDColors.ENDC)
48 49 50

    @staticmethod
    def summary(message):
51
        six.print_(CMDColors.GREEN + message + CMDColors.ENDC)
52 53 54

    @staticmethod
    def info(message):
B
Bin Li 已提交
55
        six.print_(get_frame_info() + message)
56 57 58

    @staticmethod
    def warning(message):
B
Bin Li 已提交
59 60
        six.print_(CMDColors.YELLOW + 'WARNING:' + get_frame_info() + message
                   + CMDColors.ENDC)
61 62

    @staticmethod
B
Bin Li 已提交
63 64 65 66
    def error(module, message, location_info=""):
        if not location_info:
            location_info = get_frame_info()
        six.print_(CMDColors.RED + 'ERROR: [' + module + '] ' + location_info
67
                   + message + CMDColors.ENDC)
68 69 70 71 72
        exit(1)


def mace_check(condition, module, message):
    if not condition:
B
Bin Li 已提交
73
        MaceLogger.error(module, message, get_frame_info())
74 75 76 77 78 79 80 81 82 83 84 85 86 87


################################
# String Formatter
################################
class StringFormatter:
    @staticmethod
    def table(header, data, title, align="R"):
        data_size = len(data)
        column_size = len(header)
        column_length = [len(str(ele)) + 1 for ele in header]
        for row_idx in range(data_size):
            data_tuple = data[row_idx]
            ele_size = len(data_tuple)
88
            assert (ele_size == column_size)
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 117 118 119 120 121 122
            for i in range(ele_size):
                column_length[i] = max(column_length[i],
                                       len(str(data_tuple[i])) + 1)

        table_column_length = sum(column_length) + column_size + 1
        dash_line = '-' * table_column_length + '\n'
        header_line = '=' * table_column_length + '\n'
        output = ""
        output += dash_line
        output += str(title).center(table_column_length) + '\n'
        output += dash_line
        output += '|' + '|'.join([str(header[i]).center(column_length[i])
                                  for i in range(column_size)]) + '|\n'
        output += header_line

        for data_tuple in data:
            ele_size = len(data_tuple)
            row_list = []
            for i in range(ele_size):
                if align == "R":
                    row_list.append(str(data_tuple[i]).rjust(column_length[i]))
                elif align == "L":
                    row_list.append(str(data_tuple[i]).ljust(column_length[i]))
                elif align == "C":
                    row_list.append(str(data_tuple[i])
                                    .center(column_length[i]))
            output += '|' + '|'.join(row_list) + "|\n" + dash_line
        return output

    @staticmethod
    def block(message):
        line_length = 10 + len(str(message)) + 10
        star_line = '*' * line_length + '\n'
        return star_line + str(message).center(line_length) + '\n' + star_line
L
liuqi 已提交
123 124


125 126 127 128 129 130 131
################################
# definitions
################################
class DeviceType(object):
    CPU = 'CPU'
    GPU = 'GPU'
    HEXAGON = 'HEXAGON'
B
Bin Li 已提交
132
    HTA = 'HTA'
133
    APU = 'APU'
134

B
Bin Li 已提交
135 136 137
    # for validation threshold
    QUANTIZE = 'QUANTIZE'

138

139 140 141 142
class DataFormat(object):
    NONE = "NONE"
    NHWC = "NHWC"
    NCHW = "NCHW"
143
    OIHW = "OIHW"
144 145


L
liuqi 已提交
146 147 148 149 150 151 152 153 154 155 156 157
################################
# Argument types
################################
class CaffeEnvType(enum.Enum):
    DOCKER = 0,
    LOCAL = 1,


################################
# common functions
################################
def formatted_file_name(input_file_name, input_name):
158 159 160 161
    res = input_file_name + '_'
    for c in input_name:
        res += c if c.isalnum() else '_'
    return res
L
liuqi 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207


def md5sum(s):
    md5 = hashlib.md5()
    md5.update(s.encode('utf-8'))
    return md5.hexdigest()


def get_build_binary_dir(library_name, target_abi):
    return "%s/%s/%s/%s" % (
        BUILD_OUTPUT_DIR, library_name, BUILD_TMP_DIR_NAME, target_abi)


def get_model_lib_output_path(library_name, abi):
    lib_output_path = os.path.join(BUILD_OUTPUT_DIR, library_name,
                                   MODEL_OUTPUT_DIR_NAME, abi,
                                   "%s.a" % library_name)
    return lib_output_path


def check_model_converted(library_name, model_name,
                          model_graph_format, model_data_format,
                          abi):
    model_output_dir = \
        '%s/%s/%s' % (BUILD_OUTPUT_DIR, library_name, MODEL_OUTPUT_DIR_NAME)
    if model_graph_format == ModelFormat.file:
        mace_check(os.path.exists("%s/%s.pb" % (model_output_dir, model_name)),
                   ModuleName.RUN,
                   "You should convert model first.")
    else:
        model_lib_path = get_model_lib_output_path(library_name, abi)
        mace_check(os.path.exists(model_lib_path),
                   ModuleName.RUN,
                   "You should convert model first.")
    if model_data_format == ModelFormat.file:
        mace_check(os.path.exists("%s/%s.data" %
                                  (model_output_dir, model_name)),
                   ModuleName.RUN,
                   "You should convert model first.")


def parse_device_type(runtime):
    device_type = ""

    if runtime == RuntimeType.dsp:
        device_type = DeviceType.HEXAGON
B
Bin Li 已提交
208 209
    elif runtime == RuntimeType.hta:
        device_type = DeviceType.HTA
L
liuqi 已提交
210 211 212 213
    elif runtime == RuntimeType.gpu:
        device_type = DeviceType.GPU
    elif runtime == RuntimeType.cpu:
        device_type = DeviceType.CPU
214 215
    elif runtime == RuntimeType.apu:
        device_type = DeviceType.APU
L
liuqi 已提交
216 217 218 219 220 221 222 223 224 225 226 227

    return device_type


def sha256_checksum(fname):
    hash_func = hashlib.sha256()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_func.update(chunk)
    return hash_func.hexdigest()


L
lichao18 已提交
228 229 230 231
def get_dockerfile_info(dockerfile_path="",
                        dockerfile_sha256_checksum="",
                        docker_image_tag=""):
    dockerfile_local_path = ""
232 233
    if dockerfile_path.startswith("http://") or \
            dockerfile_path.startswith("https://"):
L
lichao18 已提交
234 235 236 237 238
        dockerfile_local_path = \
            "third_party/caffe/" + docker_image_tag
        dockerfile = dockerfile_local_path + "/Dockerfile"
        if not os.path.exists(dockerfile_local_path):
            os.makedirs(dockerfile_local_path)
239 240 241 242 243 244
        if not os.path.exists(dockerfile) or \
                sha256_checksum(dockerfile) != dockerfile_sha256_checksum:
            MaceLogger.info("Downloading Dockerfile, please wait ...")
            six.moves.urllib.request.urlretrieve(dockerfile_path, dockerfile)
            MaceLogger.info("Dockerfile downloaded successfully.")

L
lichao18 已提交
245
    if dockerfile_local_path:
246 247 248 249
        if sha256_checksum(dockerfile) != dockerfile_sha256_checksum:
            MaceLogger.error(ModuleName.MODEL_CONVERTER,
                             "Dockerfile sha256checksum not match")
    else:
L
lichao18 已提交
250 251
        dockerfile_local_path = "third_party/caffe"
        docker_image_tag = "lastest"
252

L
lichao18 已提交
253
    return dockerfile_local_path, docker_image_tag
254 255


L
liuqi 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
def get_model_files(model_file_path,
                    model_sha256_checksum,
                    model_output_dir,
                    weight_file_path="",
                    weight_sha256_checksum=""):
    model_file = model_file_path
    weight_file = weight_file_path

    if model_file_path.startswith("http://") or \
            model_file_path.startswith("https://"):
        model_file = model_output_dir + "/" + md5sum(model_file_path) + ".pb"
        if not os.path.exists(model_file) or \
                sha256_checksum(model_file) != model_sha256_checksum:
            MaceLogger.info("Downloading model, please wait ...")
            six.moves.urllib.request.urlretrieve(model_file_path, model_file)
            MaceLogger.info("Model downloaded successfully.")

    if sha256_checksum(model_file) != model_sha256_checksum:
        MaceLogger.error(ModuleName.MODEL_CONVERTER,
                         "model file sha256checksum not match")

    if weight_file_path.startswith("http://") or \
            weight_file_path.startswith("https://"):
        weight_file = \
            model_output_dir + "/" + md5sum(weight_file_path) + ".caffemodel"
        if not os.path.exists(weight_file) or \
                sha256_checksum(weight_file) != weight_sha256_checksum:
            MaceLogger.info("Downloading model weight, please wait ...")
            six.moves.urllib.request.urlretrieve(weight_file_path, weight_file)
            MaceLogger.info("Model weight downloaded successfully.")

    if weight_file:
        if sha256_checksum(weight_file) != weight_sha256_checksum:
            MaceLogger.error(ModuleName.MODEL_CONVERTER,
                             "weight file sha256checksum not match")

    return model_file, weight_file


def get_opencl_binary_output_path(library_name, target_abi, device):
    target_soc = device.target_socs
297
    device_name = device.device_name
L
liuqi 已提交
298 299 300 301 302 303 304
    return '%s/%s/%s/%s/%s_%s.%s.%s.bin' % \
           (BUILD_OUTPUT_DIR,
            library_name,
            OUTPUT_OPENCL_BINARY_DIR_NAME,
            target_abi,
            library_name,
            OUTPUT_OPENCL_BINARY_FILE_NAME,
305
            device_name,
L
liuqi 已提交
306 307 308 309 310
            target_soc)


def get_opencl_parameter_output_path(library_name, target_abi, device):
    target_soc = device.target_socs
311
    device_name = device.device_name
L
liuqi 已提交
312 313 314 315 316 317 318
    return '%s/%s/%s/%s/%s_%s.%s.%s.bin' % \
           (BUILD_OUTPUT_DIR,
            library_name,
            OUTPUT_OPENCL_BINARY_DIR_NAME,
            target_abi,
            library_name,
            OUTPUT_OPENCL_PARAMETER_FILE_NAME,
319
            device_name,
L
liuqi 已提交
320 321 322 323 324 325 326 327
            target_soc)


def get_build_model_dirs(library_name,
                         model_name,
                         target_abi,
                         device,
                         model_file_path):
328
    device_name = device.device_name
L
liuqi 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    target_socs = device.target_socs
    model_path_digest = md5sum(model_file_path)
    model_output_base_dir = '{}/{}/{}/{}/{}'.format(
        BUILD_OUTPUT_DIR, library_name, BUILD_TMP_DIR_NAME,
        model_name, model_path_digest)

    if target_abi == ABIType.host:
        model_output_dir = '%s/%s' % (model_output_base_dir, target_abi)
    elif not target_socs or not device.address:
        model_output_dir = '%s/%s/%s' % (model_output_base_dir,
                                         BUILD_TMP_GENERAL_OUTPUT_DIR_NAME,
                                         target_abi)
    else:
        model_output_dir = '{}/{}_{}/{}'.format(
            model_output_base_dir,
344
            device_name,
L
liuqi 已提交
345 346 347 348 349 350 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 400 401 402 403 404 405
            target_socs,
            target_abi
        )

    mace_model_dir = '{}/{}/{}'.format(
        BUILD_OUTPUT_DIR, library_name, MODEL_OUTPUT_DIR_NAME
    )

    return model_output_base_dir, model_output_dir, mace_model_dir


def abi_to_internal(abi):
    if abi in [ABIType.armeabi_v7a, ABIType.arm64_v8a]:
        return abi
    if abi == ABIType.arm64:
        return ABIType.aarch64
    if abi == ABIType.armhf:
        return ABIType.armeabi_v7a


def infer_toolchain(abi):
    if abi in [ABIType.armeabi_v7a, ABIType.arm64_v8a]:
        return ToolchainType.android
    if abi == ABIType.armhf:
        return ToolchainType.arm_linux_gnueabihf
    if abi == ABIType.arm64:
        return ToolchainType.aarch64_linux_gnu
    return ''


################################
# YAML key word
################################
class YAMLKeyword(object):
    library_name = 'library_name'
    target_abis = 'target_abis'
    target_socs = 'target_socs'
    model_graph_format = 'model_graph_format'
    model_data_format = 'model_data_format'
    models = 'models'
    platform = 'platform'
    device_name = 'device_name'
    system = 'system'
    address = 'address'
    username = 'username'
    password = 'password'
    model_file_path = 'model_file_path'
    model_sha256_checksum = 'model_sha256_checksum'
    weight_file_path = 'weight_file_path'
    weight_sha256_checksum = 'weight_sha256_checksum'
    subgraphs = 'subgraphs'
    input_tensors = 'input_tensors'
    input_shapes = 'input_shapes'
    input_ranges = 'input_ranges'
    output_tensors = 'output_tensors'
    output_shapes = 'output_shapes'
    check_tensors = 'check_tensors'
    check_shapes = 'check_shapes'
    runtime = 'runtime'
    data_type = 'data_type'
    input_data_types = 'input_data_types'
L
liuqi 已提交
406
    output_data_types = 'output_data_types'
L
liuqi 已提交
407 408 409
    input_data_formats = 'input_data_formats'
    output_data_formats = 'output_data_formats'
    limit_opencl_kernel_time = 'limit_opencl_kernel_time'
410
    opencl_queue_window_size = 'opencl_queue_window_size'
L
liuqi 已提交
411 412 413 414
    nnlib_graph_mode = 'nnlib_graph_mode'
    obfuscate = 'obfuscate'
    winograd = 'winograd'
    quantize = 'quantize'
B
Bin Li 已提交
415
    quantize_large_weights = 'quantize_large_weights'
L
liuqi 已提交
416
    quantize_range_file = 'quantize_range_file'
B
Bin Li 已提交
417
    quantize_stat = 'quantize_stat'
L
liuqi 已提交
418 419 420 421 422
    change_concat_ranges = 'change_concat_ranges'
    validation_inputs_data = 'validation_inputs_data'
    validation_threshold = 'validation_threshold'
    graph_optimize_options = 'graph_optimize_options'  # internal use for now
    cl_mem_type = 'cl_mem_type'
L
liutuo 已提交
423
    backend = 'backend'
424
    validation_outputs_data = 'validation_outputs_data'
425
    accuracy_validation_script = 'accuracy_validation_script'
L
lichao18 已提交
426
    docker_image_tag = 'docker_image_tag'
427 428
    dockerfile_path = 'dockerfile_path'
    dockerfile_sha256_checksum = 'dockerfile_sha256_checksum'
L
liuqi 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446


################################
# SystemType
################################
class SystemType:
    host = 'host'
    android = 'android'
    arm_linux = 'arm_linux'


################################
# common device str
################################

PHONE_DATA_DIR = '/data/local/tmp/mace_run'
DEVICE_DATA_DIR = '/tmp/data/mace_run'
DEVICE_INTERIOR_DIR = PHONE_DATA_DIR + "/interior"
L
Liangliang He 已提交
447
BUILD_OUTPUT_DIR = 'build'
L
liuqi 已提交
448 449 450 451 452 453
BUILD_TMP_DIR_NAME = '_tmp'
BUILD_DOWNLOADS_DIR = BUILD_OUTPUT_DIR + '/downloads'
BUILD_TMP_GENERAL_OUTPUT_DIR_NAME = 'general'
MODEL_OUTPUT_DIR_NAME = 'model'
MACE_RUN_STATIC_NAME = "mace_run_static"
MACE_RUN_DYNAMIC_NAME = "mace_run_dynamic"
L
liyin 已提交
454 455
MACE_RUN_STATIC_TARGET = "//mace/tools:" + MACE_RUN_STATIC_NAME
MACE_RUN_DYNAMIC_TARGET = "//mace/tools:" + MACE_RUN_DYNAMIC_NAME
L
liuqi 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468
CL_COMPILED_BINARY_FILE_NAME = "mace_cl_compiled_program.bin"
BUILD_TMP_OPENCL_BIN_DIR = 'opencl_bin'
LIBMACE_DYNAMIC_PATH = "bazel-bin/mace/libmace/libmace.so"
CL_TUNED_PARAMETER_FILE_NAME = "mace_run.config"
MODEL_HEADER_DIR_PATH = 'include/mace/public'
OUTPUT_LIBRARY_DIR_NAME = 'lib'
OUTPUT_OPENCL_BINARY_DIR_NAME = 'opencl'
OUTPUT_OPENCL_BINARY_FILE_NAME = 'compiled_opencl_kernel'
OUTPUT_OPENCL_PARAMETER_FILE_NAME = 'tuned_opencl_parameter'
CODEGEN_BASE_DIR = 'mace/codegen'
MODEL_CODEGEN_DIR = CODEGEN_BASE_DIR + '/models'
ENGINE_CODEGEN_DIR = CODEGEN_BASE_DIR + '/engine'
LIB_CODEGEN_DIR = CODEGEN_BASE_DIR + '/lib'
469
OPENCL_CODEGEN_DIR = CODEGEN_BASE_DIR + '/opencl'
L
liuqi 已提交
470 471 472 473
LIBMACE_SO_TARGET = "//mace/libmace:libmace.so"
LIBMACE_STATIC_TARGET = "//mace/libmace:libmace_static"
LIBMACE_STATIC_PATH = "bazel-genfiles/mace/libmace/libmace.a"
MODEL_LIB_TARGET = "//mace/codegen:generated_models"
L
Liangliang He 已提交
474
MODEL_LIB_PATH = "bazel-bin/mace/codegen/libgenerated_models.a"
L
liuqi 已提交
475 476 477 478 479 480 481 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


################################
# Model File Format
################################
class ModelFormat(object):
    file = 'file'
    code = 'code'


################################
# ABI Type
################################
class ABIType(object):
    armeabi_v7a = 'armeabi-v7a'
    arm64_v8a = 'arm64-v8a'
    arm64 = 'arm64'
    aarch64 = 'aarch64'
    armhf = 'armhf'
    host = 'host'


################################
# Module name
################################
class ModuleName(object):
    YAML_CONFIG = 'YAML CONFIG'
    MODEL_CONVERTER = 'Model Converter'
    RUN = 'RUN'


#################################
# mace lib type
#################################
class MACELibType(object):
    static = 0
    dynamic = 1


#################################
# Run time type
#################################
class RuntimeType(object):
    cpu = 'cpu'
    gpu = 'gpu'
    dsp = 'dsp'
B
Bin Li 已提交
521
    hta = 'hta'
522
    apu = 'apu'
L
liuqi 已提交
523 524 525 526 527 528 529 530 531 532
    cpu_gpu = 'cpu+gpu'


#################################
# Tool chain Type
#################################
class ToolchainType:
    android = 'android'
    arm_linux_gnueabihf = 'arm_linux_gnueabihf'
    aarch64_linux_gnu = 'aarch64_linux_gnu'
L
liuqi 已提交
533 534 535 536 537 538 539 540


#################################
# SOC tag
#################################
class TargetSOCTag:
    all = 'all'
    random = 'random'
L
liyin 已提交
541 542 543 544 545 546 547


def split_shape(shape):
    if shape.strip() == "":
        return []
    else:
        return shape.split(',')