blob: 3eff6bf8a81f1f4bcd623b7a31f10107db702895 [file] [log] [blame]
alexanderf4e2c472021-05-14 13:14:21 +01001#!/usr/bin/env python3
Isabella Gottardi2181d0a2021-04-07 09:27:38 +01002
3# Copyright (c) 2021 Arm Limited. All rights reserved.
4# SPDX-License-Identifier: Apache-2.0
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
18import os, errno
19import urllib.request
20import subprocess
21import fnmatch
22import logging
23import sys
24
25from argparse import ArgumentParser
26from urllib.error import URLError
Kshitij Sisodia3be26232021-10-29 12:29:06 +010027from collections import namedtuple
28
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010029
30json_uc_res = [{
31 "use_case_name": "ad",
32 "resources": [{"name": "ad_medium_int8.tflite",
33 "url": "https://github.com/ARM-software/ML-zoo/raw/7c32b097f7d94aae2cd0b98a8ed5a3ba81e66b18/models/anomaly_detection/micronet_medium/tflite_int8/ad_medium_int8.tflite"},
34 {"name": "ifm0.npy",
35 "url": "https://github.com/ARM-software/ML-zoo/raw/7c32b097f7d94aae2cd0b98a8ed5a3ba81e66b18/models/anomaly_detection/micronet_medium/tflite_int8/testing_input/input/0.npy"},
36 {"name": "ofm0.npy",
37 "url": "https://github.com/ARM-software/ML-zoo/raw/7c32b097f7d94aae2cd0b98a8ed5a3ba81e66b18/models/anomaly_detection/micronet_medium/tflite_int8/testing_output/Identity/0.npy"}]
38},
39 {
40 "use_case_name": "asr",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010041 "resources": [{"name": "wav2letter_pruned_int8.tflite",
42 "url": "https://github.com/ARM-software/ML-zoo/raw/1a92aa08c0de49a7304e0a7f3f59df6f4fd33ac8/models/speech_recognition/wav2letter/tflite_pruned_int8/wav2letter_pruned_int8.tflite"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010043 {"name": "ifm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010044 "url": "https://github.com/ARM-software/ML-zoo/raw/1a92aa08c0de49a7304e0a7f3f59df6f4fd33ac8/models/speech_recognition/wav2letter/tflite_pruned_int8/testing_input/input_2_int8/0.npy"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010045 {"name": "ofm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010046 "url": "https://github.com/ARM-software/ML-zoo/raw/1a92aa08c0de49a7304e0a7f3f59df6f4fd33ac8/models/speech_recognition/wav2letter/tflite_pruned_int8/testing_output/Identity_int8/0.npy"}]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010047 },
48 {
49 "use_case_name": "img_class",
Richard Burton0d110592021-08-12 17:26:30 +010050 "resources": [{"name": "mobilenet_v2_1.0_224_INT8.tflite",
51 "url": "https://github.com/ARM-software/ML-zoo/raw/e0aa361b03c738047b9147d1a50e3f2dcb13dbcb/models/image_classification/mobilenet_v2_1.0_224/tflite_int8/mobilenet_v2_1.0_224_INT8.tflite"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010052 {"name": "ifm0.npy",
Richard Burton0d110592021-08-12 17:26:30 +010053 "url": "https://github.com/ARM-software/ML-zoo/raw/e0aa361b03c738047b9147d1a50e3f2dcb13dbcb/models/image_classification/mobilenet_v2_1.0_224/tflite_int8/testing_input/tfl.quantize/0.npy"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010054 {"name": "ofm0.npy",
Richard Burton0d110592021-08-12 17:26:30 +010055 "url": "https://github.com/ARM-software/ML-zoo/raw/e0aa361b03c738047b9147d1a50e3f2dcb13dbcb/models/image_classification/mobilenet_v2_1.0_224/tflite_int8/testing_output/MobilenetV2/Predictions/Reshape_11/0.npy"}]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010056 },
57 {
58 "use_case_name": "kws",
59 "resources": [{"name": "ds_cnn_clustered_int8.tflite",
60 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/ds_cnn_clustered_int8.tflite"},
61 {"name": "ifm0.npy",
62 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/testing_input/input_2/0.npy"},
63 {"name": "ofm0.npy",
64 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/testing_output/Identity/0.npy"}]
65 },
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010066 {
67 "use_case_name": "vww",
68 "resources": [{"name": "vww4_128_128_INT8.tflite",
69 "url": "https://github.com/ARM-software/ML-zoo/raw/7dd3b16bb84007daf88be8648983c07f3eb21140/models/visual_wake_words/micronet_vww4/tflite_int8/vww4_128_128_INT8.tflite"},
70 {"name": "ifm0.npy",
71 "url": "https://github.com/ARM-software/ML-zoo/raw/7dd3b16bb84007daf88be8648983c07f3eb21140/models/visual_wake_words/micronet_vww4/tflite_int8/testing_input/input/0.npy"},
72 {"name": "ofm0.npy",
73 "url": "https://github.com/ARM-software/ML-zoo/raw/7dd3b16bb84007daf88be8648983c07f3eb21140/models/visual_wake_words/micronet_vww4/tflite_int8/testing_output/Identity/0.npy"}]
74 },
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010075 {
76 "use_case_name": "kws_asr",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010077 "resources": [{"name": "wav2letter_pruned_int8.tflite",
78 "url": "https://github.com/ARM-software/ML-zoo/raw/1a92aa08c0de49a7304e0a7f3f59df6f4fd33ac8/models/speech_recognition/wav2letter/tflite_pruned_int8/wav2letter_pruned_int8.tflite"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010079 {"sub_folder": "asr", "name": "ifm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010080 "url": "https://github.com/ARM-software/ML-zoo/raw/1a92aa08c0de49a7304e0a7f3f59df6f4fd33ac8/models/speech_recognition/wav2letter/tflite_pruned_int8/testing_input/input_2_int8/0.npy"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010081 {"sub_folder": "asr", "name": "ofm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010082 "url": "https://github.com/ARM-software/ML-zoo/raw/1a92aa08c0de49a7304e0a7f3f59df6f4fd33ac8/models/speech_recognition/wav2letter/tflite_pruned_int8/testing_output/Identity_int8/0.npy"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010083 {"name": "ds_cnn_clustered_int8.tflite",
84 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/ds_cnn_clustered_int8.tflite"},
85 {"sub_folder": "kws", "name": "ifm0.npy",
86 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/testing_input/input_2/0.npy"},
87 {"sub_folder": "kws", "name": "ofm0.npy",
88 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/testing_output/Identity/0.npy"}]
89 },
90 {
Richard Burton00553462021-11-10 16:27:14 +000091 "use_case_name": "noise_reduction",
92 "resources": [{"name": "rnnoise_INT8.tflite",
93 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/rnnoise_INT8.tflite"},
94 {"name": "ifm0.npy",
95 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_input/main_input_int8/0.npy"},
96 {"name": "ifm1.npy",
97 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_input/vad_gru_prev_state_int8/0.npy"},
98 {"name": "ifm2.npy",
99 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_input/noise_gru_prev_state_int8/0.npy"},
100 {"name": "ifm3.npy",
101 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_input/denoise_gru_prev_state_int8/0.npy"},
102 {"name": "ofm0.npy",
103 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_int8/0.npy"},
104 {"name": "ofm1.npy",
105 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_1_int8/0.npy"},
106 {"name": "ofm2.npy",
107 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_2_int8/0.npy"},
108 {"name": "ofm3.npy",
109 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_3_int8/0.npy"},
110 {"name": "ofm4.npy",
111 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_4_int8/0.npy"},
112 ]
113 },
114 {
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100115 "use_case_name": "inference_runner",
116 "resources": [{"name": "dnn_s_quantized.tflite",
117 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/dnn_small/tflite_int8/dnn_s_quantized.tflite"}
118 ]
119 },]
120
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100121# Valid NPU configurations:
122valid_npu_config_names = [
123 'ethos-u55-32', 'ethos-u55-64',
124 'ethos-u55-128', 'ethos-u55-256',
125 'ethos-u65-256','ethos-u65-512']
126
127# Default NPU configurations (these are always run when the models are optimised)
128default_npu_config_names = [valid_npu_config_names[2], valid_npu_config_names[4]]
129
130# NPU config named tuple
131NPUConfig = namedtuple('NPUConfig',['config_name',
132 'memory_mode',
133 'system_config',
134 'ethos_u_npu_id',
135 'ethos_u_config_id'])
136
Liam Barryb52b5852021-11-15 11:41:40 +0000137# The default internal SRAM size for Corstone-300 implementation on MPS3
138mps3_max_sram_sz = 4 * 1024 * 1024 # 4 MiB
139
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100140
141def call_command(command: str) -> str:
142 """
143 Helpers function that call subprocess and return the output.
144
145 Parameters:
146 ----------
147 command (string): Specifies the command to run.
148 """
149 logging.info(command)
alexander50a06502021-05-12 19:06:02 +0100150 proc = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
151 log = proc.stdout.decode("utf-8")
152 if proc.returncode == 0:
153 logging.info(log)
154 else:
155 logging.error(log)
156 proc.check_returncode()
157 return log
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100158
159
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100160def get_default_npu_config_from_name(config_name: str) -> NPUConfig:
161 """
162 Gets the file suffix for the tflite file from the
163 `accelerator_config` string.
164
165 Parameters:
166 ----------
167 config_name (str): Ethos-U NPU configuration from valid_npu_config_names
168
169 Returns:
170 -------
171 NPUConfig: An NPU config named tuple populated with defaults for the given
172 config name
173 """
174 if config_name not in valid_npu_config_names:
175 raise ValueError(f"""
176 Invalid Ethos-U NPU configuration.
177 Select one from {valid_npu_config_names}.
178 """)
179
180 strings_ids = ["ethos-u55-", "ethos-u65-"]
181 processor_ids = ["U55", "U65"]
182 prefix_ids = ["H", "Y"]
183 memory_modes = ["Shared_Sram", "Dedicated_Sram"]
184 system_configs = ["Ethos_U55_High_End_Embedded", "Ethos_U65_High_End"]
185
186 for i in range(len(strings_ids)):
187 if config_name.startswith(strings_ids[i]):
188 npu_config_id = config_name.replace(strings_ids[i], prefix_ids[i])
189 return NPUConfig(config_name=config_name,
190 memory_mode=memory_modes[i],
191 system_config=system_configs[i],
192 ethos_u_npu_id=processor_ids[i],
193 ethos_u_config_id=npu_config_id)
194
195 return None
196
197
Liam Barryb52b5852021-11-15 11:41:40 +0000198def set_up_resources(run_vela_on_models=False,
199 additional_npu_config_names=[],
200 arena_cache_size=mps3_max_sram_sz):
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100201 """
202 Helpers function that retrieve the output from a command.
203
204 Parameters:
205 ----------
206 run_vela_on_models (bool): Specifies if run vela on downloaded models.
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100207 additional_npu_config_names(list): list of strings of Ethos-U NPU configs.
Liam Barryb52b5852021-11-15 11:41:40 +0000208 arena_cache_size(int): Specifies arena cache size in bytes.
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100209 """
210 current_file_dir = os.path.dirname(os.path.abspath(__file__))
211 download_dir = os.path.abspath(os.path.join(current_file_dir, "resources_downloaded"))
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100212
213 try:
214 # 1.1 Does the download dir exist?
215 os.mkdir(download_dir)
216 except OSError as e:
217 if e.errno == errno.EEXIST:
218 logging.info("'resources_downloaded' directory exists.")
219 else:
220 raise
221
222 # 1.2 Does the virtual environment exist?
223 env_python = str(os.path.abspath(os.path.join(download_dir, "env", "bin", "python3")))
224 env_activate = str(os.path.abspath(os.path.join(download_dir, "env", "bin", "activate")))
225 if not os.path.isdir(os.path.join(download_dir, "env")):
226 os.chdir(download_dir)
227 # Create the virtual environment
228 command = "python3 -m venv env"
229 call_command(command)
230 commands = ["pip install --upgrade pip", "pip install --upgrade setuptools"]
231 for c in commands:
232 command = f"{env_python} -m {c}"
233 call_command(command)
234 os.chdir(current_file_dir)
235 # 1.3 Make sure to have all the requirement
Nina Drozdf6753c92021-09-07 09:41:28 +0100236 requirements = ["ethos-u-vela==3.1.0"]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100237 command = f"{env_python} -m pip freeze"
238 packages = call_command(command)
239 for req in requirements:
240 if req not in packages:
241 command = f"{env_python} -m pip install {req}"
242 call_command(command)
243
244 # 2. Download models
245 for uc in json_uc_res:
246 try:
247 # Does the usecase_name download dir exist?
248 os.mkdir(os.path.join(download_dir, uc["use_case_name"]))
249 except OSError as e:
250 if e.errno != errno.EEXIST:
251 logging.error(f"Error creating {uc['use_case_name']} directory.")
252 raise
253
254 for res in uc["resources"]:
255 res_name = res["name"]
256 res_url = res["url"]
257 if "sub_folder" in res:
258 try:
259 # Does the usecase_name/sub_folder download dir exist?
260 os.mkdir(os.path.join(download_dir, uc["use_case_name"], res["sub_folder"]))
261 except OSError as e:
262 if e.errno != errno.EEXIST:
263 logging.error(f"Error creating {uc['use_case_name']} / {res['sub_folder']} directory.")
264 raise
265 res_dst = os.path.join(download_dir,
266 uc["use_case_name"],
267 res["sub_folder"],
268 res_name)
269 else:
270 res_dst = os.path.join(download_dir,
271 uc["use_case_name"],
272 res_name)
alexander3ef1fd42021-05-24 18:56:32 +0100273
274 if os.path.isfile(res_dst):
275 logging.info(f"File {res_dst} exists, skipping download.")
276 else:
277 try:
278 g = urllib.request.urlopen(res_url)
279 with open(res_dst, 'b+w') as f:
280 f.write(g.read())
281 logging.info(f"- Downloaded {res_url} to {res_dst}.")
282 except URLError:
283 logging.error(f"URLError while downloading {res_url}.")
284 raise
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100285
286 # 3. Run vela on models in resources_downloaded
287 # New models will have same name with '_vela' appended.
288 # For example:
289 # original model: ds_cnn_clustered_int8.tflite
alexander50a06502021-05-12 19:06:02 +0100290 # after vela model: ds_cnn_clustered_int8_vela_H128.tflite
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100291 #
292 # Note: To avoid to run vela twice on the same model, it's supposed that
293 # downloaded model names don't contain the 'vela' word.
294 if run_vela_on_models is True:
295 config_file = os.path.join(current_file_dir, "scripts", "vela", "default_vela.ini")
296 models = [os.path.join(dirpath, f)
297 for dirpath, dirnames, files in os.walk(download_dir)
298 for f in fnmatch.filter(files, '*.tflite') if "vela" not in f]
299
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100300 # Consolidate all config names while discarding duplicates:
301 config_names = list(set(default_npu_config_names + additional_npu_config_names))
302
303 # Get npu config tuple for each config name in a list:
304 npu_configs = [get_default_npu_config_from_name(name) for name in config_names]
305
306 logging.info(f'All models will be optimised for these configs:')
307 for config in npu_configs:
308 logging.info(config)
309
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100310 for model in models:
311 output_dir = os.path.dirname(model)
alexander3ef1fd42021-05-24 18:56:32 +0100312 # model name after compiling with vela is an initial model name + _vela suffix
313 vela_optimised_model_path = str(model).replace(".tflite", "_vela.tflite")
alexander3ef1fd42021-05-24 18:56:32 +0100314
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100315 for config in npu_configs:
316 vela_command = (f". {env_activate} && vela {model} " +
317 f"--accelerator-config={config.config_name} " +
alexanderd475f092021-06-24 15:36:49 +0100318 "--optimise Performance " +
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100319 f"--config {config_file} " +
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100320 f"--memory-mode={config.memory_mode} " +
321 f"--system-config={config.system_config} " +
Liam Barryb52b5852021-11-15 11:41:40 +0000322 f"--output-dir={output_dir} " +
323 f"--arena-cache-size={arena_cache_size} ")
alexander3ef1fd42021-05-24 18:56:32 +0100324
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100325 # we want the name to include the configuration suffix. For example: vela_H128,
326 # vela_Y512 etc.
327 new_suffix = "_vela_" + config.ethos_u_config_id + '.tflite'
328 new_vela_optimised_model_path = (
329 vela_optimised_model_path.replace("_vela.tflite", new_suffix))
Isabella Gottardi118f73e2021-09-16 17:54:35 +0100330
331 if os.path.isfile(new_vela_optimised_model_path):
332 logging.info(f"File {new_vela_optimised_model_path} exists, skipping optimisation.")
333 continue
334
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100335 call_command(vela_command)
Isabella Gottardi118f73e2021-09-16 17:54:35 +0100336
337 # rename default vela model
338 os.rename(vela_optimised_model_path, new_vela_optimised_model_path)
339 logging.info(f"Renaming {vela_optimised_model_path} to {new_vela_optimised_model_path}.")
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100340
341
342if __name__ == '__main__':
343 parser = ArgumentParser()
344 parser.add_argument("--skip-vela",
345 help="Do not run Vela optimizer on downloaded models.",
346 action="store_true")
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100347 parser.add_argument("--additional-ethos-u-config-name",
348 help=f"""Additional (non-default) configurations for Vela:
349 {valid_npu_config_names}""",
350 default=[], action="append")
Liam Barryb52b5852021-11-15 11:41:40 +0000351 parser.add_argument("--arena-cache-size",
352 help="Arena cache size in bytes",
353 type=int,
354 default=mps3_max_sram_sz)
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100355 args = parser.parse_args()
Kshitij Sisodiab9e9c892021-05-27 13:57:35 +0100356
357 logging.basicConfig(filename='log_build_default.log', level=logging.DEBUG)
358 logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
359
Liam Barryb52b5852021-11-15 11:41:40 +0000360 set_up_resources(not args.skip_vela,
361 args.additional_ethos_u_config_name,
362 args.arena_cache_size)