blob: 2556a104b5532e56e64029999cb7e88c041ac894 [file] [log] [blame]
Francis Murtaghbee4bc92019-06-18 12:30:37 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5#include <armnn/ArmNN.hpp>
6#include <armnn/TypesUtils.hpp>
7
8#if defined(ARMNN_SERIALIZER)
9#include "armnnDeserializer/IDeserializer.hpp"
10#endif
11#if defined(ARMNN_CAFFE_PARSER)
12#include "armnnCaffeParser/ICaffeParser.hpp"
13#endif
14#if defined(ARMNN_TF_PARSER)
15#include "armnnTfParser/ITfParser.hpp"
16#endif
17#if defined(ARMNN_TF_LITE_PARSER)
18#include "armnnTfLiteParser/ITfLiteParser.hpp"
19#endif
20#if defined(ARMNN_ONNX_PARSER)
21#include "armnnOnnxParser/IOnnxParser.hpp"
22#endif
23#include "CsvReader.hpp"
24#include "../InferenceTest.hpp"
25
26#include <Logging.hpp>
27#include <Profiling.hpp>
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +010028#include <ResolveType.hpp>
Francis Murtaghbee4bc92019-06-18 12:30:37 +010029
30#include <boost/algorithm/string/trim.hpp>
31#include <boost/algorithm/string/split.hpp>
32#include <boost/algorithm/string/classification.hpp>
33#include <boost/program_options.hpp>
34#include <boost/variant.hpp>
35
36#include <iostream>
37#include <fstream>
38#include <functional>
39#include <future>
40#include <algorithm>
41#include <iterator>
42
43namespace
44{
45
46// Configure boost::program_options for command-line parsing and validation.
47namespace po = boost::program_options;
48
49template<typename T, typename TParseElementFunc>
50std::vector<T> ParseArrayImpl(std::istream& stream, TParseElementFunc parseElementFunc, const char * chars = "\t ,:")
51{
52 std::vector<T> result;
53 // Processes line-by-line.
54 std::string line;
55 while (std::getline(stream, line))
56 {
57 std::vector<std::string> tokens;
58 try
59 {
60 // Coverity fix: boost::split() may throw an exception of type boost::bad_function_call.
61 boost::split(tokens, line, boost::algorithm::is_any_of(chars), boost::token_compress_on);
62 }
63 catch (const std::exception& e)
64 {
65 BOOST_LOG_TRIVIAL(error) << "An error occurred when splitting tokens: " << e.what();
66 continue;
67 }
68 for (const std::string& token : tokens)
69 {
70 if (!token.empty()) // See https://stackoverflow.com/questions/10437406/
71 {
72 try
73 {
74 result.push_back(parseElementFunc(token));
75 }
76 catch (const std::exception&)
77 {
78 BOOST_LOG_TRIVIAL(error) << "'" << token << "' is not a valid number. It has been ignored.";
79 }
80 }
81 }
82 }
83
84 return result;
85}
86
87bool CheckOption(const po::variables_map& vm,
88 const char* option)
89{
90 // Check that the given option is valid.
91 if (option == nullptr)
92 {
93 return false;
94 }
95
96 // Check whether 'option' is provided.
97 return vm.find(option) != vm.end();
98}
99
100void CheckOptionDependency(const po::variables_map& vm,
101 const char* option,
102 const char* required)
103{
104 // Check that the given options are valid.
105 if (option == nullptr || required == nullptr)
106 {
107 throw po::error("Invalid option to check dependency for");
108 }
109
110 // Check that if 'option' is provided, 'required' is also provided.
111 if (CheckOption(vm, option) && !vm[option].defaulted())
112 {
113 if (CheckOption(vm, required) == 0 || vm[required].defaulted())
114 {
115 throw po::error(std::string("Option '") + option + "' requires option '" + required + "'.");
116 }
117 }
118}
119
120void CheckOptionDependencies(const po::variables_map& vm)
121{
122 CheckOptionDependency(vm, "model-path", "model-format");
123 CheckOptionDependency(vm, "model-path", "input-name");
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100124 CheckOptionDependency(vm, "model-path", "output-name");
125 CheckOptionDependency(vm, "input-tensor-shape", "model-path");
126}
127
128template<armnn::DataType NonQuantizedType>
129auto ParseDataArray(std::istream & stream);
130
131template<armnn::DataType QuantizedType>
132auto ParseDataArray(std::istream& stream,
133 const float& quantizationScale,
134 const int32_t& quantizationOffset);
135
136template<>
137auto ParseDataArray<armnn::DataType::Float32>(std::istream & stream)
138{
139 return ParseArrayImpl<float>(stream, [](const std::string& s) { return std::stof(s); });
140}
141
142template<>
143auto ParseDataArray<armnn::DataType::Signed32>(std::istream & stream)
144{
145 return ParseArrayImpl<int>(stream, [](const std::string & s) { return std::stoi(s); });
146}
147
148template<>
Narumol Prangnawarat610256f2019-06-26 15:10:46 +0100149auto ParseDataArray<armnn::DataType::QuantisedAsymm8>(std::istream& stream)
150{
151 return ParseArrayImpl<uint8_t>(stream,
152 [](const std::string& s) { return boost::numeric_cast<uint8_t>(std::stoi(s)); });
153}
154
155template<>
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100156auto ParseDataArray<armnn::DataType::QuantisedAsymm8>(std::istream& stream,
157 const float& quantizationScale,
158 const int32_t& quantizationOffset)
159{
160 return ParseArrayImpl<uint8_t>(stream,
161 [&quantizationScale, &quantizationOffset](const std::string & s)
162 {
163 return boost::numeric_cast<uint8_t>(
Rob Hughes93667b12019-09-23 16:24:05 +0100164 armnn::Quantize<uint8_t>(std::stof(s),
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100165 quantizationScale,
166 quantizationOffset));
167 });
168}
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100169std::vector<unsigned int> ParseArray(std::istream& stream)
170{
171 return ParseArrayImpl<unsigned int>(stream,
172 [](const std::string& s) { return boost::numeric_cast<unsigned int>(std::stoi(s)); });
173}
174
175std::vector<std::string> ParseStringList(const std::string & inputString, const char * delimiter)
176{
177 std::stringstream stream(inputString);
178 return ParseArrayImpl<std::string>(stream, [](const std::string& s) { return boost::trim_copy(s); }, delimiter);
179}
180
181void RemoveDuplicateDevices(std::vector<armnn::BackendId>& computeDevices)
182{
183 // Mark the duplicate devices as 'Undefined'.
184 for (auto i = computeDevices.begin(); i != computeDevices.end(); ++i)
185 {
186 for (auto j = std::next(i); j != computeDevices.end(); ++j)
187 {
188 if (*j == *i)
189 {
190 *j = armnn::Compute::Undefined;
191 }
192 }
193 }
194
195 // Remove 'Undefined' devices.
196 computeDevices.erase(std::remove(computeDevices.begin(), computeDevices.end(), armnn::Compute::Undefined),
197 computeDevices.end());
198}
199
200struct TensorPrinter : public boost::static_visitor<>
201{
Sadik Armagan77086282019-09-02 11:46:28 +0100202 TensorPrinter(const std::string& binding, const armnn::TensorInfo& info, const std::string& outputTensorFile)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100203 : m_OutputBinding(binding)
204 , m_Scale(info.GetQuantizationScale())
205 , m_Offset(info.GetQuantizationOffset())
Sadik Armagan77086282019-09-02 11:46:28 +0100206 , m_OutputTensorFile(outputTensorFile)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100207 {}
208
209 void operator()(const std::vector<float>& values)
210 {
Sadik Armagan77086282019-09-02 11:46:28 +0100211 ForEachValue(values, [](float value)
212 {
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100213 printf("%f ", value);
214 });
Sadik Armagan77086282019-09-02 11:46:28 +0100215 WriteToFile(values);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100216 }
217
218 void operator()(const std::vector<uint8_t>& values)
219 {
220 auto& scale = m_Scale;
221 auto& offset = m_Offset;
Sadik Armagan77086282019-09-02 11:46:28 +0100222 std::vector<float> dequantizedValues;
223 ForEachValue(values, [&scale, &offset, &dequantizedValues](uint8_t value)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100224 {
Sadik Armagan77086282019-09-02 11:46:28 +0100225 auto dequantizedValue = armnn::Dequantize(value, scale, offset);
226 printf("%f ", dequantizedValue);
227 dequantizedValues.push_back(dequantizedValue);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100228 });
Sadik Armagan77086282019-09-02 11:46:28 +0100229 WriteToFile(dequantizedValues);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100230 }
231
232 void operator()(const std::vector<int>& values)
233 {
234 ForEachValue(values, [](int value)
235 {
236 printf("%d ", value);
237 });
Sadik Armagan77086282019-09-02 11:46:28 +0100238 WriteToFile(values);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100239 }
240
241private:
242 template<typename Container, typename Delegate>
243 void ForEachValue(const Container& c, Delegate delegate)
244 {
245 std::cout << m_OutputBinding << ": ";
246 for (const auto& value : c)
247 {
248 delegate(value);
249 }
250 printf("\n");
251 }
252
Sadik Armagan77086282019-09-02 11:46:28 +0100253 template<typename T>
254 void WriteToFile(const std::vector<T>& values)
255 {
256 if (!m_OutputTensorFile.empty())
257 {
258 std::ofstream outputTensorFile;
259 outputTensorFile.open(m_OutputTensorFile, std::ofstream::out | std::ofstream::trunc);
260 if (outputTensorFile.is_open())
261 {
262 outputTensorFile << m_OutputBinding << ": ";
263 std::copy(values.begin(), values.end(), std::ostream_iterator<T>(outputTensorFile, " "));
264 }
265 else
266 {
267 BOOST_LOG_TRIVIAL(info) << "Output Tensor File: " << m_OutputTensorFile << " could not be opened!";
268 }
269 outputTensorFile.close();
270 }
271 }
272
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100273 std::string m_OutputBinding;
274 float m_Scale=0.0f;
275 int m_Offset=0;
Sadik Armagan77086282019-09-02 11:46:28 +0100276 std::string m_OutputTensorFile;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100277};
278
279
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100280
281template<armnn::DataType ArmnnType, typename T = armnn::ResolveType<ArmnnType>>
282std::vector<T> GenerateDummyTensorData(unsigned int numElements)
283{
284 return std::vector<T>(numElements, static_cast<T>(0));
285}
286
287using TContainer = boost::variant<std::vector<float>, std::vector<int>, std::vector<unsigned char>>;
288using QuantizationParams = std::pair<float, int32_t>;
289
290void PopulateTensorWithData(TContainer& tensorData,
291 unsigned int numElements,
292 const std::string& dataTypeStr,
293 const armnn::Optional<QuantizationParams>& qParams,
294 const armnn::Optional<std::string>& dataFile)
295{
296 const bool readFromFile = dataFile.has_value() && !dataFile.value().empty();
297 const bool quantizeData = qParams.has_value();
298
299 std::ifstream inputTensorFile;
300 if (readFromFile)
301 {
302 inputTensorFile = std::ifstream(dataFile.value());
303 }
304
305 if (dataTypeStr.compare("float") == 0)
306 {
307 if (quantizeData)
308 {
309 const float qScale = qParams.value().first;
310 const int qOffset = qParams.value().second;
311
312 tensorData = readFromFile ?
313 ParseDataArray<armnn::DataType::QuantisedAsymm8>(inputTensorFile, qScale, qOffset) :
314 GenerateDummyTensorData<armnn::DataType::QuantisedAsymm8>(numElements);
315 }
316 else
317 {
318 tensorData = readFromFile ?
319 ParseDataArray<armnn::DataType::Float32>(inputTensorFile) :
320 GenerateDummyTensorData<armnn::DataType::Float32>(numElements);
321 }
322 }
323 else if (dataTypeStr.compare("int") == 0)
324 {
325 tensorData = readFromFile ?
326 ParseDataArray<armnn::DataType::Signed32>(inputTensorFile) :
327 GenerateDummyTensorData<armnn::DataType::Signed32>(numElements);
328 }
329 else if (dataTypeStr.compare("qasymm8") == 0)
330 {
331 tensorData = readFromFile ?
332 ParseDataArray<armnn::DataType::QuantisedAsymm8>(inputTensorFile) :
333 GenerateDummyTensorData<armnn::DataType::QuantisedAsymm8>(numElements);
334 }
335 else
336 {
337 std::string errorMessage = "Unsupported tensor data type " + dataTypeStr;
338 BOOST_LOG_TRIVIAL(fatal) << errorMessage;
339
340 inputTensorFile.close();
341 throw armnn::Exception(errorMessage);
342 }
343
344 inputTensorFile.close();
345}
346
347} // anonymous namespace
348
349bool generateTensorData = true;
350
351struct ExecuteNetworkParams
352{
353 using TensorShapePtr = std::unique_ptr<armnn::TensorShape>;
354
355 const char* m_ModelPath;
356 bool m_IsModelBinary;
357 std::vector<armnn::BackendId> m_ComputeDevices;
358 std::string m_DynamicBackendsPath;
359 std::vector<string> m_InputNames;
360 std::vector<TensorShapePtr> m_InputTensorShapes;
361 std::vector<string> m_InputTensorDataFilePaths;
362 std::vector<string> m_InputTypes;
363 bool m_QuantizeInput;
364 std::vector<string> m_OutputTypes;
365 std::vector<string> m_OutputNames;
366 std::vector<string> m_OutputTensorFiles;
367 bool m_EnableProfiling;
368 bool m_EnableFp16TurboMode;
369 double m_ThresholdTime;
370 bool m_PrintIntermediate;
371 size_t m_SubgraphId;
372 bool m_EnableLayerDetails = false;
373 bool m_GenerateTensorData;
374};
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100375
376template<typename TParser, typename TDataType>
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100377int MainImpl(const ExecuteNetworkParams& params,
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100378 const std::shared_ptr<armnn::IRuntime>& runtime = nullptr)
379{
380 using TContainer = boost::variant<std::vector<float>, std::vector<int>, std::vector<unsigned char>>;
381
382 std::vector<TContainer> inputDataContainers;
383
384 try
385 {
386 // Creates an InferenceModel, which will parse the model and load it into an IRuntime.
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100387 typename InferenceModel<TParser, TDataType>::Params inferenceModelParams;
388 inferenceModelParams.m_ModelPath = params.m_ModelPath;
389 inferenceModelParams.m_IsModelBinary = params.m_IsModelBinary;
390 inferenceModelParams.m_ComputeDevices = params.m_ComputeDevices;
391 inferenceModelParams.m_DynamicBackendsPath = params.m_DynamicBackendsPath;
392 inferenceModelParams.m_PrintIntermediateLayers = params.m_PrintIntermediate;
393 inferenceModelParams.m_VisualizePostOptimizationModel = params.m_EnableLayerDetails;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100394
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100395 for(const std::string& inputName: params.m_InputNames)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100396 {
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100397 inferenceModelParams.m_InputBindings.push_back(inputName);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100398 }
399
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100400 for(unsigned int i = 0; i < params.m_InputTensorShapes.size(); ++i)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100401 {
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100402 inferenceModelParams.m_InputShapes.push_back(*params.m_InputTensorShapes[i]);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100403 }
404
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100405 for(const std::string& outputName: params.m_OutputNames)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100406 {
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100407 inferenceModelParams.m_OutputBindings.push_back(outputName);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100408 }
409
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100410 inferenceModelParams.m_SubgraphId = params.m_SubgraphId;
411 inferenceModelParams.m_EnableFp16TurboMode = params.m_EnableFp16TurboMode;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100412
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100413 InferenceModel<TParser, TDataType> model(inferenceModelParams,
414 params.m_EnableProfiling,
415 params.m_DynamicBackendsPath,
416 runtime);
417
418 const size_t numInputs = inferenceModelParams.m_InputBindings.size();
419 for(unsigned int i = 0; i < numInputs; ++i)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100420 {
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100421 armnn::Optional<QuantizationParams> qParams = params.m_QuantizeInput ?
422 armnn::MakeOptional<QuantizationParams>(model.GetInputQuantizationParams()) :
423 armnn::EmptyOptional();
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100424
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100425 armnn::Optional<std::string> dataFile = params.m_GenerateTensorData ?
426 armnn::EmptyOptional() :
427 armnn::MakeOptional<std::string>(params.m_InputTensorDataFilePaths[i]);
428
429 unsigned int numElements = model.GetInputSize(i);
430 if (params.m_InputTensorShapes.size() > i && params.m_InputTensorShapes[i])
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100431 {
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100432 // If the user has provided a tensor shape for the current input,
433 // override numElements
434 numElements = params.m_InputTensorShapes[i]->GetNumElements();
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100435 }
436
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100437 TContainer tensorData;
438 PopulateTensorWithData(tensorData,
439 numElements,
440 params.m_InputTypes[i],
441 qParams,
442 dataFile);
443
444 inputDataContainers.push_back(tensorData);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100445 }
446
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100447 const size_t numOutputs = inferenceModelParams.m_OutputBindings.size();
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100448 std::vector<TContainer> outputDataContainers;
449
450 for (unsigned int i = 0; i < numOutputs; ++i)
451 {
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100452 if (params.m_OutputTypes[i].compare("float") == 0)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100453 {
454 outputDataContainers.push_back(std::vector<float>(model.GetOutputSize(i)));
455 }
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100456 else if (params.m_OutputTypes[i].compare("int") == 0)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100457 {
458 outputDataContainers.push_back(std::vector<int>(model.GetOutputSize(i)));
459 }
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100460 else if (params.m_OutputTypes[i].compare("qasymm8") == 0)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100461 {
462 outputDataContainers.push_back(std::vector<uint8_t>(model.GetOutputSize(i)));
463 }
464 else
465 {
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100466 BOOST_LOG_TRIVIAL(fatal) << "Unsupported tensor data type \"" << params.m_OutputTypes[i] << "\". ";
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100467 return EXIT_FAILURE;
468 }
469 }
470
471 // model.Run returns the inference time elapsed in EnqueueWorkload (in milliseconds)
472 auto inference_duration = model.Run(inputDataContainers, outputDataContainers);
473
Matteo Martincighd6f26fc2019-10-28 10:48:05 +0000474 if (params.m_GenerateTensorData)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100475 {
Matteo Martincighd6f26fc2019-10-28 10:48:05 +0000476 BOOST_LOG_TRIVIAL(warning) << "The input data was generated, note that the output will not be useful";
477 }
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100478
Matteo Martincighd6f26fc2019-10-28 10:48:05 +0000479 // Print output tensors
480 const auto& infosOut = model.GetOutputBindingInfos();
481 for (size_t i = 0; i < numOutputs; i++)
482 {
483 const armnn::TensorInfo& infoOut = infosOut[i].second;
484 auto outputTensorFile = params.m_OutputTensorFiles.empty() ? "" : params.m_OutputTensorFiles[i];
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100485
Matteo Martincighd6f26fc2019-10-28 10:48:05 +0000486 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i], infoOut, outputTensorFile);
487 boost::apply_visitor(printer, outputDataContainers[i]);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100488 }
489
490 BOOST_LOG_TRIVIAL(info) << "\nInference time: " << std::setprecision(2)
491 << std::fixed << inference_duration.count() << " ms";
492
493 // If thresholdTime == 0.0 (default), then it hasn't been supplied at command line
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100494 if (params.m_ThresholdTime != 0.0)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100495 {
496 BOOST_LOG_TRIVIAL(info) << "Threshold time: " << std::setprecision(2)
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100497 << std::fixed << params.m_ThresholdTime << " ms";
498 auto thresholdMinusInference = params.m_ThresholdTime - inference_duration.count();
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100499 BOOST_LOG_TRIVIAL(info) << "Threshold time - Inference time: " << std::setprecision(2)
500 << std::fixed << thresholdMinusInference << " ms" << "\n";
501
502 if (thresholdMinusInference < 0)
503 {
504 BOOST_LOG_TRIVIAL(fatal) << "Elapsed inference time is greater than provided threshold time.\n";
505 return EXIT_FAILURE;
506 }
507 }
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100508 }
509 catch (armnn::Exception const& e)
510 {
511 BOOST_LOG_TRIVIAL(fatal) << "Armnn Error: " << e.what();
512 return EXIT_FAILURE;
513 }
514
515 return EXIT_SUCCESS;
516}
517
518// This will run a test
519int RunTest(const std::string& format,
520 const std::string& inputTensorShapesStr,
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100521 const vector<armnn::BackendId>& computeDevices,
Matteo Martincigh00dda4a2019-08-14 11:42:30 +0100522 const std::string& dynamicBackendsPath,
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100523 const std::string& path,
524 const std::string& inputNames,
525 const std::string& inputTensorDataFilePaths,
526 const std::string& inputTypes,
Narumol Prangnawarat610256f2019-06-26 15:10:46 +0100527 bool quantizeInput,
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100528 const std::string& outputTypes,
529 const std::string& outputNames,
Sadik Armagan77086282019-09-02 11:46:28 +0100530 const std::string& outputTensorFiles,
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100531 bool enableProfiling,
532 bool enableFp16TurboMode,
533 const double& thresholdTime,
Matthew Jackson54658b92019-08-27 15:35:59 +0100534 bool printIntermediate,
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100535 const size_t subgraphId,
Andre Ghattas23ae2ea2019-08-07 12:18:38 +0100536 bool enableLayerDetails = false,
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100537 const std::shared_ptr<armnn::IRuntime>& runtime = nullptr)
538{
539 std::string modelFormat = boost::trim_copy(format);
540 std::string modelPath = boost::trim_copy(path);
541 std::vector<std::string> inputNamesVector = ParseStringList(inputNames, ",");
Francis Murtagh1555cbd2019-10-08 14:47:46 +0100542 std::vector<std::string> inputTensorShapesVector = ParseStringList(inputTensorShapesStr, ":");
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100543 std::vector<std::string> inputTensorDataFilePathsVector = ParseStringList(
544 inputTensorDataFilePaths, ",");
545 std::vector<std::string> outputNamesVector = ParseStringList(outputNames, ",");
546 std::vector<std::string> inputTypesVector = ParseStringList(inputTypes, ",");
547 std::vector<std::string> outputTypesVector = ParseStringList(outputTypes, ",");
Sadik Armagan77086282019-09-02 11:46:28 +0100548 std::vector<std::string> outputTensorFilesVector = ParseStringList(outputTensorFiles, ",");
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100549
550 // Parse model binary flag from the model-format string we got from the command-line
551 bool isModelBinary;
552 if (modelFormat.find("bin") != std::string::npos)
553 {
554 isModelBinary = true;
555 }
556 else if (modelFormat.find("txt") != std::string::npos || modelFormat.find("text") != std::string::npos)
557 {
558 isModelBinary = false;
559 }
560 else
561 {
562 BOOST_LOG_TRIVIAL(fatal) << "Unknown model format: '" << modelFormat << "'. Please include 'binary' or 'text'";
563 return EXIT_FAILURE;
564 }
565
566 if ((inputTensorShapesVector.size() != 0) && (inputTensorShapesVector.size() != inputNamesVector.size()))
567 {
568 BOOST_LOG_TRIVIAL(fatal) << "input-name and input-tensor-shape must have the same amount of elements.";
569 return EXIT_FAILURE;
570 }
571
572 if ((inputTensorDataFilePathsVector.size() != 0) &&
573 (inputTensorDataFilePathsVector.size() != inputNamesVector.size()))
574 {
575 BOOST_LOG_TRIVIAL(fatal) << "input-name and input-tensor-data must have the same amount of elements.";
576 return EXIT_FAILURE;
577 }
578
Sadik Armagan77086282019-09-02 11:46:28 +0100579 if ((outputTensorFilesVector.size() != 0) &&
580 (outputTensorFilesVector.size() != outputNamesVector.size()))
581 {
582 BOOST_LOG_TRIVIAL(fatal) << "output-name and write-outputs-to-file must have the same amount of elements.";
583 return EXIT_FAILURE;
584 }
585
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100586 if (inputTypesVector.size() == 0)
587 {
588 //Defaults the value of all inputs to "float"
589 inputTypesVector.assign(inputNamesVector.size(), "float");
590 }
Matteo Martincigh08b51862019-08-29 16:26:10 +0100591 else if ((inputTypesVector.size() != 0) && (inputTypesVector.size() != inputNamesVector.size()))
592 {
593 BOOST_LOG_TRIVIAL(fatal) << "input-name and input-type must have the same amount of elements.";
594 return EXIT_FAILURE;
595 }
596
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100597 if (outputTypesVector.size() == 0)
598 {
599 //Defaults the value of all outputs to "float"
600 outputTypesVector.assign(outputNamesVector.size(), "float");
601 }
Matteo Martincigh08b51862019-08-29 16:26:10 +0100602 else if ((outputTypesVector.size() != 0) && (outputTypesVector.size() != outputNamesVector.size()))
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100603 {
Matteo Martincigh08b51862019-08-29 16:26:10 +0100604 BOOST_LOG_TRIVIAL(fatal) << "output-name and output-type must have the same amount of elements.";
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100605 return EXIT_FAILURE;
606 }
607
608 // Parse input tensor shape from the string we got from the command-line.
609 std::vector<std::unique_ptr<armnn::TensorShape>> inputTensorShapes;
610
611 if (!inputTensorShapesVector.empty())
612 {
613 inputTensorShapes.reserve(inputTensorShapesVector.size());
614
615 for(const std::string& shape : inputTensorShapesVector)
616 {
617 std::stringstream ss(shape);
618 std::vector<unsigned int> dims = ParseArray(ss);
619
620 try
621 {
622 // Coverity fix: An exception of type armnn::InvalidArgumentException is thrown and never caught.
623 inputTensorShapes.push_back(std::make_unique<armnn::TensorShape>(dims.size(), dims.data()));
624 }
625 catch (const armnn::InvalidArgumentException& e)
626 {
627 BOOST_LOG_TRIVIAL(fatal) << "Cannot create tensor shape: " << e.what();
628 return EXIT_FAILURE;
629 }
630 }
631 }
632
633 // Check that threshold time is not less than zero
634 if (thresholdTime < 0)
635 {
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100636 BOOST_LOG_TRIVIAL(fatal) << "Threshold time supplied as a command line argument is less than zero.";
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100637 return EXIT_FAILURE;
638 }
639
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100640 ExecuteNetworkParams params;
641 params.m_ModelPath = modelPath.c_str();
642 params.m_IsModelBinary = isModelBinary;
643 params.m_ComputeDevices = computeDevices;
644 params.m_DynamicBackendsPath = dynamicBackendsPath;
645 params.m_InputNames = inputNamesVector;
646 params.m_InputTensorShapes = std::move(inputTensorShapes);
647 params.m_InputTensorDataFilePaths = inputTensorDataFilePathsVector;
648 params.m_InputTypes = inputTypesVector;
649 params.m_QuantizeInput = quantizeInput;
650 params.m_OutputTypes = outputTypesVector;
651 params.m_OutputNames = outputNamesVector;
652 params.m_OutputTensorFiles = outputTensorFilesVector;
653 params.m_EnableProfiling = enableProfiling;
654 params.m_EnableFp16TurboMode = enableFp16TurboMode;
655 params.m_ThresholdTime = thresholdTime;
656 params.m_PrintIntermediate = printIntermediate;
657 params.m_SubgraphId = subgraphId;
658 params.m_EnableLayerDetails = enableLayerDetails;
659 params.m_GenerateTensorData = inputTensorDataFilePathsVector.empty();
660
661 // Warn if ExecuteNetwork will generate dummy input data
662 if (params.m_GenerateTensorData)
663 {
664 BOOST_LOG_TRIVIAL(warning) << "No input files provided, input tensors will be filled with 0s.";
665 }
666
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100667 // Forward to implementation based on the parser type
668 if (modelFormat.find("armnn") != std::string::npos)
669 {
670#if defined(ARMNN_SERIALIZER)
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100671 return MainImpl<armnnDeserializer::IDeserializer, float>(params, runtime);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100672#else
673 BOOST_LOG_TRIVIAL(fatal) << "Not built with serialization support.";
674 return EXIT_FAILURE;
675#endif
676 }
677 else if (modelFormat.find("caffe") != std::string::npos)
678 {
679#if defined(ARMNN_CAFFE_PARSER)
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100680 return MainImpl<armnnCaffeParser::ICaffeParser, float>(params, runtime);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100681#else
682 BOOST_LOG_TRIVIAL(fatal) << "Not built with Caffe parser support.";
683 return EXIT_FAILURE;
684#endif
685 }
686 else if (modelFormat.find("onnx") != std::string::npos)
687{
688#if defined(ARMNN_ONNX_PARSER)
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100689 return MainImpl<armnnOnnxParser::IOnnxParser, float>(params, runtime);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100690#else
691 BOOST_LOG_TRIVIAL(fatal) << "Not built with Onnx parser support.";
692 return EXIT_FAILURE;
693#endif
694 }
695 else if (modelFormat.find("tensorflow") != std::string::npos)
696 {
697#if defined(ARMNN_TF_PARSER)
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100698 return MainImpl<armnnTfParser::ITfParser, float>(params, runtime);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100699#else
700 BOOST_LOG_TRIVIAL(fatal) << "Not built with Tensorflow parser support.";
701 return EXIT_FAILURE;
702#endif
703 }
704 else if(modelFormat.find("tflite") != std::string::npos)
705 {
706#if defined(ARMNN_TF_LITE_PARSER)
707 if (! isModelBinary)
708 {
709 BOOST_LOG_TRIVIAL(fatal) << "Unknown model format: '" << modelFormat << "'. Only 'binary' format supported \
710 for tflite files";
711 return EXIT_FAILURE;
712 }
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100713 return MainImpl<armnnTfLiteParser::ITfLiteParser, float>(params, runtime);
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100714#else
715 BOOST_LOG_TRIVIAL(fatal) << "Unknown model format: '" << modelFormat <<
716 "'. Please include 'caffe', 'tensorflow', 'tflite' or 'onnx'";
717 return EXIT_FAILURE;
718#endif
719 }
720 else
721 {
722 BOOST_LOG_TRIVIAL(fatal) << "Unknown model format: '" << modelFormat <<
723 "'. Please include 'caffe', 'tensorflow', 'tflite' or 'onnx'";
724 return EXIT_FAILURE;
725 }
726}
727
728int RunCsvTest(const armnnUtils::CsvRow &csvRow, const std::shared_ptr<armnn::IRuntime>& runtime,
Matthew Jackson54658b92019-08-27 15:35:59 +0100729 const bool enableProfiling, const bool enableFp16TurboMode, const double& thresholdTime,
Andre Ghattas23ae2ea2019-08-07 12:18:38 +0100730 const bool printIntermediate, bool enableLayerDetails = false)
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100731{
732 std::string modelFormat;
733 std::string modelPath;
734 std::string inputNames;
735 std::string inputTensorShapes;
736 std::string inputTensorDataFilePaths;
737 std::string outputNames;
738 std::string inputTypes;
739 std::string outputTypes;
Matteo Martincigh00dda4a2019-08-14 11:42:30 +0100740 std::string dynamicBackendsPath;
Sadik Armagan77086282019-09-02 11:46:28 +0100741 std::string outputTensorFiles;
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100742
743 size_t subgraphId = 0;
744
745 const std::string backendsMessage = std::string("The preferred order of devices to run layers on by default. ")
746 + std::string("Possible choices: ")
747 + armnn::BackendRegistryInstance().GetBackendIdsAsString();
748
749 po::options_description desc("Options");
750 try
751 {
752 desc.add_options()
753 ("model-format,f", po::value(&modelFormat),
754 "armnn-binary, caffe-binary, caffe-text, tflite-binary, onnx-binary, onnx-text, tensorflow-binary or "
755 "tensorflow-text.")
756 ("model-path,m", po::value(&modelPath), "Path to model file, e.g. .armnn, .caffemodel, .prototxt, "
757 ".tflite, .onnx")
758 ("compute,c", po::value<std::vector<armnn::BackendId>>()->multitoken(),
759 backendsMessage.c_str())
Matteo Martincigh00dda4a2019-08-14 11:42:30 +0100760 ("dynamic-backends-path,b", po::value(&dynamicBackendsPath),
761 "Path where to load any available dynamic backend from. "
762 "If left empty (the default), dynamic backends will not be used.")
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100763 ("input-name,i", po::value(&inputNames), "Identifier of the input tensors in the network separated by comma.")
764 ("subgraph-number,n", po::value<size_t>(&subgraphId)->default_value(0), "Id of the subgraph to be "
765 "executed. Defaults to 0.")
766 ("input-tensor-shape,s", po::value(&inputTensorShapes),
767 "The shape of the input tensors in the network as a flat array of integers separated by comma. "
768 "Several shapes can be passed separating them by semicolon. "
769 "This parameter is optional, depending on the network.")
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100770 ("input-tensor-data,d", po::value(&inputTensorDataFilePaths)->default_value(""),
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100771 "Path to files containing the input data as a flat array separated by whitespace. "
Aron Virginas-Tarc82c8732019-10-24 17:07:43 +0100772 "Several paths can be passed separating them by comma. If not specified, the network will be run with dummy "
773 "data (useful for profiling).")
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100774 ("input-type,y",po::value(&inputTypes), "The type of the input tensors in the network separated by comma. "
775 "If unset, defaults to \"float\" for all defined inputs. "
776 "Accepted values (float, int or qasymm8).")
Narumol Prangnawarat610256f2019-06-26 15:10:46 +0100777 ("quantize-input,q",po::bool_switch()->default_value(false),
778 "If this option is enabled, all float inputs will be quantized to qasymm8. "
779 "If unset, default to not quantized. "
780 "Accepted values (true or false)")
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100781 ("output-type,z",po::value(&outputTypes), "The type of the output tensors in the network separated by comma. "
782 "If unset, defaults to \"float\" for all defined outputs. "
783 "Accepted values (float, int or qasymm8).")
784 ("output-name,o", po::value(&outputNames),
Sadik Armagan77086282019-09-02 11:46:28 +0100785 "Identifier of the output tensors in the network separated by comma.")
786 ("write-outputs-to-file,w", po::value(&outputTensorFiles),
787 "Comma-separated list of output file paths keyed with the binding-id of the output slot. "
788 "If left empty (the default), the output tensors will not be written to a file.");
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100789 }
790 catch (const std::exception& e)
791 {
792 // Coverity points out that default_value(...) can throw a bad_lexical_cast,
793 // and that desc.add_options() can throw boost::io::too_few_args.
794 // They really won't in any of these cases.
795 BOOST_ASSERT_MSG(false, "Caught unexpected exception");
796 BOOST_LOG_TRIVIAL(fatal) << "Fatal internal error: " << e.what();
797 return EXIT_FAILURE;
798 }
799
800 std::vector<const char*> clOptions;
801 clOptions.reserve(csvRow.values.size());
802 for (const std::string& value : csvRow.values)
803 {
804 clOptions.push_back(value.c_str());
805 }
806
807 po::variables_map vm;
808 try
809 {
810 po::store(po::parse_command_line(static_cast<int>(clOptions.size()), clOptions.data(), desc), vm);
811
812 po::notify(vm);
813
814 CheckOptionDependencies(vm);
815 }
816 catch (const po::error& e)
817 {
818 std::cerr << e.what() << std::endl << std::endl;
819 std::cerr << desc << std::endl;
820 return EXIT_FAILURE;
821 }
822
Narumol Prangnawarat610256f2019-06-26 15:10:46 +0100823 // Get the value of the switch arguments.
824 bool quantizeInput = vm["quantize-input"].as<bool>();
825
Francis Murtaghbee4bc92019-06-18 12:30:37 +0100826 // Get the preferred order of compute devices.
827 std::vector<armnn::BackendId> computeDevices = vm["compute"].as<std::vector<armnn::BackendId>>();
828
829 // Remove duplicates from the list of compute devices.
830 RemoveDuplicateDevices(computeDevices);
831
832 // Check that the specified compute devices are valid.
833 std::string invalidBackends;
834 if (!CheckRequestedBackendsAreValid(computeDevices, armnn::Optional<std::string&>(invalidBackends)))
835 {
836 BOOST_LOG_TRIVIAL(fatal) << "The list of preferred devices contains invalid backend IDs: "
837 << invalidBackends;
838 return EXIT_FAILURE;
839 }
840
Matteo Martincigh00dda4a2019-08-14 11:42:30 +0100841 return RunTest(modelFormat, inputTensorShapes, computeDevices, dynamicBackendsPath, modelPath, inputNames,
Sadik Armagan77086282019-09-02 11:46:28 +0100842 inputTensorDataFilePaths, inputTypes, quantizeInput, outputTypes, outputNames, outputTensorFiles,
Andre Ghattas23ae2ea2019-08-07 12:18:38 +0100843 enableProfiling, enableFp16TurboMode, thresholdTime, printIntermediate, subgraphId,
844 enableLayerDetails);
Matteo Martincigh00dda4a2019-08-14 11:42:30 +0100845}