blob: 93ba7cd41fc3c4272092083d05e9024237a8b5ef [file] [log] [blame]
Jonathan Strandbergd2afc512021-03-19 10:31:18 +01001#!/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
21import argparse
22import multiprocessing
23import numpy
24import os
25import pathlib
26import re
27import shutil
28import subprocess
29import sys
30
31os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
Kristofer Jonssonffbd8e72021-06-15 17:51:58 +020032from tensorflow.lite.python.interpreter import Interpreter, OpResolverType
Jonathan Strandbergd2afc512021-03-19 10:31:18 +010033
34CORE_PLATFORM_PATH = pathlib.Path(__file__).resolve().parents[1]
35
36def run_cmd(cmd, **kwargs):
37 # str() is called to handle pathlib.Path objects
38 cmd_str = " ".join([str(arg) for arg in cmd])
39 print(f"Running command: {cmd_str}")
40 return subprocess.run(cmd, check=True, **kwargs)
41
42def build_core_platform(output_folder, target, toolchain):
43 build_folder = output_folder/"model"/"build"
44 cmake_cmd = ["cmake",
45 CORE_PLATFORM_PATH/"targets"/target,
46 f"-B{build_folder}",
47 f"-DCMAKE_TOOLCHAIN_FILE={CORE_PLATFORM_PATH/'cmake'/'toolchain'/(toolchain + '.cmake')}",
48 f"-DBAREMETAL_PATH={output_folder}"]
49
50 run_cmd(cmake_cmd)
51
Kristofer Jonssonffbd8e72021-06-15 17:51:58 +020052 make_cmd = ["make", "-C", build_folder, f"-j{multiprocessing.cpu_count()}", "baremetal_custom"]
Jonathan Strandbergd2afc512021-03-19 10:31:18 +010053 run_cmd(make_cmd)
54
55def generate_reference_data(output_folder, non_optimized_model_path, input_path, expected_output_path):
Kristofer Jonssonffbd8e72021-06-15 17:51:58 +020056 interpreter = Interpreter(model_path=str(non_optimized_model_path.resolve()), experimental_op_resolver_type=OpResolverType.BUILTIN_REF)
Jonathan Strandbergd2afc512021-03-19 10:31:18 +010057
58 interpreter.allocate_tensors()
59 input_detail = interpreter.get_input_details()[0]
60 output_detail = interpreter.get_output_details()[0]
61
62 input_data = None
63 if input_path is None:
64 # Randomly generate input data
65 dtype = input_detail["dtype"]
66 if dtype is numpy.float32:
67 rand = numpy.random.default_rng()
68 input_data = rand.random(size=input_detail["shape"], dtype=numpy.float32)
69 else:
70 input_data = numpy.random.randint(low=numpy.iinfo(dtype).min, high=numpy.iinfo(dtype).max, size=input_detail["shape"], dtype=dtype)
71 else:
72 # Load user provided input data
73 input_data = numpy.load(input_path)
74
75 output_data = None
76 if expected_output_path is None:
77 # Run the network with input_data to get reference output
78 interpreter.set_tensor(input_detail["index"], input_data)
79 interpreter.invoke()
80 output_data = interpreter.get_tensor(output_detail["index"])
81 else:
82 # Load user provided output data
83 output_data = numpy.load(expected_output_path)
84
85 network_input_path = output_folder/"ref_input.bin"
86 network_output_path = output_folder/"ref_output.bin"
87
88 with network_input_path.open("wb") as fp:
89 fp.write(input_data.tobytes())
90 with network_output_path.open("wb") as fp:
91 fp.write(output_data.tobytes())
92
93 output_folder = pathlib.Path(output_folder)
94 dump_c_header(network_input_path, output_folder/"input.h", "inputData", "input_data_sec", 4)
95 dump_c_header(network_output_path, output_folder/"output.h", "expectedOutputData", "expected_output_data_sec", 4)
96
97def dump_c_header(input_path, output_path, array_name, section, alignment, extra_data=""):
98 byte_array = []
99 with open(input_path, "rb") as fp:
100 byte_string = fp.read()
101 byte_array = [f"0x{format(byte, '02x')}" for byte in byte_string]
102
103 last = byte_array[-1]
104 byte_array = [byte + "," for byte in byte_array[:-1]] + [last]
105
106 byte_array = [" " + byte if idx % 12 == 0 else byte
107 for idx, byte in enumerate(byte_array)]
108
109 byte_array = [byte + "\n" if (idx + 1) % 12 == 0 else byte + " "
110 for idx, byte in enumerate(byte_array)]
111
112 with open(output_path, "w") as carray:
113 header = f"uint8_t {array_name}[] __attribute__((section(\"{section}\"), aligned({alignment}))) = {{\n"
114 carray.write(extra_data)
115 carray.write(header)
116 carray.write("".join(byte_array))
117 carray.write("\n};\n")
118
119def optimize_network(output_folder, network_path, accelerator_conf):
120 vela_cmd = ["vela",
121 network_path,
122 "--output-dir", output_folder,
123 "--accelerator-config", accelerator_conf]
124 res = run_cmd(vela_cmd)
125 optimized_model_path = output_folder/(network_path.stem + "_vela.tflite")
126 model_name = network_path.stem
127 dump_c_header(optimized_model_path, output_folder/"model.h", "networkModelData", "network_model_sec", 16, extra_data=f"const char *modelName=\"{model_name}\";\n")
128
129def run_model(output_folder):
130 build_folder = output_folder/"model"/"build"
131 model_cmd = ["ctest", "-V", "-R", "^baremetal_custom$" ]
132 res = run_cmd(model_cmd, cwd=build_folder)
133
134def main():
135 target_mapping = {
136 "corstone-300": "ethos-u55-128"
137 }
138 parser = argparse.ArgumentParser()
139 parser.add_argument("-o", "--output-folder", type=pathlib.Path, default="output", help="Output folder for build and generated files")
140 parser.add_argument("--network-path", type=pathlib.Path, required=True, help="Path to .tflite file")
141 parser.add_argument("--target", choices=target_mapping, default="corstone-300", help=f"Configure target")
142 parser.add_argument("--toolchain", choices=["armclang", "arm-none-eabi-gcc"], default="armclang", help=f"Configure toolchain")
143 parser.add_argument("--custom-input", type=pathlib.Path, help="Custom input to network")
144 parser.add_argument("--custom-output", type=pathlib.Path, help="Custom expected output data for network")
145
146 args = parser.parse_args()
147
148 args.output_folder.mkdir(exist_ok=True)
149
150 try:
151 optimize_network(args.output_folder, args.network_path, target_mapping[args.target])
152 generate_reference_data(args.output_folder, args.network_path, args.custom_input, args.custom_output)
153 build_core_platform(args.output_folder, args.target, args.toolchain)
154 run_model(args.output_folder)
155 except subprocess.CalledProcessError as err:
156 print(f"Command: '{err.cmd}' failed", file=sys.stderr)
157 return 1
158 return 0
159
160if __name__ == "__main__":
161 sys.exit(main())