blob: b5b8d8561c48c5567223ead1489f15403e169646 [file] [log] [blame]
Laurent Carlier749294b2020-06-01 09:03:17 +01001//
Sadik Armagana9c2ce12020-07-14 10:02:22 +01002// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa014fcda012018-03-09 14:13:49 +00004//
telsoa01c577f2c2018-08-31 09:22:23 +01005
Jan Eilers45274902020-10-15 18:34:43 +01006#include "NetworkExecutionUtils/NetworkExecutionUtils.hpp"
7#include "ExecuteNetworkProgramOptions.hpp"
Kevin Mayb4b3ac92021-05-21 16:42:21 +01008#include <armnn/IAsyncExecutionCallback.hpp>
9#include <AsyncExecutionCallback.hpp>
Jan Eilers45274902020-10-15 18:34:43 +010010
11#include <armnn/Logging.hpp>
Rob Hughes9542f902021-07-14 09:48:54 +010012#include <armnnUtils/Filesystem.hpp>
Francis Murtagh40d27412021-10-28 11:11:35 +010013#include <armnnUtils/TContainer.hpp>
Jim Flynn4c9ed1d2022-01-23 23:57:20 +000014#include <ProfilingOptionsConverter.hpp>
Jan Eilers45274902020-10-15 18:34:43 +010015#include <InferenceTest.hpp>
16
17#if defined(ARMNN_SERIALIZER)
18#include "armnnDeserializer/IDeserializer.hpp"
19#endif
Jan Eilers45274902020-10-15 18:34:43 +010020#if defined(ARMNN_TF_LITE_PARSER)
21#include "armnnTfLiteParser/ITfLiteParser.hpp"
22#endif
23#if defined(ARMNN_ONNX_PARSER)
24#include "armnnOnnxParser/IOnnxParser.hpp"
25#endif
Sadik Armagan5d03e312020-11-17 16:43:56 +000026#if defined(ARMNN_TFLITE_DELEGATE)
27#include <armnn_delegate.hpp>
28#include <DelegateOptions.hpp>
29
30#include <tensorflow/lite/builtin_ops.h>
31#include <tensorflow/lite/c/builtin_op_data.h>
32#include <tensorflow/lite/c/common.h>
33#include <tensorflow/lite/optional_debug_tools.h>
34#include <tensorflow/lite/kernels/builtin_op_kernels.h>
35#include <tensorflow/lite/interpreter.h>
36#include <tensorflow/lite/kernels/register.h>
37#endif
Jan Eilers45274902020-10-15 18:34:43 +010038
39#include <future>
Colm Donelan3cff15a2021-10-12 15:06:19 +010040
41/**
42 * Given a measured duration and a threshold time tell the user whether we succeeded or not.
43 *
44 * @param duration the measured inference duration.
45 * @param thresholdTime the threshold time in milliseconds.
46 * @return false if the measured time exceeded the threshold.
47 */
48bool CheckInferenceTimeThreshold(const std::chrono::duration<double, std::milli>& duration,
49 const double& thresholdTime)
50{
Jan Eilers17d34da2021-12-08 16:15:12 +000051 ARMNN_LOG(info) << "Inference time: " << std::setprecision(2)
Colm Donelan3cff15a2021-10-12 15:06:19 +010052 << std::fixed << duration.count() << " ms\n";
53 // If thresholdTime == 0.0 (default), then it hasn't been supplied at command line
54 if (thresholdTime != 0.0)
55 {
56 ARMNN_LOG(info) << "Threshold time: " << std::setprecision(2)
57 << std::fixed << thresholdTime << " ms";
58 auto thresholdMinusInference = thresholdTime - duration.count();
59 ARMNN_LOG(info) << "Threshold time - Inference time: " << std::setprecision(2)
60 << std::fixed << thresholdMinusInference << " ms" << "\n";
61 if (thresholdMinusInference < 0)
62 {
63 std::string errorMessage = "Elapsed inference time is greater than provided threshold time.";
64 ARMNN_LOG(fatal) << errorMessage;
65 return false;
66 }
67 }
68 return true;
69}
70
Sadik Armagan5d03e312020-11-17 16:43:56 +000071#if defined(ARMNN_TFLITE_DELEGATE)
Colm Donelan45142282021-10-21 23:39:52 +010072int TfLiteDelegateMainImpl(const ExecuteNetworkParams& params, const armnn::IRuntime::CreationOptions runtimeOptions)
Sadik Armagan5d03e312020-11-17 16:43:56 +000073{
Tamas Nyiri00564232021-11-28 21:31:33 +000074 // Build model and corresponding interpreter
Sadik Armagan5d03e312020-11-17 16:43:56 +000075 using namespace tflite;
Jan Eilers45274902020-10-15 18:34:43 +010076
Sadik Armagan5d03e312020-11-17 16:43:56 +000077 std::unique_ptr<tflite::FlatBufferModel> model = tflite::FlatBufferModel::BuildFromFile(params.m_ModelPath.c_str());
78
79 auto tfLiteInterpreter = std::make_unique<Interpreter>();
80 tflite::ops::builtin::BuiltinOpResolver resolver;
81
82 tflite::InterpreterBuilder builder(*model, resolver);
83 builder(&tfLiteInterpreter);
84 tfLiteInterpreter->AllocateTensors();
85
Finn Williamsf806c4d2021-02-22 15:13:12 +000086 int status = 0;
Tamas Nyiri00564232021-11-28 21:31:33 +000087
88 // Create & populate Armnn Delegate, then register it to TfLiteInterpreter
Finn Williamsf806c4d2021-02-22 15:13:12 +000089 if (params.m_TfLiteExecutor == ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteDelegate)
Sadik Armagan19a1c032021-01-20 12:17:00 +000090 {
Finn Williamsf806c4d2021-02-22 15:13:12 +000091 // Create the Armnn Delegate
Colm Donelan3cff15a2021-10-12 15:06:19 +010092 // Populate a DelegateOptions from the ExecuteNetworkParams.
93 armnnDelegate::DelegateOptions delegateOptions = params.ToDelegateOptions();
Jim Flynn4c9ed1d2022-01-23 23:57:20 +000094 delegateOptions.SetExternalProfilingParams(
Cathal Corbett5aa9fd72022-02-25 15:33:28 +000095 arm::pipe::ConvertExternalProfilingOptions(runtimeOptions.m_ProfilingOptions));
Colm Donelan3cff15a2021-10-12 15:06:19 +010096
Finn Williamsf806c4d2021-02-22 15:13:12 +000097 std::unique_ptr<TfLiteDelegate, decltype(&armnnDelegate::TfLiteArmnnDelegateDelete)>
98 theArmnnDelegate(armnnDelegate::TfLiteArmnnDelegateCreate(delegateOptions),
99 armnnDelegate::TfLiteArmnnDelegateDelete);
100 // Register armnn_delegate to TfLiteInterpreter
101 status = tfLiteInterpreter->ModifyGraphWithDelegate(std::move(theArmnnDelegate));
Ryan OSheaab8a4462022-02-03 10:45:51 +0000102 if (status != kTfLiteOk)
Finn Williamsf806c4d2021-02-22 15:13:12 +0000103 {
104 ARMNN_LOG(fatal) << "Could not register ArmNN TfLite Delegate to TfLiteInterpreter!";
105 return EXIT_FAILURE;
106 }
Sadik Armagan19a1c032021-01-20 12:17:00 +0000107 }
Finn Williamsf806c4d2021-02-22 15:13:12 +0000108 else
109 {
110 std::cout << "Running on TfLite without ArmNN delegate\n";
111 }
112
Tamas Nyiri00564232021-11-28 21:31:33 +0000113 // Load (or generate) input data for inference
Sadik Armagan5d03e312020-11-17 16:43:56 +0000114 armnn::Optional<std::string> dataFile = params.m_GenerateTensorData
115 ? armnn::EmptyOptional()
116 : armnn::MakeOptional<std::string>(params.m_InputTensorDataFilePaths[0]);
117
Colm Donelan3cff15a2021-10-12 15:06:19 +0100118 const size_t numInputs = params.m_InputNames.size();
Sadik Armagan5d03e312020-11-17 16:43:56 +0000119
Tamas Nyiri00564232021-11-28 21:31:33 +0000120 // Populate input tensor of interpreter
Sadik Armagan5d03e312020-11-17 16:43:56 +0000121 for(unsigned int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
122 {
123 int input = tfLiteInterpreter->inputs()[inputIndex];
Sadik Armagan15f7fae2020-11-18 09:37:03 +0000124 TfLiteIntArray* inputDims = tfLiteInterpreter->tensor(input)->dims;
125
Mike Kelly00e9ebf2021-09-01 17:09:12 +0100126 unsigned int inputSize = 1;
127 if (params.m_InputTensorShapes.size() > 0)
Sadik Armagan15f7fae2020-11-18 09:37:03 +0000128 {
Mike Kelly00e9ebf2021-09-01 17:09:12 +0100129 inputSize = params.m_InputTensorShapes[inputIndex]->GetNumElements();
130 }
131 else
132 {
133 for (unsigned int dim = 0; dim < static_cast<unsigned int>(inputDims->size); ++dim)
134 {
135 inputSize *= inputDims->data[dim];
136 }
Sadik Armagan15f7fae2020-11-18 09:37:03 +0000137 }
138
Sadik Armagan5d03e312020-11-17 16:43:56 +0000139 if (params.m_InputTypes[inputIndex].compare("float") == 0)
140 {
141 auto inputData = tfLiteInterpreter->typed_tensor<float>(input);
Finn Williamsbbbefec2020-11-25 14:32:42 +0000142
Matthew Sloyanf00f6c22020-12-07 13:33:24 +0000143 if(inputData == NULL)
Finn Williamsbbbefec2020-11-25 14:32:42 +0000144 {
145 ARMNN_LOG(fatal) << "Input tensor is null, input type: "
146 "\"" << params.m_InputTypes[inputIndex] << "\" may be incorrect.";
147 return EXIT_FAILURE;
148 }
149
Finn Williams56870182020-11-20 13:57:53 +0000150 std::vector<float> tensorData;
151 PopulateTensorWithDataGeneric<float>(tensorData,
Mike Kelly00e9ebf2021-09-01 17:09:12 +0100152 inputSize,
153 dataFile,
154 [](const std::string& s)
155 { return std::stof(s); });
Sadik Armagan15f7fae2020-11-18 09:37:03 +0000156
Finn Williams56870182020-11-20 13:57:53 +0000157 std::copy(tensorData.begin(), tensorData.end(), inputData);
158 }
Finn Williams35e7c1d2022-01-21 19:33:46 +0000159 else if (params.m_InputTypes[inputIndex].compare("qsymms8") == 0 ||
160 params.m_InputTypes[inputIndex].compare("qasymms8") == 0)
Finn Williams56870182020-11-20 13:57:53 +0000161 {
162 auto inputData = tfLiteInterpreter->typed_tensor<int8_t>(input);
Finn Williamsbbbefec2020-11-25 14:32:42 +0000163
Matthew Sloyanf00f6c22020-12-07 13:33:24 +0000164 if(inputData == NULL)
Finn Williamsbbbefec2020-11-25 14:32:42 +0000165 {
166 ARMNN_LOG(fatal) << "Input tensor is null, input type: "
167 "\"" << params.m_InputTypes[inputIndex] << "\" may be incorrect.";
168 return EXIT_FAILURE;
169 }
170
Finn Williams56870182020-11-20 13:57:53 +0000171 std::vector<int8_t> tensorData;
172 PopulateTensorWithDataGeneric<int8_t>(tensorData,
Mike Kelly00e9ebf2021-09-01 17:09:12 +0100173 inputSize,
Finn Williams56870182020-11-20 13:57:53 +0000174 dataFile,
175 [](const std::string& s)
176 { return armnn::numeric_cast<int8_t>(std::stoi(s)); });
177
178 std::copy(tensorData.begin(), tensorData.end(), inputData);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000179 }
180 else if (params.m_InputTypes[inputIndex].compare("int") == 0)
181 {
182 auto inputData = tfLiteInterpreter->typed_tensor<int32_t>(input);
Finn Williamsbbbefec2020-11-25 14:32:42 +0000183
Matthew Sloyanf00f6c22020-12-07 13:33:24 +0000184 if(inputData == NULL)
Finn Williamsbbbefec2020-11-25 14:32:42 +0000185 {
186 ARMNN_LOG(fatal) << "Input tensor is null, input type: "
187 "\"" << params.m_InputTypes[inputIndex] << "\" may be incorrect.";
188 return EXIT_FAILURE;
189 }
190
Finn Williams56870182020-11-20 13:57:53 +0000191 std::vector<int32_t> tensorData;
192 PopulateTensorWithDataGeneric<int32_t>(tensorData,
Mike Kelly00e9ebf2021-09-01 17:09:12 +0100193 inputSize,
Finn Williams56870182020-11-20 13:57:53 +0000194 dataFile,
195 [](const std::string& s)
196 { return std::stoi(s); });
197
198 std::copy(tensorData.begin(), tensorData.end(), inputData);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000199 }
Mike Kellyd7ed6d42021-07-21 09:42:43 +0100200 else if (params.m_InputTypes[inputIndex].compare("qasymm8") == 0 ||
201 params.m_InputTypes[inputIndex].compare("qasymmu8") == 0)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000202 {
203 auto inputData = tfLiteInterpreter->typed_tensor<uint8_t>(input);
Finn Williamsbbbefec2020-11-25 14:32:42 +0000204
Matthew Sloyanf00f6c22020-12-07 13:33:24 +0000205 if(inputData == NULL)
Finn Williamsbbbefec2020-11-25 14:32:42 +0000206 {
207 ARMNN_LOG(fatal) << "Input tensor is null, input type: "
208 "\"" << params.m_InputTypes[inputIndex] << "\" may be incorrect.";
209 return EXIT_FAILURE;
210 }
211
Finn Williams56870182020-11-20 13:57:53 +0000212 std::vector<uint8_t> tensorData;
213 PopulateTensorWithDataGeneric<uint8_t>(tensorData,
Mike Kelly00e9ebf2021-09-01 17:09:12 +0100214 inputSize,
Finn Williams56870182020-11-20 13:57:53 +0000215 dataFile,
216 [](const std::string& s)
217 { return armnn::numeric_cast<uint8_t>(std::stoi(s)); });
218
219 std::copy(tensorData.begin(), tensorData.end(), inputData);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000220 }
221 else
222 {
223 ARMNN_LOG(fatal) << "Unsupported input tensor data type \"" << params.m_InputTypes[inputIndex] << "\". ";
224 return EXIT_FAILURE;
225 }
226 }
227
Tamas Nyiri00564232021-11-28 21:31:33 +0000228 // Run inference, print the output of the inference
Sadik Armagan5d03e312020-11-17 16:43:56 +0000229 for (size_t x = 0; x < params.m_Iterations; x++)
230 {
Colm Donelan3cff15a2021-10-12 15:06:19 +0100231 // Start timer to record inference time in milliseconds.
232 const auto start_time = armnn::GetTimeNow();
Sadik Armagan5d03e312020-11-17 16:43:56 +0000233 // Run the inference
Finn Williamsf806c4d2021-02-22 15:13:12 +0000234 status = tfLiteInterpreter->Invoke();
Colm Donelan3cff15a2021-10-12 15:06:19 +0100235 const auto duration = armnn::GetTimeDuration(start_time);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000236
Tamas Nyiri00564232021-11-28 21:31:33 +0000237 // The TFLite interpreter's outputs might be in a different order than the user inputted output names.
238 std::map<unsigned int, int> paramToTfliteOutputIndex;
239 for (unsigned int paramIndex = 0; paramIndex < params.m_OutputNames.size(); ++paramIndex)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000240 {
Tamas Nyiri00564232021-11-28 21:31:33 +0000241 paramToTfliteOutputIndex[paramIndex] = -1;
242 for (unsigned int tfLiteIndex = 0; tfLiteIndex < tfLiteInterpreter->outputs().size(); ++tfLiteIndex)
243 {
244 if (params.m_OutputNames[paramIndex] == tfLiteInterpreter->GetOutputName(tfLiteIndex))
245 {
246 paramToTfliteOutputIndex[paramIndex] = tfLiteIndex;
247 }
248 }
249 }
250
251 // Print out the output
252 for (unsigned int paramOutputIndex = 0; paramOutputIndex < params.m_OutputNames.size(); ++paramOutputIndex)
253 {
254 int outputIndex = paramToTfliteOutputIndex[paramOutputIndex];
255 if (outputIndex == -1)
256 {
257 std::cout << fmt::format("Output name: {} doesn't exist.", params.m_OutputNames[paramOutputIndex]) <<
258 std::endl;
259 continue;
260 }
Sadik Armagan5d03e312020-11-17 16:43:56 +0000261 auto tfLiteDelegateOutputId = tfLiteInterpreter->outputs()[outputIndex];
Sadik Armagan15f7fae2020-11-18 09:37:03 +0000262 TfLiteIntArray* outputDims = tfLiteInterpreter->tensor(tfLiteDelegateOutputId)->dims;
Colm Donelan3cff15a2021-10-12 15:06:19 +0100263 // If we've been asked to write to a file then set a file output stream. Otherwise use stdout.
264 FILE* outputTensorFile = stdout;
265 if (!params.m_OutputTensorFiles.empty())
266 {
267 outputTensorFile = fopen(params.m_OutputTensorFiles[outputIndex].c_str(), "w");
268 if (outputTensorFile == NULL)
269 {
270 ARMNN_LOG(fatal) << "Specified output tensor file, \"" <<
271 params.m_OutputTensorFiles[outputIndex] <<
272 "\", cannot be created. Defaulting to stdout. " <<
273 "Error was: " << std::strerror(errno);
274 outputTensorFile = stdout;
275 }
276 else
277 {
278 ARMNN_LOG(info) << "Writing output " << outputIndex << "' of iteration: " << x+1 << " to file: '"
279 << params.m_OutputTensorFiles[outputIndex] << "'";
280 }
281 }
Sadik Armagan15f7fae2020-11-18 09:37:03 +0000282 long outputSize = 1;
Sadik Armagan5d03e312020-11-17 16:43:56 +0000283 for (unsigned int dim = 0; dim < static_cast<unsigned int>(outputDims->size); ++dim)
284 {
Sadik Armagan15f7fae2020-11-18 09:37:03 +0000285 outputSize *= outputDims->data[dim];
Sadik Armagan5d03e312020-11-17 16:43:56 +0000286 }
287
Tamas Nyiri00564232021-11-28 21:31:33 +0000288 std::cout << tfLiteInterpreter->GetOutputName(outputIndex) << ": ";
Ryan OSheaab8a4462022-02-03 10:45:51 +0000289 if (params.m_OutputTypes[paramOutputIndex].compare("float") == 0)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000290 {
291 auto tfLiteDelageOutputData = tfLiteInterpreter->typed_tensor<float>(tfLiteDelegateOutputId);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000292 if(tfLiteDelageOutputData == NULL)
293 {
294 ARMNN_LOG(fatal) << "Output tensor is null, output type: "
Ryan OSheaab8a4462022-02-03 10:45:51 +0000295 "\"" << params.m_OutputTypes[paramOutputIndex] << "\" may be incorrect.";
Sadik Armagan5d03e312020-11-17 16:43:56 +0000296 return EXIT_FAILURE;
297 }
298
Jan Eilers284b5d12021-09-07 12:46:15 +0100299 if (!params.m_DontPrintOutputs)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000300 {
Jan Eilers284b5d12021-09-07 12:46:15 +0100301 for (int i = 0; i < outputSize; ++i)
302 {
Colm Donelan3cff15a2021-10-12 15:06:19 +0100303 fprintf(outputTensorFile, "%f ", tfLiteDelageOutputData[i]);
Jan Eilers284b5d12021-09-07 12:46:15 +0100304 }
Sadik Armagan5d03e312020-11-17 16:43:56 +0000305 }
306 }
Ryan OSheaab8a4462022-02-03 10:45:51 +0000307 else if (params.m_OutputTypes[paramOutputIndex].compare("int") == 0)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000308 {
309 auto tfLiteDelageOutputData = tfLiteInterpreter->typed_tensor<int32_t>(tfLiteDelegateOutputId);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000310 if(tfLiteDelageOutputData == NULL)
311 {
312 ARMNN_LOG(fatal) << "Output tensor is null, output type: "
Ryan OSheaab8a4462022-02-03 10:45:51 +0000313 "\"" << params.m_OutputTypes[paramOutputIndex] << "\" may be incorrect.";
Sadik Armagan5d03e312020-11-17 16:43:56 +0000314 return EXIT_FAILURE;
315 }
316
Jan Eilers284b5d12021-09-07 12:46:15 +0100317 if (!params.m_DontPrintOutputs)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000318 {
Jan Eilers284b5d12021-09-07 12:46:15 +0100319 for (int i = 0; i < outputSize; ++i)
320 {
Colm Donelan3cff15a2021-10-12 15:06:19 +0100321 fprintf(outputTensorFile, "%d ", tfLiteDelageOutputData[i]);
Jan Eilers284b5d12021-09-07 12:46:15 +0100322 }
Sadik Armagan5d03e312020-11-17 16:43:56 +0000323 }
324 }
Ryan OSheaab8a4462022-02-03 10:45:51 +0000325 else if (params.m_OutputTypes[paramOutputIndex].compare("qsymms8") == 0 ||
326 params.m_OutputTypes[paramOutputIndex].compare("qasymms8") == 0)
Finn Williams56870182020-11-20 13:57:53 +0000327 {
328 auto tfLiteDelageOutputData = tfLiteInterpreter->typed_tensor<int8_t>(tfLiteDelegateOutputId);
329 if(tfLiteDelageOutputData == NULL)
330 {
331 ARMNN_LOG(fatal) << "Output tensor is null, output type: "
Ryan OSheaab8a4462022-02-03 10:45:51 +0000332 "\"" << params.m_OutputTypes[paramOutputIndex] << "\" may be incorrect.";
Finn Williams56870182020-11-20 13:57:53 +0000333 return EXIT_FAILURE;
334 }
335
Jan Eilers284b5d12021-09-07 12:46:15 +0100336 if (!params.m_DontPrintOutputs)
Finn Williams56870182020-11-20 13:57:53 +0000337 {
Jan Eilers284b5d12021-09-07 12:46:15 +0100338 for (int i = 0; i < outputSize; ++i)
339 {
Colm Donelan3cff15a2021-10-12 15:06:19 +0100340 fprintf(outputTensorFile, "%d ", tfLiteDelageOutputData[i]);
Jan Eilers284b5d12021-09-07 12:46:15 +0100341 }
Finn Williams56870182020-11-20 13:57:53 +0000342 }
343 }
Ryan OSheaab8a4462022-02-03 10:45:51 +0000344 else if (params.m_OutputTypes[paramOutputIndex].compare("qasymm8") == 0 ||
345 params.m_OutputTypes[paramOutputIndex].compare("qasymmu8") == 0)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000346 {
347 auto tfLiteDelageOutputData = tfLiteInterpreter->typed_tensor<uint8_t>(tfLiteDelegateOutputId);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000348 if(tfLiteDelageOutputData == NULL)
349 {
350 ARMNN_LOG(fatal) << "Output tensor is null, output type: "
Ryan OSheaab8a4462022-02-03 10:45:51 +0000351 "\"" << params.m_OutputTypes[paramOutputIndex] << "\" may be incorrect.";
Sadik Armagan5d03e312020-11-17 16:43:56 +0000352 return EXIT_FAILURE;
353 }
354
Jan Eilers284b5d12021-09-07 12:46:15 +0100355 if (!params.m_DontPrintOutputs)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000356 {
Jan Eilers284b5d12021-09-07 12:46:15 +0100357 for (int i = 0; i < outputSize; ++i)
358 {
Colm Donelan3cff15a2021-10-12 15:06:19 +0100359 fprintf(outputTensorFile, "%u ", tfLiteDelageOutputData[i]);
Jan Eilers284b5d12021-09-07 12:46:15 +0100360 }
Sadik Armagan5d03e312020-11-17 16:43:56 +0000361 }
362 }
363 else
364 {
365 ARMNN_LOG(fatal) << "Output tensor is null, output type: "
Ryan OSheaab8a4462022-02-03 10:45:51 +0000366 "\"" << params.m_OutputTypes[paramOutputIndex] <<
Sadik Armagan5d03e312020-11-17 16:43:56 +0000367 "\" may be incorrect. Output type can be specified with -z argument";
368 return EXIT_FAILURE;
369 }
370 std::cout << std::endl;
371 }
Colm Donelan3cff15a2021-10-12 15:06:19 +0100372 CheckInferenceTimeThreshold(duration, params.m_ThresholdTime);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000373 }
374
375 return status;
376}
377#endif
Jan Eilers45274902020-10-15 18:34:43 +0100378template<typename TParser, typename TDataType>
379int MainImpl(const ExecuteNetworkParams& params,
380 const std::shared_ptr<armnn::IRuntime>& runtime = nullptr)
381{
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100382 using namespace std::chrono;
Jan Eilers45274902020-10-15 18:34:43 +0100383
Francis Murtagh40d27412021-10-28 11:11:35 +0100384 std::vector<std::vector<armnnUtils::TContainer>> inputs;
385 std::vector<std::vector<armnnUtils::TContainer>> outputs;
Jan Eilers45274902020-10-15 18:34:43 +0100386
387 try
388 {
389 // Creates an InferenceModel, which will parse the model and load it into an IRuntime.
390 typename InferenceModel<TParser, TDataType>::Params inferenceModelParams;
391 inferenceModelParams.m_ModelPath = params.m_ModelPath;
392 inferenceModelParams.m_IsModelBinary = params.m_IsModelBinary;
393 inferenceModelParams.m_ComputeDevices = params.m_ComputeDevices;
394 inferenceModelParams.m_DynamicBackendsPath = params.m_DynamicBackendsPath;
395 inferenceModelParams.m_PrintIntermediateLayers = params.m_PrintIntermediate;
396 inferenceModelParams.m_VisualizePostOptimizationModel = params.m_EnableLayerDetails;
397 inferenceModelParams.m_ParseUnsupported = params.m_ParseUnsupported;
398 inferenceModelParams.m_InferOutputShape = params.m_InferOutputShape;
399 inferenceModelParams.m_EnableFastMath = params.m_EnableFastMath;
Matthew Sloyan42432112021-01-08 10:30:51 +0000400 inferenceModelParams.m_SaveCachedNetwork = params.m_SaveCachedNetwork;
401 inferenceModelParams.m_CachedNetworkFilePath = params.m_CachedNetworkFilePath;
Matthew Sloyan0a7dc6b2021-02-10 16:50:53 +0000402 inferenceModelParams.m_NumberOfThreads = params.m_NumberOfThreads;
Finn Williams40646322021-02-11 16:16:42 +0000403 inferenceModelParams.m_MLGOTuningFilePath = params.m_MLGOTuningFilePath;
Sadik Armagana04a9d72021-04-27 10:02:10 +0100404 inferenceModelParams.m_AsyncEnabled = params.m_Concurrent;
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100405 inferenceModelParams.m_ThreadPoolSize = params.m_ThreadPoolSize;
Keith Davisf4874862021-08-09 16:49:18 +0100406 inferenceModelParams.m_OutputDetailsToStdOut = params.m_OutputDetailsToStdOut;
Keith Davis4914d0c2021-08-18 17:14:05 +0100407 inferenceModelParams.m_OutputDetailsOnlyToStdOut = params.m_OutputDetailsOnlyToStdOut;
Jim Flynn15425812022-02-15 16:53:13 +0000408 inferenceModelParams.m_ImportInputsIfAligned = params.m_ImportInputsIfAligned;
Jan Eilers45274902020-10-15 18:34:43 +0100409
410 for(const std::string& inputName: params.m_InputNames)
411 {
412 inferenceModelParams.m_InputBindings.push_back(inputName);
413 }
414
415 for(unsigned int i = 0; i < params.m_InputTensorShapes.size(); ++i)
416 {
417 inferenceModelParams.m_InputShapes.push_back(*params.m_InputTensorShapes[i]);
418 }
419
420 for(const std::string& outputName: params.m_OutputNames)
421 {
422 inferenceModelParams.m_OutputBindings.push_back(outputName);
423 }
424
425 inferenceModelParams.m_SubgraphId = params.m_SubgraphId;
426 inferenceModelParams.m_EnableFp16TurboMode = params.m_EnableFp16TurboMode;
427 inferenceModelParams.m_EnableBf16TurboMode = params.m_EnableBf16TurboMode;
428
429 InferenceModel<TParser, TDataType> model(inferenceModelParams,
430 params.m_EnableProfiling,
431 params.m_DynamicBackendsPath,
432 runtime);
433
434 const size_t numInputs = inferenceModelParams.m_InputBindings.size();
Sadik Armagana04a9d72021-04-27 10:02:10 +0100435
436 armnn::Optional<QuantizationParams> qParams = params.m_QuantizeInput ?
437 armnn::MakeOptional<QuantizationParams>(
438 model.GetInputQuantizationParams()) :
439 armnn::EmptyOptional();
440
Jan Eilersf17fcd52021-07-26 22:20:00 +0100441 if (params.m_InputTensorDataFilePaths.size() > numInputs)
442 {
443 ARMNN_LOG(info) << "Given network has " << numInputs << " input/s. One input-tensor-data file is required "
444 << "for each input. The user provided "
445 << params.m_InputTensorDataFilePaths.size()
446 << " input-tensor-data file/s which will be used to fill the input/s.\n";
447 }
448
449 for(unsigned int j = 0; j < params.m_Iterations ; ++j)
Jan Eilers45274902020-10-15 18:34:43 +0100450 {
Francis Murtagh40d27412021-10-28 11:11:35 +0100451 std::vector<armnnUtils::TContainer> inputDataContainers;
Sadik Armagana04a9d72021-04-27 10:02:10 +0100452 for(unsigned int i = 0; i < numInputs; ++i)
Jan Eilers45274902020-10-15 18:34:43 +0100453 {
Tamas Nyiri00564232021-11-28 21:31:33 +0000454 // If there are fewer input files given than required for the execution of
Jan Eilersf17fcd52021-07-26 22:20:00 +0100455 // params.m_Iterations we simply start with the first input file again
456 size_t inputFileIndex = j * numInputs + i;
457 if (!params.m_InputTensorDataFilePaths.empty())
458 {
459 inputFileIndex = inputFileIndex % params.m_InputTensorDataFilePaths.size();
460 }
461
Sadik Armagana04a9d72021-04-27 10:02:10 +0100462 armnn::Optional<std::string> dataFile = params.m_GenerateTensorData ?
463 armnn::EmptyOptional() :
464 armnn::MakeOptional<std::string>(
Jan Eilersf17fcd52021-07-26 22:20:00 +0100465 params.m_InputTensorDataFilePaths.at(inputFileIndex));
Sadik Armagana04a9d72021-04-27 10:02:10 +0100466
467 unsigned int numElements = model.GetInputSize(i);
468 if (params.m_InputTensorShapes.size() > i && params.m_InputTensorShapes[i])
469 {
470 // If the user has provided a tensor shape for the current input,
471 // override numElements
472 numElements = params.m_InputTensorShapes[i]->GetNumElements();
473 }
474
Francis Murtagh40d27412021-10-28 11:11:35 +0100475 armnnUtils::TContainer tensorData;
Sadik Armagana04a9d72021-04-27 10:02:10 +0100476 PopulateTensorWithData(tensorData,
477 numElements,
478 params.m_InputTypes[i],
479 qParams,
480 dataFile);
481
482 inputDataContainers.push_back(tensorData);
Jan Eilers45274902020-10-15 18:34:43 +0100483 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100484 inputs.push_back(inputDataContainers);
Jan Eilers45274902020-10-15 18:34:43 +0100485 }
486
487 const size_t numOutputs = inferenceModelParams.m_OutputBindings.size();
Jan Eilers45274902020-10-15 18:34:43 +0100488
Colm Donelanc5e41982021-10-28 20:19:43 +0100489 // The user is allowed to specify the data type of each output tensor. It is used here to construct the
490 // result tensors for each iteration. It is possible for the user to specify a type that does not match
491 // the data type of the corresponding model output. It may not make sense, but it is historically allowed.
492 // The potential problem here is a buffer overrun when a larger data type is written into the space for a
493 // smaller one. Issue a warning to highlight the potential problem.
494 for (unsigned int outputIdx = 0; outputIdx < model.GetOutputBindingInfos().size(); ++outputIdx)
495 {
496 armnn::DataType type = model.GetOutputBindingInfo(outputIdx).second.GetDataType();
497 switch (type)
498 {
David Monahan67cc5fc2021-11-03 12:56:41 +0000499 // --output-type only supports float, int, qasymms8 or qasymmu8.
Colm Donelanc5e41982021-10-28 20:19:43 +0100500 case armnn::DataType::Float32:
501 if (params.m_OutputTypes[outputIdx].compare("float") != 0)
502 {
503 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type Float32. The " <<
504 "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
505 ". This may cause unexpected problems or random failures.";
506 }
507 break;
508 case armnn::DataType::QAsymmU8:
509 if (params.m_OutputTypes[outputIdx].compare("qasymmu8") != 0)
510 {
511 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type QAsymmU8. The " <<
512 "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
513 ". This may cause unexpected problemsor random failures.";
514 }
515 break;
516 case armnn::DataType::Signed32:
517 if (params.m_OutputTypes[outputIdx].compare("int") != 0)
518 {
519 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type Signed32. The " <<
520 "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
521 ". This may cause unexpected problems or random failures.";
522 }
523 break;
524 case armnn::DataType::QAsymmS8:
525 if (params.m_OutputTypes[outputIdx].compare("qasymms8") != 0)
526 {
527 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type QAsymmS8. The " <<
528 "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
529 ". This may cause unexpected problems or random failures.";
530 }
531 break;
532 default:
533 break;
534 }
535 }
Jan Eilersf17fcd52021-07-26 22:20:00 +0100536 for (unsigned int j = 0; j < params.m_Iterations; ++j)
Jan Eilers45274902020-10-15 18:34:43 +0100537 {
Francis Murtagh40d27412021-10-28 11:11:35 +0100538 std::vector <armnnUtils::TContainer> outputDataContainers;
Sadik Armagana04a9d72021-04-27 10:02:10 +0100539 for (unsigned int i = 0; i < numOutputs; ++i)
Jan Eilers45274902020-10-15 18:34:43 +0100540 {
Sadik Armagana04a9d72021-04-27 10:02:10 +0100541 if (params.m_OutputTypes[i].compare("float") == 0)
Jan Eilers45274902020-10-15 18:34:43 +0100542 {
Sadik Armagana04a9d72021-04-27 10:02:10 +0100543 outputDataContainers.push_back(std::vector<float>(model.GetOutputSize(i)));
Mike Kellyd7ed6d42021-07-21 09:42:43 +0100544 }
545 else if (params.m_OutputTypes[i].compare("int") == 0)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100546 {
547 outputDataContainers.push_back(std::vector<int>(model.GetOutputSize(i)));
Mike Kellyd7ed6d42021-07-21 09:42:43 +0100548 }
549 else if (params.m_OutputTypes[i].compare("qasymm8") == 0 ||
550 params.m_OutputTypes[i].compare("qasymmu8") == 0)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100551 {
552 outputDataContainers.push_back(std::vector<uint8_t>(model.GetOutputSize(i)));
Mike Kellyd7ed6d42021-07-21 09:42:43 +0100553 }
554 else if (params.m_OutputTypes[i].compare("qasymms8") == 0)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100555 {
556 outputDataContainers.push_back(std::vector<int8_t>(model.GetOutputSize(i)));
557 } else
558 {
559 ARMNN_LOG(fatal) << "Unsupported tensor data type \"" << params.m_OutputTypes[i] << "\". ";
560 return EXIT_FAILURE;
Jan Eilers45274902020-10-15 18:34:43 +0100561 }
562 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100563 outputs.push_back(outputDataContainers);
564 }
565
Jan Eilersf17fcd52021-07-26 22:20:00 +0100566 if (params.m_Iterations > 1)
567 {
568 std::stringstream msg;
569 msg << "Network will be executed " << params.m_Iterations;
570 if (params.m_Concurrent)
571 {
572 msg << " times in an asynchronous manner. ";
573 }
574 else
575 {
576 msg << " times successively. ";
577 }
578 msg << "The input-tensor-data files will be reused recursively if the user didn't provide enough to "
579 "cover each execution.";
580 ARMNN_LOG(info) << msg.str();
581 }
582
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100583 // Synchronous execution
Sadik Armagana04a9d72021-04-27 10:02:10 +0100584 if (!params.m_Concurrent)
585 {
Sadik Armagana04a9d72021-04-27 10:02:10 +0100586 for (size_t x = 0; x < params.m_Iterations; x++)
587 {
588 // model.Run returns the inference time elapsed in EnqueueWorkload (in milliseconds)
Jan Eilersf17fcd52021-07-26 22:20:00 +0100589 auto inference_duration = model.Run(inputs[x], outputs[x]);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100590
591 if (params.m_GenerateTensorData)
592 {
593 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
594 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100595 if (params.m_DontPrintOutputs)
596 {
597 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
598 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100599
600 // Print output tensors
601 const auto& infosOut = model.GetOutputBindingInfos();
602 for (size_t i = 0; i < numOutputs; i++)
603 {
604 const armnn::TensorInfo& infoOut = infosOut[i].second;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100605
Jan Eilers284b5d12021-09-07 12:46:15 +0100606 // We've made sure before that the number of output files either equals numOutputs, in which
607 // case we override those files when processing the results of each iteration (only the result
608 // of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100609 // output files for each output of each iteration.
610 size_t outputFileIndex = x * numOutputs + i;
611 if (!params.m_OutputTensorFiles.empty())
612 {
613 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
614 ARMNN_LOG(info) << "Writing output " << i << " named: '"
615 << inferenceModelParams.m_OutputBindings[i]
616 << "' of iteration: " << x+1 << " to file: '"
617 << params.m_OutputTensorFiles[outputFileIndex] << "'";
618 }
619 auto outputTensorFile = params.m_OutputTensorFiles.empty()
620 ? ""
621 : params.m_OutputTensorFiles[outputFileIndex];
Sadik Armagana04a9d72021-04-27 10:02:10 +0100622
623 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
624 infoOut,
625 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100626 params.m_DequantizeOutput,
627 !params.m_DontPrintOutputs);
Jan Eilersf17fcd52021-07-26 22:20:00 +0100628 mapbox::util::apply_visitor(printer, outputs[x][i]);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100629 }
630
631 ARMNN_LOG(info) << "\nInference time: " << std::setprecision(2)
632 << std::fixed << inference_duration.count() << " ms\n";
633
634 // If thresholdTime == 0.0 (default), then it hasn't been supplied at command line
635 if (params.m_ThresholdTime != 0.0)
636 {
637 ARMNN_LOG(info) << "Threshold time: " << std::setprecision(2)
638 << std::fixed << params.m_ThresholdTime << " ms";
639 auto thresholdMinusInference = params.m_ThresholdTime - inference_duration.count();
640 ARMNN_LOG(info) << "Threshold time - Inference time: " << std::setprecision(2)
641 << std::fixed << thresholdMinusInference << " ms" << "\n";
642
643 if (thresholdMinusInference < 0)
644 {
645 std::string errorMessage = "Elapsed inference time is greater than provided threshold time.";
646 ARMNN_LOG(fatal) << errorMessage;
647 }
648 }
649 }
650 }
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100651 // Asynchronous execution using the Arm NN thread pool
Kevin May94dd4db2021-05-26 16:01:08 +0100652 else if (params.m_ThreadPoolSize >= 1)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100653 {
654 try
655 {
656 ARMNN_LOG(info) << "Asynchronous execution with Arm NN thread pool... \n";
Finn Williamsf364d532021-06-09 17:07:33 +0100657 armnn::AsyncCallbackManager callbackManager;
Francis Murtagh40d27412021-10-28 11:11:35 +0100658 std::unordered_map<armnn::InferenceId, std::vector<armnnUtils::TContainer>&> inferenceOutputMap;
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100659
660 // Declare the latest and earliest inference times here to be used when calculating overall time
661 std::chrono::high_resolution_clock::time_point earliestStartTime;
662 std::chrono::high_resolution_clock::time_point latestEndTime =
663 std::chrono::high_resolution_clock::now();
664
665 // For the asynchronous execution, we are adding a pool of working memory handles (1 per thread) in the
666 // LoadedNetwork with each scheduled inference having a specific priority
Jan Eilersf17fcd52021-07-26 22:20:00 +0100667 for (size_t i = 0; i < params.m_Iterations; ++i)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100668 {
Finn Williamsf364d532021-06-09 17:07:33 +0100669 std::shared_ptr<armnn::AsyncExecutionCallback> cb = callbackManager.GetNewCallback();
670 inferenceOutputMap.insert({cb->GetInferenceId(), outputs[i]});
671 model.RunAsync(inputs[i], outputs[i], cb);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100672 }
673
674 // Check the results
675 unsigned int j = 0;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100676 for (size_t iteration = 0; iteration < params.m_Iterations; ++iteration)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100677 {
Finn Williamsf364d532021-06-09 17:07:33 +0100678 auto cb = callbackManager.GetNotifiedCallback();
679
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100680 // Get the results
681 auto endTime = time_point_cast<std::chrono::milliseconds>(cb->GetEndTime());
682 auto startTime = time_point_cast<std::chrono::milliseconds>(cb->GetStartTime());
683 auto inferenceDuration = endTime - startTime;
684
685 if (latestEndTime < cb->GetEndTime())
686 {
687 latestEndTime = cb->GetEndTime();
688 }
689
690 if (earliestStartTime.time_since_epoch().count() == 0)
691 {
692 earliestStartTime = cb->GetStartTime();
693 }
694 else if (earliestStartTime > cb->GetStartTime())
695 {
696 earliestStartTime = cb->GetStartTime();
697 }
698
699 if (params.m_GenerateTensorData)
700 {
701 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
702 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100703 if (params.m_DontPrintOutputs)
704 {
705 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
706 }
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100707
708 // Print output tensors
709 const auto& infosOut = model.GetOutputBindingInfos();
710 for (size_t i = 0; i < numOutputs; i++)
711 {
Jan Eilersf17fcd52021-07-26 22:20:00 +0100712 // We've made sure before that the number of output files either equals numOutputs, in which
Jan Eilers284b5d12021-09-07 12:46:15 +0100713 // case we override those files when processing the results of each iteration (only the
714 // result of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100715 // output files for each output of each iteration.
716 size_t outputFileIndex = iteration * numOutputs + i;
717 if (!params.m_OutputTensorFiles.empty())
718 {
719 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
720 ARMNN_LOG(info) << "Writing output " << i << " named: '"
721 << inferenceModelParams.m_OutputBindings[i]
722 << "' of iteration: " << iteration+1 << " to file: '"
723 << params.m_OutputTensorFiles[outputFileIndex] << "'";
724 }
725
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100726 const armnn::TensorInfo& infoOut = infosOut[i].second;
727 auto outputTensorFile = params.m_OutputTensorFiles.empty()
728 ? ""
Jan Eilersf17fcd52021-07-26 22:20:00 +0100729 : params.m_OutputTensorFiles[outputFileIndex];
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100730
731 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
732 infoOut,
733 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100734 params.m_DequantizeOutput,
735 !params.m_DontPrintOutputs);
Finn Williamsf364d532021-06-09 17:07:33 +0100736 mapbox::util::apply_visitor(printer, inferenceOutputMap.at(cb->GetInferenceId())[i]);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100737 }
738
Colm Donelan3cff15a2021-10-12 15:06:19 +0100739 CheckInferenceTimeThreshold(inferenceDuration, params.m_ThresholdTime);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100740 ++j;
741 }
742 //print duration difference between overallStartTime and overallEndTime
743 auto overallEndTime = time_point_cast<std::chrono::milliseconds>(latestEndTime);
744 auto overallStartTime = time_point_cast<std::chrono::milliseconds>(earliestStartTime);
745 auto totalInferenceDuration = overallEndTime - overallStartTime;
746 ARMNN_LOG(info) << "\nOverall Inference time: " << std::setprecision(2)
747 << std::fixed << totalInferenceDuration.count() << " ms\n";
748 }
749 catch (const armnn::Exception& e)
750 {
751 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
752 return EXIT_FAILURE;
753 }
754 }
755 // Asynchronous execution using std::launch::async
Sadik Armagana04a9d72021-04-27 10:02:10 +0100756 else
757 {
758 try
759 {
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100760 ARMNN_LOG(info) << "Asynchronous Execution with std::launch:async... \n";
Finn Williamsf364d532021-06-09 17:07:33 +0100761 std::vector<std::future<std::tuple<unsigned int,
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100762 std::chrono::duration<double, std::milli>>>> inferenceResults;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100763 inferenceResults.reserve(params.m_Iterations);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100764
765 // Create WorkingMemHandles for each inference
766 std::vector<std::unique_ptr<armnn::experimental::IWorkingMemHandle>> workingMemHandles;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100767 workingMemHandles.reserve(params.m_Iterations);
768 for (unsigned int i = 0; i < params.m_Iterations; ++i)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100769 {
770 workingMemHandles.push_back(model.CreateWorkingMemHandle());
771 }
772
773 // Run each inference in its own thread
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100774 // start a timer
775 const auto start_time = armnn::GetTimeNow();
Jan Eilersf17fcd52021-07-26 22:20:00 +0100776 for (unsigned int i = 0; i < params.m_Iterations; ++i)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100777 {
778 armnn::experimental::IWorkingMemHandle& workingMemHandleRef = *workingMemHandles[i].get();
Finn Williamsf364d532021-06-09 17:07:33 +0100779
Sadik Armagana04a9d72021-04-27 10:02:10 +0100780 inferenceResults.push_back(std::async(
781 std::launch::async, [&model, &workingMemHandleRef, &inputs, &outputs, i]() {
Finn Williamsf364d532021-06-09 17:07:33 +0100782 return model.RunAsync(workingMemHandleRef, inputs[i], outputs[i], i);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100783 }
784 ));
785 }
786
787 // Check the results
788 for (unsigned int j = 0; j < inferenceResults.size(); ++j)
789 {
790 // Get the results
791 auto inferenceResult = inferenceResults[j].get();
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100792 auto inferenceDuration = std::get<1>(inferenceResult);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100793 auto inferenceID = std::get<0>(inferenceResult);
794
795 if (params.m_GenerateTensorData)
796 {
797 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
798 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100799 if (params.m_DontPrintOutputs)
800 {
801 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
802 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100803
804 // Print output tensors
805 const auto& infosOut = model.GetOutputBindingInfos();
806 for (size_t i = 0; i < numOutputs; i++)
807 {
Jan Eilersf17fcd52021-07-26 22:20:00 +0100808 // We've made sure before that the number of output files either equals numOutputs, in which
Jan Eilers284b5d12021-09-07 12:46:15 +0100809 // case we override those files when processing the results of each iteration (only the
810 // result of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100811 // output files for each output of each iteration.
812 size_t outputFileIndex = j * numOutputs + i;
813 if (!params.m_OutputTensorFiles.empty())
814 {
815 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
816 ARMNN_LOG(info) << "Writing output " << i << " named: '"
817 << inferenceModelParams.m_OutputBindings[i]
818 << "' of iteration: " << j+1 << " to file: '"
819 << params.m_OutputTensorFiles[outputFileIndex] << "'";
820 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100821 const armnn::TensorInfo& infoOut = infosOut[i].second;
822 auto outputTensorFile = params.m_OutputTensorFiles.empty()
823 ? ""
Jan Eilersf17fcd52021-07-26 22:20:00 +0100824 : params.m_OutputTensorFiles[outputFileIndex];
Sadik Armagana04a9d72021-04-27 10:02:10 +0100825
826 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
827 infoOut,
828 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100829 params.m_DequantizeOutput,
830 !params.m_DontPrintOutputs);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100831 mapbox::util::apply_visitor(printer, outputs[j][i]);
832 }
Colm Donelan3cff15a2021-10-12 15:06:19 +0100833 CheckInferenceTimeThreshold(inferenceDuration, params.m_ThresholdTime);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100834 ARMNN_LOG(info) << "Asynchronous Execution is finished for Inference ID: " << inferenceID << " \n";
Sadik Armagana04a9d72021-04-27 10:02:10 +0100835 }
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100836 // finish timer
837 const auto duration = armnn::GetTimeDuration(start_time);
838 ARMNN_LOG(info) << "\nOverall Inference time: " << std::setprecision(2)
839 << std::fixed << duration.count() << " ms\n";
Sadik Armagana04a9d72021-04-27 10:02:10 +0100840 }
841 catch (const armnn::Exception& e)
842 {
843 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
844 return EXIT_FAILURE;
845 }
Jan Eilers45274902020-10-15 18:34:43 +0100846 }
847 }
848 catch (const armnn::Exception& e)
849 {
850 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
851 return EXIT_FAILURE;
852 }
853
854 return EXIT_SUCCESS;
855}
856
James Conroy7b4886f2019-04-11 10:23:58 +0100857// MAIN
telsoa01c577f2c2018-08-31 09:22:23 +0100858int main(int argc, const char* argv[])
859{
860 // Configures logging for both the ARMNN library and this test program.
Jan Eilers45274902020-10-15 18:34:43 +0100861 #ifdef NDEBUG
telsoa01c577f2c2018-08-31 09:22:23 +0100862 armnn::LogSeverity level = armnn::LogSeverity::Info;
Jan Eilers45274902020-10-15 18:34:43 +0100863 #else
telsoa01c577f2c2018-08-31 09:22:23 +0100864 armnn::LogSeverity level = armnn::LogSeverity::Debug;
Jan Eilers45274902020-10-15 18:34:43 +0100865 #endif
telsoa01c577f2c2018-08-31 09:22:23 +0100866 armnn::ConfigureLogging(true, true, level);
telsoa01c577f2c2018-08-31 09:22:23 +0100867
telsoa01c577f2c2018-08-31 09:22:23 +0100868
Jan Eilers45274902020-10-15 18:34:43 +0100869 // Get ExecuteNetwork parameters and runtime options from command line
Jan Eilersf17fcd52021-07-26 22:20:00 +0100870 // This might throw an InvalidArgumentException if the user provided invalid inputs
871 ProgramOptions ProgramOptions;
872 try {
873 ProgramOptions.ParseOptions(argc, argv);
874 } catch (const std::exception &e){
875 ARMNN_LOG(fatal) << e.what();
876 return EXIT_FAILURE;
877 }
Narumol Prangnawaratd8cc8112020-03-24 13:54:05 +0000878
Keith Davis4914d0c2021-08-18 17:14:05 +0100879 if ((ProgramOptions.m_ExNetParams.m_OutputDetailsToStdOut ||
880 ProgramOptions.m_ExNetParams.m_OutputDetailsOnlyToStdOut)
881 && !ProgramOptions.m_ExNetParams.m_EnableProfiling)
Keith Davisf4874862021-08-09 16:49:18 +0100882 {
883 ARMNN_LOG(fatal) << "You must enable profiling if you would like to output layer details";
884 return EXIT_FAILURE;
885 }
886
Jan Eilers45274902020-10-15 18:34:43 +0100887 std::string modelFormat = ProgramOptions.m_ExNetParams.m_ModelFormat;
888
889 // Forward to implementation based on the parser type
890 if (modelFormat.find("armnn") != std::string::npos)
Finn Williamsd7fcafa2020-04-23 17:55:18 +0100891 {
Jan Eilers45274902020-10-15 18:34:43 +0100892 #if defined(ARMNN_SERIALIZER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +0000893 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
Jan Eilers45274902020-10-15 18:34:43 +0100894 return MainImpl<armnnDeserializer::IDeserializer, float>(ProgramOptions.m_ExNetParams, runtime);
895 #else
896 ARMNN_LOG(fatal) << "Not built with serialization support.";
Finn Williamsd7fcafa2020-04-23 17:55:18 +0100897 return EXIT_FAILURE;
Jan Eilers45274902020-10-15 18:34:43 +0100898 #endif
Finn Williamsd7fcafa2020-04-23 17:55:18 +0100899 }
Jan Eilers45274902020-10-15 18:34:43 +0100900 else if (modelFormat.find("onnx") != std::string::npos)
telsoa01c577f2c2018-08-31 09:22:23 +0100901 {
Jan Eilers45274902020-10-15 18:34:43 +0100902 #if defined(ARMNN_ONNX_PARSER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +0000903 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
Jan Eilers45274902020-10-15 18:34:43 +0100904 return MainImpl<armnnOnnxParser::IOnnxParser, float>(ProgramOptions.m_ExNetParams, runtime);
905 #else
906 ARMNN_LOG(fatal) << "Not built with Onnx parser support.";
907 return EXIT_FAILURE;
908 #endif
909 }
Jan Eilers45274902020-10-15 18:34:43 +0100910 else if(modelFormat.find("tflite") != std::string::npos)
911 {
Finn Williamsf806c4d2021-02-22 15:13:12 +0000912 if (ProgramOptions.m_ExNetParams.m_TfLiteExecutor == ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteParser)
913 {
914 #if defined(ARMNN_TF_LITE_PARSER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +0000915 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
916 return MainImpl<armnnTfLiteParser::ITfLiteParser, float>(ProgramOptions.m_ExNetParams, runtime);
Finn Williamsf806c4d2021-02-22 15:13:12 +0000917 #else
Cathal Corbett5b0d8872021-12-06 17:06:12 +0000918 ARMNN_LOG(fatal) << "Not built with Tensorflow-Lite parser support.";
919 return EXIT_FAILURE;
Finn Williamsf806c4d2021-02-22 15:13:12 +0000920 #endif
921 }
922 else if (ProgramOptions.m_ExNetParams.m_TfLiteExecutor ==
923 ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteDelegate ||
924 ProgramOptions.m_ExNetParams.m_TfLiteExecutor ==
925 ExecuteNetworkParams::TfLiteExecutor::TfliteInterpreter)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000926 {
927 #if defined(ARMNN_TF_LITE_DELEGATE)
Colm Donelan45142282021-10-21 23:39:52 +0100928 return TfLiteDelegateMainImpl(ProgramOptions.m_ExNetParams, ProgramOptions.m_RuntimeOptions);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000929 #else
Finn Williamsbbbefec2020-11-25 14:32:42 +0000930 ARMNN_LOG(fatal) << "Not built with Arm NN Tensorflow-Lite delegate support.";
Sadik Armagan5d03e312020-11-17 16:43:56 +0000931 return EXIT_FAILURE;
932 #endif
933 }
Jan Eilers45274902020-10-15 18:34:43 +0100934 }
935 else
936 {
937 ARMNN_LOG(fatal) << "Unknown model format: '" << modelFormat
Nikhil Raj5d955cf2021-04-19 16:59:48 +0100938 << "'. Please include 'tflite' or 'onnx'";
Jan Eilers45274902020-10-15 18:34:43 +0100939 return EXIT_FAILURE;
telsoa014fcda012018-03-09 14:13:49 +0000940 }
941}