blob: 7c1db618415c668fa53380447b1ae65064b6348e [file] [log] [blame]
Jan Eilers45274902020-10-15 18:34:43 +01001//
2// Copyright © 2020 Arm Ltd and Contributors. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
6#include "ExecuteNetworkProgramOptions.hpp"
7#include "NetworkExecutionUtils/NetworkExecutionUtils.hpp"
8#include "InferenceTest.hpp"
9
10#include <armnn/BackendRegistry.hpp>
11#include <armnn/Exceptions.hpp>
12#include <armnn/utility/Assert.hpp>
13#include <armnn/utility/StringUtils.hpp>
14#include <armnn/Logging.hpp>
15
16#include <fmt/format.h>
17
18bool CheckOption(const cxxopts::ParseResult& result,
19 const char* option)
20{
21 // Check that the given option is valid.
22 if (option == nullptr)
23 {
24 return false;
25 }
26
27 // Check whether 'option' is provided.
28 return ((result.count(option)) ? true : false);
29}
30
31void CheckOptionDependency(const cxxopts::ParseResult& result,
32 const char* option,
33 const char* required)
34{
35 // Check that the given options are valid.
36 if (option == nullptr || required == nullptr)
37 {
38 throw cxxopts::OptionParseException("Invalid option to check dependency for");
39 }
40
41 // Check that if 'option' is provided, 'required' is also provided.
42 if (CheckOption(result, option) && !result[option].has_default())
43 {
44 if (CheckOption(result, required) == 0 || result[required].has_default())
45 {
46 throw cxxopts::OptionParseException(
47 std::string("Option '") + option + "' requires option '" + required + "'.");
48 }
49 }
50}
51
52void CheckOptionDependencies(const cxxopts::ParseResult& result)
53{
54 CheckOptionDependency(result, "model-path", "model-format");
55 CheckOptionDependency(result, "input-tensor-shape", "model-path");
56 CheckOptionDependency(result, "tuning-level", "tuning-path");
57}
58
59void RemoveDuplicateDevices(std::vector<armnn::BackendId>& computeDevices)
60{
61 // Mark the duplicate devices as 'Undefined'.
62 for (auto i = computeDevices.begin(); i != computeDevices.end(); ++i)
63 {
64 for (auto j = std::next(i); j != computeDevices.end(); ++j)
65 {
66 if (*j == *i)
67 {
68 *j = armnn::Compute::Undefined;
69 }
70 }
71 }
72
73 // Remove 'Undefined' devices.
74 computeDevices.erase(std::remove(computeDevices.begin(), computeDevices.end(), armnn::Compute::Undefined),
75 computeDevices.end());
76}
77
Jan Eilersc5b84b52021-02-16 12:40:43 +000078/// Takes a vector of backend strings and returns a vector of backendIDs.
79/// Removes duplicate entries.
80/// Can handle backend strings that contain multiple backends separated by comma e.g "CpuRef,CpuAcc"
81std::vector<armnn::BackendId> GetBackendIDs(const std::vector<std::string>& backendStringsVec)
Jan Eilers45274902020-10-15 18:34:43 +010082{
83 std::vector<armnn::BackendId> backendIDs;
Jan Eilersc5b84b52021-02-16 12:40:43 +000084 for (const auto& backendStrings : backendStringsVec)
Jan Eilers45274902020-10-15 18:34:43 +010085 {
Jan Eilersc5b84b52021-02-16 12:40:43 +000086 // Each backendStrings might contain multiple backends separated by comma e.g "CpuRef,CpuAcc"
87 std::vector<std::string> backendStringVec = ParseStringList(backendStrings, ",");
88 for (const auto& b : backendStringVec)
89 {
90 backendIDs.push_back(armnn::BackendId(b));
91 }
Jan Eilers45274902020-10-15 18:34:43 +010092 }
93
94 RemoveDuplicateDevices(backendIDs);
95
96 return backendIDs;
97}
98
99/// Provides a segfault safe way to get cxxopts option values by checking if the option was defined.
100/// If the option wasn't defined it returns an empty object.
101template<typename optionType>
102optionType GetOptionValue(std::string&& optionName, const cxxopts::ParseResult& result)
103{
104 optionType out;
105 if(result.count(optionName))
106 {
107 out = result[optionName].as<optionType>();
108 }
109 return out;
110}
111
112void LogAndThrowFatal(std::string errorMessage)
113{
114 throw armnn::InvalidArgumentException (errorMessage);
115}
116
117void CheckRequiredOptions(const cxxopts::ParseResult& result)
118{
119
120 // For each option in option-group "a) Required
121 std::vector<std::string> requiredOptions{"compute",
122 "model-format",
123 "model-path",
124 "input-name",
125 "output-name"};
126
127 bool requiredMissing = false;
128 for(auto const& str : requiredOptions)
129 {
130 if(!(result.count(str) > 0))
131 {
132 ARMNN_LOG(error) << fmt::format("The program option '{}' is mandatory but wasn't provided.", str);
133 requiredMissing = true;
134 }
135 }
136 if(requiredMissing)
137 {
138 throw armnn::InvalidArgumentException ("Some required arguments are missing");
139 }
140}
141
142void ProgramOptions::ValidateExecuteNetworkParams()
143{
144 m_ExNetParams.ValidateParams();
145}
146
147void ProgramOptions::ValidateRuntimeOptions()
148{
149 if (m_RuntimeOptions.m_ProfilingOptions.m_TimelineEnabled &&
150 !m_RuntimeOptions.m_ProfilingOptions.m_EnableProfiling)
151 {
152 LogAndThrowFatal("Timeline profiling requires external profiling to be turned on");
153 }
154}
155
156
157ProgramOptions::ProgramOptions() : m_CxxOptions{"ExecuteNetwork",
158 "Executes a neural network model using the provided input "
159 "tensor. Prints the resulting output tensor."}
160{
161 try
162 {
163 // cxxopts doesn't provide a mechanism to ensure required options are given. There is a
164 // separate function CheckRequiredOptions() for that.
165 m_CxxOptions.add_options("a) Required")
166 ("c,compute",
Jan Eilersc5b84b52021-02-16 12:40:43 +0000167 "Which device to run layers on by default. If a single device doesn't support all layers in the model "
168 "you can specify a second or third to fall back on. Possible choices: "
Jan Eilers45274902020-10-15 18:34:43 +0100169 + armnn::BackendRegistryInstance().GetBackendIdsAsString()
Jan Eilersc5b84b52021-02-16 12:40:43 +0000170 + " NOTE: Multiple compute devices need to be passed as a comma separated list without whitespaces "
171 "e.g. GpuAcc,CpuAcc,CpuRef or by repeating the program option e.g. '-c Cpuacc -c CpuRef'. "
172 "Duplicates are ignored.",
Jan Eilers3dda41d2020-11-11 11:44:14 +0000173 cxxopts::value<std::vector<std::string>>())
Jan Eilers45274902020-10-15 18:34:43 +0100174
175 ("f,model-format",
Nikhil Raj6dd178f2021-04-02 22:04:39 +0100176 "armnn-binary, onnx-binary, onnx-text, tflite-binary, tensorflow-binary or "
Jan Eilers45274902020-10-15 18:34:43 +0100177 "tensorflow-text.",
178 cxxopts::value<std::string>())
179
180 ("m,model-path",
Nikhil Raj6dd178f2021-04-02 22:04:39 +0100181 "Path to model file, e.g. .armnn, , .prototxt, .tflite, .onnx",
Jan Eilers45274902020-10-15 18:34:43 +0100182 cxxopts::value<std::string>(m_ExNetParams.m_ModelPath))
183
184 ("i,input-name",
185 "Identifier of the input tensors in the network separated by comma.",
186 cxxopts::value<std::string>())
187
188 ("o,output-name",
189 "Identifier of the output tensors in the network separated by comma.",
190 cxxopts::value<std::string>());
191
192 m_CxxOptions.add_options("b) General")
193 ("b,dynamic-backends-path",
194 "Path where to load any available dynamic backend from. "
195 "If left empty (the default), dynamic backends will not be used.",
196 cxxopts::value<std::string>(m_RuntimeOptions.m_DynamicBackendsPath))
197
198 ("d,input-tensor-data",
199 "Path to files containing the input data as a flat array separated by whitespace. "
200 "Several paths can be passed by separating them with a comma. If not specified, the network will be "
201 "run with dummy data (useful for profiling).",
202 cxxopts::value<std::string>()->default_value(""))
203
204 ("h,help", "Display usage information")
205
206 ("infer-output-shape",
207 "Infers output tensor shape from input tensor shape and validate where applicable (where supported by "
208 "parser)",
209 cxxopts::value<bool>(m_ExNetParams.m_InferOutputShape)->default_value("false")->implicit_value("true"))
210
211 ("iterations",
212 "Number of iterations to run the network for, default is set to 1",
213 cxxopts::value<size_t>(m_ExNetParams.m_Iterations)->default_value("1"))
214
215 ("l,dequantize-output",
216 "If this option is enabled, all quantized outputs will be dequantized to float. "
217 "If unset, default to not get dequantized. "
218 "Accepted values (true or false)",
219 cxxopts::value<bool>(m_ExNetParams.m_DequantizeOutput)->default_value("false")->implicit_value("true"))
220
221 ("p,print-intermediate-layers",
222 "If this option is enabled, the output of every graph layer will be printed.",
223 cxxopts::value<bool>(m_ExNetParams.m_PrintIntermediate)->default_value("false")
224 ->implicit_value("true"))
225
226 ("parse-unsupported",
227 "Add unsupported operators as stand-in layers (where supported by parser)",
228 cxxopts::value<bool>(m_ExNetParams.m_ParseUnsupported)->default_value("false")->implicit_value("true"))
229
230 ("q,quantize-input",
231 "If this option is enabled, all float inputs will be quantized to qasymm8. "
232 "If unset, default to not quantized. Accepted values (true or false)",
233 cxxopts::value<bool>(m_ExNetParams.m_QuantizeInput)->default_value("false")->implicit_value("true"))
234
235 ("r,threshold-time",
236 "Threshold time is the maximum allowed time for inference measured in milliseconds. If the actual "
237 "inference time is greater than the threshold time, the test will fail. By default, no threshold "
238 "time is used.",
239 cxxopts::value<double>(m_ExNetParams.m_ThresholdTime)->default_value("0.0"))
240
241 ("s,input-tensor-shape",
242 "The shape of the input tensors in the network as a flat array of integers separated by comma."
243 "Several shapes can be passed by separating them with a colon (:).",
244 cxxopts::value<std::string>())
245
246 ("v,visualize-optimized-model",
247 "Enables built optimized model visualizer. If unset, defaults to off.",
248 cxxopts::value<bool>(m_ExNetParams.m_EnableLayerDetails)->default_value("false")
249 ->implicit_value("true"))
250
251 ("w,write-outputs-to-file",
252 "Comma-separated list of output file paths keyed with the binding-id of the output slot. "
253 "If left empty (the default), the output tensors will not be written to a file.",
254 cxxopts::value<std::string>())
255
256 ("x,subgraph-number",
257 "Id of the subgraph to be executed. Defaults to 0.",
258 cxxopts::value<size_t>(m_ExNetParams.m_SubgraphId)->default_value("0"))
259
260 ("y,input-type",
261 "The type of the input tensors in the network separated by comma. "
262 "If unset, defaults to \"float\" for all defined inputs. "
263 "Accepted values (float, int or qasymm8).",
264 cxxopts::value<std::string>())
265
266 ("z,output-type",
267 "The type of the output tensors in the network separated by comma. "
268 "If unset, defaults to \"float\" for all defined outputs. "
269 "Accepted values (float, int or qasymm8).",
Finn Williamsf806c4d2021-02-22 15:13:12 +0000270 cxxopts::value<std::string>())
271
272 ("T,tflite-executor",
273 "Set the executor for the tflite model: parser, delegate, tflite"
274 "parser is the ArmNNTfLiteParser, "
275 "delegate is the ArmNNTfLiteDelegate, "
276 "tflite is the TfliteInterpreter",
277 cxxopts::value<std::string>()->default_value("parser"))
278
279 ("D,armnn-tflite-delegate",
280 "Enable Arm NN TfLite delegate. "
281 "This option is depreciated please use tflite-executor instead",
282 cxxopts::value<bool>(m_ExNetParams.m_EnableDelegate)->default_value("false")->implicit_value("true"));
Jan Eilers45274902020-10-15 18:34:43 +0100283
284 m_CxxOptions.add_options("c) Optimization")
285 ("bf16-turbo-mode",
286 "If this option is enabled, FP32 layers, "
287 "weights and biases will be converted to BFloat16 where the backend supports it",
288 cxxopts::value<bool>(m_ExNetParams.m_EnableBf16TurboMode)
289 ->default_value("false")->implicit_value("true"))
290
291 ("enable-fast-math",
292 "Enables fast_math options in backends that support it. Using the fast_math flag can lead to "
293 "performance improvements but may result in reduced or different precision.",
294 cxxopts::value<bool>(m_ExNetParams.m_EnableFastMath)->default_value("false")->implicit_value("true"))
295
Matthew Sloyan0a7dc6b2021-02-10 16:50:53 +0000296 ("number-of-threads",
297 "Assign the number of threads used by the CpuAcc backend. "
298 "Input value must be between 1 and 64. "
299 "Default is set to 0 (Backend will decide number of threads to use).",
300 cxxopts::value<unsigned int>(m_ExNetParams.m_NumberOfThreads)->default_value("0"))
301
Matthew Sloyan42432112021-01-08 10:30:51 +0000302 ("save-cached-network",
Matthew Sloyan9d7a3322021-01-12 16:19:43 +0000303 "Enables saving of the cached network to a file given with the cached-network-filepath option. "
Matthew Sloyan42432112021-01-08 10:30:51 +0000304 "See also --cached-network-filepath",
305 cxxopts::value<bool>(m_ExNetParams.m_SaveCachedNetwork)
306 ->default_value("false")->implicit_value("true"))
307
308 ("cached-network-filepath",
Matthew Sloyan9d7a3322021-01-12 16:19:43 +0000309 "If non-empty, the given file will be used to load/save the cached network. "
310 "If save-cached-network is given then the cached network will be saved to the given file. "
311 "To save the cached network a file must already exist. "
312 "If save-cached-network is not given then the cached network will be loaded from the given file. "
313 "This will remove initial compilation time of kernels and speed up the first execution.",
Matthew Sloyan42432112021-01-08 10:30:51 +0000314 cxxopts::value<std::string>(m_ExNetParams.m_CachedNetworkFilePath)->default_value(""))
315
Jan Eilers45274902020-10-15 18:34:43 +0100316 ("fp16-turbo-mode",
317 "If this option is enabled, FP32 layers, "
318 "weights and biases will be converted to FP16 where the backend supports it",
319 cxxopts::value<bool>(m_ExNetParams.m_EnableFp16TurboMode)
320 ->default_value("false")->implicit_value("true"))
321
322 ("tuning-level",
323 "Sets the tuning level which enables a tuning run which will update/create a tuning file. "
324 "Available options are: 1 (Rapid), 2 (Normal), 3 (Exhaustive). "
325 "Requires tuning-path to be set, default is set to 0 (No tuning run)",
326 cxxopts::value<int>(m_ExNetParams.m_TuningLevel)->default_value("0"))
327
328 ("tuning-path",
329 "Path to tuning file. Enables use of CL tuning",
Finn Williams40646322021-02-11 16:16:42 +0000330 cxxopts::value<std::string>(m_ExNetParams.m_TuningPath))
331
332 ("MLGOTuningFilePath",
333 "Path to tuning file. Enables use of CL MLGO tuning",
334 cxxopts::value<std::string>(m_ExNetParams.m_MLGOTuningFilePath));
Jan Eilers45274902020-10-15 18:34:43 +0100335
336 m_CxxOptions.add_options("d) Profiling")
337 ("a,enable-external-profiling",
338 "If enabled external profiling will be switched on",
339 cxxopts::value<bool>(m_RuntimeOptions.m_ProfilingOptions.m_EnableProfiling)
340 ->default_value("false")->implicit_value("true"))
341
342 ("e,event-based-profiling",
343 "Enables built in profiler. If unset, defaults to off.",
344 cxxopts::value<bool>(m_ExNetParams.m_EnableProfiling)->default_value("false")->implicit_value("true"))
345
346 ("g,file-only-external-profiling",
347 "If enabled then the 'file-only' test mode of external profiling will be enabled",
348 cxxopts::value<bool>(m_RuntimeOptions.m_ProfilingOptions.m_FileOnly)
349 ->default_value("false")->implicit_value("true"))
350
351 ("file-format",
352 "If profiling is enabled specifies the output file format",
353 cxxopts::value<std::string>(m_RuntimeOptions.m_ProfilingOptions.m_FileFormat)->default_value("binary"))
354
355 ("j,outgoing-capture-file",
356 "If specified the outgoing external profiling packets will be captured in this binary file",
357 cxxopts::value<std::string>(m_RuntimeOptions.m_ProfilingOptions.m_OutgoingCaptureFile))
358
359 ("k,incoming-capture-file",
360 "If specified the incoming external profiling packets will be captured in this binary file",
361 cxxopts::value<std::string>(m_RuntimeOptions.m_ProfilingOptions.m_IncomingCaptureFile))
362
363 ("timeline-profiling",
364 "If enabled timeline profiling will be switched on, requires external profiling",
365 cxxopts::value<bool>(m_RuntimeOptions.m_ProfilingOptions.m_TimelineEnabled)
366 ->default_value("false")->implicit_value("true"))
367
368 ("u,counter-capture-period",
369 "If profiling is enabled in 'file-only' mode this is the capture period that will be used in the test",
370 cxxopts::value<uint32_t>(m_RuntimeOptions.m_ProfilingOptions.m_CapturePeriod)->default_value("150"));
371 }
372 catch (const std::exception& e)
373 {
374 ARMNN_ASSERT_MSG(false, "Caught unexpected exception");
375 ARMNN_LOG(fatal) << "Fatal internal error: " << e.what();
376 exit(EXIT_FAILURE);
377 }
378}
379
380ProgramOptions::ProgramOptions(int ac, const char* av[]): ProgramOptions()
381{
382 ParseOptions(ac, av);
383}
384
385void ProgramOptions::ParseOptions(int ac, const char* av[])
386{
387 // Parses the command-line.
388 m_CxxResult = m_CxxOptions.parse(ac, av);
389
390 if (m_CxxResult.count("help") || ac <= 1)
391 {
392 std::cout << m_CxxOptions.help() << std::endl;
393 exit(EXIT_SUCCESS);
394 }
395
396 CheckRequiredOptions(m_CxxResult);
397 CheckOptionDependencies(m_CxxResult);
398
399 // Some options can't be assigned directly because they need some post-processing:
Jan Eilers3dda41d2020-11-11 11:44:14 +0000400 auto computeDevices = GetOptionValue<std::vector<std::string>>("compute", m_CxxResult);
401 m_ExNetParams.m_ComputeDevices = GetBackendIDs(computeDevices);
Jan Eilers45274902020-10-15 18:34:43 +0100402 m_ExNetParams.m_ModelFormat =
403 armnn::stringUtils::StringTrimCopy(GetOptionValue<std::string>("model-format", m_CxxResult));
404 m_ExNetParams.m_InputNames =
405 ParseStringList(GetOptionValue<std::string>("input-name", m_CxxResult), ",");
406 m_ExNetParams.m_InputTensorDataFilePaths =
407 ParseStringList(GetOptionValue<std::string>("input-tensor-data", m_CxxResult), ",");
408 m_ExNetParams.m_OutputNames =
409 ParseStringList(GetOptionValue<std::string>("output-name", m_CxxResult), ",");
410 m_ExNetParams.m_InputTypes =
411 ParseStringList(GetOptionValue<std::string>("input-type", m_CxxResult), ",");
412 m_ExNetParams.m_OutputTypes =
413 ParseStringList(GetOptionValue<std::string>("output-type", m_CxxResult), ",");
414 m_ExNetParams.m_OutputTensorFiles =
415 ParseStringList(GetOptionValue<std::string>("write-outputs-to-file", m_CxxResult), ",");
416 m_ExNetParams.m_GenerateTensorData =
417 m_ExNetParams.m_InputTensorDataFilePaths.empty();
Francis Murtaghbf18a262020-10-27 15:20:40 +0000418 m_ExNetParams.m_DynamicBackendsPath = m_RuntimeOptions.m_DynamicBackendsPath;
Jan Eilers45274902020-10-15 18:34:43 +0100419
Sadik Armagan8c7a28b2021-04-01 17:27:21 +0100420 m_RuntimeOptions.m_EnableGpuProfiling = m_ExNetParams.m_EnableProfiling;
Finn Williamsf806c4d2021-02-22 15:13:12 +0000421
422 std::string tfliteExecutor = GetOptionValue<std::string>("tflite-executor", m_CxxResult);
423
424 if (tfliteExecutor.size() == 0 || tfliteExecutor == "parser")
425 {
426 m_ExNetParams.m_TfLiteExecutor = ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteParser;
427 }
428 else if (tfliteExecutor == "delegate")
429 {
430 m_ExNetParams.m_TfLiteExecutor = ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteDelegate;
431 }
432 else if (tfliteExecutor == "tflite")
433 {
434 m_ExNetParams.m_TfLiteExecutor = ExecuteNetworkParams::TfLiteExecutor::TfliteInterpreter;
435 }
436 else
437 {
438 ARMNN_LOG(info) << fmt::format("Invalid tflite-executor option '{}'.", tfliteExecutor);
439 throw armnn::InvalidArgumentException ("Invalid tflite-executor option");
440 }
441
442 if (m_ExNetParams.m_EnableDelegate)
443 {
444 m_ExNetParams.m_TfLiteExecutor = ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteDelegate;
445 ARMNN_LOG(info) << fmt::format("armnn-tflite-delegate option is being depreciated, "
446 "please use tflite-executor instead.");
447 }
448
449
450
Jan Eilers45274902020-10-15 18:34:43 +0100451 // Parse input tensor shape from the string we got from the command-line.
452 std::vector<std::string> inputTensorShapesVector =
453 ParseStringList(GetOptionValue<std::string>("input-tensor-shape", m_CxxResult), ":");
454
455 if (!inputTensorShapesVector.empty())
456 {
457 m_ExNetParams.m_InputTensorShapes.reserve(inputTensorShapesVector.size());
458
459 for(const std::string& shape : inputTensorShapesVector)
460 {
461 std::stringstream ss(shape);
462 std::vector<unsigned int> dims = ParseArray(ss);
463
464 m_ExNetParams.m_InputTensorShapes.push_back(
465 std::make_unique<armnn::TensorShape>(static_cast<unsigned int>(dims.size()), dims.data()));
466 }
467 }
468
469 // We have to validate ExecuteNetworkParams first so that the tuning path and level is validated
470 ValidateExecuteNetworkParams();
471
472 // Parse CL tuning parameters to runtime options
473 if (!m_ExNetParams.m_TuningPath.empty())
474 {
475 m_RuntimeOptions.m_BackendOptions.emplace_back(
476 armnn::BackendOptions
477 {
478 "GpuAcc",
479 {
480 {"TuningLevel", m_ExNetParams.m_TuningLevel},
481 {"TuningFile", m_ExNetParams.m_TuningPath.c_str()},
Finn Williams40646322021-02-11 16:16:42 +0000482 {"KernelProfilingEnabled", m_ExNetParams.m_EnableProfiling},
483 {"MLGOTuningFilePath", m_ExNetParams.m_MLGOTuningFilePath}
Jan Eilers45274902020-10-15 18:34:43 +0100484 }
485 }
486 );
487 }
488
489 ValidateRuntimeOptions();
490}
491