blob: 1f19584c68e83daec8997cd901d36721a029b6a5 [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(
95 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;
Jan Eilers45274902020-10-15 18:34:43 +0100408
409 for(const std::string& inputName: params.m_InputNames)
410 {
411 inferenceModelParams.m_InputBindings.push_back(inputName);
412 }
413
414 for(unsigned int i = 0; i < params.m_InputTensorShapes.size(); ++i)
415 {
416 inferenceModelParams.m_InputShapes.push_back(*params.m_InputTensorShapes[i]);
417 }
418
419 for(const std::string& outputName: params.m_OutputNames)
420 {
421 inferenceModelParams.m_OutputBindings.push_back(outputName);
422 }
423
424 inferenceModelParams.m_SubgraphId = params.m_SubgraphId;
425 inferenceModelParams.m_EnableFp16TurboMode = params.m_EnableFp16TurboMode;
426 inferenceModelParams.m_EnableBf16TurboMode = params.m_EnableBf16TurboMode;
427
428 InferenceModel<TParser, TDataType> model(inferenceModelParams,
429 params.m_EnableProfiling,
430 params.m_DynamicBackendsPath,
431 runtime);
432
433 const size_t numInputs = inferenceModelParams.m_InputBindings.size();
Sadik Armagana04a9d72021-04-27 10:02:10 +0100434
435 armnn::Optional<QuantizationParams> qParams = params.m_QuantizeInput ?
436 armnn::MakeOptional<QuantizationParams>(
437 model.GetInputQuantizationParams()) :
438 armnn::EmptyOptional();
439
Jan Eilersf17fcd52021-07-26 22:20:00 +0100440 if (params.m_InputTensorDataFilePaths.size() > numInputs)
441 {
442 ARMNN_LOG(info) << "Given network has " << numInputs << " input/s. One input-tensor-data file is required "
443 << "for each input. The user provided "
444 << params.m_InputTensorDataFilePaths.size()
445 << " input-tensor-data file/s which will be used to fill the input/s.\n";
446 }
447
448 for(unsigned int j = 0; j < params.m_Iterations ; ++j)
Jan Eilers45274902020-10-15 18:34:43 +0100449 {
Francis Murtagh40d27412021-10-28 11:11:35 +0100450 std::vector<armnnUtils::TContainer> inputDataContainers;
Sadik Armagana04a9d72021-04-27 10:02:10 +0100451 for(unsigned int i = 0; i < numInputs; ++i)
Jan Eilers45274902020-10-15 18:34:43 +0100452 {
Tamas Nyiri00564232021-11-28 21:31:33 +0000453 // If there are fewer input files given than required for the execution of
Jan Eilersf17fcd52021-07-26 22:20:00 +0100454 // params.m_Iterations we simply start with the first input file again
455 size_t inputFileIndex = j * numInputs + i;
456 if (!params.m_InputTensorDataFilePaths.empty())
457 {
458 inputFileIndex = inputFileIndex % params.m_InputTensorDataFilePaths.size();
459 }
460
Sadik Armagana04a9d72021-04-27 10:02:10 +0100461 armnn::Optional<std::string> dataFile = params.m_GenerateTensorData ?
462 armnn::EmptyOptional() :
463 armnn::MakeOptional<std::string>(
Jan Eilersf17fcd52021-07-26 22:20:00 +0100464 params.m_InputTensorDataFilePaths.at(inputFileIndex));
Sadik Armagana04a9d72021-04-27 10:02:10 +0100465
466 unsigned int numElements = model.GetInputSize(i);
467 if (params.m_InputTensorShapes.size() > i && params.m_InputTensorShapes[i])
468 {
469 // If the user has provided a tensor shape for the current input,
470 // override numElements
471 numElements = params.m_InputTensorShapes[i]->GetNumElements();
472 }
473
Francis Murtagh40d27412021-10-28 11:11:35 +0100474 armnnUtils::TContainer tensorData;
Sadik Armagana04a9d72021-04-27 10:02:10 +0100475 PopulateTensorWithData(tensorData,
476 numElements,
477 params.m_InputTypes[i],
478 qParams,
479 dataFile);
480
481 inputDataContainers.push_back(tensorData);
Jan Eilers45274902020-10-15 18:34:43 +0100482 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100483 inputs.push_back(inputDataContainers);
Jan Eilers45274902020-10-15 18:34:43 +0100484 }
485
486 const size_t numOutputs = inferenceModelParams.m_OutputBindings.size();
Jan Eilers45274902020-10-15 18:34:43 +0100487
Colm Donelanc5e41982021-10-28 20:19:43 +0100488 // The user is allowed to specify the data type of each output tensor. It is used here to construct the
489 // result tensors for each iteration. It is possible for the user to specify a type that does not match
490 // the data type of the corresponding model output. It may not make sense, but it is historically allowed.
491 // The potential problem here is a buffer overrun when a larger data type is written into the space for a
492 // smaller one. Issue a warning to highlight the potential problem.
493 for (unsigned int outputIdx = 0; outputIdx < model.GetOutputBindingInfos().size(); ++outputIdx)
494 {
495 armnn::DataType type = model.GetOutputBindingInfo(outputIdx).second.GetDataType();
496 switch (type)
497 {
David Monahan67cc5fc2021-11-03 12:56:41 +0000498 // --output-type only supports float, int, qasymms8 or qasymmu8.
Colm Donelanc5e41982021-10-28 20:19:43 +0100499 case armnn::DataType::Float32:
500 if (params.m_OutputTypes[outputIdx].compare("float") != 0)
501 {
502 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type Float32. The " <<
503 "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
504 ". This may cause unexpected problems or random failures.";
505 }
506 break;
507 case armnn::DataType::QAsymmU8:
508 if (params.m_OutputTypes[outputIdx].compare("qasymmu8") != 0)
509 {
510 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type QAsymmU8. The " <<
511 "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
512 ". This may cause unexpected problemsor random failures.";
513 }
514 break;
515 case armnn::DataType::Signed32:
516 if (params.m_OutputTypes[outputIdx].compare("int") != 0)
517 {
518 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type Signed32. The " <<
519 "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
520 ". This may cause unexpected problems or random failures.";
521 }
522 break;
523 case armnn::DataType::QAsymmS8:
524 if (params.m_OutputTypes[outputIdx].compare("qasymms8") != 0)
525 {
526 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type QAsymmS8. The " <<
527 "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
528 ". This may cause unexpected problems or random failures.";
529 }
530 break;
531 default:
532 break;
533 }
534 }
Jan Eilersf17fcd52021-07-26 22:20:00 +0100535 for (unsigned int j = 0; j < params.m_Iterations; ++j)
Jan Eilers45274902020-10-15 18:34:43 +0100536 {
Francis Murtagh40d27412021-10-28 11:11:35 +0100537 std::vector <armnnUtils::TContainer> outputDataContainers;
Sadik Armagana04a9d72021-04-27 10:02:10 +0100538 for (unsigned int i = 0; i < numOutputs; ++i)
Jan Eilers45274902020-10-15 18:34:43 +0100539 {
Sadik Armagana04a9d72021-04-27 10:02:10 +0100540 if (params.m_OutputTypes[i].compare("float") == 0)
Jan Eilers45274902020-10-15 18:34:43 +0100541 {
Sadik Armagana04a9d72021-04-27 10:02:10 +0100542 outputDataContainers.push_back(std::vector<float>(model.GetOutputSize(i)));
Mike Kellyd7ed6d42021-07-21 09:42:43 +0100543 }
544 else if (params.m_OutputTypes[i].compare("int") == 0)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100545 {
546 outputDataContainers.push_back(std::vector<int>(model.GetOutputSize(i)));
Mike Kellyd7ed6d42021-07-21 09:42:43 +0100547 }
548 else if (params.m_OutputTypes[i].compare("qasymm8") == 0 ||
549 params.m_OutputTypes[i].compare("qasymmu8") == 0)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100550 {
551 outputDataContainers.push_back(std::vector<uint8_t>(model.GetOutputSize(i)));
Mike Kellyd7ed6d42021-07-21 09:42:43 +0100552 }
553 else if (params.m_OutputTypes[i].compare("qasymms8") == 0)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100554 {
555 outputDataContainers.push_back(std::vector<int8_t>(model.GetOutputSize(i)));
556 } else
557 {
558 ARMNN_LOG(fatal) << "Unsupported tensor data type \"" << params.m_OutputTypes[i] << "\". ";
559 return EXIT_FAILURE;
Jan Eilers45274902020-10-15 18:34:43 +0100560 }
561 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100562 outputs.push_back(outputDataContainers);
563 }
564
Jan Eilersf17fcd52021-07-26 22:20:00 +0100565 if (params.m_Iterations > 1)
566 {
567 std::stringstream msg;
568 msg << "Network will be executed " << params.m_Iterations;
569 if (params.m_Concurrent)
570 {
571 msg << " times in an asynchronous manner. ";
572 }
573 else
574 {
575 msg << " times successively. ";
576 }
577 msg << "The input-tensor-data files will be reused recursively if the user didn't provide enough to "
578 "cover each execution.";
579 ARMNN_LOG(info) << msg.str();
580 }
581
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100582 // Synchronous execution
Sadik Armagana04a9d72021-04-27 10:02:10 +0100583 if (!params.m_Concurrent)
584 {
Sadik Armagana04a9d72021-04-27 10:02:10 +0100585 for (size_t x = 0; x < params.m_Iterations; x++)
586 {
587 // model.Run returns the inference time elapsed in EnqueueWorkload (in milliseconds)
Jan Eilersf17fcd52021-07-26 22:20:00 +0100588 auto inference_duration = model.Run(inputs[x], outputs[x]);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100589
590 if (params.m_GenerateTensorData)
591 {
592 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
593 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100594 if (params.m_DontPrintOutputs)
595 {
596 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
597 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100598
599 // Print output tensors
600 const auto& infosOut = model.GetOutputBindingInfos();
601 for (size_t i = 0; i < numOutputs; i++)
602 {
603 const armnn::TensorInfo& infoOut = infosOut[i].second;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100604
Jan Eilers284b5d12021-09-07 12:46:15 +0100605 // We've made sure before that the number of output files either equals numOutputs, in which
606 // case we override those files when processing the results of each iteration (only the result
607 // of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100608 // output files for each output of each iteration.
609 size_t outputFileIndex = x * numOutputs + i;
610 if (!params.m_OutputTensorFiles.empty())
611 {
612 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
613 ARMNN_LOG(info) << "Writing output " << i << " named: '"
614 << inferenceModelParams.m_OutputBindings[i]
615 << "' of iteration: " << x+1 << " to file: '"
616 << params.m_OutputTensorFiles[outputFileIndex] << "'";
617 }
618 auto outputTensorFile = params.m_OutputTensorFiles.empty()
619 ? ""
620 : params.m_OutputTensorFiles[outputFileIndex];
Sadik Armagana04a9d72021-04-27 10:02:10 +0100621
622 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
623 infoOut,
624 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100625 params.m_DequantizeOutput,
626 !params.m_DontPrintOutputs);
Jan Eilersf17fcd52021-07-26 22:20:00 +0100627 mapbox::util::apply_visitor(printer, outputs[x][i]);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100628 }
629
630 ARMNN_LOG(info) << "\nInference time: " << std::setprecision(2)
631 << std::fixed << inference_duration.count() << " ms\n";
632
633 // If thresholdTime == 0.0 (default), then it hasn't been supplied at command line
634 if (params.m_ThresholdTime != 0.0)
635 {
636 ARMNN_LOG(info) << "Threshold time: " << std::setprecision(2)
637 << std::fixed << params.m_ThresholdTime << " ms";
638 auto thresholdMinusInference = params.m_ThresholdTime - inference_duration.count();
639 ARMNN_LOG(info) << "Threshold time - Inference time: " << std::setprecision(2)
640 << std::fixed << thresholdMinusInference << " ms" << "\n";
641
642 if (thresholdMinusInference < 0)
643 {
644 std::string errorMessage = "Elapsed inference time is greater than provided threshold time.";
645 ARMNN_LOG(fatal) << errorMessage;
646 }
647 }
648 }
649 }
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100650 // Asynchronous execution using the Arm NN thread pool
Kevin May94dd4db2021-05-26 16:01:08 +0100651 else if (params.m_ThreadPoolSize >= 1)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100652 {
653 try
654 {
655 ARMNN_LOG(info) << "Asynchronous execution with Arm NN thread pool... \n";
Finn Williamsf364d532021-06-09 17:07:33 +0100656 armnn::AsyncCallbackManager callbackManager;
Francis Murtagh40d27412021-10-28 11:11:35 +0100657 std::unordered_map<armnn::InferenceId, std::vector<armnnUtils::TContainer>&> inferenceOutputMap;
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100658
659 // Declare the latest and earliest inference times here to be used when calculating overall time
660 std::chrono::high_resolution_clock::time_point earliestStartTime;
661 std::chrono::high_resolution_clock::time_point latestEndTime =
662 std::chrono::high_resolution_clock::now();
663
664 // For the asynchronous execution, we are adding a pool of working memory handles (1 per thread) in the
665 // LoadedNetwork with each scheduled inference having a specific priority
Jan Eilersf17fcd52021-07-26 22:20:00 +0100666 for (size_t i = 0; i < params.m_Iterations; ++i)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100667 {
Finn Williamsf364d532021-06-09 17:07:33 +0100668 std::shared_ptr<armnn::AsyncExecutionCallback> cb = callbackManager.GetNewCallback();
669 inferenceOutputMap.insert({cb->GetInferenceId(), outputs[i]});
670 model.RunAsync(inputs[i], outputs[i], cb);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100671 }
672
673 // Check the results
674 unsigned int j = 0;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100675 for (size_t iteration = 0; iteration < params.m_Iterations; ++iteration)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100676 {
Finn Williamsf364d532021-06-09 17:07:33 +0100677 auto cb = callbackManager.GetNotifiedCallback();
678
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100679 // Get the results
680 auto endTime = time_point_cast<std::chrono::milliseconds>(cb->GetEndTime());
681 auto startTime = time_point_cast<std::chrono::milliseconds>(cb->GetStartTime());
682 auto inferenceDuration = endTime - startTime;
683
684 if (latestEndTime < cb->GetEndTime())
685 {
686 latestEndTime = cb->GetEndTime();
687 }
688
689 if (earliestStartTime.time_since_epoch().count() == 0)
690 {
691 earliestStartTime = cb->GetStartTime();
692 }
693 else if (earliestStartTime > cb->GetStartTime())
694 {
695 earliestStartTime = cb->GetStartTime();
696 }
697
698 if (params.m_GenerateTensorData)
699 {
700 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
701 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100702 if (params.m_DontPrintOutputs)
703 {
704 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
705 }
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100706
707 // Print output tensors
708 const auto& infosOut = model.GetOutputBindingInfos();
709 for (size_t i = 0; i < numOutputs; i++)
710 {
Jan Eilersf17fcd52021-07-26 22:20:00 +0100711 // We've made sure before that the number of output files either equals numOutputs, in which
Jan Eilers284b5d12021-09-07 12:46:15 +0100712 // case we override those files when processing the results of each iteration (only the
713 // result of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100714 // output files for each output of each iteration.
715 size_t outputFileIndex = iteration * numOutputs + i;
716 if (!params.m_OutputTensorFiles.empty())
717 {
718 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
719 ARMNN_LOG(info) << "Writing output " << i << " named: '"
720 << inferenceModelParams.m_OutputBindings[i]
721 << "' of iteration: " << iteration+1 << " to file: '"
722 << params.m_OutputTensorFiles[outputFileIndex] << "'";
723 }
724
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100725 const armnn::TensorInfo& infoOut = infosOut[i].second;
726 auto outputTensorFile = params.m_OutputTensorFiles.empty()
727 ? ""
Jan Eilersf17fcd52021-07-26 22:20:00 +0100728 : params.m_OutputTensorFiles[outputFileIndex];
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100729
730 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
731 infoOut,
732 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100733 params.m_DequantizeOutput,
734 !params.m_DontPrintOutputs);
Finn Williamsf364d532021-06-09 17:07:33 +0100735 mapbox::util::apply_visitor(printer, inferenceOutputMap.at(cb->GetInferenceId())[i]);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100736 }
737
Colm Donelan3cff15a2021-10-12 15:06:19 +0100738 CheckInferenceTimeThreshold(inferenceDuration, params.m_ThresholdTime);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100739 ++j;
740 }
741 //print duration difference between overallStartTime and overallEndTime
742 auto overallEndTime = time_point_cast<std::chrono::milliseconds>(latestEndTime);
743 auto overallStartTime = time_point_cast<std::chrono::milliseconds>(earliestStartTime);
744 auto totalInferenceDuration = overallEndTime - overallStartTime;
745 ARMNN_LOG(info) << "\nOverall Inference time: " << std::setprecision(2)
746 << std::fixed << totalInferenceDuration.count() << " ms\n";
747 }
748 catch (const armnn::Exception& e)
749 {
750 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
751 return EXIT_FAILURE;
752 }
753 }
754 // Asynchronous execution using std::launch::async
Sadik Armagana04a9d72021-04-27 10:02:10 +0100755 else
756 {
757 try
758 {
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100759 ARMNN_LOG(info) << "Asynchronous Execution with std::launch:async... \n";
Finn Williamsf364d532021-06-09 17:07:33 +0100760 std::vector<std::future<std::tuple<unsigned int,
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100761 std::chrono::duration<double, std::milli>>>> inferenceResults;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100762 inferenceResults.reserve(params.m_Iterations);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100763
764 // Create WorkingMemHandles for each inference
765 std::vector<std::unique_ptr<armnn::experimental::IWorkingMemHandle>> workingMemHandles;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100766 workingMemHandles.reserve(params.m_Iterations);
767 for (unsigned int i = 0; i < params.m_Iterations; ++i)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100768 {
769 workingMemHandles.push_back(model.CreateWorkingMemHandle());
770 }
771
772 // Run each inference in its own thread
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100773 // start a timer
774 const auto start_time = armnn::GetTimeNow();
Jan Eilersf17fcd52021-07-26 22:20:00 +0100775 for (unsigned int i = 0; i < params.m_Iterations; ++i)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100776 {
777 armnn::experimental::IWorkingMemHandle& workingMemHandleRef = *workingMemHandles[i].get();
Finn Williamsf364d532021-06-09 17:07:33 +0100778
Sadik Armagana04a9d72021-04-27 10:02:10 +0100779 inferenceResults.push_back(std::async(
780 std::launch::async, [&model, &workingMemHandleRef, &inputs, &outputs, i]() {
Finn Williamsf364d532021-06-09 17:07:33 +0100781 return model.RunAsync(workingMemHandleRef, inputs[i], outputs[i], i);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100782 }
783 ));
784 }
785
786 // Check the results
787 for (unsigned int j = 0; j < inferenceResults.size(); ++j)
788 {
789 // Get the results
790 auto inferenceResult = inferenceResults[j].get();
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100791 auto inferenceDuration = std::get<1>(inferenceResult);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100792 auto inferenceID = std::get<0>(inferenceResult);
793
794 if (params.m_GenerateTensorData)
795 {
796 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
797 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100798 if (params.m_DontPrintOutputs)
799 {
800 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
801 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100802
803 // Print output tensors
804 const auto& infosOut = model.GetOutputBindingInfos();
805 for (size_t i = 0; i < numOutputs; i++)
806 {
Jan Eilersf17fcd52021-07-26 22:20:00 +0100807 // We've made sure before that the number of output files either equals numOutputs, in which
Jan Eilers284b5d12021-09-07 12:46:15 +0100808 // case we override those files when processing the results of each iteration (only the
809 // result of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100810 // output files for each output of each iteration.
811 size_t outputFileIndex = j * numOutputs + i;
812 if (!params.m_OutputTensorFiles.empty())
813 {
814 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
815 ARMNN_LOG(info) << "Writing output " << i << " named: '"
816 << inferenceModelParams.m_OutputBindings[i]
817 << "' of iteration: " << j+1 << " to file: '"
818 << params.m_OutputTensorFiles[outputFileIndex] << "'";
819 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100820 const armnn::TensorInfo& infoOut = infosOut[i].second;
821 auto outputTensorFile = params.m_OutputTensorFiles.empty()
822 ? ""
Jan Eilersf17fcd52021-07-26 22:20:00 +0100823 : params.m_OutputTensorFiles[outputFileIndex];
Sadik Armagana04a9d72021-04-27 10:02:10 +0100824
825 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
826 infoOut,
827 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100828 params.m_DequantizeOutput,
829 !params.m_DontPrintOutputs);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100830 mapbox::util::apply_visitor(printer, outputs[j][i]);
831 }
Colm Donelan3cff15a2021-10-12 15:06:19 +0100832 CheckInferenceTimeThreshold(inferenceDuration, params.m_ThresholdTime);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100833 ARMNN_LOG(info) << "Asynchronous Execution is finished for Inference ID: " << inferenceID << " \n";
Sadik Armagana04a9d72021-04-27 10:02:10 +0100834 }
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100835 // finish timer
836 const auto duration = armnn::GetTimeDuration(start_time);
837 ARMNN_LOG(info) << "\nOverall Inference time: " << std::setprecision(2)
838 << std::fixed << duration.count() << " ms\n";
Sadik Armagana04a9d72021-04-27 10:02:10 +0100839 }
840 catch (const armnn::Exception& e)
841 {
842 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
843 return EXIT_FAILURE;
844 }
Jan Eilers45274902020-10-15 18:34:43 +0100845 }
846 }
847 catch (const armnn::Exception& e)
848 {
849 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
850 return EXIT_FAILURE;
851 }
852
853 return EXIT_SUCCESS;
854}
855
James Conroy7b4886f2019-04-11 10:23:58 +0100856// MAIN
telsoa01c577f2c2018-08-31 09:22:23 +0100857int main(int argc, const char* argv[])
858{
859 // Configures logging for both the ARMNN library and this test program.
Jan Eilers45274902020-10-15 18:34:43 +0100860 #ifdef NDEBUG
telsoa01c577f2c2018-08-31 09:22:23 +0100861 armnn::LogSeverity level = armnn::LogSeverity::Info;
Jan Eilers45274902020-10-15 18:34:43 +0100862 #else
telsoa01c577f2c2018-08-31 09:22:23 +0100863 armnn::LogSeverity level = armnn::LogSeverity::Debug;
Jan Eilers45274902020-10-15 18:34:43 +0100864 #endif
telsoa01c577f2c2018-08-31 09:22:23 +0100865 armnn::ConfigureLogging(true, true, level);
telsoa01c577f2c2018-08-31 09:22:23 +0100866
telsoa01c577f2c2018-08-31 09:22:23 +0100867
Jan Eilers45274902020-10-15 18:34:43 +0100868 // Get ExecuteNetwork parameters and runtime options from command line
Jan Eilersf17fcd52021-07-26 22:20:00 +0100869 // This might throw an InvalidArgumentException if the user provided invalid inputs
870 ProgramOptions ProgramOptions;
871 try {
872 ProgramOptions.ParseOptions(argc, argv);
873 } catch (const std::exception &e){
874 ARMNN_LOG(fatal) << e.what();
875 return EXIT_FAILURE;
876 }
Narumol Prangnawaratd8cc8112020-03-24 13:54:05 +0000877
Keith Davis4914d0c2021-08-18 17:14:05 +0100878 if ((ProgramOptions.m_ExNetParams.m_OutputDetailsToStdOut ||
879 ProgramOptions.m_ExNetParams.m_OutputDetailsOnlyToStdOut)
880 && !ProgramOptions.m_ExNetParams.m_EnableProfiling)
Keith Davisf4874862021-08-09 16:49:18 +0100881 {
882 ARMNN_LOG(fatal) << "You must enable profiling if you would like to output layer details";
883 return EXIT_FAILURE;
884 }
885
Jan Eilers45274902020-10-15 18:34:43 +0100886 std::string modelFormat = ProgramOptions.m_ExNetParams.m_ModelFormat;
887
888 // Forward to implementation based on the parser type
889 if (modelFormat.find("armnn") != std::string::npos)
Finn Williamsd7fcafa2020-04-23 17:55:18 +0100890 {
Jan Eilers45274902020-10-15 18:34:43 +0100891 #if defined(ARMNN_SERIALIZER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +0000892 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
Jan Eilers45274902020-10-15 18:34:43 +0100893 return MainImpl<armnnDeserializer::IDeserializer, float>(ProgramOptions.m_ExNetParams, runtime);
894 #else
895 ARMNN_LOG(fatal) << "Not built with serialization support.";
Finn Williamsd7fcafa2020-04-23 17:55:18 +0100896 return EXIT_FAILURE;
Jan Eilers45274902020-10-15 18:34:43 +0100897 #endif
Finn Williamsd7fcafa2020-04-23 17:55:18 +0100898 }
Jan Eilers45274902020-10-15 18:34:43 +0100899 else if (modelFormat.find("onnx") != std::string::npos)
telsoa01c577f2c2018-08-31 09:22:23 +0100900 {
Jan Eilers45274902020-10-15 18:34:43 +0100901 #if defined(ARMNN_ONNX_PARSER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +0000902 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
Jan Eilers45274902020-10-15 18:34:43 +0100903 return MainImpl<armnnOnnxParser::IOnnxParser, float>(ProgramOptions.m_ExNetParams, runtime);
904 #else
905 ARMNN_LOG(fatal) << "Not built with Onnx parser support.";
906 return EXIT_FAILURE;
907 #endif
908 }
Jan Eilers45274902020-10-15 18:34:43 +0100909 else if(modelFormat.find("tflite") != std::string::npos)
910 {
Finn Williamsf806c4d2021-02-22 15:13:12 +0000911 if (ProgramOptions.m_ExNetParams.m_TfLiteExecutor == ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteParser)
912 {
913 #if defined(ARMNN_TF_LITE_PARSER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +0000914 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
915 return MainImpl<armnnTfLiteParser::ITfLiteParser, float>(ProgramOptions.m_ExNetParams, runtime);
Finn Williamsf806c4d2021-02-22 15:13:12 +0000916 #else
Cathal Corbett5b0d8872021-12-06 17:06:12 +0000917 ARMNN_LOG(fatal) << "Not built with Tensorflow-Lite parser support.";
918 return EXIT_FAILURE;
Finn Williamsf806c4d2021-02-22 15:13:12 +0000919 #endif
920 }
921 else if (ProgramOptions.m_ExNetParams.m_TfLiteExecutor ==
922 ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteDelegate ||
923 ProgramOptions.m_ExNetParams.m_TfLiteExecutor ==
924 ExecuteNetworkParams::TfLiteExecutor::TfliteInterpreter)
Sadik Armagan5d03e312020-11-17 16:43:56 +0000925 {
926 #if defined(ARMNN_TF_LITE_DELEGATE)
Colm Donelan45142282021-10-21 23:39:52 +0100927 return TfLiteDelegateMainImpl(ProgramOptions.m_ExNetParams, ProgramOptions.m_RuntimeOptions);
Sadik Armagan5d03e312020-11-17 16:43:56 +0000928 #else
Finn Williamsbbbefec2020-11-25 14:32:42 +0000929 ARMNN_LOG(fatal) << "Not built with Arm NN Tensorflow-Lite delegate support.";
Sadik Armagan5d03e312020-11-17 16:43:56 +0000930 return EXIT_FAILURE;
931 #endif
932 }
Jan Eilers45274902020-10-15 18:34:43 +0100933 }
934 else
935 {
936 ARMNN_LOG(fatal) << "Unknown model format: '" << modelFormat
Nikhil Raj5d955cf2021-04-19 16:59:48 +0100937 << "'. Please include 'tflite' or 'onnx'";
Jan Eilers45274902020-10-15 18:34:43 +0100938 return EXIT_FAILURE;
telsoa014fcda012018-03-09 14:13:49 +0000939 }
940}