blob: 1d3922a15c42d391b7af583c609510657f77545f [file] [log] [blame]
alexanderf4e2c472021-05-14 13:14:21 +01001#!/usr/bin/env python3
Isabella Gottardief2b9dd2022-02-16 14:24:03 +00002# Copyright (c) 2021-2022 Arm Limited. All rights reserved.
Isabella Gottardi2181d0a2021-04-07 09:27:38 +01003# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000016import errno
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010017import fnmatch
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000018import json
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010019import logging
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000020import os
21import re
22import shutil
23import subprocess
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010024import sys
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000025import urllib.request
26from argparse import ArgumentParser
27from argparse import ArgumentTypeError
Kshitij Sisodia3be26232021-10-29 12:29:06 +010028from collections import namedtuple
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000029from urllib.error import URLError
Richard Burton17069622022-03-17 10:54:26 +000030from pathlib import Path
Isabella Gottardi6c2ea452022-03-11 13:25:08 +000031
Kshitij Sisodia6a2ac462022-03-01 17:36:06 +000032from scripts.py.check_update_resources_downloaded import get_md5sum_for_file
Kshitij Sisodia3be26232021-10-29 12:29:06 +010033
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010034
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000035json_uc_res = [
36 {
37 "use_case_name": "ad",
38 "url_prefix": [
39 "https://github.com/ARM-software/ML-zoo/raw/7c32b097f7d94aae2cd0b98a8ed5a3ba81e66b18/models/anomaly_detection/micronet_medium/tflite_int8/"
40 ],
41 "resources": [
42 {
43 "name": "ad_medium_int8.tflite",
44 "url": "{url_prefix:0}ad_medium_int8.tflite",
45 },
46 {"name": "ifm0.npy", "url": "{url_prefix:0}testing_input/input/0.npy"},
47 {"name": "ofm0.npy", "url": "{url_prefix:0}testing_output/Identity/0.npy"},
48 ],
49 },
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010050 {
51 "use_case_name": "asr",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000052 "url_prefix": [
53 "https://github.com/ARM-software/ML-zoo/raw/1a92aa08c0de49a7304e0a7f3f59df6f4fd33ac8/models/speech_recognition/wav2letter/tflite_pruned_int8/"
54 ],
55 "resources": [
56 {
57 "name": "wav2letter_pruned_int8.tflite",
58 "url": "{url_prefix:0}wav2letter_pruned_int8.tflite",
59 },
60 {
61 "name": "ifm0.npy",
62 "url": "{url_prefix:0}testing_input/input_2_int8/0.npy",
63 },
64 {
65 "name": "ofm0.npy",
66 "url": "{url_prefix:0}testing_output/Identity_int8/0.npy",
67 },
68 ],
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010069 },
70 {
71 "use_case_name": "img_class",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000072 "url_prefix": [
73 "https://github.com/ARM-software/ML-zoo/raw/e0aa361b03c738047b9147d1a50e3f2dcb13dbcb/models/image_classification/mobilenet_v2_1.0_224/tflite_int8/"
74 ],
75 "resources": [
76 {
77 "name": "mobilenet_v2_1.0_224_INT8.tflite",
78 "url": "{url_prefix:0}mobilenet_v2_1.0_224_INT8.tflite",
79 },
80 {
81 "name": "ifm0.npy",
82 "url": "{url_prefix:0}testing_input/tfl.quantize/0.npy",
83 },
84 {
85 "name": "ofm0.npy",
86 "url": "{url_prefix:0}testing_output/MobilenetV2/Predictions/Reshape_11/0.npy",
87 },
88 ],
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010089 },
90 {
Michael Levit06fcf752022-01-12 11:53:46 +020091 "use_case_name": "object_detection",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +000092 "url_prefix": [
93 "https://github.com/emza-vs/ModelZoo/blob/v1.0/object_detection/"
94 ],
95 "resources": [
96 {
97 "name": "yolo-fastest_192_face_v4.tflite",
98 "url": "{url_prefix:0}yolo-fastest_192_face_v4.tflite?raw=true",
99 }
100 ],
Michael Levit06fcf752022-01-12 11:53:46 +0200101 },
102 {
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100103 "use_case_name": "kws",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000104 "url_prefix": [
105 "https://github.com/ARM-software/ML-zoo/raw/9f506fe52b39df545f0e6c5ff9223f671bc5ae00/models/keyword_spotting/micronet_medium/tflite_int8/"
106 ],
107 "resources": [
108 {"name": "ifm0.npy", "url": "{url_prefix:0}testing_input/input/0.npy"},
109 {"name": "ofm0.npy", "url": "{url_prefix:0}testing_output/Identity/0.npy"},
110 {
111 "name": "kws_micronet_m.tflite",
112 "url": "{url_prefix:0}kws_micronet_m.tflite",
113 },
114 ],
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100115 },
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000116 {
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100117 "use_case_name": "vww",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000118 "url_prefix": [
119 "https://github.com/ARM-software/ML-zoo/raw/7dd3b16bb84007daf88be8648983c07f3eb21140/models/visual_wake_words/micronet_vww4/tflite_int8/"
120 ],
121 "resources": [
122 {
123 "name": "vww4_128_128_INT8.tflite",
124 "url": "{url_prefix:0}vww4_128_128_INT8.tflite",
125 },
126 {"name": "ifm0.npy", "url": "{url_prefix:0}testing_input/input/0.npy"},
127 {"name": "ofm0.npy", "url": "{url_prefix:0}testing_output/Identity/0.npy"},
128 ],
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100129 },
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100130 {
131 "use_case_name": "kws_asr",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000132 "url_prefix": [
133 "https://github.com/ARM-software/ML-zoo/raw/1a92aa08c0de49a7304e0a7f3f59df6f4fd33ac8/models/speech_recognition/wav2letter/tflite_pruned_int8/",
134 "https://github.com/ARM-software/ML-zoo/raw/9f506fe52b39df545f0e6c5ff9223f671bc5ae00/models/keyword_spotting/micronet_medium/tflite_int8/",
135 ],
136 "resources": [
137 {
138 "name": "wav2letter_pruned_int8.tflite",
139 "url": "{url_prefix:0}wav2letter_pruned_int8.tflite",
140 },
141 {
142 "sub_folder": "asr",
143 "name": "ifm0.npy",
144 "url": "{url_prefix:0}testing_input/input_2_int8/0.npy",
145 },
146 {
147 "sub_folder": "asr",
148 "name": "ofm0.npy",
149 "url": "{url_prefix:0}testing_output/Identity_int8/0.npy",
150 },
151 {
152 "sub_folder": "kws",
153 "name": "ifm0.npy",
154 "url": "{url_prefix:1}testing_input/input/0.npy",
155 },
156 {
157 "sub_folder": "kws",
158 "name": "ofm0.npy",
159 "url": "{url_prefix:1}testing_output/Identity/0.npy",
160 },
161 {
162 "name": "kws_micronet_m.tflite",
163 "url": "{url_prefix:1}kws_micronet_m.tflite",
164 },
165 ],
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100166 },
167 {
Richard Burton00553462021-11-10 16:27:14 +0000168 "use_case_name": "noise_reduction",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000169 "url_prefix": [
170 "https://github.com/ARM-software/ML-zoo/raw/a061600058097a2785d6f1f7785e5a2d2a142955/models/noise_suppression/RNNoise/tflite_int8/"
171 ],
172 "resources": [
173 {"name": "rnnoise_INT8.tflite", "url": "{url_prefix:0}rnnoise_INT8.tflite"},
174 {
175 "name": "ifm0.npy",
176 "url": "{url_prefix:0}testing_input/main_input_int8/0.npy",
177 },
178 {
179 "name": "ifm1.npy",
180 "url": "{url_prefix:0}testing_input/vad_gru_prev_state_int8/0.npy",
181 },
182 {
183 "name": "ifm2.npy",
184 "url": "{url_prefix:0}testing_input/noise_gru_prev_state_int8/0.npy",
185 },
186 {
187 "name": "ifm3.npy",
188 "url": "{url_prefix:0}testing_input/denoise_gru_prev_state_int8/0.npy",
189 },
190 {
191 "name": "ofm0.npy",
192 "url": "{url_prefix:0}testing_output/Identity_int8/0.npy",
193 },
194 {
195 "name": "ofm1.npy",
196 "url": "{url_prefix:0}testing_output/Identity_1_int8/0.npy",
197 },
198 {
199 "name": "ofm2.npy",
200 "url": "{url_prefix:0}testing_output/Identity_2_int8/0.npy",
201 },
202 {
203 "name": "ofm3.npy",
204 "url": "{url_prefix:0}testing_output/Identity_3_int8/0.npy",
205 },
206 {
207 "name": "ofm4.npy",
208 "url": "{url_prefix:0}testing_output/Identity_4_int8/0.npy",
209 },
210 ],
Richard Burton00553462021-11-10 16:27:14 +0000211 },
212 {
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100213 "use_case_name": "inference_runner",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000214 "url_prefix": [
215 "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/dnn_small/tflite_int8/"
216 ],
217 "resources": [
218 {
219 "name": "dnn_s_quantized.tflite",
220 "url": "{url_prefix:0}dnn_s_quantized.tflite",
221 }
222 ],
223 },
224]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100225
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100226# Valid NPU configurations:
227valid_npu_config_names = [
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000228 "ethos-u55-32",
229 "ethos-u55-64",
230 "ethos-u55-128",
231 "ethos-u55-256",
232 "ethos-u65-256",
233 "ethos-u65-512",
234]
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100235
236# Default NPU configurations (these are always run when the models are optimised)
237default_npu_config_names = [valid_npu_config_names[2], valid_npu_config_names[4]]
238
239# NPU config named tuple
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000240NPUConfig = namedtuple(
241 "NPUConfig",
242 [
243 "config_name",
244 "memory_mode",
245 "system_config",
246 "ethos_u_npu_id",
247 "ethos_u_config_id",
248 "arena_cache_size",
249 ],
250)
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100251
Kshitij Sisodia661959c2021-11-24 10:39:52 +0000252# The internal SRAM size for Corstone-300 implementation on MPS3 specified by AN552
Kshitij Sisodia8c61c0a2022-05-17 11:16:22 +0100253# The internal SRAM size for Corstone-310 implementation on MPS3 specified by AN555
254# is 4MB, but we are content with the 2MB specified below.
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000255mps3_max_sram_sz = 2 * 1024 * 1024 # 2 MiB (2 banks of 1 MiB each)
Liam Barryb52b5852021-11-15 11:41:40 +0000256
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100257
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000258def call_command(command: str, verbose: bool = True) -> str:
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100259 """
260 Helpers function that call subprocess and return the output.
261
262 Parameters:
263 ----------
264 command (string): Specifies the command to run.
265 """
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000266 if verbose:
267 logging.info(command)
268 proc = subprocess.run(
269 command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True
270 )
alexander50a06502021-05-12 19:06:02 +0100271 log = proc.stdout.decode("utf-8")
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000272 if proc.returncode == 0 and verbose:
alexander50a06502021-05-12 19:06:02 +0100273 logging.info(log)
274 else:
275 logging.error(log)
276 proc.check_returncode()
277 return log
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100278
279
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000280def get_default_npu_config_from_name(
281 config_name: str, arena_cache_size: int = 0
282) -> NPUConfig:
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100283 """
Richard Burton17069622022-03-17 10:54:26 +0000284 Gets the file suffix for the TFLite file from the
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100285 `accelerator_config` string.
286
287 Parameters:
288 ----------
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000289 config_name (str): Ethos-U NPU configuration from valid_npu_config_names
290
291 arena_cache_size (int): Specifies arena cache size in bytes. If a value
292 greater than 0 is provided, this will be taken
293 as the cache size. If 0, the default values, as per
294 the NPU config requirements, are used.
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100295
296 Returns:
297 -------
298 NPUConfig: An NPU config named tuple populated with defaults for the given
299 config name
300 """
301 if config_name not in valid_npu_config_names:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000302 raise ValueError(
303 f"""
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100304 Invalid Ethos-U NPU configuration.
305 Select one from {valid_npu_config_names}.
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000306 """
307 )
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100308
309 strings_ids = ["ethos-u55-", "ethos-u65-"]
310 processor_ids = ["U55", "U65"]
311 prefix_ids = ["H", "Y"]
312 memory_modes = ["Shared_Sram", "Dedicated_Sram"]
313 system_configs = ["Ethos_U55_High_End_Embedded", "Ethos_U65_High_End"]
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000314 memory_modes_arena = {
Richard Burton17069622022-03-17 10:54:26 +0000315 # For shared SRAM memory mode, we use the MPS3 SRAM size by default.
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000316 "Shared_Sram": mps3_max_sram_sz if arena_cache_size <= 0 else arena_cache_size,
Richard Burton17069622022-03-17 10:54:26 +0000317 # For dedicated SRAM memory mode, we do not override the arena size. This is expected to
318 # be defined in the Vela configuration file instead.
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000319 "Dedicated_Sram": None if arena_cache_size <= 0 else arena_cache_size,
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000320 }
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100321
322 for i in range(len(strings_ids)):
323 if config_name.startswith(strings_ids[i]):
324 npu_config_id = config_name.replace(strings_ids[i], prefix_ids[i])
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000325 return NPUConfig(
326 config_name=config_name,
327 memory_mode=memory_modes[i],
328 system_config=system_configs[i],
329 ethos_u_npu_id=processor_ids[i],
330 ethos_u_config_id=npu_config_id,
331 arena_cache_size=memory_modes_arena[memory_modes[i]],
332 )
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100333
334 return None
335
336
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000337def remove_tree_dir(dir_path):
338 try:
Richard Burton17069622022-03-17 10:54:26 +0000339 # Remove the full directory.
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000340 shutil.rmtree(dir_path)
Richard Burton17069622022-03-17 10:54:26 +0000341 # Re-create an empty one.
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000342 os.mkdir(dir_path)
343 except Exception as e:
344 logging.error(f"Failed to delete {dir_path}.")
345
346
347def set_up_resources(
348 run_vela_on_models: bool = False,
Richard Burton17069622022-03-17 10:54:26 +0000349 additional_npu_config_names: tuple = (),
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000350 arena_cache_size: int = 0,
351 check_clean_folder: bool = False,
Kshitij Sisodia9c6f9f82022-05-20 14:30:02 +0100352 additional_requirements_file: str = "") -> (Path, Path):
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100353 """
354 Helpers function that retrieve the output from a command.
355
356 Parameters:
357 ----------
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000358 run_vela_on_models (bool): Specifies if run vela on downloaded models.
359 additional_npu_config_names(list): list of strings of Ethos-U NPU configs.
360 arena_cache_size (int): Specifies arena cache size in bytes. If a value
361 greater than 0 is provided, this will be taken
362 as the cache size. If 0, the default values, as per
363 the NPU config requirements, are used.
Kshitij Sisodia6a2ac462022-03-01 17:36:06 +0000364 check_clean_folder (bool): Indicates whether the resources folder needs to
365 be checked for updates and cleaned.
Kshitij Sisodiac22e80e2022-03-14 09:26:48 +0000366 additional_requirements_file (str): Path to a requirements.txt file if
367 additional packages need to be
368 installed.
Kshitij Sisodia9c6f9f82022-05-20 14:30:02 +0100369
370 Returns
371 -------
372
373 Tuple of pair of Paths: (download_directory_path, virtual_env_path)
374
375 download_directory_path: Root of the directory where the resources have been downloaded to.
376 virtual_env_path: Path to the root of virtual environment.
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100377 """
Richard Burton17069622022-03-17 10:54:26 +0000378 # Paths.
379 current_file_dir = Path(__file__).parent.resolve()
380 download_dir = current_file_dir / "resources_downloaded"
381 metadata_file_path = download_dir / "resources_downloaded_metadata.json"
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000382
383 metadata_dict = dict()
Nina Drozd28224302022-09-06 17:00:34 +0100384 vela_version = "3.5.0"
Richard Burtonc3722032022-05-31 11:27:26 +0100385 py3_major_version_minimum = 3 # Python >= 3.7 is required
386 py3_minor_version_minimum = 7
Isabella Gottardi6c2ea452022-03-11 13:25:08 +0000387
388 # Is Python minimum requirement matched?
389 py3_version = sys.version_info
390 if (
391 py3_version.major < py3_major_version_minimum
392 or py3_version.minor < py3_minor_version_minimum
393 ):
394 raise Exception(
Richard Burtonc3722032022-05-31 11:27:26 +0100395 "ERROR: Python3.7+ is required, please see the documentation on how to update it."
Isabella Gottardi6c2ea452022-03-11 13:25:08 +0000396 )
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000397
Kshitij Sisodia6a2ac462022-03-01 17:36:06 +0000398 setup_script_hash_verified = False
Richard Burton17069622022-03-17 10:54:26 +0000399 setup_script_hash = get_md5sum_for_file(Path(__file__).resolve())
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100400
401 try:
402 # 1.1 Does the download dir exist?
Richard Burton17069622022-03-17 10:54:26 +0000403 download_dir.mkdir()
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100404 except OSError as e:
405 if e.errno == errno.EEXIST:
406 logging.info("'resources_downloaded' directory exists.")
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000407 # Check and clean?
Richard Burton17069622022-03-17 10:54:26 +0000408 if check_clean_folder and metadata_file_path.is_file():
409 with open(metadata_file_path) as metadata_file:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000410 metadata_dict = json.load(metadata_file)
411 vela_in_metadata = metadata_dict["ethosu_vela_version"]
412 if vela_in_metadata != vela_version:
413 # Check if all the resources needs to be removed and regenerated.
414 # This can happen when the Vela version has changed.
415 logging.info(
416 f"Vela version in metadata is {vela_in_metadata}, current {vela_version}. Removing the resources and re-download them."
417 )
418 remove_tree_dir(download_dir)
419 metadata_dict = dict()
420 else:
Kshitij Sisodia6a2ac462022-03-01 17:36:06 +0000421 # Check if the set_up_default_resorces.py has changed from last setup
422 setup_script_hash_verified = (
Isabella Gottardi6c2ea452022-03-11 13:25:08 +0000423 metadata_dict.get("set_up_script_md5sum")
424 == setup_script_hash
425 )
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100426 else:
427 raise
428
429 # 1.2 Does the virtual environment exist?
Kshitij Sisodia9c6f9f82022-05-20 14:30:02 +0100430 env_dirname = "env"
431 env_path = download_dir / env_dirname
432 env_python = str(env_path / "bin" / "python3")
433 env_activate = str(env_path / "bin" / "activate")
Richard Burton17069622022-03-17 10:54:26 +0000434
Kshitij Sisodia9c6f9f82022-05-20 14:30:02 +0100435 if not env_path.is_dir():
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100436 os.chdir(download_dir)
Richard Burton17069622022-03-17 10:54:26 +0000437 # Create the virtual environment.
Kshitij Sisodia9c6f9f82022-05-20 14:30:02 +0100438 command = f"python3 -m venv {env_dirname}"
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100439 call_command(command)
440 commands = ["pip install --upgrade pip", "pip install --upgrade setuptools"]
441 for c in commands:
442 command = f"{env_python} -m {c}"
443 call_command(command)
444 os.chdir(current_file_dir)
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000445
Kshitij Sisodiac22e80e2022-03-14 09:26:48 +0000446 # 1.3 Make sure to have all the requirements
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000447 requirements = [f"ethos-u-vela=={vela_version}"]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100448 command = f"{env_python} -m pip freeze"
449 packages = call_command(command)
450 for req in requirements:
451 if req not in packages:
452 command = f"{env_python} -m pip install {req}"
453 call_command(command)
454
Kshitij Sisodiac22e80e2022-03-14 09:26:48 +0000455 # 1.4 Install additional requirements, if a valid file has been provided
456 if additional_requirements_file and os.path.isfile(additional_requirements_file):
457 command = f"{env_python} -m pip install -r {additional_requirements_file}"
458 call_command(command)
459
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100460 # 2. Download models
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000461 logging.info("Downloading resources.")
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100462 for uc in json_uc_res:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000463 use_case_name = uc["use_case_name"]
464 res_url_prefix = uc["url_prefix"]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100465 try:
466 # Does the usecase_name download dir exist?
Richard Burton17069622022-03-17 10:54:26 +0000467 (download_dir / use_case_name).mkdir()
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100468 except OSError as e:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000469 if e.errno == errno.EEXIST:
Richard Burton17069622022-03-17 10:54:26 +0000470 # The usecase_name download dir exist.
Kshitij Sisodia6a2ac462022-03-01 17:36:06 +0000471 if check_clean_folder and not setup_script_hash_verified:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000472 for idx, metadata_uc_url_prefix in enumerate(
473 [
474 f
475 for f in metadata_dict["resources_info"]
476 if f["use_case_name"] == use_case_name
477 ][0]["url_prefix"]
478 ):
479 if metadata_uc_url_prefix != res_url_prefix[idx]:
480 logging.info(f"Removing {use_case_name} resources.")
Richard Burton17069622022-03-17 10:54:26 +0000481 remove_tree_dir(download_dir / use_case_name)
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000482 break
483 elif e.errno != errno.EEXIST:
484 logging.error(f"Error creating {use_case_name} directory.")
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100485 raise
486
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000487 reg_expr_str = r"{url_prefix:(.*\d)}"
488 reg_expr_pattern = re.compile(reg_expr_str)
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100489 for res in uc["resources"]:
490 res_name = res["name"]
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000491 url_prefix_idx = int(reg_expr_pattern.search(res["url"]).group(1))
492 res_url = res_url_prefix[url_prefix_idx] + re.sub(
493 reg_expr_str, "", res["url"]
494 )
495
496 sub_folder = ""
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100497 if "sub_folder" in res:
498 try:
499 # Does the usecase_name/sub_folder download dir exist?
Richard Burton17069622022-03-17 10:54:26 +0000500 (download_dir / use_case_name / res["sub_folder"]).mkdir()
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100501 except OSError as e:
502 if e.errno != errno.EEXIST:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000503 logging.error(
504 f"Error creating {use_case_name} / {res['sub_folder']} directory."
505 )
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100506 raise
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000507 sub_folder = res["sub_folder"]
508
Richard Burton17069622022-03-17 10:54:26 +0000509 res_dst = download_dir / use_case_name / sub_folder / res_name
alexander3ef1fd42021-05-24 18:56:32 +0100510
Richard Burton17069622022-03-17 10:54:26 +0000511 if res_dst.is_file():
alexander3ef1fd42021-05-24 18:56:32 +0100512 logging.info(f"File {res_dst} exists, skipping download.")
513 else:
514 try:
515 g = urllib.request.urlopen(res_url)
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000516 with open(res_dst, "b+w") as f:
alexander3ef1fd42021-05-24 18:56:32 +0100517 f.write(g.read())
518 logging.info(f"- Downloaded {res_url} to {res_dst}.")
519 except URLError:
520 logging.error(f"URLError while downloading {res_url}.")
521 raise
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100522
523 # 3. Run vela on models in resources_downloaded
524 # New models will have same name with '_vela' appended.
525 # For example:
Kshitij Sisodia76a15802021-12-24 11:05:11 +0000526 # original model: kws_micronet_m.tflite
527 # after vela model: kws_micronet_m_vela_H128.tflite
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100528 #
529 # Note: To avoid to run vela twice on the same model, it's supposed that
530 # downloaded model names don't contain the 'vela' word.
531 if run_vela_on_models is True:
Richard Burton17069622022-03-17 10:54:26 +0000532 config_file = current_file_dir / "scripts" / "vela" / "default_vela.ini"
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000533 models = [
Richard Burton17069622022-03-17 10:54:26 +0000534 Path(dirpath) / f
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000535 for dirpath, dirnames, files in os.walk(download_dir)
536 for f in fnmatch.filter(files, "*.tflite")
537 if "vela" not in f
538 ]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100539
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100540 # Consolidate all config names while discarding duplicates:
541 config_names = list(set(default_npu_config_names + additional_npu_config_names))
542
543 # Get npu config tuple for each config name in a list:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000544 npu_configs = [
545 get_default_npu_config_from_name(name, arena_cache_size)
546 for name in config_names
547 ]
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100548
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000549 logging.info(f"All models will be optimised for these configs:")
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100550 for config in npu_configs:
551 logging.info(config)
552
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000553 optimisation_skipped = False
554
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100555 for model in models:
Richard Burton17069622022-03-17 10:54:26 +0000556 output_dir = model.parent
alexander3ef1fd42021-05-24 18:56:32 +0100557 # model name after compiling with vela is an initial model name + _vela suffix
Richard Burton17069622022-03-17 10:54:26 +0000558 vela_optimised_model_path = model.parent / (model.stem + "_vela.tflite")
alexander3ef1fd42021-05-24 18:56:32 +0100559
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100560 for config in npu_configs:
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000561 vela_command_arena_cache_size = ""
562
563 if config.arena_cache_size:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000564 vela_command_arena_cache_size = (
565 f"--arena-cache-size={config.arena_cache_size}"
566 )
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000567
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000568 vela_command = (
569 f". {env_activate} && vela {model} "
570 + f"--accelerator-config={config.config_name} "
571 + "--optimise Performance "
572 + f"--config {config_file} "
573 + f"--memory-mode={config.memory_mode} "
574 + f"--system-config={config.system_config} "
575 + f"--output-dir={output_dir} "
576 + f"{vela_command_arena_cache_size}"
577 )
alexander3ef1fd42021-05-24 18:56:32 +0100578
Richard Burton17069622022-03-17 10:54:26 +0000579 # We want the name to include the configuration suffix. For example: vela_H128,
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100580 # vela_Y512 etc.
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000581 new_suffix = "_vela_" + config.ethos_u_config_id + ".tflite"
Richard Burton17069622022-03-17 10:54:26 +0000582 new_vela_optimised_model_path = model.parent / (model.stem + new_suffix)
Isabella Gottardi118f73e2021-09-16 17:54:35 +0100583
Richard Burton17069622022-03-17 10:54:26 +0000584 if new_vela_optimised_model_path.is_file():
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000585 logging.info(
586 f"File {new_vela_optimised_model_path} exists, skipping optimisation."
587 )
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000588 optimisation_skipped = True
Isabella Gottardi118f73e2021-09-16 17:54:35 +0100589 continue
590
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100591 call_command(vela_command)
Isabella Gottardi118f73e2021-09-16 17:54:35 +0100592
Richard Burton17069622022-03-17 10:54:26 +0000593 # Rename default vela model.
594 vela_optimised_model_path.rename(new_vela_optimised_model_path)
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000595 logging.info(
596 f"Renaming {vela_optimised_model_path} to {new_vela_optimised_model_path}."
597 )
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100598
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000599 # If any optimisation was skipped, show how to regenerate:
600 if optimisation_skipped:
601 logging.warning("One or more optimisations were skipped.")
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000602 logging.warning(
603 f"To optimise all the models, please remove the directory {download_dir}."
604 )
605
606 # 4. Collect and write metadata
607 logging.info("Collecting and write metadata.")
608 metadata_dict["ethosu_vela_version"] = vela_version
Kshitij Sisodia6a2ac462022-03-01 17:36:06 +0000609 metadata_dict["set_up_script_md5sum"] = setup_script_hash.strip("\n")
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000610 metadata_dict["resources_info"] = json_uc_res
611
612 with open(metadata_file_path, "w") as metadata_file:
613 json.dump(metadata_dict, metadata_file, indent=4)
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000614
Kshitij Sisodia9c6f9f82022-05-20 14:30:02 +0100615 return download_dir, env_path
616
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000617
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000618if __name__ == "__main__":
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100619 parser = ArgumentParser()
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000620 parser.add_argument(
621 "--skip-vela",
622 help="Do not run Vela optimizer on downloaded models.",
623 action="store_true",
624 )
625 parser.add_argument(
626 "--additional-ethos-u-config-name",
627 help=f"""Additional (non-default) configurations for Vela:
Kshitij Sisodia3be26232021-10-29 12:29:06 +0100628 {valid_npu_config_names}""",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000629 default=[],
630 action="append",
631 )
632 parser.add_argument(
633 "--arena-cache-size",
634 help="Arena cache size in bytes (if overriding the defaults)",
635 type=int,
636 default=0,
637 )
638 parser.add_argument(
639 "--clean",
Richard Burton17069622022-03-17 10:54:26 +0000640 help="Clean the directory and optimize the downloaded resources",
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000641 action="store_true",
642 )
Kshitij Sisodiac22e80e2022-03-14 09:26:48 +0000643 parser.add_argument(
644 "--requirements-file",
645 help="Path to requirements.txt file to install additional packages",
646 type=str,
Richard Burton17069622022-03-17 10:54:26 +0000647 default=Path(__file__).parent.resolve() / 'scripts' / 'py' / 'requirements.txt'
Kshitij Sisodiac22e80e2022-03-14 09:26:48 +0000648 )
649
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100650 args = parser.parse_args()
Kshitij Sisodiab9e9c892021-05-27 13:57:35 +0100651
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000652 if args.arena_cache_size < 0:
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000653 raise ArgumentTypeError("Arena cache size cannot not be less than 0")
Isabella Gottardi3acaaee2021-11-30 12:33:27 +0000654
Richard Burton17069622022-03-17 10:54:26 +0000655 if not Path(args.requirements_file).is_file():
Kshitij Sisodiac22e80e2022-03-14 09:26:48 +0000656 raise ArgumentTypeError(f"Invalid requirements file: {args.requirements_file}")
657
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000658 logging.basicConfig(filename="log_build_default.log", level=logging.DEBUG)
Kshitij Sisodiab9e9c892021-05-27 13:57:35 +0100659 logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
660
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000661 set_up_resources(
662 not args.skip_vela,
663 args.additional_ethos_u_config_name,
664 args.arena_cache_size,
665 args.clean,
Isabella Gottardi6c2ea452022-03-11 13:25:08 +0000666 args.requirements_file,
Isabella Gottardief2b9dd2022-02-16 14:24:03 +0000667 )