blob: 3675c5bd2f94d7766e0d9d68ab8359a1627378b7 [file] [log] [blame]
alexander3c798932021-03-26 21:42:19 +00001/*
Richard Burtondf88c5d2023-05-30 17:40:39 +01002 * SPDX-FileCopyrightText: Copyright 2021-2023 Arm Limited and/or its affiliates
Kshitij Sisodia47406fe2022-12-05 17:18:50 +00003 * <open-source-office@arm.com> SPDX-License-Identifier: Apache-2.0
alexander3c798932021-03-26 21:42:19 +00004 *
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>
Liam Barry677d43f2023-08-03 18:21:58 +010021#include <memory>
alexander3c798932021-03-26 21:42:19 +000022
Kshitij Sisodia47406fe2022-12-05 17:18:50 +000023arm::app::Model::Model() : m_inited(false), m_type(kTfLiteNoType) {}
alexander3c798932021-03-26 21:42:19 +000024
Liam Barry677d43f2023-08-03 18:21:58 +010025/* Initialise the model */
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +010026bool arm::app::Model::Init(uint8_t* tensorArenaAddr,
27 uint32_t tensorArenaSize,
Kshitij Sisodia937052d2022-05-13 16:44:16 +010028 const uint8_t* nnModelAddr,
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +010029 uint32_t nnModelSize,
30 tflite::MicroAllocator* allocator)
alexander3c798932021-03-26 21:42:19 +000031{
32 /* Following tf lite micro example:
33 * Map the model into a usable data structure. This doesn't involve any
34 * copying or parsing, it's a very lightweight operation. */
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +010035 debug("loading model from @ 0x%p\n", nnModelAddr);
36 debug("model size: %" PRIu32 " bytes.\n", nnModelSize);
37
38 this->m_pModel = ::tflite::GetModel(nnModelAddr);
alexander3c798932021-03-26 21:42:19 +000039
Isabella Gottardi56ee6202021-05-12 08:27:15 +010040 if (this->m_pModel->version() != TFLITE_SCHEMA_VERSION) {
Kshitij Sisodia47406fe2022-12-05 17:18:50 +000041 printf_err("Model's schema version %" PRIu32 " is not equal "
42 "to supported version %d.",
43 this->m_pModel->version(),
44 TFLITE_SCHEMA_VERSION);
alexander3c798932021-03-26 21:42:19 +000045 return false;
46 }
47
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +010048 this->m_modelAddr = nnModelAddr;
49 this->m_modelSize = nnModelSize;
50
alexander3c798932021-03-26 21:42:19 +000051 /* Pull in only the operation implementations we need.
52 * This relies on a complete list of all the ops needed by this graph.
53 * An easier approach is to just use the AllOpsResolver, but this will
54 * incur some penalty in code space for op implementations that are not
55 * needed by this graph.
56 * static ::tflite::ops::micro::AllOpsResolver resolver; */
57 /* NOLINTNEXTLINE(runtime-global-variables) */
58 debug("loading op resolver\n");
59
60 this->EnlistOperations();
61
62 /* Create allocator instance, if it doesn't exist */
Isabella Gottardi56ee6202021-05-12 08:27:15 +010063 this->m_pAllocator = allocator;
64 if (!this->m_pAllocator) {
alexander3c798932021-03-26 21:42:19 +000065 /* Create an allocator instance */
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +010066 info("Creating allocator using tensor arena at 0x%p\n", tensorArenaAddr);
alexander3c798932021-03-26 21:42:19 +000067
Kshitij Sisodia47406fe2022-12-05 17:18:50 +000068 this->m_pAllocator = tflite::MicroAllocator::Create(tensorArenaAddr, tensorArenaSize);
alexander3c798932021-03-26 21:42:19 +000069
Isabella Gottardi56ee6202021-05-12 08:27:15 +010070 if (!this->m_pAllocator) {
alexander3c798932021-03-26 21:42:19 +000071 printf_err("Failed to create allocator\n");
72 return false;
73 }
Isabella Gottardi56ee6202021-05-12 08:27:15 +010074 debug("Created new allocator @ 0x%p\n", this->m_pAllocator);
alexander3c798932021-03-26 21:42:19 +000075 } else {
Isabella Gottardi56ee6202021-05-12 08:27:15 +010076 debug("Using existing allocator @ 0x%p\n", this->m_pAllocator);
alexander3c798932021-03-26 21:42:19 +000077 }
78
Liam Barry677d43f2023-08-03 18:21:58 +010079 this->m_pInterpreter = std::make_unique<tflite::MicroInterpreter>(
80 this->m_pModel, this->GetOpResolver(), this->m_pAllocator);
alexander3c798932021-03-26 21:42:19 +000081
Isabella Gottardi56ee6202021-05-12 08:27:15 +010082 if (!this->m_pInterpreter) {
alexander3c798932021-03-26 21:42:19 +000083 printf_err("Failed to allocate interpreter\n");
84 return false;
85 }
86
87 /* Allocate memory from the tensor_arena for the model's tensors. */
88 info("Allocating tensors\n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +010089 TfLiteStatus allocate_status = this->m_pInterpreter->AllocateTensors();
alexander3c798932021-03-26 21:42:19 +000090
91 if (allocate_status != kTfLiteOk) {
alexander3c798932021-03-26 21:42:19 +000092 printf_err("tensor allocation failed!\n");
alexander3c798932021-03-26 21:42:19 +000093 return false;
94 }
95
96 /* Get information about the memory area to use for the model's input. */
Isabella Gottardi56ee6202021-05-12 08:27:15 +010097 this->m_input.resize(this->GetNumInputs());
alexander3c798932021-03-26 21:42:19 +000098 for (size_t inIndex = 0; inIndex < this->GetNumInputs(); inIndex++)
Isabella Gottardi56ee6202021-05-12 08:27:15 +010099 this->m_input[inIndex] = this->m_pInterpreter->input(inIndex);
alexander3c798932021-03-26 21:42:19 +0000100
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100101 this->m_output.resize(this->GetNumOutputs());
alexander3c798932021-03-26 21:42:19 +0000102 for (size_t outIndex = 0; outIndex < this->GetNumOutputs(); outIndex++)
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100103 this->m_output[outIndex] = this->m_pInterpreter->output(outIndex);
alexander3c798932021-03-26 21:42:19 +0000104
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100105 if (this->m_input.empty() || this->m_output.empty()) {
alexander3c798932021-03-26 21:42:19 +0000106 printf_err("failed to get tensors\n");
107 return false;
108 } else {
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000109 this->m_type = this->m_input[0]->type; /* Input 0 should be the main input */
alexander3c798932021-03-26 21:42:19 +0000110
111 /* Clear the input & output tensors */
112 for (size_t inIndex = 0; inIndex < this->GetNumInputs(); inIndex++) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100113 std::memset(this->m_input[inIndex]->data.data, 0, this->m_input[inIndex]->bytes);
alexander3c798932021-03-26 21:42:19 +0000114 }
115 for (size_t outIndex = 0; outIndex < this->GetNumOutputs(); outIndex++) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100116 std::memset(this->m_output[outIndex]->data.data, 0, this->m_output[outIndex]->bytes);
alexander3c798932021-03-26 21:42:19 +0000117 }
118
119 this->LogInterpreterInfo();
120 }
121
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100122 this->m_inited = true;
alexander3c798932021-03-26 21:42:19 +0000123 return true;
124}
125
126tflite::MicroAllocator* arm::app::Model::GetAllocator()
127{
128 if (this->IsInited()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100129 return this->m_pAllocator;
alexander3c798932021-03-26 21:42:19 +0000130 }
131 return nullptr;
132}
133
134void arm::app::Model::LogTensorInfo(TfLiteTensor* tensor)
135{
136 if (!tensor) {
137 printf_err("Invalid tensor\n");
138 assert(tensor);
139 return;
140 }
141
142 debug("\ttensor is assigned to 0x%p\n", tensor);
143 info("\ttensor type is %s\n", TfLiteTypeGetName(tensor->type));
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000144 info("\ttensor occupies %zu bytes with dimensions\n", tensor->bytes);
145 for (int i = 0; i < tensor->dims->size; ++i) {
146 info("\t\t%d: %3d\n", i, tensor->dims->data[i]);
alexander3c798932021-03-26 21:42:19 +0000147 }
148
149 TfLiteQuantization quant = tensor->quantization;
150 if (kTfLiteAffineQuantization == quant.type) {
151 auto* quantParams = (TfLiteAffineQuantization*)quant.params;
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100152 info("Quant dimension: %" PRIi32 "\n", quantParams->quantized_dimension);
alexander3c798932021-03-26 21:42:19 +0000153 for (int i = 0; i < quantParams->scale->size; ++i) {
154 info("Scale[%d] = %f\n", i, quantParams->scale->data[i]);
155 }
156 for (int i = 0; i < quantParams->zero_point->size; ++i) {
157 info("ZeroPoint[%d] = %d\n", i, quantParams->zero_point->data[i]);
158 }
159 }
160}
161
162void arm::app::Model::LogInterpreterInfo()
163{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100164 if (!this->m_pInterpreter) {
alexander3c798932021-03-26 21:42:19 +0000165 printf_err("Invalid interpreter\n");
166 return;
167 }
168
169 info("Model INPUT tensors: \n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100170 for (auto input : this->m_input) {
alexander3c798932021-03-26 21:42:19 +0000171 this->LogTensorInfo(input);
172 }
173
174 info("Model OUTPUT tensors: \n");
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100175 for (auto output : this->m_output) {
alexander3c798932021-03-26 21:42:19 +0000176 this->LogTensorInfo(output);
177 }
178
179 info("Activation buffer (a.k.a tensor arena) size used: %zu\n",
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000180 this->m_pInterpreter->arena_used_bytes());
alexander3c798932021-03-26 21:42:19 +0000181
Richard Burton0d110592021-08-12 17:26:30 +0100182 /* We expect there to be only one subgraph. */
183 const uint32_t nOperators = tflite::NumSubgraphOperators(this->m_pModel, 0);
184 info("Number of operators: %" PRIu32 "\n", nOperators);
alexander3c798932021-03-26 21:42:19 +0000185
Richard Burton0d110592021-08-12 17:26:30 +0100186 const tflite::SubGraph* subgraph = this->m_pModel->subgraphs()->Get(0);
187
188 auto* opcodes = this->m_pModel->operator_codes();
189
190 /* For each operator, display registration information. */
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000191 for (size_t i = 0; i < nOperators; ++i) {
192 const tflite::Operator* op = subgraph->operators()->Get(i);
Richard Burton0d110592021-08-12 17:26:30 +0100193 const tflite::OperatorCode* opcode = opcodes->Get(op->opcode_index());
Nina Drozd05c1c5a2023-08-22 12:41:55 +0100194 const TFLMRegistration* reg = nullptr;
Richard Burton0d110592021-08-12 17:26:30 +0100195
Richard Burton71f282e2022-12-01 12:31:23 +0000196 tflite::GetRegistrationFromOpCode(opcode, this->GetOpResolver(), &reg);
alexander31ae9f02022-02-10 16:15:54 +0000197 std::string opName;
alexander3c798932021-03-26 21:42:19 +0000198
199 if (reg) {
200 if (tflite::BuiltinOperator_CUSTOM == reg->builtin_code) {
201 opName = std::string(reg->custom_name);
202 } else {
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000203 opName = std::string(
204 EnumNameBuiltinOperator(tflite::BuiltinOperator(reg->builtin_code)));
alexander3c798932021-03-26 21:42:19 +0000205 }
206 }
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100207 info("\tOperator %zu: %s\n", i, opName.c_str());
alexander3c798932021-03-26 21:42:19 +0000208 }
209}
210
211bool arm::app::Model::IsInited() const
212{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100213 return this->m_inited;
alexander3c798932021-03-26 21:42:19 +0000214}
215
216bool arm::app::Model::IsDataSigned() const
217{
218 return this->GetType() == kTfLiteInt8;
219}
220
Cisco Cervellera02101092021-09-07 11:34:43 +0100221bool arm::app::Model::ContainsEthosUOperator() const
222{
223 /* We expect there to be only one subgraph. */
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000224 const uint32_t nOperators = tflite::NumSubgraphOperators(this->m_pModel, 0);
Cisco Cervellera02101092021-09-07 11:34:43 +0100225 const tflite::SubGraph* subgraph = this->m_pModel->subgraphs()->Get(0);
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000226 const auto* opcodes = this->m_pModel->operator_codes();
Cisco Cervellera02101092021-09-07 11:34:43 +0100227
228 /* check for custom operators */
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000229 for (size_t i = 0; (i < nOperators); ++i) {
230 const tflite::Operator* op = subgraph->operators()->Get(i);
Cisco Cervellera02101092021-09-07 11:34:43 +0100231 const tflite::OperatorCode* opcode = opcodes->Get(op->opcode_index());
232
233 auto builtin_code = tflite::GetBuiltinCode(opcode);
234 if ((builtin_code == tflite::BuiltinOperator_CUSTOM) &&
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000235 (nullptr != opcode->custom_code()) &&
236 ("ethos-u" == std::string(opcode->custom_code()->c_str()))) {
Cisco Cervellera02101092021-09-07 11:34:43 +0100237 return true;
238 }
239 }
240 return false;
241}
242
alexander3c798932021-03-26 21:42:19 +0000243bool arm::app::Model::RunInference()
244{
245 bool inference_state = false;
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100246 if (this->m_pModel && this->m_pInterpreter) {
247 if (kTfLiteOk != this->m_pInterpreter->Invoke()) {
alexander3c798932021-03-26 21:42:19 +0000248 printf_err("Invoke failed.\n");
249 } else {
250 inference_state = true;
251 }
252 } else {
253 printf_err("Error: No interpreter!\n");
254 }
255 return inference_state;
256}
257
258TfLiteTensor* arm::app::Model::GetInputTensor(size_t index) const
259{
260 if (index < this->GetNumInputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100261 return this->m_input.at(index);
alexander3c798932021-03-26 21:42:19 +0000262 }
263 return nullptr;
264}
265
266TfLiteTensor* arm::app::Model::GetOutputTensor(size_t index) const
267{
268 if (index < this->GetNumOutputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100269 return this->m_output.at(index);
alexander3c798932021-03-26 21:42:19 +0000270 }
271 return nullptr;
272}
273
274size_t arm::app::Model::GetNumInputs() const
275{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100276 if (this->m_pModel && this->m_pInterpreter) {
277 return this->m_pInterpreter->inputs_size();
alexander3c798932021-03-26 21:42:19 +0000278 }
279 return 0;
280}
281
282size_t arm::app::Model::GetNumOutputs() const
283{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100284 if (this->m_pModel && this->m_pInterpreter) {
285 return this->m_pInterpreter->outputs_size();
alexander3c798932021-03-26 21:42:19 +0000286 }
287 return 0;
288}
289
alexander3c798932021-03-26 21:42:19 +0000290TfLiteType arm::app::Model::GetType() const
291{
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100292 return this->m_type;
alexander3c798932021-03-26 21:42:19 +0000293}
294
295TfLiteIntArray* arm::app::Model::GetInputShape(size_t index) const
296{
297 if (index < this->GetNumInputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100298 return this->m_input.at(index)->dims;
alexander3c798932021-03-26 21:42:19 +0000299 }
300 return nullptr;
301}
302
303TfLiteIntArray* arm::app::Model::GetOutputShape(size_t index) const
304{
305 if (index < this->GetNumOutputs()) {
Isabella Gottardi56ee6202021-05-12 08:27:15 +0100306 return this->m_output.at(index)->dims;
alexander3c798932021-03-26 21:42:19 +0000307 }
308 return nullptr;
309}
310
311bool arm::app::Model::ShowModelInfoHandler()
312{
313 if (!this->IsInited()) {
314 printf_err("Model is not initialised! Terminating processing.\n");
315 return false;
316 }
317
318 PrintTensorFlowVersion();
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +0100319 info("Model address: 0x%p", this->ModelPointer());
320 info("Model size: %" PRIu32 " bytes.", this->ModelSize());
alexander3c798932021-03-26 21:42:19 +0000321 info("Model info:\n");
322 this->LogInterpreterInfo();
323
Kshitij Sisodia47406fe2022-12-05 17:18:50 +0000324 info("The model is optimised for Ethos-U NPU: %s.\n",
325 this->ContainsEthosUOperator() ? "yes" : "no");
alexander3c798932021-03-26 21:42:19 +0000326
327 return true;
328}
alexander3c798932021-03-26 21:42:19 +0000329
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +0100330const uint8_t* arm::app::Model::ModelPointer()
alexander3c798932021-03-26 21:42:19 +0000331{
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +0100332 return this->m_modelAddr;
alexander3c798932021-03-26 21:42:19 +0000333}
334
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +0100335uint32_t arm::app::Model::ModelSize()
alexander3c798932021-03-26 21:42:19 +0000336{
Kshitij Sisodiaaa4bcb12022-05-06 09:13:03 +0100337 return this->m_modelSize;
338}