blob: ddabf3c11f1f18002fca0d9ea4193e65a31dda2b [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
Jan Eilers45274902020-10-15 18:34:43 +0100449 const size_t numOutputs = inferenceModelParams.m_OutputBindings.size();
Jan Eilers45274902020-10-15 18:34:43 +0100450
Colm Donelanc5e41982021-10-28 20:19:43 +0100451 // The user is allowed to specify the data type of each output tensor. It is used here to construct the
452 // result tensors for each iteration. It is possible for the user to specify a type that does not match
453 // the data type of the corresponding model output. It may not make sense, but it is historically allowed.
454 // The potential problem here is a buffer overrun when a larger data type is written into the space for a
455 // smaller one. Issue a warning to highlight the potential problem.
456 for (unsigned int outputIdx = 0; outputIdx < model.GetOutputBindingInfos().size(); ++outputIdx)
457 {
458 armnn::DataType type = model.GetOutputBindingInfo(outputIdx).second.GetDataType();
459 switch (type)
460 {
David Monahan67cc5fc2021-11-03 12:56:41 +0000461 // --output-type only supports float, int, qasymms8 or qasymmu8.
Colm Donelanc5e41982021-10-28 20:19:43 +0100462 case armnn::DataType::Float32:
463 if (params.m_OutputTypes[outputIdx].compare("float") != 0)
464 {
Ryan OSheadfbec2d2022-03-28 10:55:48 +0100465 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type Float32. The "
466 << "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
Colm Donelanc5e41982021-10-28 20:19:43 +0100467 ". This may cause unexpected problems or random failures.";
468 }
469 break;
470 case armnn::DataType::QAsymmU8:
471 if (params.m_OutputTypes[outputIdx].compare("qasymmu8") != 0)
472 {
Ryan OSheadfbec2d2022-03-28 10:55:48 +0100473 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type QAsymmU8. The "
474 << "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
475 ". This may cause unexpected problems or random failures.";
Colm Donelanc5e41982021-10-28 20:19:43 +0100476 }
477 break;
478 case armnn::DataType::Signed32:
479 if (params.m_OutputTypes[outputIdx].compare("int") != 0)
480 {
Ryan OSheadfbec2d2022-03-28 10:55:48 +0100481 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type Signed32. The "
482 << "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
Colm Donelanc5e41982021-10-28 20:19:43 +0100483 ". This may cause unexpected problems or random failures.";
484 }
485 break;
486 case armnn::DataType::QAsymmS8:
487 if (params.m_OutputTypes[outputIdx].compare("qasymms8") != 0)
488 {
Ryan OSheadfbec2d2022-03-28 10:55:48 +0100489 ARMNN_LOG(warning) << "Model output index: " << outputIdx << " has data type QAsymmS8. The "
490 << "corresponding --output-type is " << params.m_OutputTypes[outputIdx] <<
Colm Donelanc5e41982021-10-28 20:19:43 +0100491 ". This may cause unexpected problems or random failures.";
492 }
493 break;
494 default:
495 break;
496 }
497 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100498
Ryan OSheadfbec2d2022-03-28 10:55:48 +0100499 if (!params.m_ReuseBuffers)
500 {
501 for (unsigned int j = 0; j < params.m_Iterations; ++j)
502 {
503 std::vector<armnnUtils::TContainer> inputDataContainers;
504 for (unsigned int i = 0; i < numInputs; ++i)
505 {
506 // If there are fewer input files given than required for the execution of
507 // params.m_Iterations we simply start with the first input file again
508 size_t inputFileIndex = j * numInputs + i;
509 if (!params.m_InputTensorDataFilePaths.empty())
510 {
511 inputFileIndex = inputFileIndex % params.m_InputTensorDataFilePaths.size();
512 }
513
514 armnn::Optional<std::string> dataFile = params.m_GenerateTensorData ?
515 armnn::EmptyOptional() :
516 armnn::MakeOptional<std::string>(
517 params.m_InputTensorDataFilePaths.at(
518 inputFileIndex));
519
520 unsigned int numElements = model.GetInputSize(i);
521 if (params.m_InputTensorShapes.size() > i && params.m_InputTensorShapes[i])
522 {
523 // If the user has provided a tensor shape for the current input,
524 // override numElements
525 numElements = params.m_InputTensorShapes[i]->GetNumElements();
526 }
527
528 armnnUtils::TContainer tensorData;
529 PopulateTensorWithData(tensorData,
530 numElements,
531 params.m_InputTypes[i],
532 qParams,
533 dataFile);
534
535 inputDataContainers.push_back(tensorData);
536 }
537 inputs.push_back(inputDataContainers);
538 }
539
540 for (unsigned int j = 0; j < params.m_Iterations; ++j)
541 {
542 std::vector<armnnUtils::TContainer> outputDataContainers;
543 for (unsigned int i = 0; i < numOutputs; ++i)
544 {
545 if (params.m_OutputTypes[i].compare("float") == 0)
546 {
547 outputDataContainers.push_back(std::vector<float>(model.GetOutputSize(i)));
548 }
549 else if (params.m_OutputTypes[i].compare("int") == 0)
550 {
551 outputDataContainers.push_back(std::vector<int>(model.GetOutputSize(i)));
552 }
553 else if (params.m_OutputTypes[i].compare("qasymm8") == 0 ||
554 params.m_OutputTypes[i].compare("qasymmu8") == 0)
555 {
556 outputDataContainers.push_back(std::vector<uint8_t>(model.GetOutputSize(i)));
557 }
558 else if (params.m_OutputTypes[i].compare("qasymms8") == 0)
559 {
560 outputDataContainers.push_back(std::vector<int8_t>(model.GetOutputSize(i)));
561 }
562 else
563 {
564 ARMNN_LOG(fatal) << "Unsupported tensor data type \"" << params.m_OutputTypes[i] << "\". ";
565 return EXIT_FAILURE;
566 }
567 }
568 outputs.push_back(outputDataContainers);
569 }
570 }
Jan Eilersf17fcd52021-07-26 22:20:00 +0100571 if (params.m_Iterations > 1)
572 {
573 std::stringstream msg;
574 msg << "Network will be executed " << params.m_Iterations;
575 if (params.m_Concurrent)
576 {
577 msg << " times in an asynchronous manner. ";
578 }
579 else
580 {
581 msg << " times successively. ";
582 }
583 msg << "The input-tensor-data files will be reused recursively if the user didn't provide enough to "
584 "cover each execution.";
585 ARMNN_LOG(info) << msg.str();
586 }
587
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100588 // Synchronous execution
Ryan OSheadfbec2d2022-03-28 10:55:48 +0100589 if (!params.m_Concurrent && !params.m_ReuseBuffers)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100590 {
Sadik Armagana04a9d72021-04-27 10:02:10 +0100591 for (size_t x = 0; x < params.m_Iterations; x++)
592 {
593 // model.Run returns the inference time elapsed in EnqueueWorkload (in milliseconds)
Jan Eilersf17fcd52021-07-26 22:20:00 +0100594 auto inference_duration = model.Run(inputs[x], outputs[x]);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100595
596 if (params.m_GenerateTensorData)
597 {
598 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
599 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100600 if (params.m_DontPrintOutputs)
601 {
602 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
603 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100604
605 // Print output tensors
606 const auto& infosOut = model.GetOutputBindingInfos();
607 for (size_t i = 0; i < numOutputs; i++)
608 {
609 const armnn::TensorInfo& infoOut = infosOut[i].second;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100610
Jan Eilers284b5d12021-09-07 12:46:15 +0100611 // We've made sure before that the number of output files either equals numOutputs, in which
612 // case we override those files when processing the results of each iteration (only the result
613 // of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100614 // output files for each output of each iteration.
615 size_t outputFileIndex = x * numOutputs + i;
616 if (!params.m_OutputTensorFiles.empty())
617 {
618 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
619 ARMNN_LOG(info) << "Writing output " << i << " named: '"
620 << inferenceModelParams.m_OutputBindings[i]
621 << "' of iteration: " << x+1 << " to file: '"
622 << params.m_OutputTensorFiles[outputFileIndex] << "'";
623 }
624 auto outputTensorFile = params.m_OutputTensorFiles.empty()
625 ? ""
626 : params.m_OutputTensorFiles[outputFileIndex];
Sadik Armagana04a9d72021-04-27 10:02:10 +0100627
628 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
629 infoOut,
630 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100631 params.m_DequantizeOutput,
632 !params.m_DontPrintOutputs);
Jan Eilersf17fcd52021-07-26 22:20:00 +0100633 mapbox::util::apply_visitor(printer, outputs[x][i]);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100634 }
635
636 ARMNN_LOG(info) << "\nInference time: " << std::setprecision(2)
637 << std::fixed << inference_duration.count() << " ms\n";
638
639 // If thresholdTime == 0.0 (default), then it hasn't been supplied at command line
640 if (params.m_ThresholdTime != 0.0)
641 {
642 ARMNN_LOG(info) << "Threshold time: " << std::setprecision(2)
643 << std::fixed << params.m_ThresholdTime << " ms";
644 auto thresholdMinusInference = params.m_ThresholdTime - inference_duration.count();
645 ARMNN_LOG(info) << "Threshold time - Inference time: " << std::setprecision(2)
646 << std::fixed << thresholdMinusInference << " ms" << "\n";
647
648 if (thresholdMinusInference < 0)
649 {
650 std::string errorMessage = "Elapsed inference time is greater than provided threshold time.";
651 ARMNN_LOG(fatal) << errorMessage;
652 }
653 }
654 }
655 }
Ryan OSheadfbec2d2022-03-28 10:55:48 +0100656 // Synchronous Execution using a single buffer for input and output data
657 else if(!params.m_Concurrent)
658 {
659 std::vector<armnnUtils::TContainer> input;
660 std::vector<armnnUtils::TContainer> output;
661
662 for (unsigned int i = 0; i < numInputs; ++i)
663 {
664 // If there are fewer input files given than required for the execution of
665 // params.m_Iterations we simply start with the first input file again
666 size_t inputFileIndex = numInputs + i;
667 if (!params.m_InputTensorDataFilePaths.empty())
668 {
669 inputFileIndex = inputFileIndex % params.m_InputTensorDataFilePaths.size();
670 }
671
672 armnn::Optional<std::string> dataFile = params.m_GenerateTensorData ?
673 armnn::EmptyOptional() :
674 armnn::MakeOptional<std::string>(
675 params.m_InputTensorDataFilePaths.at(
676 inputFileIndex));
677
678 unsigned int numElements = model.GetInputSize(i);
679 if (params.m_InputTensorShapes.size() > i && params.m_InputTensorShapes[i])
680 {
681 // If the user has provided a tensor shape for the current input,
682 // override numElements
683 numElements = params.m_InputTensorShapes[i]->GetNumElements();
684 }
685
686 armnnUtils::TContainer tensorData;
687 PopulateTensorWithData(tensorData,
688 numElements,
689 params.m_InputTypes[i],
690 qParams,
691 dataFile);
692
693 input.push_back(tensorData);
694 }
695
696 for (unsigned int i = 0; i < numOutputs; ++i)
697 {
698 if (params.m_OutputTypes[i].compare("float") == 0)
699 {
700 output.push_back(std::vector<float>(model.GetOutputSize(i)));
701 } else if (params.m_OutputTypes[i].compare("int") == 0) {
702 output.push_back(std::vector<int>(model.GetOutputSize(i)));
703 } else if (params.m_OutputTypes[i].compare("qasymm8") == 0 ||
704 params.m_OutputTypes[i].compare("qasymmu8") == 0)
705 {
706 output.push_back(std::vector<uint8_t>(model.GetOutputSize(i)));
707 } else if (params.m_OutputTypes[i].compare("qasymms8") == 0)
708 {
709 output.push_back(std::vector<int8_t>(model.GetOutputSize(i)));
710 } else {
711 ARMNN_LOG(fatal) << "Unsupported tensor data type \"" << params.m_OutputTypes[i] << "\". ";
712 return EXIT_FAILURE;
713 }
714 }
715
716 std::vector<std::chrono::duration<double, std::milli>> timings;
717 timings.reserve(params.m_Iterations);
718 for (size_t x = 0; x < params.m_Iterations; x++)
719 {
720 // model.Run returns the inference time elapsed in EnqueueWorkload (in milliseconds)
721 auto inference_duration = model.Run(input, output);
722 timings.push_back(inference_duration);
723 }
724
725 if (params.m_GenerateTensorData)
726 {
727 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
728 }
729 if (params.m_DontPrintOutputs)
730 {
731 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
732 }
733
734 // Print output. This only needs to happen once as input is the same for each iteration.
735 const auto &infosOut = model.GetOutputBindingInfos();
736 for (size_t i = 0; i < numOutputs; i++)
737 {
738 const armnn::TensorInfo &infoOut = infosOut[i].second;
739
740 // We've made sure before that the number of output files either equals numOutputs, in which
741 // case we override those files when processing the results of each iteration (only the result
742 // of the last iteration will be stored), or there are enough
743 // output files for each output of each iteration.
744 size_t outputFileIndex = numOutputs + i;
745 if (!params.m_OutputTensorFiles.empty())
746 {
747 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
748 ARMNN_LOG(info) << "Writing output " << i << " named: '"
749 << inferenceModelParams.m_OutputBindings[i] <<" to file: '"
750 << params.m_OutputTensorFiles[outputFileIndex] << "'";
751 }
752 auto outputTensorFile = params.m_OutputTensorFiles.empty()
753 ? ""
754 : params.m_OutputTensorFiles[outputFileIndex];
755
756 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
757 infoOut,
758 outputTensorFile,
759 params.m_DequantizeOutput,
760 !params.m_DontPrintOutputs);
761 mapbox::util::apply_visitor(printer, output[i]);
762 }
763
764 for(auto inference: timings)
765 {
766
767 ARMNN_LOG(info) << "\nInference time: " << std::setprecision(2)
768 << std::fixed << inference.count() << " ms\n";
769
770 // If thresholdTime == 0.0 (default), then it hasn't been supplied at command line
771 if (params.m_ThresholdTime != 0.0)
772 {
773 ARMNN_LOG(info) << "Threshold time: " << std::setprecision(2)
774 << std::fixed << params.m_ThresholdTime << " ms";
775 auto thresholdMinusInference = params.m_ThresholdTime - inference.count();
776 ARMNN_LOG(info) << "Threshold time - Inference time: " << std::setprecision(2)
777 << std::fixed << thresholdMinusInference << " ms" << "\n";
778
779 if (thresholdMinusInference < 0)
780 {
781 std::string errorMessage = "Elapsed inference time is greater than provided threshold time.";
782 ARMNN_LOG(fatal) << errorMessage;
783 }
784 }
785 }
786 }
787
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100788 // Asynchronous execution using the Arm NN thread pool
Kevin May94dd4db2021-05-26 16:01:08 +0100789 else if (params.m_ThreadPoolSize >= 1)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100790 {
791 try
792 {
793 ARMNN_LOG(info) << "Asynchronous execution with Arm NN thread pool... \n";
Finn Williamsf364d532021-06-09 17:07:33 +0100794 armnn::AsyncCallbackManager callbackManager;
Francis Murtagh40d27412021-10-28 11:11:35 +0100795 std::unordered_map<armnn::InferenceId, std::vector<armnnUtils::TContainer>&> inferenceOutputMap;
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100796
797 // Declare the latest and earliest inference times here to be used when calculating overall time
798 std::chrono::high_resolution_clock::time_point earliestStartTime;
799 std::chrono::high_resolution_clock::time_point latestEndTime =
800 std::chrono::high_resolution_clock::now();
801
802 // For the asynchronous execution, we are adding a pool of working memory handles (1 per thread) in the
803 // LoadedNetwork with each scheduled inference having a specific priority
Jan Eilersf17fcd52021-07-26 22:20:00 +0100804 for (size_t i = 0; i < params.m_Iterations; ++i)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100805 {
Finn Williamsf364d532021-06-09 17:07:33 +0100806 std::shared_ptr<armnn::AsyncExecutionCallback> cb = callbackManager.GetNewCallback();
807 inferenceOutputMap.insert({cb->GetInferenceId(), outputs[i]});
808 model.RunAsync(inputs[i], outputs[i], cb);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100809 }
810
811 // Check the results
812 unsigned int j = 0;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100813 for (size_t iteration = 0; iteration < params.m_Iterations; ++iteration)
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100814 {
Finn Williamsf364d532021-06-09 17:07:33 +0100815 auto cb = callbackManager.GetNotifiedCallback();
816
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100817 // Get the results
818 auto endTime = time_point_cast<std::chrono::milliseconds>(cb->GetEndTime());
819 auto startTime = time_point_cast<std::chrono::milliseconds>(cb->GetStartTime());
820 auto inferenceDuration = endTime - startTime;
821
822 if (latestEndTime < cb->GetEndTime())
823 {
824 latestEndTime = cb->GetEndTime();
825 }
826
827 if (earliestStartTime.time_since_epoch().count() == 0)
828 {
829 earliestStartTime = cb->GetStartTime();
830 }
831 else if (earliestStartTime > cb->GetStartTime())
832 {
833 earliestStartTime = cb->GetStartTime();
834 }
835
836 if (params.m_GenerateTensorData)
837 {
838 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
839 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100840 if (params.m_DontPrintOutputs)
841 {
842 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
843 }
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100844
845 // Print output tensors
846 const auto& infosOut = model.GetOutputBindingInfos();
847 for (size_t i = 0; i < numOutputs; i++)
848 {
Jan Eilersf17fcd52021-07-26 22:20:00 +0100849 // We've made sure before that the number of output files either equals numOutputs, in which
Jan Eilers284b5d12021-09-07 12:46:15 +0100850 // case we override those files when processing the results of each iteration (only the
851 // result of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100852 // output files for each output of each iteration.
853 size_t outputFileIndex = iteration * numOutputs + i;
854 if (!params.m_OutputTensorFiles.empty())
855 {
856 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
857 ARMNN_LOG(info) << "Writing output " << i << " named: '"
858 << inferenceModelParams.m_OutputBindings[i]
859 << "' of iteration: " << iteration+1 << " to file: '"
860 << params.m_OutputTensorFiles[outputFileIndex] << "'";
861 }
862
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100863 const armnn::TensorInfo& infoOut = infosOut[i].second;
864 auto outputTensorFile = params.m_OutputTensorFiles.empty()
865 ? ""
Jan Eilersf17fcd52021-07-26 22:20:00 +0100866 : params.m_OutputTensorFiles[outputFileIndex];
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100867
868 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
869 infoOut,
870 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100871 params.m_DequantizeOutput,
872 !params.m_DontPrintOutputs);
Finn Williamsf364d532021-06-09 17:07:33 +0100873 mapbox::util::apply_visitor(printer, inferenceOutputMap.at(cb->GetInferenceId())[i]);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100874 }
875
Colm Donelan3cff15a2021-10-12 15:06:19 +0100876 CheckInferenceTimeThreshold(inferenceDuration, params.m_ThresholdTime);
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100877 ++j;
878 }
879 //print duration difference between overallStartTime and overallEndTime
880 auto overallEndTime = time_point_cast<std::chrono::milliseconds>(latestEndTime);
881 auto overallStartTime = time_point_cast<std::chrono::milliseconds>(earliestStartTime);
882 auto totalInferenceDuration = overallEndTime - overallStartTime;
883 ARMNN_LOG(info) << "\nOverall Inference time: " << std::setprecision(2)
884 << std::fixed << totalInferenceDuration.count() << " ms\n";
885 }
886 catch (const armnn::Exception& e)
887 {
888 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
889 return EXIT_FAILURE;
890 }
891 }
892 // Asynchronous execution using std::launch::async
Sadik Armagana04a9d72021-04-27 10:02:10 +0100893 else
894 {
895 try
896 {
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100897 ARMNN_LOG(info) << "Asynchronous Execution with std::launch:async... \n";
Finn Williamsf364d532021-06-09 17:07:33 +0100898 std::vector<std::future<std::tuple<unsigned int,
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100899 std::chrono::duration<double, std::milli>>>> inferenceResults;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100900 inferenceResults.reserve(params.m_Iterations);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100901
902 // Create WorkingMemHandles for each inference
903 std::vector<std::unique_ptr<armnn::experimental::IWorkingMemHandle>> workingMemHandles;
Jan Eilersf17fcd52021-07-26 22:20:00 +0100904 workingMemHandles.reserve(params.m_Iterations);
905 for (unsigned int i = 0; i < params.m_Iterations; ++i)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100906 {
907 workingMemHandles.push_back(model.CreateWorkingMemHandle());
908 }
909
910 // Run each inference in its own thread
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100911 // start a timer
912 const auto start_time = armnn::GetTimeNow();
Jan Eilersf17fcd52021-07-26 22:20:00 +0100913 for (unsigned int i = 0; i < params.m_Iterations; ++i)
Sadik Armagana04a9d72021-04-27 10:02:10 +0100914 {
915 armnn::experimental::IWorkingMemHandle& workingMemHandleRef = *workingMemHandles[i].get();
Finn Williamsf364d532021-06-09 17:07:33 +0100916
Sadik Armagana04a9d72021-04-27 10:02:10 +0100917 inferenceResults.push_back(std::async(
918 std::launch::async, [&model, &workingMemHandleRef, &inputs, &outputs, i]() {
Finn Williamsf364d532021-06-09 17:07:33 +0100919 return model.RunAsync(workingMemHandleRef, inputs[i], outputs[i], i);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100920 }
921 ));
922 }
923
924 // Check the results
925 for (unsigned int j = 0; j < inferenceResults.size(); ++j)
926 {
927 // Get the results
928 auto inferenceResult = inferenceResults[j].get();
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100929 auto inferenceDuration = std::get<1>(inferenceResult);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100930 auto inferenceID = std::get<0>(inferenceResult);
931
932 if (params.m_GenerateTensorData)
933 {
934 ARMNN_LOG(warning) << "The input data was generated, note that the output will not be useful";
935 }
Jan Eilers284b5d12021-09-07 12:46:15 +0100936 if (params.m_DontPrintOutputs)
937 {
938 ARMNN_LOG(info) << "Printing outputs to console is disabled.";
939 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100940
941 // Print output tensors
942 const auto& infosOut = model.GetOutputBindingInfos();
943 for (size_t i = 0; i < numOutputs; i++)
944 {
Jan Eilersf17fcd52021-07-26 22:20:00 +0100945 // We've made sure before that the number of output files either equals numOutputs, in which
Jan Eilers284b5d12021-09-07 12:46:15 +0100946 // case we override those files when processing the results of each iteration (only the
947 // result of the last iteration will be stored), or there are enough
Jan Eilersf17fcd52021-07-26 22:20:00 +0100948 // output files for each output of each iteration.
949 size_t outputFileIndex = j * numOutputs + i;
950 if (!params.m_OutputTensorFiles.empty())
951 {
952 outputFileIndex = outputFileIndex % params.m_OutputTensorFiles.size();
953 ARMNN_LOG(info) << "Writing output " << i << " named: '"
954 << inferenceModelParams.m_OutputBindings[i]
955 << "' of iteration: " << j+1 << " to file: '"
956 << params.m_OutputTensorFiles[outputFileIndex] << "'";
957 }
Sadik Armagana04a9d72021-04-27 10:02:10 +0100958 const armnn::TensorInfo& infoOut = infosOut[i].second;
959 auto outputTensorFile = params.m_OutputTensorFiles.empty()
960 ? ""
Jan Eilersf17fcd52021-07-26 22:20:00 +0100961 : params.m_OutputTensorFiles[outputFileIndex];
Sadik Armagana04a9d72021-04-27 10:02:10 +0100962
963 TensorPrinter printer(inferenceModelParams.m_OutputBindings[i],
964 infoOut,
965 outputTensorFile,
Jan Eilers284b5d12021-09-07 12:46:15 +0100966 params.m_DequantizeOutput,
967 !params.m_DontPrintOutputs);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100968 mapbox::util::apply_visitor(printer, outputs[j][i]);
969 }
Colm Donelan3cff15a2021-10-12 15:06:19 +0100970 CheckInferenceTimeThreshold(inferenceDuration, params.m_ThresholdTime);
Sadik Armagana04a9d72021-04-27 10:02:10 +0100971 ARMNN_LOG(info) << "Asynchronous Execution is finished for Inference ID: " << inferenceID << " \n";
Sadik Armagana04a9d72021-04-27 10:02:10 +0100972 }
Kevin Mayb4b3ac92021-05-21 16:42:21 +0100973 // finish timer
974 const auto duration = armnn::GetTimeDuration(start_time);
975 ARMNN_LOG(info) << "\nOverall Inference time: " << std::setprecision(2)
976 << std::fixed << duration.count() << " ms\n";
Sadik Armagana04a9d72021-04-27 10:02:10 +0100977 }
978 catch (const armnn::Exception& e)
979 {
980 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
981 return EXIT_FAILURE;
982 }
Jan Eilers45274902020-10-15 18:34:43 +0100983 }
984 }
985 catch (const armnn::Exception& e)
986 {
987 ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
988 return EXIT_FAILURE;
989 }
990
991 return EXIT_SUCCESS;
992}
993
James Conroy7b4886f2019-04-11 10:23:58 +0100994// MAIN
telsoa01c577f2c2018-08-31 09:22:23 +0100995int main(int argc, const char* argv[])
996{
997 // Configures logging for both the ARMNN library and this test program.
Jan Eilers45274902020-10-15 18:34:43 +0100998 #ifdef NDEBUG
telsoa01c577f2c2018-08-31 09:22:23 +0100999 armnn::LogSeverity level = armnn::LogSeverity::Info;
Jan Eilers45274902020-10-15 18:34:43 +01001000 #else
telsoa01c577f2c2018-08-31 09:22:23 +01001001 armnn::LogSeverity level = armnn::LogSeverity::Debug;
Jan Eilers45274902020-10-15 18:34:43 +01001002 #endif
telsoa01c577f2c2018-08-31 09:22:23 +01001003 armnn::ConfigureLogging(true, true, level);
telsoa01c577f2c2018-08-31 09:22:23 +01001004
telsoa01c577f2c2018-08-31 09:22:23 +01001005
Jan Eilers45274902020-10-15 18:34:43 +01001006 // Get ExecuteNetwork parameters and runtime options from command line
Jan Eilersf17fcd52021-07-26 22:20:00 +01001007 // This might throw an InvalidArgumentException if the user provided invalid inputs
1008 ProgramOptions ProgramOptions;
1009 try {
1010 ProgramOptions.ParseOptions(argc, argv);
1011 } catch (const std::exception &e){
1012 ARMNN_LOG(fatal) << e.what();
1013 return EXIT_FAILURE;
1014 }
Narumol Prangnawaratd8cc8112020-03-24 13:54:05 +00001015
Keith Davis4914d0c2021-08-18 17:14:05 +01001016 if ((ProgramOptions.m_ExNetParams.m_OutputDetailsToStdOut ||
1017 ProgramOptions.m_ExNetParams.m_OutputDetailsOnlyToStdOut)
1018 && !ProgramOptions.m_ExNetParams.m_EnableProfiling)
Keith Davisf4874862021-08-09 16:49:18 +01001019 {
1020 ARMNN_LOG(fatal) << "You must enable profiling if you would like to output layer details";
1021 return EXIT_FAILURE;
1022 }
1023
Jan Eilers45274902020-10-15 18:34:43 +01001024 std::string modelFormat = ProgramOptions.m_ExNetParams.m_ModelFormat;
1025
1026 // Forward to implementation based on the parser type
1027 if (modelFormat.find("armnn") != std::string::npos)
Finn Williamsd7fcafa2020-04-23 17:55:18 +01001028 {
Jan Eilers45274902020-10-15 18:34:43 +01001029 #if defined(ARMNN_SERIALIZER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +00001030 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
Jan Eilers45274902020-10-15 18:34:43 +01001031 return MainImpl<armnnDeserializer::IDeserializer, float>(ProgramOptions.m_ExNetParams, runtime);
1032 #else
1033 ARMNN_LOG(fatal) << "Not built with serialization support.";
Finn Williamsd7fcafa2020-04-23 17:55:18 +01001034 return EXIT_FAILURE;
Jan Eilers45274902020-10-15 18:34:43 +01001035 #endif
Finn Williamsd7fcafa2020-04-23 17:55:18 +01001036 }
Jan Eilers45274902020-10-15 18:34:43 +01001037 else if (modelFormat.find("onnx") != std::string::npos)
telsoa01c577f2c2018-08-31 09:22:23 +01001038 {
Jan Eilers45274902020-10-15 18:34:43 +01001039 #if defined(ARMNN_ONNX_PARSER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +00001040 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
Jan Eilers45274902020-10-15 18:34:43 +01001041 return MainImpl<armnnOnnxParser::IOnnxParser, float>(ProgramOptions.m_ExNetParams, runtime);
1042 #else
1043 ARMNN_LOG(fatal) << "Not built with Onnx parser support.";
1044 return EXIT_FAILURE;
1045 #endif
1046 }
Jan Eilers45274902020-10-15 18:34:43 +01001047 else if(modelFormat.find("tflite") != std::string::npos)
1048 {
Finn Williamsf806c4d2021-02-22 15:13:12 +00001049 if (ProgramOptions.m_ExNetParams.m_TfLiteExecutor == ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteParser)
1050 {
1051 #if defined(ARMNN_TF_LITE_PARSER)
Cathal Corbett5b0d8872021-12-06 17:06:12 +00001052 std::shared_ptr<armnn::IRuntime> runtime(armnn::IRuntime::Create(ProgramOptions.m_RuntimeOptions));
1053 return MainImpl<armnnTfLiteParser::ITfLiteParser, float>(ProgramOptions.m_ExNetParams, runtime);
Finn Williamsf806c4d2021-02-22 15:13:12 +00001054 #else
Cathal Corbett5b0d8872021-12-06 17:06:12 +00001055 ARMNN_LOG(fatal) << "Not built with Tensorflow-Lite parser support.";
1056 return EXIT_FAILURE;
Finn Williamsf806c4d2021-02-22 15:13:12 +00001057 #endif
1058 }
1059 else if (ProgramOptions.m_ExNetParams.m_TfLiteExecutor ==
1060 ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteDelegate ||
1061 ProgramOptions.m_ExNetParams.m_TfLiteExecutor ==
1062 ExecuteNetworkParams::TfLiteExecutor::TfliteInterpreter)
Sadik Armagan5d03e312020-11-17 16:43:56 +00001063 {
1064 #if defined(ARMNN_TF_LITE_DELEGATE)
Colm Donelan45142282021-10-21 23:39:52 +01001065 return TfLiteDelegateMainImpl(ProgramOptions.m_ExNetParams, ProgramOptions.m_RuntimeOptions);
Sadik Armagan5d03e312020-11-17 16:43:56 +00001066 #else
Finn Williamsbbbefec2020-11-25 14:32:42 +00001067 ARMNN_LOG(fatal) << "Not built with Arm NN Tensorflow-Lite delegate support.";
Sadik Armagan5d03e312020-11-17 16:43:56 +00001068 return EXIT_FAILURE;
1069 #endif
1070 }
Jan Eilers45274902020-10-15 18:34:43 +01001071 }
1072 else
1073 {
1074 ARMNN_LOG(fatal) << "Unknown model format: '" << modelFormat
Nikhil Raj5d955cf2021-04-19 16:59:48 +01001075 << "'. Please include 'tflite' or 'onnx'";
Jan Eilers45274902020-10-15 18:34:43 +01001076 return EXIT_FAILURE;
telsoa014fcda012018-03-09 14:13:49 +00001077 }
1078}