blob: 80ef3c367e6900f9d4bd396f0187c44333a10092 [file] [log] [blame]
alexander3c798932021-03-26 21:42:19 +00001/*
2 * Copyright (c) 2021 Arm Limited. All rights reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17#include "Model.hpp"
18
19#include "hal.h"
20
21#include <cstdint>
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +010022#include <inttypes.h>
alexander3c798932021-03-26 21:42:19 +000023
24/* Initialise the model */
25arm::app::Model::~Model()
26{
Isabella Gottardi56ee6202021-05-12 08:27:15 +010027 if (this->m_pInterpreter) {
28 delete this->m_pInterpreter;
alexander3c798932021-03-26 21:42:19 +000029 }
30
31 /**
32 * No clean-up function available for allocator in TensorFlow Lite Micro yet.
33 **/
34}
35
36arm::app::Model::Model() :
Isabella Gottardi56ee6202021-05-12 08:27:15 +010037 m_inited (false),
38 m_type(kTfLiteNoType)
alexander3c798932021-03-26 21:42:19 +000039{
Isabella Gottardi56ee6202021-05-12 08:27:15 +010040 this->m_pErrorReporter = &this->m_uErrorReporter;
alexander3c798932021-03-26 21:42:19 +000041}
42
43bool arm::app::Model::Init(tflite::MicroAllocator* allocator)
44{
45 /* Following tf lite micro example:
46 * Map the model into a usable data structure. This doesn't involve any
47 * copying or parsing, it's a very lightweight operation. */
48 const uint8_t* model_addr = ModelPointer();
49 debug("loading model from @ 0x%p\n", model_addr);
Isabella Gottardi56ee6202021-05-12 08:27:15 +010050 this->m_pModel = ::tflite::GetModel(model_addr);
alexander3c798932021-03-26 21:42:19 +000051
Isabella Gottardi56ee6202021-05-12 08:27:15 +010052 if (this->m_pModel->version() != TFLITE_SCHEMA_VERSION) {
53 this->m_pErrorReporter->Report(
alexander3c798932021-03-26 21:42:19 +000054 "[ERROR] model's schema version %d is not equal "
55 "to supported version %d.",
Isabella Gottardi56ee6202021-05-12 08:27:15 +010056 this->m_pModel->version(), TFLITE_SCHEMA_VERSION);
alexander3c798932021-03-26 21:42:19 +000057 return false;
58 }
59
60 /* Pull in only the operation implementations we need.
61 * This relies on a complete list of all the ops needed by this graph.
62 * An easier approach is to just use the AllOpsResolver, but this will
63 * incur some penalty in code space for op implementations that are not
64 * needed by this graph.
65 * static ::tflite::ops::micro::AllOpsResolver resolver; */
66 /* NOLINTNEXTLINE(runtime-global-variables) */
67 debug("loading op resolver\n");
68
69 this->EnlistOperations();
70
71 /* Create allocator instance, if it doesn't exist */
Isabella Gottardi56ee6202021-05-12 08:27:15 +010072 this->m_pAllocator = allocator;
73 if (!this->m_pAllocator) {
alexander3c798932021-03-26 21:42:19 +000074 /* Create an allocator instance */
75 info("Creating allocator using tensor arena in %s\n",
76 ACTIVATION_BUF_SECTION_NAME);
77
Isabella Gottardi56ee6202021-05-12 08:27:15 +010078 this->m_pAllocator = tflite::MicroAllocator::Create(
alexander3c798932021-03-26 21:42:19 +000079 this->GetTensorArena(),
80 this->GetActivationBufferSize(),
Isabella Gottardi56ee6202021-05-12 08:27:15 +010081 this->m_pErrorReporter);
alexander3c798932021-03-26 21:42:19 +000082
Isabella Gottardi56ee6202021-05-12 08:27:15 +010083 if (!this->m_pAllocator) {
alexander3c798932021-03-26 21:42:19 +000084 printf_err("Failed to create allocator\n");
85 return false;
86 }
Isabella Gottardi56ee6202021-05-12 08:27:15 +010087 debug("Created new allocator @ 0x%p\n", this->m_pAllocator);
alexander3c798932021-03-26 21:42:19 +000088 } else {
Isabella Gottardi56ee6202021-05-12 08:27:15 +010089 debug("Using existing allocator @ 0x%p\n", this->m_pAllocator);
alexander3c798932021-03-26 21:42:19 +000090 }
91
Isabella Gottardi56ee6202021-05-12 08:27:15 +010092 this->m_pInterpreter = new ::tflite::MicroInterpreter(
93 this->m_pModel, this->GetOpResolver(),
94 this->m_pAllocator, this->m_pErrorReporter);
alexander3c798932021-03-26 21:42:19 +000095
Isabella Gottardi56ee6202021-05-12 08:27:15 +010096 if (!this->m_pInterpreter) {
alexander3c798932021-03-26 21:42:19 +000097 printf_err("Failed to allocate interpreter\n");
98 return false;
99 }
100
101 /* Allocate memory from the tensor_arena for the model's tensors. */
102 info("Allocating tensors\n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100103 TfLiteStatus allocate_status = this->m_pInterpreter->AllocateTensors();
alexander3c798932021-03-26 21:42:19 +0000104
105 if (allocate_status != kTfLiteOk) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100106 this->m_pErrorReporter->Report("[ERROR] allocateTensors() failed");
alexander3c798932021-03-26 21:42:19 +0000107 printf_err("tensor allocation failed!\n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100108 delete this->m_pInterpreter;
alexander3c798932021-03-26 21:42:19 +0000109 return false;
110 }
111
112 /* Get information about the memory area to use for the model's input. */
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100113 this->m_input.resize(this->GetNumInputs());
alexander3c798932021-03-26 21:42:19 +0000114 for (size_t inIndex = 0; inIndex < this->GetNumInputs(); inIndex++)
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100115 this->m_input[inIndex] = this->m_pInterpreter->input(inIndex);
alexander3c798932021-03-26 21:42:19 +0000116
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100117 this->m_output.resize(this->GetNumOutputs());
alexander3c798932021-03-26 21:42:19 +0000118 for (size_t outIndex = 0; outIndex < this->GetNumOutputs(); outIndex++)
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100119 this->m_output[outIndex] = this->m_pInterpreter->output(outIndex);
alexander3c798932021-03-26 21:42:19 +0000120
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100121 if (this->m_input.empty() || this->m_output.empty()) {
alexander3c798932021-03-26 21:42:19 +0000122 printf_err("failed to get tensors\n");
123 return false;
124 } else {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100125 this->m_type = this->m_input[0]->type; /* Input 0 should be the main input */
alexander3c798932021-03-26 21:42:19 +0000126
127 /* Clear the input & output tensors */
128 for (size_t inIndex = 0; inIndex < this->GetNumInputs(); inIndex++) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100129 std::memset(this->m_input[inIndex]->data.data, 0, this->m_input[inIndex]->bytes);
alexander3c798932021-03-26 21:42:19 +0000130 }
131 for (size_t outIndex = 0; outIndex < this->GetNumOutputs(); outIndex++) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100132 std::memset(this->m_output[outIndex]->data.data, 0, this->m_output[outIndex]->bytes);
alexander3c798932021-03-26 21:42:19 +0000133 }
134
135 this->LogInterpreterInfo();
136 }
137
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100138 this->m_inited = true;
alexander3c798932021-03-26 21:42:19 +0000139 return true;
140}
141
142tflite::MicroAllocator* arm::app::Model::GetAllocator()
143{
144 if (this->IsInited()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100145 return this->m_pAllocator;
alexander3c798932021-03-26 21:42:19 +0000146 }
147 return nullptr;
148}
149
150void arm::app::Model::LogTensorInfo(TfLiteTensor* tensor)
151{
152 if (!tensor) {
153 printf_err("Invalid tensor\n");
154 assert(tensor);
155 return;
156 }
157
158 debug("\ttensor is assigned to 0x%p\n", tensor);
159 info("\ttensor type is %s\n", TfLiteTypeGetName(tensor->type));
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100160 info("\ttensor occupies %zu bytes with dimensions\n",
161 tensor->bytes);
alexander3c798932021-03-26 21:42:19 +0000162 for (int i = 0 ; i < tensor->dims->size; ++i) {
163 info ("\t\t%d: %3d\n", i, tensor->dims->data[i]);
164 }
165
166 TfLiteQuantization quant = tensor->quantization;
167 if (kTfLiteAffineQuantization == quant.type) {
168 auto* quantParams = (TfLiteAffineQuantization*)quant.params;
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100169 info("Quant dimension: %" PRIi32 "\n", quantParams->quantized_dimension);
alexander3c798932021-03-26 21:42:19 +0000170 for (int i = 0; i < quantParams->scale->size; ++i) {
171 info("Scale[%d] = %f\n", i, quantParams->scale->data[i]);
172 }
173 for (int i = 0; i < quantParams->zero_point->size; ++i) {
174 info("ZeroPoint[%d] = %d\n", i, quantParams->zero_point->data[i]);
175 }
176 }
177}
178
179void arm::app::Model::LogInterpreterInfo()
180{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100181 if (!this->m_pInterpreter) {
alexander3c798932021-03-26 21:42:19 +0000182 printf_err("Invalid interpreter\n");
183 return;
184 }
185
186 info("Model INPUT tensors: \n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100187 for (auto input : this->m_input) {
alexander3c798932021-03-26 21:42:19 +0000188 this->LogTensorInfo(input);
189 }
190
191 info("Model OUTPUT tensors: \n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100192 for (auto output : this->m_output) {
alexander3c798932021-03-26 21:42:19 +0000193 this->LogTensorInfo(output);
194 }
195
196 info("Activation buffer (a.k.a tensor arena) size used: %zu\n",
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100197 this->m_pInterpreter->arena_used_bytes());
alexander3c798932021-03-26 21:42:19 +0000198
Richard Burton0d110592021-08-12 17:26:30 +0100199 /* We expect there to be only one subgraph. */
200 const uint32_t nOperators = tflite::NumSubgraphOperators(this->m_pModel, 0);
201 info("Number of operators: %" PRIu32 "\n", nOperators);
alexander3c798932021-03-26 21:42:19 +0000202
Richard Burton0d110592021-08-12 17:26:30 +0100203 const tflite::SubGraph* subgraph = this->m_pModel->subgraphs()->Get(0);
204
205 auto* opcodes = this->m_pModel->operator_codes();
206
207 /* For each operator, display registration information. */
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100208 for (size_t i = 0 ; i < nOperators; ++i) {
Richard Burton0d110592021-08-12 17:26:30 +0100209 const tflite::Operator* op = subgraph->operators()->Get(i);
210 const tflite::OperatorCode* opcode = opcodes->Get(op->opcode_index());
211 const TfLiteRegistration* reg = nullptr;
212
213 tflite::GetRegistrationFromOpCode(opcode, this->GetOpResolver(),
214 this->m_pErrorReporter, &reg);
alexander3c798932021-03-26 21:42:19 +0000215 std::string opName{""};
216
217 if (reg) {
218 if (tflite::BuiltinOperator_CUSTOM == reg->builtin_code) {
219 opName = std::string(reg->custom_name);
220 } else {
221 opName = std::string(EnumNameBuiltinOperator(
222 tflite::BuiltinOperator(reg->builtin_code)));
223 }
224 }
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100225 info("\tOperator %zu: %s\n", i, opName.c_str());
alexander3c798932021-03-26 21:42:19 +0000226 }
227}
228
229bool arm::app::Model::IsInited() const
230{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100231 return this->m_inited;
alexander3c798932021-03-26 21:42:19 +0000232}
233
234bool arm::app::Model::IsDataSigned() const
235{
236 return this->GetType() == kTfLiteInt8;
237}
238
239bool arm::app::Model::RunInference()
240{
241 bool inference_state = false;
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100242 if (this->m_pModel && this->m_pInterpreter) {
243 if (kTfLiteOk != this->m_pInterpreter->Invoke()) {
alexander3c798932021-03-26 21:42:19 +0000244 printf_err("Invoke failed.\n");
245 } else {
246 inference_state = true;
247 }
248 } else {
249 printf_err("Error: No interpreter!\n");
250 }
251 return inference_state;
252}
253
254TfLiteTensor* arm::app::Model::GetInputTensor(size_t index) const
255{
256 if (index < this->GetNumInputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100257 return this->m_input.at(index);
alexander3c798932021-03-26 21:42:19 +0000258 }
259 return nullptr;
260}
261
262TfLiteTensor* arm::app::Model::GetOutputTensor(size_t index) const
263{
264 if (index < this->GetNumOutputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100265 return this->m_output.at(index);
alexander3c798932021-03-26 21:42:19 +0000266 }
267 return nullptr;
268}
269
270size_t arm::app::Model::GetNumInputs() const
271{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100272 if (this->m_pModel && this->m_pInterpreter) {
273 return this->m_pInterpreter->inputs_size();
alexander3c798932021-03-26 21:42:19 +0000274 }
275 return 0;
276}
277
278size_t arm::app::Model::GetNumOutputs() const
279{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100280 if (this->m_pModel && this->m_pInterpreter) {
281 return this->m_pInterpreter->outputs_size();
alexander3c798932021-03-26 21:42:19 +0000282 }
283 return 0;
284}
285
286
287TfLiteType arm::app::Model::GetType() const
288{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100289 return this->m_type;
alexander3c798932021-03-26 21:42:19 +0000290}
291
292TfLiteIntArray* arm::app::Model::GetInputShape(size_t index) const
293{
294 if (index < this->GetNumInputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100295 return this->m_input.at(index)->dims;
alexander3c798932021-03-26 21:42:19 +0000296 }
297 return nullptr;
298}
299
300TfLiteIntArray* arm::app::Model::GetOutputShape(size_t index) const
301{
302 if (index < this->GetNumOutputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100303 return this->m_output.at(index)->dims;
alexander3c798932021-03-26 21:42:19 +0000304 }
305 return nullptr;
306}
307
308bool arm::app::Model::ShowModelInfoHandler()
309{
310 if (!this->IsInited()) {
311 printf_err("Model is not initialised! Terminating processing.\n");
312 return false;
313 }
314
315 PrintTensorFlowVersion();
316 info("Model info:\n");
317 this->LogInterpreterInfo();
318
319#if defined(ARM_NPU)
320 info("Use of Arm uNPU is enabled\n");
321#else /* ARM_NPU */
322 info("Use of Arm uNPU is disabled\n");
323#endif /* ARM_NPU */
324
325 return true;
326}
327namespace arm {
328namespace app {
alexanderc350cdc2021-04-29 20:36:09 +0100329 static uint8_t tensor_arena[ACTIVATION_BUF_SZ] ACTIVATION_BUF_ATTRIBUTE;
alexander3c798932021-03-26 21:42:19 +0000330} /* namespace app */
331} /* namespace arm */
332
333size_t arm::app::Model::GetActivationBufferSize()
334{
335 return ACTIVATION_BUF_SZ;
336}
337
338uint8_t *arm::app::Model::GetTensorArena()
339{
alexanderc350cdc2021-04-29 20:36:09 +0100340 return tensor_arena;
alexander3c798932021-03-26 21:42:19 +0000341}