blob: 1de22ed5d097656e2aedc13cab7a39ecb9a936d5 [file] [log] [blame]
telsoa014fcda012018-03-09 14:13:49 +00001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa014fcda012018-03-09 14:13:49 +00004//
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +01005#include <armnn/ArmNN.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +01006#include <armnn/TypesUtils.hpp>
7
Aron Virginas-Tar64e4ccb2019-02-12 11:27:53 +00008#if defined(ARMNN_SERIALIZER)
Derek Lamberti0028d1b2019-02-20 13:57:42 +00009#include "armnnDeserializer/IDeserializer.hpp"
Aron Virginas-Tar64e4ccb2019-02-12 11:27:53 +000010#endif
telsoa014fcda012018-03-09 14:13:49 +000011#if defined(ARMNN_CAFFE_PARSER)
12#include "armnnCaffeParser/ICaffeParser.hpp"
13#endif
surmeh01bceff2f2018-03-29 16:29:27 +010014#if defined(ARMNN_TF_PARSER)
15#include "armnnTfParser/ITfParser.hpp"
16#endif
telsoa01c577f2c2018-08-31 09:22:23 +010017#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"
telsoa014fcda012018-03-09 14:13:49 +000024#include "../InferenceTest.hpp"
25
telsoa01c577f2c2018-08-31 09:22:23 +010026#include <Logging.hpp>
27#include <Profiling.hpp>
28
29#include <boost/algorithm/string/trim.hpp>
telsoa014fcda012018-03-09 14:13:49 +000030#include <boost/algorithm/string/split.hpp>
31#include <boost/algorithm/string/classification.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010032#include <boost/program_options.hpp>
Ferran Balaguerc602f292019-02-08 17:09:55 +000033#include <boost/variant.hpp>
telsoa014fcda012018-03-09 14:13:49 +000034
35#include <iostream>
36#include <fstream>
telsoa01c577f2c2018-08-31 09:22:23 +010037#include <functional>
38#include <future>
39#include <algorithm>
40#include <iterator>
telsoa014fcda012018-03-09 14:13:49 +000041
42namespace
43{
44
telsoa01c577f2c2018-08-31 09:22:23 +010045// Configure boost::program_options for command-line parsing and validation.
46namespace po = boost::program_options;
47
telsoa014fcda012018-03-09 14:13:49 +000048template<typename T, typename TParseElementFunc>
Ferran Balaguerc602f292019-02-08 17:09:55 +000049std::vector<T> ParseArrayImpl(std::istream& stream, TParseElementFunc parseElementFunc, const char * chars = "\t ,:")
telsoa014fcda012018-03-09 14:13:49 +000050{
51 std::vector<T> result;
telsoa01c577f2c2018-08-31 09:22:23 +010052 // Processes line-by-line.
telsoa014fcda012018-03-09 14:13:49 +000053 std::string line;
54 while (std::getline(stream, line))
55 {
56 std::vector<std::string> tokens;
surmeh013537c2c2018-05-18 16:31:43 +010057 try
58 {
59 // Coverity fix: boost::split() may throw an exception of type boost::bad_function_call.
Ferran Balaguerc602f292019-02-08 17:09:55 +000060 boost::split(tokens, line, boost::algorithm::is_any_of(chars), boost::token_compress_on);
surmeh013537c2c2018-05-18 16:31:43 +010061 }
62 catch (const std::exception& e)
63 {
64 BOOST_LOG_TRIVIAL(error) << "An error occurred when splitting tokens: " << e.what();
65 continue;
66 }
telsoa014fcda012018-03-09 14:13:49 +000067 for (const std::string& token : tokens)
68 {
69 if (!token.empty()) // See https://stackoverflow.com/questions/10437406/
70 {
71 try
72 {
73 result.push_back(parseElementFunc(token));
74 }
75 catch (const std::exception&)
76 {
77 BOOST_LOG_TRIVIAL(error) << "'" << token << "' is not a valid number. It has been ignored.";
78 }
79 }
80 }
81 }
82
83 return result;
84}
85
telsoa01c577f2c2018-08-31 09:22:23 +010086bool CheckOption(const po::variables_map& vm,
87 const char* option)
88{
89 // Check that the given option is valid.
90 if (option == nullptr)
91 {
92 return false;
93 }
94
95 // Check whether 'option' is provided.
96 return vm.find(option) != vm.end();
97}
98
99void CheckOptionDependency(const po::variables_map& vm,
100 const char* option,
101 const char* required)
102{
103 // Check that the given options are valid.
104 if (option == nullptr || required == nullptr)
105 {
106 throw po::error("Invalid option to check dependency for");
107 }
108
109 // Check that if 'option' is provided, 'required' is also provided.
110 if (CheckOption(vm, option) && !vm[option].defaulted())
111 {
112 if (CheckOption(vm, required) == 0 || vm[required].defaulted())
113 {
114 throw po::error(std::string("Option '") + option + "' requires option '" + required + "'.");
115 }
116 }
117}
118
119void CheckOptionDependencies(const po::variables_map& vm)
120{
121 CheckOptionDependency(vm, "model-path", "model-format");
122 CheckOptionDependency(vm, "model-path", "input-name");
123 CheckOptionDependency(vm, "model-path", "input-tensor-data");
124 CheckOptionDependency(vm, "model-path", "output-name");
125 CheckOptionDependency(vm, "input-tensor-shape", "model-path");
telsoa014fcda012018-03-09 14:13:49 +0000126}
127
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000128template<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);
telsoa014fcda012018-03-09 14:13:49 +0000135
136template<>
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000137auto ParseDataArray<armnn::DataType::Float32>(std::istream & stream)
telsoa014fcda012018-03-09 14:13:49 +0000138{
139 return ParseArrayImpl<float>(stream, [](const std::string& s) { return std::stof(s); });
140}
141
142template<>
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000143auto ParseDataArray<armnn::DataType::Signed32>(std::istream & stream)
144{
145 return ParseArrayImpl<int>(stream, [](const std::string & s) { return std::stoi(s); });
146}
147
148template<>
149auto ParseDataArray<armnn::DataType::QuantisedAsymm8>(std::istream& stream,
150 const float& quantizationScale,
151 const int32_t& quantizationOffset)
152{
153 return ParseArrayImpl<uint8_t>(stream,
154 [&quantizationScale, &quantizationOffset](const std::string & s)
155 {
156 return boost::numeric_cast<uint8_t>(
157 armnn::Quantize<u_int8_t>(std::stof(s),
158 quantizationScale,
159 quantizationOffset));
160 });
161}
162
telsoa014fcda012018-03-09 14:13:49 +0000163std::vector<unsigned int> ParseArray(std::istream& stream)
164{
165 return ParseArrayImpl<unsigned int>(stream,
166 [](const std::string& s) { return boost::numeric_cast<unsigned int>(std::stoi(s)); });
167}
168
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000169std::vector<std::string> ParseStringList(const std::string & inputString, const char * delimiter)
Ferran Balaguerc602f292019-02-08 17:09:55 +0000170{
171 std::stringstream stream(inputString);
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000172 return ParseArrayImpl<std::string>(stream, [](const std::string& s) { return boost::trim_copy(s); }, delimiter);
telsoa014fcda012018-03-09 14:13:49 +0000173}
174
David Beckf0b48452018-10-19 15:20:56 +0100175void RemoveDuplicateDevices(std::vector<armnn::BackendId>& computeDevices)
telsoa014fcda012018-03-09 14:13:49 +0000176{
telsoa01c577f2c2018-08-31 09:22:23 +0100177 // Mark the duplicate devices as 'Undefined'.
178 for (auto i = computeDevices.begin(); i != computeDevices.end(); ++i)
179 {
180 for (auto j = std::next(i); j != computeDevices.end(); ++j)
181 {
182 if (*j == *i)
183 {
184 *j = armnn::Compute::Undefined;
185 }
186 }
187 }
188
189 // Remove 'Undefined' devices.
190 computeDevices.erase(std::remove(computeDevices.begin(), computeDevices.end(), armnn::Compute::Undefined),
191 computeDevices.end());
192}
193
telsoa01c577f2c2018-08-31 09:22:23 +0100194} // namespace
195
196template<typename TParser, typename TDataType>
197int MainImpl(const char* modelPath,
198 bool isModelBinary,
Aron Virginas-Tar339bcae2019-01-31 16:44:26 +0000199 const std::vector<armnn::BackendId>& computeDevices,
Ferran Balaguerc602f292019-02-08 17:09:55 +0000200 const std::vector<string>& inputNames,
201 const std::vector<std::unique_ptr<armnn::TensorShape>>& inputTensorShapes,
202 const std::vector<string>& inputTensorDataFilePaths,
203 const std::vector<string>& inputTypes,
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000204 const std::vector<string>& outputTypes,
Ferran Balaguerc602f292019-02-08 17:09:55 +0000205 const std::vector<string>& outputNames,
telsoa01c577f2c2018-08-31 09:22:23 +0100206 bool enableProfiling,
Ruomei Yan2fcce082019-04-02 16:47:34 +0100207 bool enableFp16TurboMode,
James Conroy7b4886f2019-04-11 10:23:58 +0100208 const double& thresholdTime,
telsoa01c577f2c2018-08-31 09:22:23 +0100209 const size_t subgraphId,
210 const std::shared_ptr<armnn::IRuntime>& runtime = nullptr)
211{
Ferran Balaguerc602f292019-02-08 17:09:55 +0000212 using TContainer = boost::variant<std::vector<float>, std::vector<int>, std::vector<unsigned char>>;
Aron Virginas-Tar7cf0eaa2019-01-24 17:05:36 +0000213
Ferran Balaguerc602f292019-02-08 17:09:55 +0000214 std::vector<TContainer> inputDataContainers;
215
telsoa014fcda012018-03-09 14:13:49 +0000216 try
217 {
telsoa01c577f2c2018-08-31 09:22:23 +0100218 // Creates an InferenceModel, which will parse the model and load it into an IRuntime.
telsoa014fcda012018-03-09 14:13:49 +0000219 typename InferenceModel<TParser, TDataType>::Params params;
220 params.m_ModelPath = modelPath;
221 params.m_IsModelBinary = isModelBinary;
Aron Virginas-Tar339bcae2019-01-31 16:44:26 +0000222 params.m_ComputeDevices = computeDevices;
Ferran Balaguerc602f292019-02-08 17:09:55 +0000223
224 for(const std::string& inputName: inputNames)
225 {
226 params.m_InputBindings.push_back(inputName);
227 }
228
229 for(unsigned int i = 0; i < inputTensorShapes.size(); ++i)
230 {
231 params.m_InputShapes.push_back(*inputTensorShapes[i]);
232 }
233
234 for(const std::string& outputName: outputNames)
235 {
236 params.m_OutputBindings.push_back(outputName);
237 }
238
telsoa01c577f2c2018-08-31 09:22:23 +0100239 params.m_SubgraphId = subgraphId;
Ruomei Yan2fcce082019-04-02 16:47:34 +0100240 params.m_EnableFp16TurboMode = enableFp16TurboMode;
Matthew Bentham3e68b972019-04-09 13:10:46 +0100241 InferenceModel<TParser, TDataType> model(params, enableProfiling, runtime);
telsoa014fcda012018-03-09 14:13:49 +0000242
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000243 for(unsigned int i = 0; i < inputTensorDataFilePaths.size(); ++i)
244 {
245 std::ifstream inputTensorFile(inputTensorDataFilePaths[i]);
246
247 if (inputTypes[i].compare("float") == 0)
248 {
249 inputDataContainers.push_back(
250 ParseDataArray<armnn::DataType::Float32>(inputTensorFile));
251 }
252 else if (inputTypes[i].compare("int") == 0)
253 {
254 inputDataContainers.push_back(
255 ParseDataArray<armnn::DataType::Signed32>(inputTensorFile));
256 }
257 else if (inputTypes[i].compare("qasymm8") == 0)
258 {
259 auto inputBinding = model.GetInputBindingInfo();
260 inputDataContainers.push_back(
261 ParseDataArray<armnn::DataType::QuantisedAsymm8>(inputTensorFile,
262 inputBinding.second.GetQuantizationScale(),
263 inputBinding.second.GetQuantizationOffset()));
264 }
265 else
266 {
267 BOOST_LOG_TRIVIAL(fatal) << "Unsupported tensor data type \"" << inputTypes[i] << "\". ";
268 return EXIT_FAILURE;
269 }
270
271 inputTensorFile.close();
272 }
273
Ferran Balaguerc602f292019-02-08 17:09:55 +0000274 const size_t numOutputs = params.m_OutputBindings.size();
275 std::vector<TContainer> outputDataContainers;
Aron Virginas-Tar9b937472019-01-30 17:41:47 +0000276
Ferran Balaguerc602f292019-02-08 17:09:55 +0000277 for (unsigned int i = 0; i < numOutputs; ++i)
278 {
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000279 if (outputTypes[i].compare("float") == 0)
280 {
281 outputDataContainers.push_back(std::vector<float>(model.GetOutputSize(i)));
282 }
283 else if (outputTypes[i].compare("int") == 0)
284 {
285 outputDataContainers.push_back(std::vector<int>(model.GetOutputSize(i)));
286 }
287 else if (outputTypes[i].compare("qasymm8") == 0)
288 {
289 outputDataContainers.push_back(std::vector<uint8_t>(model.GetOutputSize(i)));
290 }
291 else
292 {
293 BOOST_LOG_TRIVIAL(fatal) << "Unsupported tensor data type \"" << outputTypes[i] << "\". ";
294 return EXIT_FAILURE;
295 }
Ferran Balaguerc602f292019-02-08 17:09:55 +0000296 }
Aron Virginas-Tar93f5f972019-01-31 13:12:34 +0000297
James Conroy7b4886f2019-04-11 10:23:58 +0100298 // model.Run returns the inference time elapsed in EnqueueWorkload (in milliseconds)
299 auto inference_duration = model.Run(inputDataContainers, outputDataContainers);
telsoa014fcda012018-03-09 14:13:49 +0000300
Aron Virginas-Tar7cf0eaa2019-01-24 17:05:36 +0000301 // Print output tensors
302 for (size_t i = 0; i < numOutputs; i++)
303 {
Ferran Balaguerc602f292019-02-08 17:09:55 +0000304 boost::apply_visitor([&](auto&& value)
305 {
306 std::cout << params.m_OutputBindings[i] << ": ";
307 for (size_t i = 0; i < value.size(); ++i)
308 {
309 printf("%f ", static_cast<float>(value[i]));
310 }
311 printf("\n");
312 },
313 outputDataContainers[i]);
Aron Virginas-Tar7cf0eaa2019-01-24 17:05:36 +0000314 }
James Conroy7b4886f2019-04-11 10:23:58 +0100315
316 BOOST_LOG_TRIVIAL(info) << "\nInference time: " << std::setprecision(2)
317 << std::fixed << inference_duration.count() << " ms";
318
319 // If thresholdTime == 0.0 (default), then it hasn't been supplied at command line
320 if (thresholdTime != 0.0)
321 {
322 BOOST_LOG_TRIVIAL(info) << "Threshold time: " << std::setprecision(2)
323 << std::fixed << thresholdTime << " ms";
324 auto thresholdMinusInference = thresholdTime - inference_duration.count();
325 BOOST_LOG_TRIVIAL(info) << "Threshold time - Inference time: " << std::setprecision(2)
326 << std::fixed << thresholdMinusInference << " ms" << "\n";
327
328 if (thresholdMinusInference < 0)
329 {
330 BOOST_LOG_TRIVIAL(fatal) << "Elapsed inference time is greater than provided threshold time.\n";
331 return EXIT_FAILURE;
332 }
333 }
334
335
telsoa014fcda012018-03-09 14:13:49 +0000336 }
337 catch (armnn::Exception const& e)
338 {
339 BOOST_LOG_TRIVIAL(fatal) << "Armnn Error: " << e.what();
telsoa01c577f2c2018-08-31 09:22:23 +0100340 return EXIT_FAILURE;
telsoa014fcda012018-03-09 14:13:49 +0000341 }
342
telsoa01c577f2c2018-08-31 09:22:23 +0100343 return EXIT_SUCCESS;
telsoa014fcda012018-03-09 14:13:49 +0000344}
345
telsoa01c577f2c2018-08-31 09:22:23 +0100346// This will run a test
Ferran Balaguerc602f292019-02-08 17:09:55 +0000347int RunTest(const std::string& format,
348 const std::string& inputTensorShapesStr,
David Beckf0b48452018-10-19 15:20:56 +0100349 const vector<armnn::BackendId>& computeDevice,
Ferran Balaguerc602f292019-02-08 17:09:55 +0000350 const std::string& path,
351 const std::string& inputNames,
352 const std::string& inputTensorDataFilePaths,
353 const std::string& inputTypes,
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000354 const std::string& outputTypes,
Ferran Balaguerc602f292019-02-08 17:09:55 +0000355 const std::string& outputNames,
telsoa01c577f2c2018-08-31 09:22:23 +0100356 bool enableProfiling,
Ruomei Yan2fcce082019-04-02 16:47:34 +0100357 bool enableFp16TurboMode,
James Conroy7b4886f2019-04-11 10:23:58 +0100358 const double& thresholdTime,
telsoa01c577f2c2018-08-31 09:22:23 +0100359 const size_t subgraphId,
360 const std::shared_ptr<armnn::IRuntime>& runtime = nullptr)
telsoa014fcda012018-03-09 14:13:49 +0000361{
Ferran Balaguerc602f292019-02-08 17:09:55 +0000362 std::string modelFormat = boost::trim_copy(format);
363 std::string modelPath = boost::trim_copy(path);
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000364 std::vector<std::string> inputNamesVector = ParseStringList(inputNames, ",");
365 std::vector<std::string> inputTensorShapesVector = ParseStringList(inputTensorShapesStr, ";");
366 std::vector<std::string> inputTensorDataFilePathsVector = ParseStringList(
367 inputTensorDataFilePaths, ",");
368 std::vector<std::string> outputNamesVector = ParseStringList(outputNames, ",");
369 std::vector<std::string> inputTypesVector = ParseStringList(inputTypes, ",");
370 std::vector<std::string> outputTypesVector = ParseStringList(outputTypes, ",");
Ferran Balaguerc602f292019-02-08 17:09:55 +0000371
telsoa014fcda012018-03-09 14:13:49 +0000372 // Parse model binary flag from the model-format string we got from the command-line
373 bool isModelBinary;
374 if (modelFormat.find("bin") != std::string::npos)
375 {
376 isModelBinary = true;
377 }
378 else if (modelFormat.find("txt") != std::string::npos || modelFormat.find("text") != std::string::npos)
379 {
380 isModelBinary = false;
381 }
382 else
383 {
384 BOOST_LOG_TRIVIAL(fatal) << "Unknown model format: '" << modelFormat << "'. Please include 'binary' or 'text'";
telsoa01c577f2c2018-08-31 09:22:23 +0100385 return EXIT_FAILURE;
telsoa014fcda012018-03-09 14:13:49 +0000386 }
387
Ferran Balaguerc602f292019-02-08 17:09:55 +0000388 if ((inputTensorShapesVector.size() != 0) && (inputTensorShapesVector.size() != inputNamesVector.size()))
telsoa014fcda012018-03-09 14:13:49 +0000389 {
Ferran Balaguerc602f292019-02-08 17:09:55 +0000390 BOOST_LOG_TRIVIAL(fatal) << "input-name and input-tensor-shape must have the same amount of elements.";
391 return EXIT_FAILURE;
392 }
surmeh013537c2c2018-05-18 16:31:43 +0100393
Ferran Balaguerc602f292019-02-08 17:09:55 +0000394 if ((inputTensorDataFilePathsVector.size() != 0) &&
395 (inputTensorDataFilePathsVector.size() != inputNamesVector.size()))
396 {
397 BOOST_LOG_TRIVIAL(fatal) << "input-name and input-tensor-data must have the same amount of elements.";
398 return EXIT_FAILURE;
399 }
400
401 if (inputTypesVector.size() == 0)
402 {
403 //Defaults the value of all inputs to "float"
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000404 inputTypesVector.assign(inputNamesVector.size(), "float");
405 }
406 if (outputTypesVector.size() == 0)
407 {
408 //Defaults the value of all outputs to "float"
409 outputTypesVector.assign(outputNamesVector.size(), "float");
Ferran Balaguerc602f292019-02-08 17:09:55 +0000410 }
411 else if ((inputTypesVector.size() != 0) && (inputTypesVector.size() != inputNamesVector.size()))
412 {
413 BOOST_LOG_TRIVIAL(fatal) << "input-name and input-type must have the same amount of elements.";
414 return EXIT_FAILURE;
415 }
416
417 // Parse input tensor shape from the string we got from the command-line.
418 std::vector<std::unique_ptr<armnn::TensorShape>> inputTensorShapes;
419
420 if (!inputTensorShapesVector.empty())
421 {
422 inputTensorShapes.reserve(inputTensorShapesVector.size());
423
424 for(const std::string& shape : inputTensorShapesVector)
surmeh013537c2c2018-05-18 16:31:43 +0100425 {
Ferran Balaguerc602f292019-02-08 17:09:55 +0000426 std::stringstream ss(shape);
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000427 std::vector<unsigned int> dims = ParseArray(ss);
Ferran Balaguerc602f292019-02-08 17:09:55 +0000428
429 try
430 {
431 // Coverity fix: An exception of type armnn::InvalidArgumentException is thrown and never caught.
432 inputTensorShapes.push_back(std::make_unique<armnn::TensorShape>(dims.size(), dims.data()));
433 }
434 catch (const armnn::InvalidArgumentException& e)
435 {
436 BOOST_LOG_TRIVIAL(fatal) << "Cannot create tensor shape: " << e.what();
437 return EXIT_FAILURE;
438 }
surmeh013537c2c2018-05-18 16:31:43 +0100439 }
telsoa014fcda012018-03-09 14:13:49 +0000440 }
441
James Conroy7b4886f2019-04-11 10:23:58 +0100442 // Check that threshold time is not less than zero
443 if (thresholdTime < 0)
444 {
445 BOOST_LOG_TRIVIAL(fatal) << "Threshold time supplied as a commoand line argument is less than zero.";
446 return EXIT_FAILURE;
447 }
448
telsoa014fcda012018-03-09 14:13:49 +0000449 // Forward to implementation based on the parser type
Aron Virginas-Tar64e4ccb2019-02-12 11:27:53 +0000450 if (modelFormat.find("armnn") != std::string::npos)
451 {
452#if defined(ARMNN_SERIALIZER)
Derek Lamberti0028d1b2019-02-20 13:57:42 +0000453 return MainImpl<armnnDeserializer::IDeserializer, float>(
Aron Virginas-Tar64e4ccb2019-02-12 11:27:53 +0000454 modelPath.c_str(), isModelBinary, computeDevice,
455 inputNamesVector, inputTensorShapes,
James Conroy7b4886f2019-04-11 10:23:58 +0100456 inputTensorDataFilePathsVector, inputTypesVector,
457 outputTypesVector, outputNamesVector, enableProfiling,
458 enableFp16TurboMode, thresholdTime, subgraphId, runtime);
Aron Virginas-Tar64e4ccb2019-02-12 11:27:53 +0000459#else
460 BOOST_LOG_TRIVIAL(fatal) << "Not built with serialization support.";
461 return EXIT_FAILURE;
462#endif
463 }
464 else if (modelFormat.find("caffe") != std::string::npos)
telsoa014fcda012018-03-09 14:13:49 +0000465 {
466#if defined(ARMNN_CAFFE_PARSER)
467 return MainImpl<armnnCaffeParser::ICaffeParser, float>(modelPath.c_str(), isModelBinary, computeDevice,
Ferran Balaguerc602f292019-02-08 17:09:55 +0000468 inputNamesVector, inputTensorShapes,
469 inputTensorDataFilePathsVector, inputTypesVector,
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000470 outputTypesVector, outputNamesVector, enableProfiling,
James Conroy7b4886f2019-04-11 10:23:58 +0100471 enableFp16TurboMode, thresholdTime, subgraphId, runtime);
telsoa014fcda012018-03-09 14:13:49 +0000472#else
473 BOOST_LOG_TRIVIAL(fatal) << "Not built with Caffe parser support.";
telsoa01c577f2c2018-08-31 09:22:23 +0100474 return EXIT_FAILURE;
475#endif
476 }
477 else if (modelFormat.find("onnx") != std::string::npos)
478{
479#if defined(ARMNN_ONNX_PARSER)
480 return MainImpl<armnnOnnxParser::IOnnxParser, float>(modelPath.c_str(), isModelBinary, computeDevice,
Ferran Balaguerc602f292019-02-08 17:09:55 +0000481 inputNamesVector, inputTensorShapes,
482 inputTensorDataFilePathsVector, inputTypesVector,
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000483 outputTypesVector, outputNamesVector, enableProfiling,
James Conroy7b4886f2019-04-11 10:23:58 +0100484 enableFp16TurboMode, thresholdTime, subgraphId, runtime);
telsoa01c577f2c2018-08-31 09:22:23 +0100485#else
486 BOOST_LOG_TRIVIAL(fatal) << "Not built with Onnx parser support.";
487 return EXIT_FAILURE;
telsoa014fcda012018-03-09 14:13:49 +0000488#endif
489 }
490 else if (modelFormat.find("tensorflow") != std::string::npos)
491 {
surmeh01bceff2f2018-03-29 16:29:27 +0100492#if defined(ARMNN_TF_PARSER)
493 return MainImpl<armnnTfParser::ITfParser, float>(modelPath.c_str(), isModelBinary, computeDevice,
Ferran Balaguerc602f292019-02-08 17:09:55 +0000494 inputNamesVector, inputTensorShapes,
495 inputTensorDataFilePathsVector, inputTypesVector,
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000496 outputTypesVector, outputNamesVector, enableProfiling,
James Conroy7b4886f2019-04-11 10:23:58 +0100497 enableFp16TurboMode, thresholdTime, subgraphId, runtime);
surmeh01bceff2f2018-03-29 16:29:27 +0100498#else
telsoa014fcda012018-03-09 14:13:49 +0000499 BOOST_LOG_TRIVIAL(fatal) << "Not built with Tensorflow parser support.";
telsoa01c577f2c2018-08-31 09:22:23 +0100500 return EXIT_FAILURE;
501#endif
502 }
503 else if(modelFormat.find("tflite") != std::string::npos)
504 {
505#if defined(ARMNN_TF_LITE_PARSER)
506 if (! isModelBinary)
507 {
508 BOOST_LOG_TRIVIAL(fatal) << "Unknown model format: '" << modelFormat << "'. Only 'binary' format supported \
509 for tflite files";
510 return EXIT_FAILURE;
511 }
512 return MainImpl<armnnTfLiteParser::ITfLiteParser, float>(modelPath.c_str(), isModelBinary, computeDevice,
Ferran Balaguerc602f292019-02-08 17:09:55 +0000513 inputNamesVector, inputTensorShapes,
514 inputTensorDataFilePathsVector, inputTypesVector,
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000515 outputTypesVector, outputNamesVector, enableProfiling,
James Conroy7b4886f2019-04-11 10:23:58 +0100516 enableFp16TurboMode, thresholdTime, subgraphId,
517 runtime);
telsoa01c577f2c2018-08-31 09:22:23 +0100518#else
519 BOOST_LOG_TRIVIAL(fatal) << "Unknown model format: '" << modelFormat <<
520 "'. Please include 'caffe', 'tensorflow', 'tflite' or 'onnx'";
521 return EXIT_FAILURE;
surmeh01bceff2f2018-03-29 16:29:27 +0100522#endif
telsoa014fcda012018-03-09 14:13:49 +0000523 }
524 else
525 {
526 BOOST_LOG_TRIVIAL(fatal) << "Unknown model format: '" << modelFormat <<
telsoa01c577f2c2018-08-31 09:22:23 +0100527 "'. Please include 'caffe', 'tensorflow', 'tflite' or 'onnx'";
528 return EXIT_FAILURE;
529 }
530}
531
Ruomei Yan2fcce082019-04-02 16:47:34 +0100532int RunCsvTest(const armnnUtils::CsvRow &csvRow, const std::shared_ptr<armnn::IRuntime>& runtime,
James Conroy7b4886f2019-04-11 10:23:58 +0100533 const bool enableProfiling, const bool enableFp16TurboMode, const double& thresholdTime)
telsoa01c577f2c2018-08-31 09:22:23 +0100534{
535 std::string modelFormat;
536 std::string modelPath;
Ferran Balaguerc602f292019-02-08 17:09:55 +0000537 std::string inputNames;
538 std::string inputTensorShapes;
539 std::string inputTensorDataFilePaths;
540 std::string outputNames;
541 std::string inputTypes;
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000542 std::string outputTypes;
telsoa01c577f2c2018-08-31 09:22:23 +0100543
544 size_t subgraphId = 0;
545
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +0100546 const std::string backendsMessage = std::string("The preferred order of devices to run layers on by default. ")
547 + std::string("Possible choices: ")
548 + armnn::BackendRegistryInstance().GetBackendIdsAsString();
549
telsoa01c577f2c2018-08-31 09:22:23 +0100550 po::options_description desc("Options");
551 try
552 {
553 desc.add_options()
554 ("model-format,f", po::value(&modelFormat),
Aron Virginas-Tar64e4ccb2019-02-12 11:27:53 +0000555 "armnn-binary, caffe-binary, caffe-text, tflite-binary, onnx-binary, onnx-text, tensorflow-binary or "
556 "tensorflow-text.")
557 ("model-path,m", po::value(&modelPath), "Path to model file, e.g. .armnn, .caffemodel, .prototxt, "
558 ".tflite, .onnx")
David Beckf0b48452018-10-19 15:20:56 +0100559 ("compute,c", po::value<std::vector<armnn::BackendId>>()->multitoken(),
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +0100560 backendsMessage.c_str())
Ferran Balaguerc602f292019-02-08 17:09:55 +0000561 ("input-name,i", po::value(&inputNames), "Identifier of the input tensors in the network separated by comma.")
telsoa01c577f2c2018-08-31 09:22:23 +0100562 ("subgraph-number,n", po::value<size_t>(&subgraphId)->default_value(0), "Id of the subgraph to be "
Ferran Balaguerc602f292019-02-08 17:09:55 +0000563 "executed. Defaults to 0.")
564 ("input-tensor-shape,s", po::value(&inputTensorShapes),
565 "The shape of the input tensors in the network as a flat array of integers separated by comma. "
566 "Several shapes can be passed separating them by semicolon. "
telsoa01c577f2c2018-08-31 09:22:23 +0100567 "This parameter is optional, depending on the network.")
Ferran Balaguerc602f292019-02-08 17:09:55 +0000568 ("input-tensor-data,d", po::value(&inputTensorDataFilePaths),
569 "Path to files containing the input data as a flat array separated by whitespace. "
570 "Several paths can be passed separating them by comma.")
571 ("input-type,y",po::value(&inputTypes), "The type of the input tensors in the network separated by comma. "
572 "If unset, defaults to \"float\" for all defined inputs. "
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000573 "Accepted values (float, int or qasymm8).")
574 ("output-type,z",po::value(&outputTypes), "The type of the output tensors in the network separated by comma. "
575 "If unset, defaults to \"float\" for all defined outputs. "
576 "Accepted values (float, int or qasymm8).")
Ferran Balaguerc602f292019-02-08 17:09:55 +0000577 ("output-name,o", po::value(&outputNames),
578 "Identifier of the output tensors in the network separated by comma.");
telsoa01c577f2c2018-08-31 09:22:23 +0100579 }
580 catch (const std::exception& e)
581 {
582 // Coverity points out that default_value(...) can throw a bad_lexical_cast,
583 // and that desc.add_options() can throw boost::io::too_few_args.
584 // They really won't in any of these cases.
585 BOOST_ASSERT_MSG(false, "Caught unexpected exception");
586 BOOST_LOG_TRIVIAL(fatal) << "Fatal internal error: " << e.what();
587 return EXIT_FAILURE;
588 }
589
590 std::vector<const char*> clOptions;
591 clOptions.reserve(csvRow.values.size());
592 for (const std::string& value : csvRow.values)
593 {
594 clOptions.push_back(value.c_str());
595 }
596
597 po::variables_map vm;
598 try
599 {
600 po::store(po::parse_command_line(static_cast<int>(clOptions.size()), clOptions.data(), desc), vm);
601
602 po::notify(vm);
603
604 CheckOptionDependencies(vm);
605 }
606 catch (const po::error& e)
607 {
608 std::cerr << e.what() << std::endl << std::endl;
609 std::cerr << desc << std::endl;
610 return EXIT_FAILURE;
611 }
612
telsoa01c577f2c2018-08-31 09:22:23 +0100613 // Get the preferred order of compute devices.
David Beckf0b48452018-10-19 15:20:56 +0100614 std::vector<armnn::BackendId> computeDevices = vm["compute"].as<std::vector<armnn::BackendId>>();
telsoa01c577f2c2018-08-31 09:22:23 +0100615
616 // Remove duplicates from the list of compute devices.
617 RemoveDuplicateDevices(computeDevices);
618
619 // Check that the specified compute devices are valid.
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +0100620 std::string invalidBackends;
621 if (!CheckRequestedBackendsAreValid(computeDevices, armnn::Optional<std::string&>(invalidBackends)))
telsoa01c577f2c2018-08-31 09:22:23 +0100622 {
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +0100623 BOOST_LOG_TRIVIAL(fatal) << "The list of preferred devices contains invalid backend IDs: "
624 << invalidBackends;
telsoa01c577f2c2018-08-31 09:22:23 +0100625 return EXIT_FAILURE;
626 }
627
James Conroy7b4886f2019-04-11 10:23:58 +0100628 return RunTest(modelFormat, inputTensorShapes, computeDevices, modelPath, inputNames,
629 inputTensorDataFilePaths, inputTypes, outputTypes, outputNames,
630 enableProfiling, enableFp16TurboMode, thresholdTime, subgraphId);
telsoa01c577f2c2018-08-31 09:22:23 +0100631}
632
James Conroy7b4886f2019-04-11 10:23:58 +0100633// MAIN
telsoa01c577f2c2018-08-31 09:22:23 +0100634int main(int argc, const char* argv[])
635{
636 // Configures logging for both the ARMNN library and this test program.
637#ifdef NDEBUG
638 armnn::LogSeverity level = armnn::LogSeverity::Info;
639#else
640 armnn::LogSeverity level = armnn::LogSeverity::Debug;
641#endif
642 armnn::ConfigureLogging(true, true, level);
643 armnnUtils::ConfigureLogging(boost::log::core::get().get(), true, true, level);
644
645 std::string testCasesFile;
646
647 std::string modelFormat;
648 std::string modelPath;
Ferran Balaguerc602f292019-02-08 17:09:55 +0000649 std::string inputNames;
650 std::string inputTensorShapes;
651 std::string inputTensorDataFilePaths;
652 std::string outputNames;
653 std::string inputTypes;
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000654 std::string outputTypes;
telsoa01c577f2c2018-08-31 09:22:23 +0100655
James Conroy7b4886f2019-04-11 10:23:58 +0100656 double thresholdTime = 0.0;
657
telsoa01c577f2c2018-08-31 09:22:23 +0100658 size_t subgraphId = 0;
659
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +0100660 const std::string backendsMessage = "Which device to run layers on by default. Possible choices: "
661 + armnn::BackendRegistryInstance().GetBackendIdsAsString();
662
telsoa01c577f2c2018-08-31 09:22:23 +0100663 po::options_description desc("Options");
664 try
665 {
666 desc.add_options()
667 ("help", "Display usage information")
668 ("test-cases,t", po::value(&testCasesFile), "Path to a CSV file containing test cases to run. "
669 "If set, further parameters -- with the exception of compute device and concurrency -- will be ignored, "
670 "as they are expected to be defined in the file for each test in particular.")
671 ("concurrent,n", po::bool_switch()->default_value(false),
672 "Whether or not the test cases should be executed in parallel")
Matteo Martincigh49124022019-01-11 13:25:59 +0000673 ("model-format,f", po::value(&modelFormat)->required(),
Aron Virginas-Tar64e4ccb2019-02-12 11:27:53 +0000674 "armnn-binary, caffe-binary, caffe-text, onnx-binary, onnx-text, tflite-binary, tensorflow-binary or "
675 "tensorflow-text.")
676 ("model-path,m", po::value(&modelPath)->required(), "Path to model file, e.g. .armnn, .caffemodel, "
677 ".prototxt, .tflite, .onnx")
David Beckf0b48452018-10-19 15:20:56 +0100678 ("compute,c", po::value<std::vector<std::string>>()->multitoken(),
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +0100679 backendsMessage.c_str())
Ferran Balaguerc602f292019-02-08 17:09:55 +0000680 ("input-name,i", po::value(&inputNames),
681 "Identifier of the input tensors in the network separated by comma.")
telsoa01c577f2c2018-08-31 09:22:23 +0100682 ("subgraph-number,x", po::value<size_t>(&subgraphId)->default_value(0), "Id of the subgraph to be executed."
683 "Defaults to 0")
Ferran Balaguerc602f292019-02-08 17:09:55 +0000684 ("input-tensor-shape,s", po::value(&inputTensorShapes),
685 "The shape of the input tensors in the network as a flat array of integers separated by comma. "
686 "Several shapes can be passed separating them by semicolon. "
telsoa01c577f2c2018-08-31 09:22:23 +0100687 "This parameter is optional, depending on the network.")
Ferran Balaguerc602f292019-02-08 17:09:55 +0000688 ("input-tensor-data,d", po::value(&inputTensorDataFilePaths),
689 "Path to files containing the input data as a flat array separated by whitespace. "
690 "Several paths can be passed separating them by comma. ")
691 ("input-type,y",po::value(&inputTypes), "The type of the input tensors in the network separated by comma. "
692 "If unset, defaults to \"float\" for all defined inputs. "
Éanna Ó Catháinb3d481a2019-02-26 11:26:24 +0000693 "Accepted values (float, int or qasymm8)")
694 ("output-type,z",po::value(&outputTypes),
695 "The type of the output tensors in the network separated by comma. "
696 "If unset, defaults to \"float\" for all defined outputs. "
697 "Accepted values (float, int or qasymm8).")
Ferran Balaguerc602f292019-02-08 17:09:55 +0000698 ("output-name,o", po::value(&outputNames),
699 "Identifier of the output tensors in the network separated by comma.")
telsoa01c577f2c2018-08-31 09:22:23 +0100700 ("event-based-profiling,e", po::bool_switch()->default_value(false),
Ruomei Yan2fcce082019-04-02 16:47:34 +0100701 "Enables built in profiler. If unset, defaults to off.")
702 ("fp16-turbo-mode,h", po::bool_switch()->default_value(false), "If this option is enabled, FP32 layers, "
James Conroy7b4886f2019-04-11 10:23:58 +0100703 "weights and biases will be converted to FP16 where the backend supports it")
704 ("threshold-time,r", po::value<double>(&thresholdTime)->default_value(0.0),
705 "Threshold time is the maximum allowed time for inference measured in milliseconds. If the actual "
706 "inference time is greater than the threshold time, the test will fail. By default, no threshold "
707 "time is used.");
telsoa01c577f2c2018-08-31 09:22:23 +0100708 }
709 catch (const std::exception& e)
710 {
711 // Coverity points out that default_value(...) can throw a bad_lexical_cast,
712 // and that desc.add_options() can throw boost::io::too_few_args.
713 // They really won't in any of these cases.
714 BOOST_ASSERT_MSG(false, "Caught unexpected exception");
715 BOOST_LOG_TRIVIAL(fatal) << "Fatal internal error: " << e.what();
716 return EXIT_FAILURE;
717 }
718
719 // Parses the command-line.
720 po::variables_map vm;
721 try
722 {
723 po::store(po::parse_command_line(argc, argv, desc), vm);
724
725 if (CheckOption(vm, "help") || argc <= 1)
726 {
727 std::cout << "Executes a neural network model using the provided input tensor. " << std::endl;
728 std::cout << "Prints the resulting output tensor." << std::endl;
729 std::cout << std::endl;
730 std::cout << desc << std::endl;
731 return EXIT_SUCCESS;
732 }
733
734 po::notify(vm);
735 }
736 catch (const po::error& e)
737 {
738 std::cerr << e.what() << std::endl << std::endl;
739 std::cerr << desc << std::endl;
740 return EXIT_FAILURE;
741 }
742
743 // Get the value of the switch arguments.
744 bool concurrent = vm["concurrent"].as<bool>();
745 bool enableProfiling = vm["event-based-profiling"].as<bool>();
Ruomei Yan2fcce082019-04-02 16:47:34 +0100746 bool enableFp16TurboMode = vm["fp16-turbo-mode"].as<bool>();
telsoa01c577f2c2018-08-31 09:22:23 +0100747
748 // Check whether we have to load test cases from a file.
749 if (CheckOption(vm, "test-cases"))
750 {
751 // Check that the file exists.
752 if (!boost::filesystem::exists(testCasesFile))
753 {
754 BOOST_LOG_TRIVIAL(fatal) << "Given file \"" << testCasesFile << "\" does not exist";
755 return EXIT_FAILURE;
756 }
757
758 // Parse CSV file and extract test cases
759 armnnUtils::CsvReader reader;
760 std::vector<armnnUtils::CsvRow> testCases = reader.ParseFile(testCasesFile);
761
762 // Check that there is at least one test case to run
763 if (testCases.empty())
764 {
765 BOOST_LOG_TRIVIAL(fatal) << "Given file \"" << testCasesFile << "\" has no test cases";
766 return EXIT_FAILURE;
767 }
768
769 // Create runtime
770 armnn::IRuntime::CreationOptions options;
Nina Drozd549ae372018-09-10 14:26:44 +0100771 options.m_EnableGpuProfiling = enableProfiling;
772
telsoa01c577f2c2018-08-31 09:22:23 +0100773 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(options));
774
775 const std::string executableName("ExecuteNetwork");
776
777 // Check whether we need to run the test cases concurrently
778 if (concurrent)
779 {
780 std::vector<std::future<int>> results;
781 results.reserve(testCases.size());
782
783 // Run each test case in its own thread
784 for (auto& testCase : testCases)
785 {
786 testCase.values.insert(testCase.values.begin(), executableName);
Nina Drozd549ae372018-09-10 14:26:44 +0100787 results.push_back(std::async(std::launch::async, RunCsvTest, std::cref(testCase), std::cref(runtime),
James Conroy7b4886f2019-04-11 10:23:58 +0100788 enableProfiling, enableFp16TurboMode, thresholdTime));
telsoa01c577f2c2018-08-31 09:22:23 +0100789 }
790
791 // Check results
792 for (auto& result : results)
793 {
794 if (result.get() != EXIT_SUCCESS)
795 {
796 return EXIT_FAILURE;
797 }
798 }
799 }
800 else
801 {
802 // Run tests sequentially
803 for (auto& testCase : testCases)
804 {
805 testCase.values.insert(testCase.values.begin(), executableName);
James Conroy7b4886f2019-04-11 10:23:58 +0100806 if (RunCsvTest(testCase, runtime, enableProfiling, enableFp16TurboMode, thresholdTime) != EXIT_SUCCESS)
telsoa01c577f2c2018-08-31 09:22:23 +0100807 {
808 return EXIT_FAILURE;
809 }
810 }
811 }
812
813 return EXIT_SUCCESS;
814 }
815 else // Run single test
816 {
Aron Virginas-Tar382e21c2019-01-22 14:10:39 +0000817 // Get the preferred order of compute devices. If none are specified, default to using CpuRef
818 const std::string computeOption("compute");
819 std::vector<std::string> computeDevicesAsStrings = CheckOption(vm, computeOption.c_str()) ?
820 vm[computeOption].as<std::vector<std::string>>() :
821 std::vector<std::string>({ "CpuRef" });
Matteo Martincigh067112f2018-10-29 11:01:09 +0000822 std::vector<armnn::BackendId> computeDevices(computeDevicesAsStrings.begin(), computeDevicesAsStrings.end());
telsoa01c577f2c2018-08-31 09:22:23 +0100823
824 // Remove duplicates from the list of compute devices.
825 RemoveDuplicateDevices(computeDevices);
826
827 // Check that the specified compute devices are valid.
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +0100828 std::string invalidBackends;
829 if (!CheckRequestedBackendsAreValid(computeDevices, armnn::Optional<std::string&>(invalidBackends)))
telsoa01c577f2c2018-08-31 09:22:23 +0100830 {
Aron Virginas-Tar5cc8e562018-10-23 15:14:46 +0100831 BOOST_LOG_TRIVIAL(fatal) << "The list of preferred devices contains invalid backend IDs: "
832 << invalidBackends;
telsoa01c577f2c2018-08-31 09:22:23 +0100833 return EXIT_FAILURE;
834 }
835
836 try
837 {
838 CheckOptionDependencies(vm);
839 }
840 catch (const po::error& e)
841 {
842 std::cerr << e.what() << std::endl << std::endl;
843 std::cerr << desc << std::endl;
844 return EXIT_FAILURE;
845 }
846
James Conroy7b4886f2019-04-11 10:23:58 +0100847 return RunTest(modelFormat, inputTensorShapes, computeDevices, modelPath, inputNames,
848 inputTensorDataFilePaths, inputTypes, outputTypes, outputNames,
849 enableProfiling, enableFp16TurboMode, thresholdTime, subgraphId);
telsoa014fcda012018-03-09 14:13:49 +0000850 }
851}