blob: a080e57d0ce53491901b09c5d9ab34ac99216122 [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
78/// Takes a vector of backend strings and returns a vector of backendIDs. Removes duplicate entries.
79std::vector<armnn::BackendId> GetBackendIDs(const std::vector<std::string>& backendStrings)
80{
81 std::vector<armnn::BackendId> backendIDs;
82 for (const auto& b : backendStrings)
83 {
84 backendIDs.push_back(armnn::BackendId(b));
85 }
86
87 RemoveDuplicateDevices(backendIDs);
88
89 return backendIDs;
90}
91
92/// Provides a segfault safe way to get cxxopts option values by checking if the option was defined.
93/// If the option wasn't defined it returns an empty object.
94template<typename optionType>
95optionType GetOptionValue(std::string&& optionName, const cxxopts::ParseResult& result)
96{
97 optionType out;
98 if(result.count(optionName))
99 {
100 out = result[optionName].as<optionType>();
101 }
102 return out;
103}
104
105void LogAndThrowFatal(std::string errorMessage)
106{
107 throw armnn::InvalidArgumentException (errorMessage);
108}
109
110void CheckRequiredOptions(const cxxopts::ParseResult& result)
111{
112
113 // For each option in option-group "a) Required
114 std::vector<std::string> requiredOptions{"compute",
115 "model-format",
116 "model-path",
117 "input-name",
118 "output-name"};
119
120 bool requiredMissing = false;
121 for(auto const& str : requiredOptions)
122 {
123 if(!(result.count(str) > 0))
124 {
125 ARMNN_LOG(error) << fmt::format("The program option '{}' is mandatory but wasn't provided.", str);
126 requiredMissing = true;
127 }
128 }
129 if(requiredMissing)
130 {
131 throw armnn::InvalidArgumentException ("Some required arguments are missing");
132 }
133}
134
135void ProgramOptions::ValidateExecuteNetworkParams()
136{
137 m_ExNetParams.ValidateParams();
138}
139
140void ProgramOptions::ValidateRuntimeOptions()
141{
142 if (m_RuntimeOptions.m_ProfilingOptions.m_TimelineEnabled &&
143 !m_RuntimeOptions.m_ProfilingOptions.m_EnableProfiling)
144 {
145 LogAndThrowFatal("Timeline profiling requires external profiling to be turned on");
146 }
147}
148
149
150ProgramOptions::ProgramOptions() : m_CxxOptions{"ExecuteNetwork",
151 "Executes a neural network model using the provided input "
152 "tensor. Prints the resulting output tensor."}
153{
154 try
155 {
156 // cxxopts doesn't provide a mechanism to ensure required options are given. There is a
157 // separate function CheckRequiredOptions() for that.
158 m_CxxOptions.add_options("a) Required")
159 ("c,compute",
160 "Which device to run layers on by default. Possible choices: "
161 + armnn::BackendRegistryInstance().GetBackendIdsAsString()
162 + " NOTE: Compute devices need to be passed as a comma separated list without whitespaces "
163 "e.g. CpuRef,CpuAcc",
Jan Eilers3dda41d2020-11-11 11:44:14 +0000164 cxxopts::value<std::vector<std::string>>())
Jan Eilers45274902020-10-15 18:34:43 +0100165
166 ("f,model-format",
167 "armnn-binary, caffe-binary, caffe-text, onnx-binary, onnx-text, tflite-binary, tensorflow-binary or "
168 "tensorflow-text.",
169 cxxopts::value<std::string>())
170
Sadik Armagan5d03e312020-11-17 16:43:56 +0000171 ("D,armnn-tflite-delegate",
172 "enable Arm NN TfLite delegate",
173 cxxopts::value<bool>(m_ExNetParams.m_EnableDelegate)->default_value("false")->implicit_value("true"))
174
Jan Eilers45274902020-10-15 18:34:43 +0100175 ("m,model-path",
176 "Path to model file, e.g. .armnn, .caffemodel, .prototxt, .tflite, .onnx",
177 cxxopts::value<std::string>(m_ExNetParams.m_ModelPath))
178
179 ("i,input-name",
180 "Identifier of the input tensors in the network separated by comma.",
181 cxxopts::value<std::string>())
182
183 ("o,output-name",
184 "Identifier of the output tensors in the network separated by comma.",
185 cxxopts::value<std::string>());
186
187 m_CxxOptions.add_options("b) General")
188 ("b,dynamic-backends-path",
189 "Path where to load any available dynamic backend from. "
190 "If left empty (the default), dynamic backends will not be used.",
191 cxxopts::value<std::string>(m_RuntimeOptions.m_DynamicBackendsPath))
192
193 ("d,input-tensor-data",
194 "Path to files containing the input data as a flat array separated by whitespace. "
195 "Several paths can be passed by separating them with a comma. If not specified, the network will be "
196 "run with dummy data (useful for profiling).",
197 cxxopts::value<std::string>()->default_value(""))
198
199 ("h,help", "Display usage information")
200
201 ("infer-output-shape",
202 "Infers output tensor shape from input tensor shape and validate where applicable (where supported by "
203 "parser)",
204 cxxopts::value<bool>(m_ExNetParams.m_InferOutputShape)->default_value("false")->implicit_value("true"))
205
206 ("iterations",
207 "Number of iterations to run the network for, default is set to 1",
208 cxxopts::value<size_t>(m_ExNetParams.m_Iterations)->default_value("1"))
209
210 ("l,dequantize-output",
211 "If this option is enabled, all quantized outputs will be dequantized to float. "
212 "If unset, default to not get dequantized. "
213 "Accepted values (true or false)",
214 cxxopts::value<bool>(m_ExNetParams.m_DequantizeOutput)->default_value("false")->implicit_value("true"))
215
216 ("p,print-intermediate-layers",
217 "If this option is enabled, the output of every graph layer will be printed.",
218 cxxopts::value<bool>(m_ExNetParams.m_PrintIntermediate)->default_value("false")
219 ->implicit_value("true"))
220
221 ("parse-unsupported",
222 "Add unsupported operators as stand-in layers (where supported by parser)",
223 cxxopts::value<bool>(m_ExNetParams.m_ParseUnsupported)->default_value("false")->implicit_value("true"))
224
225 ("q,quantize-input",
226 "If this option is enabled, all float inputs will be quantized to qasymm8. "
227 "If unset, default to not quantized. Accepted values (true or false)",
228 cxxopts::value<bool>(m_ExNetParams.m_QuantizeInput)->default_value("false")->implicit_value("true"))
229
230 ("r,threshold-time",
231 "Threshold time is the maximum allowed time for inference measured in milliseconds. If the actual "
232 "inference time is greater than the threshold time, the test will fail. By default, no threshold "
233 "time is used.",
234 cxxopts::value<double>(m_ExNetParams.m_ThresholdTime)->default_value("0.0"))
235
236 ("s,input-tensor-shape",
237 "The shape of the input tensors in the network as a flat array of integers separated by comma."
238 "Several shapes can be passed by separating them with a colon (:).",
239 cxxopts::value<std::string>())
240
241 ("v,visualize-optimized-model",
242 "Enables built optimized model visualizer. If unset, defaults to off.",
243 cxxopts::value<bool>(m_ExNetParams.m_EnableLayerDetails)->default_value("false")
244 ->implicit_value("true"))
245
246 ("w,write-outputs-to-file",
247 "Comma-separated list of output file paths keyed with the binding-id of the output slot. "
248 "If left empty (the default), the output tensors will not be written to a file.",
249 cxxopts::value<std::string>())
250
251 ("x,subgraph-number",
252 "Id of the subgraph to be executed. Defaults to 0.",
253 cxxopts::value<size_t>(m_ExNetParams.m_SubgraphId)->default_value("0"))
254
255 ("y,input-type",
256 "The type of the input tensors in the network separated by comma. "
257 "If unset, defaults to \"float\" for all defined inputs. "
258 "Accepted values (float, int or qasymm8).",
259 cxxopts::value<std::string>())
260
261 ("z,output-type",
262 "The type of the output tensors in the network separated by comma. "
263 "If unset, defaults to \"float\" for all defined outputs. "
264 "Accepted values (float, int or qasymm8).",
265 cxxopts::value<std::string>());
266
267 m_CxxOptions.add_options("c) Optimization")
268 ("bf16-turbo-mode",
269 "If this option is enabled, FP32 layers, "
270 "weights and biases will be converted to BFloat16 where the backend supports it",
271 cxxopts::value<bool>(m_ExNetParams.m_EnableBf16TurboMode)
272 ->default_value("false")->implicit_value("true"))
273
274 ("enable-fast-math",
275 "Enables fast_math options in backends that support it. Using the fast_math flag can lead to "
276 "performance improvements but may result in reduced or different precision.",
277 cxxopts::value<bool>(m_ExNetParams.m_EnableFastMath)->default_value("false")->implicit_value("true"))
278
Matthew Sloyan42432112021-01-08 10:30:51 +0000279 ("save-cached-network",
Matthew Sloyan9d7a3322021-01-12 16:19:43 +0000280 "Enables saving of the cached network to a file given with the cached-network-filepath option. "
Matthew Sloyan42432112021-01-08 10:30:51 +0000281 "See also --cached-network-filepath",
282 cxxopts::value<bool>(m_ExNetParams.m_SaveCachedNetwork)
283 ->default_value("false")->implicit_value("true"))
284
285 ("cached-network-filepath",
Matthew Sloyan9d7a3322021-01-12 16:19:43 +0000286 "If non-empty, the given file will be used to load/save the cached network. "
287 "If save-cached-network is given then the cached network will be saved to the given file. "
288 "To save the cached network a file must already exist. "
289 "If save-cached-network is not given then the cached network will be loaded from the given file. "
290 "This will remove initial compilation time of kernels and speed up the first execution.",
Matthew Sloyan42432112021-01-08 10:30:51 +0000291 cxxopts::value<std::string>(m_ExNetParams.m_CachedNetworkFilePath)->default_value(""))
292
Jan Eilers45274902020-10-15 18:34:43 +0100293 ("fp16-turbo-mode",
294 "If this option is enabled, FP32 layers, "
295 "weights and biases will be converted to FP16 where the backend supports it",
296 cxxopts::value<bool>(m_ExNetParams.m_EnableFp16TurboMode)
297 ->default_value("false")->implicit_value("true"))
298
299 ("tuning-level",
300 "Sets the tuning level which enables a tuning run which will update/create a tuning file. "
301 "Available options are: 1 (Rapid), 2 (Normal), 3 (Exhaustive). "
302 "Requires tuning-path to be set, default is set to 0 (No tuning run)",
303 cxxopts::value<int>(m_ExNetParams.m_TuningLevel)->default_value("0"))
304
305 ("tuning-path",
306 "Path to tuning file. Enables use of CL tuning",
307 cxxopts::value<std::string>(m_ExNetParams.m_TuningPath));
308
309 m_CxxOptions.add_options("d) Profiling")
310 ("a,enable-external-profiling",
311 "If enabled external profiling will be switched on",
312 cxxopts::value<bool>(m_RuntimeOptions.m_ProfilingOptions.m_EnableProfiling)
313 ->default_value("false")->implicit_value("true"))
314
315 ("e,event-based-profiling",
316 "Enables built in profiler. If unset, defaults to off.",
317 cxxopts::value<bool>(m_ExNetParams.m_EnableProfiling)->default_value("false")->implicit_value("true"))
318
319 ("g,file-only-external-profiling",
320 "If enabled then the 'file-only' test mode of external profiling will be enabled",
321 cxxopts::value<bool>(m_RuntimeOptions.m_ProfilingOptions.m_FileOnly)
322 ->default_value("false")->implicit_value("true"))
323
324 ("file-format",
325 "If profiling is enabled specifies the output file format",
326 cxxopts::value<std::string>(m_RuntimeOptions.m_ProfilingOptions.m_FileFormat)->default_value("binary"))
327
328 ("j,outgoing-capture-file",
329 "If specified the outgoing external profiling packets will be captured in this binary file",
330 cxxopts::value<std::string>(m_RuntimeOptions.m_ProfilingOptions.m_OutgoingCaptureFile))
331
332 ("k,incoming-capture-file",
333 "If specified the incoming external profiling packets will be captured in this binary file",
334 cxxopts::value<std::string>(m_RuntimeOptions.m_ProfilingOptions.m_IncomingCaptureFile))
335
336 ("timeline-profiling",
337 "If enabled timeline profiling will be switched on, requires external profiling",
338 cxxopts::value<bool>(m_RuntimeOptions.m_ProfilingOptions.m_TimelineEnabled)
339 ->default_value("false")->implicit_value("true"))
340
341 ("u,counter-capture-period",
342 "If profiling is enabled in 'file-only' mode this is the capture period that will be used in the test",
343 cxxopts::value<uint32_t>(m_RuntimeOptions.m_ProfilingOptions.m_CapturePeriod)->default_value("150"));
344 }
345 catch (const std::exception& e)
346 {
347 ARMNN_ASSERT_MSG(false, "Caught unexpected exception");
348 ARMNN_LOG(fatal) << "Fatal internal error: " << e.what();
349 exit(EXIT_FAILURE);
350 }
351}
352
353ProgramOptions::ProgramOptions(int ac, const char* av[]): ProgramOptions()
354{
355 ParseOptions(ac, av);
356}
357
358void ProgramOptions::ParseOptions(int ac, const char* av[])
359{
360 // Parses the command-line.
361 m_CxxResult = m_CxxOptions.parse(ac, av);
362
363 if (m_CxxResult.count("help") || ac <= 1)
364 {
365 std::cout << m_CxxOptions.help() << std::endl;
366 exit(EXIT_SUCCESS);
367 }
368
369 CheckRequiredOptions(m_CxxResult);
370 CheckOptionDependencies(m_CxxResult);
371
372 // Some options can't be assigned directly because they need some post-processing:
Jan Eilers3dda41d2020-11-11 11:44:14 +0000373 auto computeDevices = GetOptionValue<std::vector<std::string>>("compute", m_CxxResult);
374 m_ExNetParams.m_ComputeDevices = GetBackendIDs(computeDevices);
Jan Eilers45274902020-10-15 18:34:43 +0100375 m_ExNetParams.m_ModelFormat =
376 armnn::stringUtils::StringTrimCopy(GetOptionValue<std::string>("model-format", m_CxxResult));
377 m_ExNetParams.m_InputNames =
378 ParseStringList(GetOptionValue<std::string>("input-name", m_CxxResult), ",");
379 m_ExNetParams.m_InputTensorDataFilePaths =
380 ParseStringList(GetOptionValue<std::string>("input-tensor-data", m_CxxResult), ",");
381 m_ExNetParams.m_OutputNames =
382 ParseStringList(GetOptionValue<std::string>("output-name", m_CxxResult), ",");
383 m_ExNetParams.m_InputTypes =
384 ParseStringList(GetOptionValue<std::string>("input-type", m_CxxResult), ",");
385 m_ExNetParams.m_OutputTypes =
386 ParseStringList(GetOptionValue<std::string>("output-type", m_CxxResult), ",");
387 m_ExNetParams.m_OutputTensorFiles =
388 ParseStringList(GetOptionValue<std::string>("write-outputs-to-file", m_CxxResult), ",");
389 m_ExNetParams.m_GenerateTensorData =
390 m_ExNetParams.m_InputTensorDataFilePaths.empty();
Francis Murtaghbf18a262020-10-27 15:20:40 +0000391 m_ExNetParams.m_DynamicBackendsPath = m_RuntimeOptions.m_DynamicBackendsPath;
Jan Eilers45274902020-10-15 18:34:43 +0100392
393 // Parse input tensor shape from the string we got from the command-line.
394 std::vector<std::string> inputTensorShapesVector =
395 ParseStringList(GetOptionValue<std::string>("input-tensor-shape", m_CxxResult), ":");
396
397 if (!inputTensorShapesVector.empty())
398 {
399 m_ExNetParams.m_InputTensorShapes.reserve(inputTensorShapesVector.size());
400
401 for(const std::string& shape : inputTensorShapesVector)
402 {
403 std::stringstream ss(shape);
404 std::vector<unsigned int> dims = ParseArray(ss);
405
406 m_ExNetParams.m_InputTensorShapes.push_back(
407 std::make_unique<armnn::TensorShape>(static_cast<unsigned int>(dims.size()), dims.data()));
408 }
409 }
410
411 // We have to validate ExecuteNetworkParams first so that the tuning path and level is validated
412 ValidateExecuteNetworkParams();
413
414 // Parse CL tuning parameters to runtime options
415 if (!m_ExNetParams.m_TuningPath.empty())
416 {
417 m_RuntimeOptions.m_BackendOptions.emplace_back(
418 armnn::BackendOptions
419 {
420 "GpuAcc",
421 {
422 {"TuningLevel", m_ExNetParams.m_TuningLevel},
423 {"TuningFile", m_ExNetParams.m_TuningPath.c_str()},
424 {"KernelProfilingEnabled", m_ExNetParams.m_EnableProfiling}
425 }
426 }
427 );
428 }
429
430 ValidateRuntimeOptions();
431}
432