Jonathan Strandberg | d2afc51 | 2021-03-19 10:31:18 +0100 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | |
| 3 | # |
| 4 | # Copyright (c) 2021 Arm Limited. All rights reserved. |
| 5 | # |
| 6 | # SPDX-License-Identifier: Apache-2.0 |
| 7 | # |
| 8 | # Licensed under the Apache License, Version 2.0 (the License); you may |
| 9 | # not use this file except in compliance with the License. |
| 10 | # You may obtain a copy of the License at |
| 11 | # |
| 12 | # www.apache.org/licenses/LICENSE-2.0 |
| 13 | # |
| 14 | # Unless required by applicable law or agreed to in writing, software |
| 15 | # distributed under the License is distributed on an AS IS BASIS, WITHOUT |
| 16 | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | # See the License for the specific language governing permissions and |
| 18 | # limitations under the License. |
| 19 | # |
| 20 | |
| 21 | import argparse |
| 22 | import multiprocessing |
| 23 | import numpy |
| 24 | import os |
| 25 | import pathlib |
| 26 | import re |
| 27 | import shutil |
| 28 | import subprocess |
| 29 | import sys |
| 30 | |
| 31 | os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' |
| 32 | from tensorflow.lite.python.interpreter import Interpreter |
| 33 | |
| 34 | |
| 35 | CORE_PLATFORM_PATH = pathlib.Path(__file__).resolve().parents[1] |
| 36 | |
| 37 | def run_cmd(cmd, **kwargs): |
| 38 | # str() is called to handle pathlib.Path objects |
| 39 | cmd_str = " ".join([str(arg) for arg in cmd]) |
| 40 | print(f"Running command: {cmd_str}") |
| 41 | return subprocess.run(cmd, check=True, **kwargs) |
| 42 | |
| 43 | def build_core_platform(output_folder, target, toolchain): |
| 44 | build_folder = output_folder/"model"/"build" |
| 45 | cmake_cmd = ["cmake", |
| 46 | CORE_PLATFORM_PATH/"targets"/target, |
| 47 | f"-B{build_folder}", |
| 48 | f"-DCMAKE_TOOLCHAIN_FILE={CORE_PLATFORM_PATH/'cmake'/'toolchain'/(toolchain + '.cmake')}", |
| 49 | f"-DBAREMETAL_PATH={output_folder}"] |
| 50 | |
| 51 | run_cmd(cmake_cmd) |
| 52 | |
| 53 | make_cmd = ["make", "-C", build_folder, f"-j{multiprocessing.cpu_count()}"] |
| 54 | run_cmd(make_cmd) |
| 55 | |
| 56 | def generate_reference_data(output_folder, non_optimized_model_path, input_path, expected_output_path): |
| 57 | interpreter = Interpreter(model_path=str(non_optimized_model_path.resolve())) |
| 58 | |
| 59 | interpreter.allocate_tensors() |
| 60 | input_detail = interpreter.get_input_details()[0] |
| 61 | output_detail = interpreter.get_output_details()[0] |
| 62 | |
| 63 | input_data = None |
| 64 | if input_path is None: |
| 65 | # Randomly generate input data |
| 66 | dtype = input_detail["dtype"] |
| 67 | if dtype is numpy.float32: |
| 68 | rand = numpy.random.default_rng() |
| 69 | input_data = rand.random(size=input_detail["shape"], dtype=numpy.float32) |
| 70 | else: |
| 71 | input_data = numpy.random.randint(low=numpy.iinfo(dtype).min, high=numpy.iinfo(dtype).max, size=input_detail["shape"], dtype=dtype) |
| 72 | else: |
| 73 | # Load user provided input data |
| 74 | input_data = numpy.load(input_path) |
| 75 | |
| 76 | output_data = None |
| 77 | if expected_output_path is None: |
| 78 | # Run the network with input_data to get reference output |
| 79 | interpreter.set_tensor(input_detail["index"], input_data) |
| 80 | interpreter.invoke() |
| 81 | output_data = interpreter.get_tensor(output_detail["index"]) |
| 82 | else: |
| 83 | # Load user provided output data |
| 84 | output_data = numpy.load(expected_output_path) |
| 85 | |
| 86 | network_input_path = output_folder/"ref_input.bin" |
| 87 | network_output_path = output_folder/"ref_output.bin" |
| 88 | |
| 89 | with network_input_path.open("wb") as fp: |
| 90 | fp.write(input_data.tobytes()) |
| 91 | with network_output_path.open("wb") as fp: |
| 92 | fp.write(output_data.tobytes()) |
| 93 | |
| 94 | output_folder = pathlib.Path(output_folder) |
| 95 | dump_c_header(network_input_path, output_folder/"input.h", "inputData", "input_data_sec", 4) |
| 96 | dump_c_header(network_output_path, output_folder/"output.h", "expectedOutputData", "expected_output_data_sec", 4) |
| 97 | |
| 98 | def dump_c_header(input_path, output_path, array_name, section, alignment, extra_data=""): |
| 99 | byte_array = [] |
| 100 | with open(input_path, "rb") as fp: |
| 101 | byte_string = fp.read() |
| 102 | byte_array = [f"0x{format(byte, '02x')}" for byte in byte_string] |
| 103 | |
| 104 | last = byte_array[-1] |
| 105 | byte_array = [byte + "," for byte in byte_array[:-1]] + [last] |
| 106 | |
| 107 | byte_array = [" " + byte if idx % 12 == 0 else byte |
| 108 | for idx, byte in enumerate(byte_array)] |
| 109 | |
| 110 | byte_array = [byte + "\n" if (idx + 1) % 12 == 0 else byte + " " |
| 111 | for idx, byte in enumerate(byte_array)] |
| 112 | |
| 113 | with open(output_path, "w") as carray: |
| 114 | header = f"uint8_t {array_name}[] __attribute__((section(\"{section}\"), aligned({alignment}))) = {{\n" |
| 115 | carray.write(extra_data) |
| 116 | carray.write(header) |
| 117 | carray.write("".join(byte_array)) |
| 118 | carray.write("\n};\n") |
| 119 | |
| 120 | def optimize_network(output_folder, network_path, accelerator_conf): |
| 121 | vela_cmd = ["vela", |
| 122 | network_path, |
| 123 | "--output-dir", output_folder, |
| 124 | "--accelerator-config", accelerator_conf] |
| 125 | res = run_cmd(vela_cmd) |
| 126 | optimized_model_path = output_folder/(network_path.stem + "_vela.tflite") |
| 127 | model_name = network_path.stem |
| 128 | dump_c_header(optimized_model_path, output_folder/"model.h", "networkModelData", "network_model_sec", 16, extra_data=f"const char *modelName=\"{model_name}\";\n") |
| 129 | |
| 130 | def run_model(output_folder): |
| 131 | build_folder = output_folder/"model"/"build" |
| 132 | model_cmd = ["ctest", "-V", "-R", "^baremetal_custom$" ] |
| 133 | res = run_cmd(model_cmd, cwd=build_folder) |
| 134 | |
| 135 | def main(): |
| 136 | target_mapping = { |
| 137 | "corstone-300": "ethos-u55-128" |
| 138 | } |
| 139 | parser = argparse.ArgumentParser() |
| 140 | parser.add_argument("-o", "--output-folder", type=pathlib.Path, default="output", help="Output folder for build and generated files") |
| 141 | parser.add_argument("--network-path", type=pathlib.Path, required=True, help="Path to .tflite file") |
| 142 | parser.add_argument("--target", choices=target_mapping, default="corstone-300", help=f"Configure target") |
| 143 | parser.add_argument("--toolchain", choices=["armclang", "arm-none-eabi-gcc"], default="armclang", help=f"Configure toolchain") |
| 144 | parser.add_argument("--custom-input", type=pathlib.Path, help="Custom input to network") |
| 145 | parser.add_argument("--custom-output", type=pathlib.Path, help="Custom expected output data for network") |
| 146 | |
| 147 | args = parser.parse_args() |
| 148 | |
| 149 | args.output_folder.mkdir(exist_ok=True) |
| 150 | |
| 151 | try: |
| 152 | optimize_network(args.output_folder, args.network_path, target_mapping[args.target]) |
| 153 | generate_reference_data(args.output_folder, args.network_path, args.custom_input, args.custom_output) |
| 154 | build_core_platform(args.output_folder, args.target, args.toolchain) |
| 155 | run_model(args.output_folder) |
| 156 | except subprocess.CalledProcessError as err: |
| 157 | print(f"Command: '{err.cmd}' failed", file=sys.stderr) |
| 158 | return 1 |
| 159 | return 0 |
| 160 | |
| 161 | if __name__ == "__main__": |
| 162 | sys.exit(main()) |