blob: 22a1a4d32863cc7d9b7eef9d1a9f8c908ea95a15 [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"
alexander31ae9f02022-02-10 16:15:54 +000018#include "log_macros.h"
alexander3c798932021-03-26 21:42:19 +000019
alexander31ae9f02022-02-10 16:15:54 +000020#include <cinttypes>
alexander3c798932021-03-26 21:42:19 +000021
22/* Initialise the model */
23arm::app::Model::~Model()
24{
alexander31ae9f02022-02-10 16:15:54 +000025 delete this->m_pInterpreter;
alexander3c798932021-03-26 21:42:19 +000026 /**
27 * No clean-up function available for allocator in TensorFlow Lite Micro yet.
28 **/
29}
30
31arm::app::Model::Model() :
Isabella Gottardi56ee6202021-05-12 08:27:15 +010032 m_inited (false),
33 m_type(kTfLiteNoType)
alexander3c798932021-03-26 21:42:19 +000034{
Kshitij Sisodiadd6d07b2022-05-03 10:10:14 +010035 this->m_pErrorReporter = tflite::GetMicroErrorReporter();
alexander3c798932021-03-26 21:42:19 +000036}
37
38bool arm::app::Model::Init(tflite::MicroAllocator* allocator)
39{
40 /* Following tf lite micro example:
41 * Map the model into a usable data structure. This doesn't involve any
42 * copying or parsing, it's a very lightweight operation. */
43 const uint8_t* model_addr = ModelPointer();
44 debug("loading model from @ 0x%p\n", model_addr);
Isabella Gottardi56ee6202021-05-12 08:27:15 +010045 this->m_pModel = ::tflite::GetModel(model_addr);
alexander3c798932021-03-26 21:42:19 +000046
Isabella Gottardi56ee6202021-05-12 08:27:15 +010047 if (this->m_pModel->version() != TFLITE_SCHEMA_VERSION) {
48 this->m_pErrorReporter->Report(
alexander3c798932021-03-26 21:42:19 +000049 "[ERROR] model's schema version %d is not equal "
50 "to supported version %d.",
Isabella Gottardi56ee6202021-05-12 08:27:15 +010051 this->m_pModel->version(), TFLITE_SCHEMA_VERSION);
alexander3c798932021-03-26 21:42:19 +000052 return false;
53 }
54
55 /* Pull in only the operation implementations we need.
56 * This relies on a complete list of all the ops needed by this graph.
57 * An easier approach is to just use the AllOpsResolver, but this will
58 * incur some penalty in code space for op implementations that are not
59 * needed by this graph.
60 * static ::tflite::ops::micro::AllOpsResolver resolver; */
61 /* NOLINTNEXTLINE(runtime-global-variables) */
62 debug("loading op resolver\n");
63
64 this->EnlistOperations();
Cisco Cervellera02101092021-09-07 11:34:43 +010065
66#if !defined(ARM_NPU)
67 /* If it is not a NPU build check if the model contains a NPU operator */
68 bool contains_ethosu_operator = this->ContainsEthosUOperator();
69 if (contains_ethosu_operator)
70 {
71 printf_err("Ethos-U operator present in the model but this build does not include Ethos-U drivers\n");
72 return false;
73 }
74#endif /* ARM_NPU */
alexander3c798932021-03-26 21:42:19 +000075
76 /* Create allocator instance, if it doesn't exist */
Isabella Gottardi56ee6202021-05-12 08:27:15 +010077 this->m_pAllocator = allocator;
78 if (!this->m_pAllocator) {
alexander3c798932021-03-26 21:42:19 +000079 /* Create an allocator instance */
80 info("Creating allocator using tensor arena in %s\n",
81 ACTIVATION_BUF_SECTION_NAME);
82
Isabella Gottardi56ee6202021-05-12 08:27:15 +010083 this->m_pAllocator = tflite::MicroAllocator::Create(
alexander3c798932021-03-26 21:42:19 +000084 this->GetTensorArena(),
85 this->GetActivationBufferSize(),
Isabella Gottardi56ee6202021-05-12 08:27:15 +010086 this->m_pErrorReporter);
alexander3c798932021-03-26 21:42:19 +000087
Isabella Gottardi56ee6202021-05-12 08:27:15 +010088 if (!this->m_pAllocator) {
alexander3c798932021-03-26 21:42:19 +000089 printf_err("Failed to create allocator\n");
90 return false;
91 }
Isabella Gottardi56ee6202021-05-12 08:27:15 +010092 debug("Created new allocator @ 0x%p\n", this->m_pAllocator);
alexander3c798932021-03-26 21:42:19 +000093 } else {
Isabella Gottardi56ee6202021-05-12 08:27:15 +010094 debug("Using existing allocator @ 0x%p\n", this->m_pAllocator);
alexander3c798932021-03-26 21:42:19 +000095 }
96
Isabella Gottardi56ee6202021-05-12 08:27:15 +010097 this->m_pInterpreter = new ::tflite::MicroInterpreter(
98 this->m_pModel, this->GetOpResolver(),
99 this->m_pAllocator, this->m_pErrorReporter);
alexander3c798932021-03-26 21:42:19 +0000100
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100101 if (!this->m_pInterpreter) {
alexander3c798932021-03-26 21:42:19 +0000102 printf_err("Failed to allocate interpreter\n");
103 return false;
104 }
105
106 /* Allocate memory from the tensor_arena for the model's tensors. */
107 info("Allocating tensors\n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100108 TfLiteStatus allocate_status = this->m_pInterpreter->AllocateTensors();
alexander3c798932021-03-26 21:42:19 +0000109
110 if (allocate_status != kTfLiteOk) {
alexander3c798932021-03-26 21:42:19 +0000111 printf_err("tensor allocation failed!\n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100112 delete this->m_pInterpreter;
alexander3c798932021-03-26 21:42:19 +0000113 return false;
114 }
115
116 /* Get information about the memory area to use for the model's input. */
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100117 this->m_input.resize(this->GetNumInputs());
alexander3c798932021-03-26 21:42:19 +0000118 for (size_t inIndex = 0; inIndex < this->GetNumInputs(); inIndex++)
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100119 this->m_input[inIndex] = this->m_pInterpreter->input(inIndex);
alexander3c798932021-03-26 21:42:19 +0000120
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100121 this->m_output.resize(this->GetNumOutputs());
alexander3c798932021-03-26 21:42:19 +0000122 for (size_t outIndex = 0; outIndex < this->GetNumOutputs(); outIndex++)
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100123 this->m_output[outIndex] = this->m_pInterpreter->output(outIndex);
alexander3c798932021-03-26 21:42:19 +0000124
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100125 if (this->m_input.empty() || this->m_output.empty()) {
alexander3c798932021-03-26 21:42:19 +0000126 printf_err("failed to get tensors\n");
127 return false;
128 } else {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100129 this->m_type = this->m_input[0]->type; /* Input 0 should be the main input */
alexander3c798932021-03-26 21:42:19 +0000130
131 /* Clear the input & output tensors */
132 for (size_t inIndex = 0; inIndex < this->GetNumInputs(); inIndex++) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100133 std::memset(this->m_input[inIndex]->data.data, 0, this->m_input[inIndex]->bytes);
alexander3c798932021-03-26 21:42:19 +0000134 }
135 for (size_t outIndex = 0; outIndex < this->GetNumOutputs(); outIndex++) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100136 std::memset(this->m_output[outIndex]->data.data, 0, this->m_output[outIndex]->bytes);
alexander3c798932021-03-26 21:42:19 +0000137 }
138
139 this->LogInterpreterInfo();
140 }
141
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100142 this->m_inited = true;
alexander3c798932021-03-26 21:42:19 +0000143 return true;
144}
145
146tflite::MicroAllocator* arm::app::Model::GetAllocator()
147{
148 if (this->IsInited()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100149 return this->m_pAllocator;
alexander3c798932021-03-26 21:42:19 +0000150 }
151 return nullptr;
152}
153
154void arm::app::Model::LogTensorInfo(TfLiteTensor* tensor)
155{
156 if (!tensor) {
157 printf_err("Invalid tensor\n");
158 assert(tensor);
159 return;
160 }
161
162 debug("\ttensor is assigned to 0x%p\n", tensor);
163 info("\ttensor type is %s\n", TfLiteTypeGetName(tensor->type));
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100164 info("\ttensor occupies %zu bytes with dimensions\n",
165 tensor->bytes);
alexander3c798932021-03-26 21:42:19 +0000166 for (int i = 0 ; i < tensor->dims->size; ++i) {
167 info ("\t\t%d: %3d\n", i, tensor->dims->data[i]);
168 }
169
170 TfLiteQuantization quant = tensor->quantization;
171 if (kTfLiteAffineQuantization == quant.type) {
172 auto* quantParams = (TfLiteAffineQuantization*)quant.params;
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100173 info("Quant dimension: %" PRIi32 "\n", quantParams->quantized_dimension);
alexander3c798932021-03-26 21:42:19 +0000174 for (int i = 0; i < quantParams->scale->size; ++i) {
175 info("Scale[%d] = %f\n", i, quantParams->scale->data[i]);
176 }
177 for (int i = 0; i < quantParams->zero_point->size; ++i) {
178 info("ZeroPoint[%d] = %d\n", i, quantParams->zero_point->data[i]);
179 }
180 }
181}
182
183void arm::app::Model::LogInterpreterInfo()
184{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100185 if (!this->m_pInterpreter) {
alexander3c798932021-03-26 21:42:19 +0000186 printf_err("Invalid interpreter\n");
187 return;
188 }
189
190 info("Model INPUT tensors: \n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100191 for (auto input : this->m_input) {
alexander3c798932021-03-26 21:42:19 +0000192 this->LogTensorInfo(input);
193 }
194
195 info("Model OUTPUT tensors: \n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100196 for (auto output : this->m_output) {
alexander3c798932021-03-26 21:42:19 +0000197 this->LogTensorInfo(output);
198 }
199
200 info("Activation buffer (a.k.a tensor arena) size used: %zu\n",
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100201 this->m_pInterpreter->arena_used_bytes());
alexander3c798932021-03-26 21:42:19 +0000202
Richard Burton0d110592021-08-12 17:26:30 +0100203 /* We expect there to be only one subgraph. */
204 const uint32_t nOperators = tflite::NumSubgraphOperators(this->m_pModel, 0);
205 info("Number of operators: %" PRIu32 "\n", nOperators);
alexander3c798932021-03-26 21:42:19 +0000206
Richard Burton0d110592021-08-12 17:26:30 +0100207 const tflite::SubGraph* subgraph = this->m_pModel->subgraphs()->Get(0);
208
209 auto* opcodes = this->m_pModel->operator_codes();
210
211 /* For each operator, display registration information. */
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100212 for (size_t i = 0 ; i < nOperators; ++i) {
Richard Burton0d110592021-08-12 17:26:30 +0100213 const tflite::Operator* op = subgraph->operators()->Get(i);
214 const tflite::OperatorCode* opcode = opcodes->Get(op->opcode_index());
215 const TfLiteRegistration* reg = nullptr;
216
217 tflite::GetRegistrationFromOpCode(opcode, this->GetOpResolver(),
218 this->m_pErrorReporter, &reg);
alexander31ae9f02022-02-10 16:15:54 +0000219 std::string opName;
alexander3c798932021-03-26 21:42:19 +0000220
221 if (reg) {
222 if (tflite::BuiltinOperator_CUSTOM == reg->builtin_code) {
223 opName = std::string(reg->custom_name);
224 } else {
225 opName = std::string(EnumNameBuiltinOperator(
226 tflite::BuiltinOperator(reg->builtin_code)));
227 }
228 }
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100229 info("\tOperator %zu: %s\n", i, opName.c_str());
alexander3c798932021-03-26 21:42:19 +0000230 }
231}
232
233bool arm::app::Model::IsInited() const
234{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100235 return this->m_inited;
alexander3c798932021-03-26 21:42:19 +0000236}
237
238bool arm::app::Model::IsDataSigned() const
239{
240 return this->GetType() == kTfLiteInt8;
241}
242
Cisco Cervellera02101092021-09-07 11:34:43 +0100243bool arm::app::Model::ContainsEthosUOperator() const
244{
245 /* We expect there to be only one subgraph. */
246 const uint32_t nOperators = tflite::NumSubgraphOperators(this->m_pModel, 0);
247 const tflite::SubGraph* subgraph = this->m_pModel->subgraphs()->Get(0);
248 const auto* opcodes = this->m_pModel->operator_codes();
249
250 /* check for custom operators */
251 for (size_t i = 0; (i < nOperators); ++i)
252 {
253 const tflite::Operator* op = subgraph->operators()->Get(i);
254 const tflite::OperatorCode* opcode = opcodes->Get(op->opcode_index());
255
256 auto builtin_code = tflite::GetBuiltinCode(opcode);
257 if ((builtin_code == tflite::BuiltinOperator_CUSTOM) &&
258 ( nullptr != opcode->custom_code()) &&
alexander31ae9f02022-02-10 16:15:54 +0000259 ( "ethos-u" == std::string(opcode->custom_code()->c_str())))
Cisco Cervellera02101092021-09-07 11:34:43 +0100260 {
261 return true;
262 }
263 }
264 return false;
265}
266
alexander3c798932021-03-26 21:42:19 +0000267bool arm::app::Model::RunInference()
268{
269 bool inference_state = false;
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100270 if (this->m_pModel && this->m_pInterpreter) {
271 if (kTfLiteOk != this->m_pInterpreter->Invoke()) {
alexander3c798932021-03-26 21:42:19 +0000272 printf_err("Invoke failed.\n");
273 } else {
274 inference_state = true;
275 }
276 } else {
277 printf_err("Error: No interpreter!\n");
278 }
279 return inference_state;
280}
281
282TfLiteTensor* arm::app::Model::GetInputTensor(size_t index) const
283{
284 if (index < this->GetNumInputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100285 return this->m_input.at(index);
alexander3c798932021-03-26 21:42:19 +0000286 }
287 return nullptr;
288}
289
290TfLiteTensor* arm::app::Model::GetOutputTensor(size_t index) const
291{
292 if (index < this->GetNumOutputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100293 return this->m_output.at(index);
alexander3c798932021-03-26 21:42:19 +0000294 }
295 return nullptr;
296}
297
298size_t arm::app::Model::GetNumInputs() const
299{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100300 if (this->m_pModel && this->m_pInterpreter) {
301 return this->m_pInterpreter->inputs_size();
alexander3c798932021-03-26 21:42:19 +0000302 }
303 return 0;
304}
305
306size_t arm::app::Model::GetNumOutputs() const
307{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100308 if (this->m_pModel && this->m_pInterpreter) {
309 return this->m_pInterpreter->outputs_size();
alexander3c798932021-03-26 21:42:19 +0000310 }
311 return 0;
312}
313
314
315TfLiteType arm::app::Model::GetType() const
316{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100317 return this->m_type;
alexander3c798932021-03-26 21:42:19 +0000318}
319
320TfLiteIntArray* arm::app::Model::GetInputShape(size_t index) const
321{
322 if (index < this->GetNumInputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100323 return this->m_input.at(index)->dims;
alexander3c798932021-03-26 21:42:19 +0000324 }
325 return nullptr;
326}
327
328TfLiteIntArray* arm::app::Model::GetOutputShape(size_t index) const
329{
330 if (index < this->GetNumOutputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100331 return this->m_output.at(index)->dims;
alexander3c798932021-03-26 21:42:19 +0000332 }
333 return nullptr;
334}
335
336bool arm::app::Model::ShowModelInfoHandler()
337{
338 if (!this->IsInited()) {
339 printf_err("Model is not initialised! Terminating processing.\n");
340 return false;
341 }
342
343 PrintTensorFlowVersion();
344 info("Model info:\n");
345 this->LogInterpreterInfo();
346
alexander31ae9f02022-02-10 16:15:54 +0000347 info("The model is optimised for Ethos-U NPU: %s.\n", this->ContainsEthosUOperator()? "yes": "no");
alexander3c798932021-03-26 21:42:19 +0000348
349 return true;
350}
351namespace arm {
352namespace app {
alexanderc350cdc2021-04-29 20:36:09 +0100353 static uint8_t tensor_arena[ACTIVATION_BUF_SZ] ACTIVATION_BUF_ATTRIBUTE;
alexander3c798932021-03-26 21:42:19 +0000354} /* namespace app */
355} /* namespace arm */
356
357size_t arm::app::Model::GetActivationBufferSize()
358{
359 return ACTIVATION_BUF_SZ;
360}
361
362uint8_t *arm::app::Model::GetTensorArena()
363{
alexanderc350cdc2021-04-29 20:36:09 +0100364 return tensor_arena;
alexander3c798932021-03-26 21:42:19 +0000365}