blob: 418af4f46e5db68b76bd238b0973b7f8d4a49d62 [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
27
28json_uc_res = [{
29 "use_case_name": "ad",
30 "resources": [{"name": "ad_medium_int8.tflite",
31 "url": "https://github.com/ARM-software/ML-zoo/raw/7c32b097f7d94aae2cd0b98a8ed5a3ba81e66b18/models/anomaly_detection/micronet_medium/tflite_int8/ad_medium_int8.tflite"},
32 {"name": "ifm0.npy",
33 "url": "https://github.com/ARM-software/ML-zoo/raw/7c32b097f7d94aae2cd0b98a8ed5a3ba81e66b18/models/anomaly_detection/micronet_medium/tflite_int8/testing_input/input/0.npy"},
34 {"name": "ofm0.npy",
35 "url": "https://github.com/ARM-software/ML-zoo/raw/7c32b097f7d94aae2cd0b98a8ed5a3ba81e66b18/models/anomaly_detection/micronet_medium/tflite_int8/testing_output/Identity/0.npy"}]
36},
37 {
38 "use_case_name": "asr",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010039 "resources": [{"name": "wav2letter_pruned_int8.tflite",
40 "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 +010041 {"name": "ifm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010042 "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 +010043 {"name": "ofm0.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_output/Identity_int8/0.npy"}]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010045 },
46 {
47 "use_case_name": "img_class",
Richard Burton0d110592021-08-12 17:26:30 +010048 "resources": [{"name": "mobilenet_v2_1.0_224_INT8.tflite",
49 "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 +010050 {"name": "ifm0.npy",
Richard Burton0d110592021-08-12 17:26:30 +010051 "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 +010052 {"name": "ofm0.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_output/MobilenetV2/Predictions/Reshape_11/0.npy"}]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +010054 },
55 {
56 "use_case_name": "kws",
57 "resources": [{"name": "ds_cnn_clustered_int8.tflite",
58 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/ds_cnn_clustered_int8.tflite"},
59 {"name": "ifm0.npy",
60 "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"},
61 {"name": "ofm0.npy",
62 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/testing_output/Identity/0.npy"}]
63 },
64 {
65 "use_case_name": "kws_asr",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010066 "resources": [{"name": "wav2letter_pruned_int8.tflite",
67 "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 +010068 {"sub_folder": "asr", "name": "ifm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010069 "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 +010070 {"sub_folder": "asr", "name": "ofm0.npy",
Kshitij Sisodiae12ac832021-05-20 11:18:53 +010071 "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 +010072 {"name": "ds_cnn_clustered_int8.tflite",
73 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/ds_cnn_clustered_int8.tflite"},
74 {"sub_folder": "kws", "name": "ifm0.npy",
75 "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"},
76 {"sub_folder": "kws", "name": "ofm0.npy",
77 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/ds_cnn_large/tflite_clustered_int8/testing_output/Identity/0.npy"}]
78 },
79 {
80 "use_case_name": "inference_runner",
81 "resources": [{"name": "dnn_s_quantized.tflite",
82 "url": "https://github.com/ARM-software/ML-zoo/raw/68b5fbc77ed28e67b2efc915997ea4477c1d9d5b/models/keyword_spotting/dnn_small/tflite_int8/dnn_s_quantized.tflite"}
83 ]
84 },]
85
86
87def call_command(command: str) -> str:
88 """
89 Helpers function that call subprocess and return the output.
90
91 Parameters:
92 ----------
93 command (string): Specifies the command to run.
94 """
95 logging.info(command)
alexander50a06502021-05-12 19:06:02 +010096 proc = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
97 log = proc.stdout.decode("utf-8")
98 if proc.returncode == 0:
99 logging.info(log)
100 else:
101 logging.error(log)
102 proc.check_returncode()
103 return log
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100104
105
106def set_up_resources(run_vela_on_models=False):
107 """
108 Helpers function that retrieve the output from a command.
109
110 Parameters:
111 ----------
112 run_vela_on_models (bool): Specifies if run vela on downloaded models.
113 """
114 current_file_dir = os.path.dirname(os.path.abspath(__file__))
115 download_dir = os.path.abspath(os.path.join(current_file_dir, "resources_downloaded"))
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100116
117 try:
118 # 1.1 Does the download dir exist?
119 os.mkdir(download_dir)
120 except OSError as e:
121 if e.errno == errno.EEXIST:
122 logging.info("'resources_downloaded' directory exists.")
123 else:
124 raise
125
126 # 1.2 Does the virtual environment exist?
127 env_python = str(os.path.abspath(os.path.join(download_dir, "env", "bin", "python3")))
128 env_activate = str(os.path.abspath(os.path.join(download_dir, "env", "bin", "activate")))
129 if not os.path.isdir(os.path.join(download_dir, "env")):
130 os.chdir(download_dir)
131 # Create the virtual environment
132 command = "python3 -m venv env"
133 call_command(command)
134 commands = ["pip install --upgrade pip", "pip install --upgrade setuptools"]
135 for c in commands:
136 command = f"{env_python} -m {c}"
137 call_command(command)
138 os.chdir(current_file_dir)
139 # 1.3 Make sure to have all the requirement
alexanderd475f092021-06-24 15:36:49 +0100140 requirements = ["ethos-u-vela==3.0.0"]
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100141 command = f"{env_python} -m pip freeze"
142 packages = call_command(command)
143 for req in requirements:
144 if req not in packages:
145 command = f"{env_python} -m pip install {req}"
146 call_command(command)
147
148 # 2. Download models
149 for uc in json_uc_res:
150 try:
151 # Does the usecase_name download dir exist?
152 os.mkdir(os.path.join(download_dir, uc["use_case_name"]))
153 except OSError as e:
154 if e.errno != errno.EEXIST:
155 logging.error(f"Error creating {uc['use_case_name']} directory.")
156 raise
157
158 for res in uc["resources"]:
159 res_name = res["name"]
160 res_url = res["url"]
161 if "sub_folder" in res:
162 try:
163 # Does the usecase_name/sub_folder download dir exist?
164 os.mkdir(os.path.join(download_dir, uc["use_case_name"], res["sub_folder"]))
165 except OSError as e:
166 if e.errno != errno.EEXIST:
167 logging.error(f"Error creating {uc['use_case_name']} / {res['sub_folder']} directory.")
168 raise
169 res_dst = os.path.join(download_dir,
170 uc["use_case_name"],
171 res["sub_folder"],
172 res_name)
173 else:
174 res_dst = os.path.join(download_dir,
175 uc["use_case_name"],
176 res_name)
alexander3ef1fd42021-05-24 18:56:32 +0100177
178 if os.path.isfile(res_dst):
179 logging.info(f"File {res_dst} exists, skipping download.")
180 else:
181 try:
182 g = urllib.request.urlopen(res_url)
183 with open(res_dst, 'b+w') as f:
184 f.write(g.read())
185 logging.info(f"- Downloaded {res_url} to {res_dst}.")
186 except URLError:
187 logging.error(f"URLError while downloading {res_url}.")
188 raise
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100189
190 # 3. Run vela on models in resources_downloaded
191 # New models will have same name with '_vela' appended.
192 # For example:
193 # original model: ds_cnn_clustered_int8.tflite
alexander50a06502021-05-12 19:06:02 +0100194 # after vela model: ds_cnn_clustered_int8_vela_H128.tflite
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100195 #
196 # Note: To avoid to run vela twice on the same model, it's supposed that
197 # downloaded model names don't contain the 'vela' word.
198 if run_vela_on_models is True:
199 config_file = os.path.join(current_file_dir, "scripts", "vela", "default_vela.ini")
200 models = [os.path.join(dirpath, f)
201 for dirpath, dirnames, files in os.walk(download_dir)
202 for f in fnmatch.filter(files, '*.tflite') if "vela" not in f]
203
204 for model in models:
205 output_dir = os.path.dirname(model)
alexander3ef1fd42021-05-24 18:56:32 +0100206 # model name after compiling with vela is an initial model name + _vela suffix
207 vela_optimised_model_path = str(model).replace(".tflite", "_vela.tflite")
208 # we want it to be initial model name + _vela_H128 suffix which indicates selected MAC config.
209 new_vela_optimised_model_path = vela_optimised_model_path.replace("_vela.tflite", "_vela_H128.tflite")
210
211 if os.path.isfile(new_vela_optimised_model_path):
212 logging.info(f"File {new_vela_optimised_model_path} exists, skipping optimisation.")
213 continue
214
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100215 command = (f". {env_activate} && vela {model} " +
216 "--accelerator-config=ethos-u55-128 " +
alexanderd475f092021-06-24 15:36:49 +0100217 "--optimise Performance " +
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100218 f"--config {config_file} " +
219 "--memory-mode=Shared_Sram " +
220 "--system-config=Ethos_U55_High_End_Embedded " +
221 f"--output-dir={output_dir}")
222 call_command(command)
alexander3ef1fd42021-05-24 18:56:32 +0100223
alexander50a06502021-05-12 19:06:02 +0100224 # rename default vela model
225 os.rename(vela_optimised_model_path, new_vela_optimised_model_path)
Isabella Gottardi958133d2021-05-07 11:57:30 +0100226 logging.info(f"Renaming {vela_optimised_model_path} to {new_vela_optimised_model_path}.")
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100227
228
229if __name__ == '__main__':
230 parser = ArgumentParser()
231 parser.add_argument("--skip-vela",
232 help="Do not run Vela optimizer on downloaded models.",
233 action="store_true")
234 args = parser.parse_args()
Kshitij Sisodiab9e9c892021-05-27 13:57:35 +0100235
236 logging.basicConfig(filename='log_build_default.log', level=logging.DEBUG)
237 logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
238
Isabella Gottardi2181d0a2021-04-07 09:27:38 +0100239 set_up_resources(not args.skip_vela)