blob: 5ff829eb69d0f244db09da9ddd5dba3dca57e41d [file] [log] [blame]
alexanderf4e2c472021-05-14 13:14:21 +01001#!/usr/bin/env python3
Isabella Gottardi2181d0a2021-04-07 09:27:38 +01002
Michael Levit06fcf752022-01-12 11:53:46 +02003# Copyright (c) 2022 Arm Limited. All rights reserved.
Isabella Gottardi2181d0a2021-04-07 09:27:38 +01004# 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
Isabella Gottardi3acaaee2021-11-30 12:33:27 +000025from argparse import ArgumentParser, ArgumentTypeError
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010026from 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 {
Michael Levit06fcf752022-01-12 11:53:46 +020058 "use_case_name": "object_detection",
59 "resources": [{"name": "yolo-fastest_192_face_v4.tflite",
60 "url": "https://github.com/emza-vs/ModelZoo/blob/v1.0/object_detection/yolo-fastest_192_face_v4.tflite?raw=true"}]
61 },
62 {
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010063 "use_case_name": "kws",
Kshitij Sisodia76a15802021-12-24 11:05:11 +000064 "resources": [{"name": "ifm0.npy",
65 "url": "https://github.com/ARM-software/ML-zoo/raw/9f506fe52b39df545f0e6c5ff9223f671bc5ae00/models/keyword_spotting/micronet_medium/tflite_int8/testing_input/input/0.npy"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010066 {"name": "ofm0.npy",
Kshitij Sisodia76a15802021-12-24 11:05:11 +000067 "url": "https://github.com/ARM-software/ML-zoo/raw/9f506fe52b39df545f0e6c5ff9223f671bc5ae00/models/keyword_spotting/micronet_medium/tflite_int8/testing_output/Identity/0.npy"},
68 {"name": "kws_micronet_m.tflite",
69 "url": " https://github.com/ARM-software/ML-zoo/raw/9f506fe52b39df545f0e6c5ff9223f671bc5ae00/models/keyword_spotting/micronet_medium/tflite_int8/kws_micronet_m.tflite"}]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010070 },
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010071 {
72 "use_case_name": "vww",
73 "resources": [{"name": "vww4_128_128_INT8.tflite",
74 "url": "https://github.com/ARM-software/ML-zoo/raw/7dd3b16bb84007daf88be8648983c07f3eb21140/models/visual_wake_words/micronet_vww4/tflite_int8/vww4_128_128_INT8.tflite"},
75 {"name": "ifm0.npy",
76 "url": "https://github.com/ARM-software/ML-zoo/raw/7dd3b16bb84007daf88be8648983c07f3eb21140/models/visual_wake_words/micronet_vww4/tflite_int8/testing_input/input/0.npy"},
77 {"name": "ofm0.npy",
78 "url": "https://github.com/ARM-software/ML-zoo/raw/7dd3b16bb84007daf88be8648983c07f3eb21140/models/visual_wake_words/micronet_vww4/tflite_int8/testing_output/Identity/0.npy"}]
79 },
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010080 {
81 "use_case_name": "kws_asr",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010082 "resources": [{"name": "wav2letter_pruned_int8.tflite",
83 "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 +010084 {"sub_folder": "asr", "name": "ifm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010085 "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 +010086 {"sub_folder": "asr", "name": "ofm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010087 "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 +010088 {"sub_folder": "kws", "name": "ifm0.npy",
Kshitij Sisodia76a15802021-12-24 11:05:11 +000089 "url": "https://github.com/ARM-software/ML-zoo/raw/9f506fe52b39df545f0e6c5ff9223f671bc5ae00/models/keyword_spotting/micronet_medium/tflite_int8/testing_input/input/0.npy"},
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010090 {"sub_folder": "kws", "name": "ofm0.npy",
Kshitij Sisodia76a15802021-12-24 11:05:11 +000091 "url": "https://github.com/ARM-software/ML-zoo/raw/9f506fe52b39df545f0e6c5ff9223f671bc5ae00/models/keyword_spotting/micronet_medium/tflite_int8/testing_output/Identity/0.npy"},
92 {"name": "kws_micronet_m.tflite",
93 "url": "https://github.com/ARM-software/ML-zoo/raw/9f506fe52b39df545f0e6c5ff9223f671bc5ae00/models/keyword_spotting/micronet_medium/tflite_int8/kws_micronet_m.tflite"}]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010094 },
95 {
Richard Burton00553462021-11-10 16:27:14 +000096 "use_case_name": "noise_reduction",
97 "resources": [{"name": "rnnoise_INT8.tflite",
98 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/rnnoise_INT8.tflite"},
99 {"name": "ifm0.npy",
100 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_input/main_input_int8/0.npy"},
101 {"name": "ifm1.npy",
102 "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"},
103 {"name": "ifm2.npy",
104 "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"},
105 {"name": "ifm3.npy",
106 "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"},
107 {"name": "ofm0.npy",
108 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_int8/0.npy"},
109 {"name": "ofm1.npy",
110 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_1_int8/0.npy"},
111 {"name": "ofm2.npy",
112 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_2_int8/0.npy"},
113 {"name": "ofm3.npy",
114 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_3_int8/0.npy"},
115 {"name": "ofm4.npy",
116 "url": "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/testing_output/Identity_4_int8/0.npy"},
117 ]
118 },
119 {
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100120 "use_case_name": "inference_runner",
121 "resources": [{"name": "dnn_s_quantized.tflite",
122 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/dnn_small/tflite_int8/dnn_s_quantized.tflite"}
123 ]
124 },]
125
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100126# Valid NPU configurations:
127valid_npu_config_names = [
128 'ethos-u55-32', 'ethos-u55-64',
129 'ethos-u55-128', 'ethos-u55-256',
130 'ethos-u65-256','ethos-u65-512']
131
132# Default NPU configurations (these are always run when the models are optimised)
133default_npu_config_names = [valid_npu_config_names[2], valid_npu_config_names[4]]
134
135# NPU config named tuple
136NPUConfig = namedtuple('NPUConfig',['config_name',
137 'memory_mode',
138 'system_config',
139 'ethos_u_npu_id',
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000140 'ethos_u_config_id',
141 'arena_cache_size'])
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100142
Kshitij Sisodia661959c2021-11-24 10:39:52 +0000143# The internal SRAM size for Corstone-300 implementation on MPS3 specified by AN552
144mps3_max_sram_sz = 2 * 1024 * 1024 # 2 MiB (2 banks of 1 MiB each)
Liam Barryb52b5852021-11-15 11:41:40 +0000145
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100146
147def call_command(command: str) -> str:
148 """
149 Helpers function that call subprocess and return the output.
150
151 Parameters:
152 ----------
153 command (string): Specifies the command to run.
154 """
155 logging.info(command)
alexander50a06502021-05-12 19:06:02 +0100156 proc = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
157 log = proc.stdout.decode("utf-8")
158 if proc.returncode == 0:
159 logging.info(log)
160 else:
161 logging.error(log)
162 proc.check_returncode()
163 return log
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100164
165
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000166def get_default_npu_config_from_name(config_name: str, arena_cache_size: int = 0) -> NPUConfig:
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100167 """
168 Gets the file suffix for the tflite file from the
169 `accelerator_config` string.
170
171 Parameters:
172 ----------
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000173 config_name (str): Ethos-U NPU configuration from valid_npu_config_names
174
175 arena_cache_size (int): Specifies arena cache size in bytes. If a value
176 greater than 0 is provided, this will be taken
177 as the cache size. If 0, the default values, as per
178 the NPU config requirements, are used.
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100179
180 Returns:
181 -------
182 NPUConfig: An NPU config named tuple populated with defaults for the given
183 config name
184 """
185 if config_name not in valid_npu_config_names:
186 raise ValueError(f"""
187 Invalid Ethos-U NPU configuration.
188 Select one from {valid_npu_config_names}.
189 """)
190
191 strings_ids = ["ethos-u55-", "ethos-u65-"]
192 processor_ids = ["U55", "U65"]
193 prefix_ids = ["H", "Y"]
194 memory_modes = ["Shared_Sram", "Dedicated_Sram"]
195 system_configs = ["Ethos_U55_High_End_Embedded", "Ethos_U65_High_End"]
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000196 memory_modes_arena = {
197 # For shared SRAM memory mode, we use the MPS3 SRAM size by default
198 "Shared_Sram" : mps3_max_sram_sz if arena_cache_size <= 0 else arena_cache_size,
199 # For dedicated SRAM memory mode, we do no override the arena size. This is expected to
200 # be defined in the vela configuration file instead.
201 "Dedicated_Sram" : None if arena_cache_size <= 0 else arena_cache_size
202 }
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100203
204 for i in range(len(strings_ids)):
205 if config_name.startswith(strings_ids[i]):
206 npu_config_id = config_name.replace(strings_ids[i], prefix_ids[i])
207 return NPUConfig(config_name=config_name,
208 memory_mode=memory_modes[i],
209 system_config=system_configs[i],
210 ethos_u_npu_id=processor_ids[i],
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000211 ethos_u_config_id=npu_config_id,
212 arena_cache_size=memory_modes_arena[memory_modes[i]])
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100213
214 return None
215
216
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000217def set_up_resources(run_vela_on_models: bool = False,
218 additional_npu_config_names: list = [],
219 arena_cache_size: int = 0):
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100220 """
221 Helpers function that retrieve the output from a command.
222
223 Parameters:
224 ----------
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000225 run_vela_on_models (bool): Specifies if run vela on downloaded models.
226 additional_npu_config_names(list): list of strings of Ethos-U NPU configs.
227 arena_cache_size (int): Specifies arena cache size in bytes. If a value
228 greater than 0 is provided, this will be taken
229 as the cache size. If 0, the default values, as per
230 the NPU config requirements, are used.
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100231 """
232 current_file_dir = os.path.dirname(os.path.abspath(__file__))
233 download_dir = os.path.abspath(os.path.join(current_file_dir, "resources_downloaded"))
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100234
235 try:
236 # 1.1 Does the download dir exist?
237 os.mkdir(download_dir)
238 except OSError as e:
239 if e.errno == errno.EEXIST:
240 logging.info("'resources_downloaded' directory exists.")
241 else:
242 raise
243
244 # 1.2 Does the virtual environment exist?
245 env_python = str(os.path.abspath(os.path.join(download_dir, "env", "bin", "python3")))
246 env_activate = str(os.path.abspath(os.path.join(download_dir, "env", "bin", "activate")))
247 if not os.path.isdir(os.path.join(download_dir, "env")):
248 os.chdir(download_dir)
249 # Create the virtual environment
250 command = "python3 -m venv env"
251 call_command(command)
252 commands = ["pip install --upgrade pip", "pip install --upgrade setuptools"]
253 for c in commands:
254 command = f"{env_python} -m {c}"
255 call_command(command)
256 os.chdir(current_file_dir)
257 # 1.3 Make sure to have all the requirement
Richard Burton2de7ba02021-11-30 15:51:15 +0000258 requirements = ["ethos-u-vela==3.2.0"]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100259 command = f"{env_python} -m pip freeze"
260 packages = call_command(command)
261 for req in requirements:
262 if req not in packages:
263 command = f"{env_python} -m pip install {req}"
264 call_command(command)
265
266 # 2. Download models
267 for uc in json_uc_res:
268 try:
269 # Does the usecase_name download dir exist?
270 os.mkdir(os.path.join(download_dir, uc["use_case_name"]))
271 except OSError as e:
272 if e.errno != errno.EEXIST:
273 logging.error(f"Error creating {uc['use_case_name']} directory.")
274 raise
275
276 for res in uc["resources"]:
277 res_name = res["name"]
278 res_url = res["url"]
279 if "sub_folder" in res:
280 try:
281 # Does the usecase_name/sub_folder download dir exist?
282 os.mkdir(os.path.join(download_dir, uc["use_case_name"], res["sub_folder"]))
283 except OSError as e:
284 if e.errno != errno.EEXIST:
285 logging.error(f"Error creating {uc['use_case_name']} / {res['sub_folder']} directory.")
286 raise
287 res_dst = os.path.join(download_dir,
288 uc["use_case_name"],
289 res["sub_folder"],
290 res_name)
291 else:
292 res_dst = os.path.join(download_dir,
293 uc["use_case_name"],
294 res_name)
alexander3ef1fd42021-05-24 18:56:32 +0100295
296 if os.path.isfile(res_dst):
297 logging.info(f"File {res_dst} exists, skipping download.")
298 else:
299 try:
300 g = urllib.request.urlopen(res_url)
301 with open(res_dst, 'b+w') as f:
302 f.write(g.read())
303 logging.info(f"- Downloaded {res_url} to {res_dst}.")
304 except URLError:
305 logging.error(f"URLError while downloading {res_url}.")
306 raise
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100307
308 # 3. Run vela on models in resources_downloaded
309 # New models will have same name with '_vela' appended.
310 # For example:
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000311 # original model: kws_micronet_m.tflite
312 # after vela model: kws_micronet_m_vela_H128.tflite
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100313 #
314 # Note: To avoid to run vela twice on the same model, it's supposed that
315 # downloaded model names don't contain the 'vela' word.
316 if run_vela_on_models is True:
317 config_file = os.path.join(current_file_dir, "scripts", "vela", "default_vela.ini")
318 models = [os.path.join(dirpath, f)
319 for dirpath, dirnames, files in os.walk(download_dir)
320 for f in fnmatch.filter(files, '*.tflite') if "vela" not in f]
321
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100322 # Consolidate all config names while discarding duplicates:
323 config_names = list(set(default_npu_config_names + additional_npu_config_names))
324
325 # Get npu config tuple for each config name in a list:
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000326 npu_configs = [get_default_npu_config_from_name(name, arena_cache_size) for name in config_names]
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100327
328 logging.info(f'All models will be optimised for these configs:')
329 for config in npu_configs:
330 logging.info(config)
331
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000332 optimisation_skipped = False
333
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100334 for model in models:
335 output_dir = os.path.dirname(model)
alexander3ef1fd42021-05-24 18:56:32 +0100336 # model name after compiling with vela is an initial model name + _vela suffix
337 vela_optimised_model_path = str(model).replace(".tflite", "_vela.tflite")
alexander3ef1fd42021-05-24 18:56:32 +0100338
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100339 for config in npu_configs:
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000340 vela_command_arena_cache_size = ""
341
342 if config.arena_cache_size:
343 vela_command_arena_cache_size = f"--arena-cache-size={config.arena_cache_size}"
344
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100345 vela_command = (f". {env_activate} && vela {model} " +
346 f"--accelerator-config={config.config_name} " +
alexanderd475f092021-06-24 15:36:49 +0100347 "--optimise Performance " +
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100348 f"--config {config_file} " +
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100349 f"--memory-mode={config.memory_mode} " +
350 f"--system-config={config.system_config} " +
Liam Barryb52b5852021-11-15 11:41:40 +0000351 f"--output-dir={output_dir} " +
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000352 f"{vela_command_arena_cache_size}")
alexander3ef1fd42021-05-24 18:56:32 +0100353
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100354 # we want the name to include the configuration suffix. For example: vela_H128,
355 # vela_Y512 etc.
356 new_suffix = "_vela_" + config.ethos_u_config_id + '.tflite'
357 new_vela_optimised_model_path = (
358 vela_optimised_model_path.replace("_vela.tflite", new_suffix))
Isabella Gottardi118f73e2021-09-16 17:54:35 +0100359
360 if os.path.isfile(new_vela_optimised_model_path):
361 logging.info(f"File {new_vela_optimised_model_path} exists, skipping optimisation.")
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000362 optimisation_skipped = True
Isabella Gottardi118f73e2021-09-16 17:54:35 +0100363 continue
364
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100365 call_command(vela_command)
Isabella Gottardi118f73e2021-09-16 17:54:35 +0100366
367 # rename default vela model
368 os.rename(vela_optimised_model_path, new_vela_optimised_model_path)
369 logging.info(f"Renaming {vela_optimised_model_path} to {new_vela_optimised_model_path}.")
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100370
371
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000372 # If any optimisation was skipped, show how to regenerate:
373 if optimisation_skipped:
374 logging.warning("One or more optimisations were skipped.")
375 logging.warning(f"To optimise all the models, please remove the directory {download_dir}.")
376
377
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100378if __name__ == '__main__':
379 parser = ArgumentParser()
380 parser.add_argument("--skip-vela",
381 help="Do not run Vela optimizer on downloaded models.",
382 action="store_true")
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100383 parser.add_argument("--additional-ethos-u-config-name",
384 help=f"""Additional (non-default) configurations for Vela:
385 {valid_npu_config_names}""",
386 default=[], action="append")
Liam Barryb52b5852021-11-15 11:41:40 +0000387 parser.add_argument("--arena-cache-size",
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000388 help="Arena cache size in bytes (if overriding the defaults)",
Liam Barryb52b5852021-11-15 11:41:40 +0000389 type=int,
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000390 default=0)
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100391 args = parser.parse_args()
Kshitij Sisodiab9e9c892021-05-27 13:57:35 +0100392
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000393 if args.arena_cache_size < 0:
394 raise ArgumentTypeError('Arena cache size cannot not be less than 0')
395
Kshitij Sisodiab9e9c892021-05-27 13:57:35 +0100396 logging.basicConfig(filename='log_build_default.log', level=logging.DEBUG)
397 logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
398
Liam Barryb52b5852021-11-15 11:41:40 +0000399 set_up_resources(not args.skip_vela,
400 args.additional_ethos_u_config_name,
401 args.arena_cache_size)