1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
|
//
// Copyright © 2022-2024 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#if defined(ARMNN_TFLITE_OPAQUE_DELEGATE)
#include <../delegate/opaque/include/armnn_delegate.hpp>
#endif
#include <tensorflow/lite/core/c/c_api.h>
#include "TfliteExecutor.hpp"
#include <tensorflow/lite/kernels/kernel_util.h>
#include <../delegate/common/src/DelegateUtils.hpp>
#include <chrono>
#include <string>
#include <thread>
std::string TfLiteStatusToString(const TfLiteStatus status)
{
switch (status)
{
case kTfLiteOk:
return "Status: Ok.";
// Generally referring to an error in the runtime (i.e. interpreter)
case kTfLiteError:
return "Status: Tf runtime error.";
// Generally referring to an error from a TfLiteDelegate itself.
case kTfLiteDelegateError:
return "Status: The loaded delegate has returned an error.";
// Generally referring to an error in applying a delegate due to
// incompatibility between runtime and delegate, e.g., this error is returned
// when trying to apply a TF Lite delegate onto a model graph that's already
// immutable.
case kTfLiteApplicationError:
return "Status: Application error. An incompatibility between the Tf runtime and the loaded delegate.";
// Generally referring to serialized delegate data not being found.
// See tflite::delegates::Serialization.
case kTfLiteDelegateDataNotFound:
return "Status: data not found.";
// Generally referring to data-writing issues in delegate serialization.
// See tflite::delegates::Serialization.
case kTfLiteDelegateDataWriteError:
return "Status: Error writing serialization data.";
// Generally referring to data-reading issues in delegate serialization.
// See tflite::delegates::Serialization.
case kTfLiteDelegateDataReadError:
return "Status: Error reading serialization data.";
// Generally referring to issues when the TF Lite model has ops that cannot be
// resolved at runtime. This could happen when the specific op is not
// registered or built with the TF Lite framework.
case kTfLiteUnresolvedOps:
return "Status: Model contains an operation that is not recognised by the runtime.";
// Generally referring to invocation cancelled by the user.
case kTfLiteCancelled:
return "Status: invocation has been cancelled by the user.";
}
return "Unknown status result.";
}
TfLiteExecutor::TfLiteExecutor(const ExecuteNetworkParams& params, armnn::IRuntime::CreationOptions runtimeOptions)
: m_Params(params)
{
using namespace std::chrono_literals;
m_Model = tflite::FlatBufferModel::BuildFromFile(m_Params.m_ModelPath.c_str());
if (!m_Model)
{
LogAndThrow("Failed to load TfLite model from: " + m_Params.m_ModelPath);
}
m_TfLiteInterpreter = std::make_unique<Interpreter>();
tflite::ops::builtin::BuiltinOpResolver resolver;
tflite::InterpreterBuilder builder(*m_Model, resolver);
if (m_Params.m_TfLiteExecutor == ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteOpaqueDelegate)
{
#if defined(ARMNN_TFLITE_OPAQUE_DELEGATE)
if (builder(&m_TfLiteInterpreter) != kTfLiteOk)
{
LogAndThrow("Error loading the model into the TfLiteInterpreter.");
}
// Populate a DelegateOptions from the ExecuteNetworkParams.
armnnDelegate::DelegateOptions delegateOptions = m_Params.ToDelegateOptions();
delegateOptions.SetRuntimeOptions(runtimeOptions);
std::unique_ptr<TfLiteDelegate, decltype(&armnnOpaqueDelegate::TfLiteArmnnOpaqueDelegateDelete)>
theArmnnDelegate(armnnOpaqueDelegate::TfLiteArmnnOpaqueDelegateCreate(delegateOptions),
armnnOpaqueDelegate::TfLiteArmnnOpaqueDelegateDelete);
// Register armnn_delegate to TfLiteInterpreter
auto result = m_TfLiteInterpreter->ModifyGraphWithDelegate(std::move(theArmnnDelegate));
if (result != kTfLiteOk)
{
LogAndThrow("Could not register ArmNN TfLite Opaque Delegate to TfLiteInterpreter: " +
TfLiteStatusToString(result) + ".");
}
#else
LogAndThrow("Not built with Arm NN Tensorflow-Lite opaque delegate support.");
#endif
}
else if (m_Params.m_TfLiteExecutor == ExecuteNetworkParams::TfLiteExecutor::ArmNNTfLiteDelegate)
{
#if defined(ARMNN_TFLITE_DELEGATE)
if (builder(&m_TfLiteInterpreter) != kTfLiteOk)
{
LogAndThrow("Error loading the model into the TfLiteInterpreter.");
}
// Create the Armnn Delegate
// Populate a DelegateOptions from the ExecuteNetworkParams.
armnnDelegate::DelegateOptions delegateOptions = m_Params.ToDelegateOptions();
delegateOptions.SetRuntimeOptions(runtimeOptions);
std::unique_ptr<TfLiteDelegate, decltype(&armnnDelegate::TfLiteArmnnDelegateDelete)>
theArmnnDelegate(armnnDelegate::TfLiteArmnnDelegateCreate(delegateOptions),
armnnDelegate::TfLiteArmnnDelegateDelete);
// Register armnn_delegate to TfLiteInterpreter
auto result = m_TfLiteInterpreter->ModifyGraphWithDelegate(std::move(theArmnnDelegate));
if (result != kTfLiteOk)
{
// We'll make an exception for kTfLiteApplicationError and allow it through in special circumstances.
if (result == kTfLiteApplicationError)
{
std::cout << std::endl;
ARMNN_LOG(warning) << "*****";
ARMNN_LOG(warning) << "***** Calling ModifyGraphWithDelegate on the TfLite runtime resulted in "
"kTfLiteApplicationError. We will allow inference to continue but be warned the "
"results may be surprising!";
ARMNN_LOG(warning) << "***** There will now be a 5 second delay.";
ARMNN_LOG(warning) << "*****\n";
// Insert an intentional delay so the user is aware of this significant warning.
std::this_thread::sleep_for(5000ms);
}
else
{
LogAndThrow("Could not register ArmNN TfLite Delegate to TfLiteInterpreter: " +
TfLiteStatusToString(result) + ".");
}
}
#else
LogAndThrow("Not built with Arm NN Tensorflow-Lite delegate support.");
#endif
}
else
{
if (builder(&m_TfLiteInterpreter) != kTfLiteOk)
{
LogAndThrow("Error loading the model into the TfLiteInterpreter.");
}
std::cout << "Running on TfLite without ArmNN delegate\n";
}
if (m_TfLiteInterpreter->AllocateTensors() != kTfLiteOk)
{
LogAndThrow("Failed to allocate tensors in the TfLiteInterpreter.");
}
const size_t numInputs = m_TfLiteInterpreter->inputs().size();
for(unsigned int inputIndex = 0; inputIndex < numInputs; ++inputIndex)
{
armnn::Optional<std::string> dataFile = m_Params.m_GenerateTensorData
? armnn::EmptyOptional()
: armnn::MakeOptional<std::string>(m_Params.m_InputTensorDataFilePaths[inputIndex]);
int input = m_TfLiteInterpreter->inputs()[inputIndex];
const auto& inputName = m_TfLiteInterpreter->tensor(input)->name;
// Before we start, check if the tensor is constant.
if (!tflite::IsConstantTensor(m_TfLiteInterpreter->tensor(input)))
{
TfLiteIntArray* inputDims = m_TfLiteInterpreter->tensor(input)->dims;
unsigned int inputSize = 1;
for (unsigned int dim = 0; dim < static_cast<unsigned int>(inputDims->size); ++dim)
{
inputSize *= inputDims->data[dim];
}
const auto& dataType = m_TfLiteInterpreter->tensor(input)->type;
switch (dataType)
{
case kTfLiteFloat32:
{
auto inputData = m_TfLiteInterpreter->typed_tensor<float>(input);
PopulateTensorWithData<float>(inputData, inputSize, dataFile, inputName);
break;
}
case kTfLiteInt32:
{
auto inputData = m_TfLiteInterpreter->typed_tensor<int32_t>(input);
PopulateTensorWithData<int32_t>(inputData, inputSize, dataFile, inputName);
break;
}
case kTfLiteUInt8:
{
auto inputData = m_TfLiteInterpreter->typed_tensor<uint8_t>(input);
PopulateTensorWithData<uint8_t>(inputData, inputSize, dataFile, inputName);
break;
}
case kTfLiteInt16:
{
auto inputData = m_TfLiteInterpreter->typed_tensor<int16_t>(input);
PopulateTensorWithData<int16_t>(inputData, inputSize, dataFile, inputName);
break;
}
case kTfLiteInt8:
{
auto inputData = m_TfLiteInterpreter->typed_tensor<int8_t>(input);
PopulateTensorWithData<int8_t>(inputData, inputSize, dataFile, inputName);
break;
}
default:
{
LogAndThrow("Unsupported input tensor data type");
}
}
}
else
{
ARMNN_LOG(info) << "Input tensor \"" << inputName << "\" is constant and will not be populated with data.";
}
}
}
std::vector<const void *> TfLiteExecutor::Execute()
{
TfLiteStatus status;
std::vector<const void*> results;
for (size_t x = 0; x < m_Params.m_Iterations; x++)
{
// Start timer to record inference time in milliseconds.
const auto start_time = armnn::GetTimeNow();
// Run the inference
status = m_TfLiteInterpreter->Invoke();
if (status != kTfLiteOk)
{
LogAndThrow("Failed to execute the inference on the TfLite runtime.. The result was: " +
TfLiteStatusToString(status) + ".");
}
const auto duration = armnn::GetTimeDuration(start_time);
if (!m_Params.m_DontPrintOutputs)
{
// Print out the output
for (unsigned int outputIndex = 0; outputIndex < m_TfLiteInterpreter->outputs().size(); ++outputIndex)
{
auto tfLiteDelegateOutputId = m_TfLiteInterpreter->outputs()[outputIndex];
TfLiteIntArray* outputDims = m_TfLiteInterpreter->tensor(tfLiteDelegateOutputId)->dims;
// If we've been asked to write to a file then set a file output stream. Otherwise use stdout.
FILE* outputTensorFile = stdout;
bool isNumpyOutput = false;
if (!m_Params.m_OutputTensorFiles.empty())
{
isNumpyOutput = m_Params.m_OutputTensorFiles[outputIndex].find(".npy") != std::string::npos;
outputTensorFile = fopen(m_Params.m_OutputTensorFiles[outputIndex].c_str(), "w");
if (outputTensorFile == NULL)
{
LogAndThrow("Specified output tensor file, \"" + m_Params.m_OutputTensorFiles[outputIndex] +
"\", cannot be created. Defaulting to stdout. Error was: " + std::strerror(errno));
}
else
{
ARMNN_LOG(info) << "Writing output " << outputIndex << " of iteration: " << x + 1
<< " to file: '" << m_Params.m_OutputTensorFiles[outputIndex] << "'";
}
}
long outputSize = 1;
for (unsigned int dim = 0; dim < static_cast<unsigned int>(outputDims->size); ++dim)
{
outputSize *= outputDims->data[dim];
}
// outputDims->data can be a Flexible Array Member (int data[];) in a C extern code in TF common.h
// TensorShape constructor argument is an unsigned int *
// so reinterpret_cast is used here to ensure the correct type of data is passed
armnn::TensorShape shape(static_cast<unsigned int>(outputDims->size),
reinterpret_cast<unsigned int *>(outputDims->data));
armnn::DataType dataType(GetDataType(*m_TfLiteInterpreter->tensor(tfLiteDelegateOutputId)));
std::cout << m_TfLiteInterpreter->tensor(tfLiteDelegateOutputId)->name << ": ";
switch (m_TfLiteInterpreter->tensor(tfLiteDelegateOutputId)->type)
{
case kTfLiteFloat32:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<float>(
tfLiteDelegateOutputId);
results.push_back(tfLiteDelegateOutputData);
if (isNumpyOutput)
{
armnnNumpy::WriteToNumpyFile(m_Params.m_OutputTensorFiles[outputIndex],
tfLiteDelegateOutputData,
outputSize,
dataType,
shape);
}
else
{
for (int i = 0; i < outputSize; ++i)
{
fprintf(outputTensorFile, "%f ", tfLiteDelegateOutputData[i]);
}
}
break;
}
case kTfLiteInt32:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<int32_t>(
tfLiteDelegateOutputId);
results.push_back(tfLiteDelegateOutputData);
if (isNumpyOutput)
{
armnnNumpy::WriteToNumpyFile(m_Params.m_OutputTensorFiles[outputIndex],
tfLiteDelegateOutputData,
outputSize,
dataType,
shape);
}
else
{
for (int i = 0; i < outputSize; ++i)
{
fprintf(outputTensorFile, "%d ", tfLiteDelegateOutputData[i]);
}
}
break;
}
case kTfLiteUInt8:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<uint8_t>(
tfLiteDelegateOutputId);
results.push_back(tfLiteDelegateOutputData);
if (isNumpyOutput)
{
armnnNumpy::WriteToNumpyFile(m_Params.m_OutputTensorFiles[outputIndex],
tfLiteDelegateOutputData,
outputSize,
dataType,
shape);
}
else
{
for (int i = 0; i < outputSize; ++i)
{
fprintf(outputTensorFile, "%u ", tfLiteDelegateOutputData[i]);
}
}
break;
}
case kTfLiteInt8:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<int8_t>(
tfLiteDelegateOutputId);
results.push_back(tfLiteDelegateOutputData);
if (isNumpyOutput)
{
armnnNumpy::WriteToNumpyFile(m_Params.m_OutputTensorFiles[outputIndex],
tfLiteDelegateOutputData,
outputSize,
dataType,
shape);
}
else
{
for (int i = 0; i < outputSize; ++i)
{
fprintf(outputTensorFile, "%d ", tfLiteDelegateOutputData[i]);
}
}
break;
}
case kTfLiteBool:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<bool>(
tfLiteDelegateOutputId);
results.push_back(tfLiteDelegateOutputData);
if (isNumpyOutput)
{
armnnNumpy::WriteToNumpyFile(m_Params.m_OutputTensorFiles[outputIndex],
tfLiteDelegateOutputData,
outputSize,
dataType,
shape);
}
else
{
for (int i = 0; i < outputSize; ++i)
{
fprintf(outputTensorFile, "%u ", tfLiteDelegateOutputData[i]);
}
}
break;
}
default:
{
LogAndThrow("Unsupported output type");
}
}
std::cout << std::endl;
}
}
CheckInferenceTimeThreshold(duration, m_Params.m_ThresholdTime);
}
return results;
}
void TfLiteExecutor::CompareAndPrintResult(std::vector<const void*> otherOutput)
{
for (unsigned int outputIndex = 0; outputIndex < m_TfLiteInterpreter->outputs().size(); ++outputIndex)
{
auto tfLiteDelegateOutputId = m_TfLiteInterpreter->outputs()[outputIndex];
size_t size = m_TfLiteInterpreter->tensor(tfLiteDelegateOutputId)->bytes;
double result = 1; // Presume failure.
switch (m_TfLiteInterpreter->tensor(tfLiteDelegateOutputId)->type)
{
case kTfLiteFloat32:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<float>(tfLiteDelegateOutputId);
result = ComputeByteLevelRMSE(tfLiteDelegateOutputData, otherOutput[outputIndex], size);
break;
}
case kTfLiteInt32:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<int32_t>(tfLiteDelegateOutputId);
result = ComputeByteLevelRMSE(tfLiteDelegateOutputData, otherOutput[outputIndex], size);
break;
}
case kTfLiteUInt8:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<uint8_t>(tfLiteDelegateOutputId);
result = ComputeByteLevelRMSE(tfLiteDelegateOutputData, otherOutput[outputIndex], size);
break;
}
case kTfLiteInt8:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<int8_t>(tfLiteDelegateOutputId);
result = ComputeByteLevelRMSE(tfLiteDelegateOutputData, otherOutput[outputIndex], size);
break;
}
case kTfLiteBool:
{
auto tfLiteDelegateOutputData = m_TfLiteInterpreter->typed_tensor<bool>(tfLiteDelegateOutputId);
result = ComputeByteLevelRMSE(tfLiteDelegateOutputData, otherOutput[outputIndex], size);
break;
}
default:
{
LogAndThrow("Unsupported output type");
}
}
std::cout << "Byte level root mean square error: " << result << "\n";
}
};
|