summaryrefslogtreecommitdiff
path: root/src/inference_engine_tflite.cpp
blob: 8f22bd996a7272eff890f2e33c4240a6558cb583 (plain)
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
/**
 * Copyright (c) 2019 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <inference_engine_error.h>
#include "inference_engine_tflite_private.h"

#include <fstream>
#include <iostream>
#include <unistd.h>
#include <time.h>
#include <queue>

// H/W
#define MV_INFERENCE_TFLITE_MAX_THREAD_NUM -1

namespace InferenceEngineImpl
{
namespace TFLiteImpl
{
	InferenceTFLite::InferenceTFLite(void) : mTargetTypes(INFERENCE_TARGET_NONE)
	{
		LOGI("ENTER");
		LOGI("LEAVE");
	}

	InferenceTFLite::~InferenceTFLite()
	{
		;
	}

	int InferenceTFLite::SetPrivateData(void *data)
	{
		// Nothing to do yet.

		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::SetTargetDevices(int types)
	{
		LOGI("ENTER");

		switch (types) {
		case INFERENCE_TARGET_CPU:
			LOGI("Device type is CPU.");
			break;
		case INFERENCE_TARGET_GPU:
			LOGI("Device type is GPU.");
			break;
		case INFERENCE_TARGET_CUSTOM:
		case INFERENCE_TARGET_NONE:
		default:
			LOGW("Not supported device type [%d], Set CPU mode",
				 (int) mTargetTypes);
			return INFERENCE_ENGINE_ERROR_INVALID_PARAMETER;
		}

		mTargetTypes = types;

		LOGI("LEAVE");
		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::SetCLTuner(const inference_engine_cltuner *cltuner)
	{
		LOGI("ENTER");

		// Nothing to do because TFLITE doesn't support CLTuner feature yet.

		LOGI("LEAVE");

		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::Load(std::vector<std::string> model_paths,
							  inference_model_format_e model_format)
	{
		int ret = INFERENCE_ENGINE_ERROR_NONE;

		mWeightFile = model_paths.back();

		if (access(mWeightFile.c_str(), F_OK)) {
			LOGE("model file path [%s]", mWeightFile.c_str());
			return INFERENCE_ENGINE_ERROR_INVALID_PATH;
		}

		LOGI("mWeightFile.c_str() result [%s]", mWeightFile.c_str());

		mFlatBuffModel =
				tflite::FlatBufferModel::BuildFromFile(mWeightFile.c_str());
		if (!mFlatBuffModel) {
			LOGE("Failed to mmap model %s", mWeightFile.c_str());
			return INFERENCE_ENGINE_ERROR_INVALID_DATA;
		}

		tflite::ops::builtin::BuiltinOpResolver resolver;

		tflite::InterpreterBuilder(*mFlatBuffModel, resolver)(&mInterpreter);
		if (!mInterpreter) {
			LOGE("Failed to construct interpreter");
			return INFERENCE_ENGINE_ERROR_INVALID_OPERATION;
		}

		LOGI("Inferece targets are: [%d]", mTargetTypes);

		if (mTargetTypes == INFERENCE_TARGET_GPU) {
			TfLiteGpuDelegateOptionsV2 options = TfLiteGpuDelegateOptionsV2Default();
			TfLiteDelegate *delegate = TfLiteGpuDelegateV2Create(&options);
			if (!delegate){
				LOGE("Failed to GPU delegate");
				return INFERENCE_ENGINE_ERROR_INVALID_OPERATION;
			}

			if (mInterpreter->ModifyGraphWithDelegate(delegate) != kTfLiteOk)
			{
				LOGE("Failed to construct GPU delegate");
				return INFERENCE_ENGINE_ERROR_INVALID_OPERATION;
			}
		}

		mInterpreter->SetNumThreads(MV_INFERENCE_TFLITE_MAX_THREAD_NUM);
		LOGI("mInterpreter->tensors_size() :[%zu]",
			 mInterpreter->tensors_size());

		FillLayerId(mInputLayerId, mInputLayers, mInterpreter->inputs());
		FillLayerId(mOutputLayerId, mOutputLayers, mInterpreter->outputs());

		if (mInterpreter->AllocateTensors() != kTfLiteOk) {
			LOGE("Fail to allocate tensor");
			return INFERENCE_ENGINE_ERROR_OUT_OF_MEMORY;
		}

		return ret;
	}

	int InferenceTFLite::GetInputTensorBuffers(
			std::map<std::string, inference_engine_tensor_buffer> &buffers)
	{
		LOGI("ENTER");

		if (mInputLayers.empty()) {
			SetInterpreterInfo();
		}

		mInputData.clear();

		void *pBuff = NULL;

		for (auto& layer : mInputLayers) {
			size_t size = 1;
			inference_engine_tensor_buffer buffer;
			for (auto& dim : layer.second.shape)
				size *= dim;

			if ((layer.second).data_type == INFERENCE_TENSOR_DATA_TYPE_UINT8) {
				mInputData.push_back(
						mInterpreter->typed_tensor<uint8_t>(mInputLayerId[layer.first]));
				pBuff = mInputData.back();
				buffer = { pBuff, INFERENCE_TENSOR_DATA_TYPE_UINT8, size, 1 };
			} else if ((layer.second).data_type == INFERENCE_TENSOR_DATA_TYPE_FLOAT32) {
				mInputData.push_back(
						mInterpreter->typed_tensor<float>(mInputLayerId[layer.first]));
				pBuff = mInputData.back();
				buffer = { pBuff, INFERENCE_TENSOR_DATA_TYPE_FLOAT32, size * 4, 1 };
			} else {
				LOGE("Not supported");
				return INFERENCE_ENGINE_ERROR_NOT_SUPPORTED_FORMAT;
			}
			buffers.insert(std::make_pair(layer.first, buffer));
		}

		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::GetOutputTensorBuffers(
			std::map<std::string, inference_engine_tensor_buffer> &buffers)
	{
		LOGI("ENTER");

		if (mOutputLayers.empty()) {
			SetInterpreterInfo();
		}

		void *pBuff = NULL;
		for (auto& layer : mOutputLayers) {
			inference_engine_tensor_buffer buffer;
			size_t size = 1;
			for (int idx2 = 0; idx2 < mInterpreter->tensor(mOutputLayerId[layer.first])->dims->size; ++idx2)
				size *= mInterpreter->tensor(mOutputLayerId[layer.first])->dims->data[idx2];

			if (mInterpreter->tensor(mOutputLayerId[layer.first])->type == kTfLiteUInt8) {
				LOGI("type is kTfLiteUInt8");
				pBuff = (void *) mInterpreter->typed_tensor<uint8_t>(mOutputLayerId[layer.first]);
				buffer = { pBuff, INFERENCE_TENSOR_DATA_TYPE_UINT8, size, 1 };
			} else if (mInterpreter->tensor(mOutputLayerId[layer.first])->type == kTfLiteInt64) {
				LOGI("type is kTfLiteInt64");
				pBuff = (void*)mInterpreter->typed_tensor<int64_t>(mOutputLayerId[layer.first]);
				buffer = {pBuff, INFERENCE_TENSOR_DATA_TYPE_INT64, size * 8, 1};
			} else if (mInterpreter->tensor(mOutputLayerId[layer.first])->type == kTfLiteFloat32) {
				LOGI("type is kTfLiteFloat32");
				pBuff = (void *) mInterpreter->typed_tensor<float>(mOutputLayerId[layer.first]);
				buffer = { pBuff, INFERENCE_TENSOR_DATA_TYPE_FLOAT32, size * 4, 1 };
			} else {
				LOGE("Not supported");
				return INFERENCE_ENGINE_ERROR_NOT_SUPPORTED_FORMAT;
			}

			buffers.insert(std::make_pair(mInterpreter->tensor(mOutputLayerId[layer.first])->name, buffer));
		}
		LOGI("LEAVE");
		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::GetInputLayerProperty(
			inference_engine_layer_property &property)
	{
		LOGI("ENTER");

		SetInterpreterInfo();
		property.layers = mInputLayers;

		LOGI("LEAVE");

		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::GetOutputLayerProperty(
			inference_engine_layer_property &property)
	{
		LOGI("ENTER");

		mOutputLayers.clear();

		for (auto& layer :mOutputLayerId) {
			if (layer.second < 0) {
				LOGE("Invalid output layer ID [%d]", layer.second);
				return INFERENCE_ENGINE_ERROR_INVALID_OPERATION;
			}

			inference_engine_tensor_info tensor_info;

			LOGI("mInterpreter->tensor(%d)->dims name[%s] size[%d] type[%d]",
				 layer.second,
				 mInterpreter->tensor(layer.second)->name,
				 mInterpreter->tensor(layer.second)->dims->size,
				 mInterpreter->tensor(layer.second)->type);

			std::vector<size_t> shape_nhwc;
			for (int idx = 0; idx < mInterpreter->tensor(layer.second)->dims->size; idx++)
				shape_nhwc.push_back(mInterpreter->tensor(layer.second)->dims->data[idx]);

			//tflite only supports NHWC (https://www.tensorflow.org/lite/guide/ops_compatibility).
			tensor_info.shape = shape_nhwc;
			tensor_info.shape_type = INFERENCE_TENSOR_SHAPE_NHWC;
			if (mInterpreter->tensor(layer.second)->type == kTfLiteUInt8) {
				LOGI("type is kTfLiteUInt8");
				tensor_info.data_type = INFERENCE_TENSOR_DATA_TYPE_UINT8;
			} else if (mInterpreter->tensor(layer.second)->type == kTfLiteInt64) {
				LOGI("type is kTfLiteInt64");
				tensor_info.data_type = INFERENCE_TENSOR_DATA_TYPE_INT64;
			} else if (mInterpreter->tensor(layer.second)->type == kTfLiteFloat32) {
				LOGI("type is kTfLiteFloat32");
				tensor_info.data_type = INFERENCE_TENSOR_DATA_TYPE_FLOAT32;
			} else {
				LOGE("Not supported");
				return INFERENCE_ENGINE_ERROR_NOT_SUPPORTED_FORMAT;
			}
			tensor_info.size = 1;

			for (auto & dim : tensor_info.shape)
				tensor_info.size *= dim;

			mOutputLayers.insert(std::make_pair(mInterpreter->tensor(layer.second)->name, tensor_info));
		}

		property.layers = mOutputLayers;

		LOGI("LEAVE");
		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::SetInputLayerProperty(
			inference_engine_layer_property &property)
	{
		LOGI("ENTER");

		for (auto& layer : property.layers)
			LOGI("input layer name = %s", layer.first.c_str());

		mInputLayers.clear();
		mInputLayers = property.layers;

		LOGI("LEAVE");

		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::SetOutputLayerProperty(
			inference_engine_layer_property &property)
	{
		LOGI("ENTER");

		for (auto& layer : property.layers)
			LOGI("input layer name = %s", layer.first.c_str());

		mOutputLayers.clear();
		mOutputLayers = property.layers;

		LOGI("LEAVE");

		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::GetBackendCapacity(inference_engine_capacity *capacity)
	{
		LOGI("ENTER");

		if (capacity == NULL) {
			LOGE("Bad pointer.");
			return INFERENCE_ENGINE_ERROR_INVALID_PARAMETER;
		}

		capacity->supported_accel_devices = INFERENCE_TARGET_CPU |
											INFERENCE_TARGET_GPU;

		LOGI("LEAVE");

		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::Run(
			std::map<std::string, inference_engine_tensor_buffer> &input_buffers,
			std::map<std::string, inference_engine_tensor_buffer> &output_buffers)
	{
		LOGI("ENTER");
		TfLiteStatus status = mInterpreter->Invoke();

		if (status != kTfLiteOk) {
			LOGE("Fail to invoke with kTfLiteError");
			return INFERENCE_ENGINE_ERROR_INVALID_OPERATION;
		}

		LOGI("LEAVE");
		return INFERENCE_ENGINE_ERROR_NONE;
	}

	int InferenceTFLite::SetInterpreterInfo()
	{
		int ret = INFERENCE_ENGINE_ERROR_NONE;
		LOGI("ENTER");

		if (mInputLayers.empty()) {
			LOGI("mInputLayer is empty. layers and tensors that mInterpreter has will be returned.");

			ret = FillLayer(mInputLayers, mInputLayerId);
			if (ret != INFERENCE_ENGINE_ERROR_NONE)
				return ret;
		}

		if (mOutputLayers.empty()) {
			LOGI("mOutputLayers is empty. layers and tensors that mInterpreter has will be returned.");
			ret = FillLayer(mOutputLayers, mOutputLayerId);
			if (ret != INFERENCE_ENGINE_ERROR_NONE)
				return ret;
		}
		LOGI("LEAVE");
		return INFERENCE_ENGINE_ERROR_NONE;
	}

	void InferenceTFLite::FillLayerId(std::map<std::string, int>& layerId,
			std::map<std::string, inference_engine_tensor_info>& layers,
			const std::vector<int>& buffer)
	{
		layerId.clear();

		if (!buffer.empty()) {
			for (auto& idx : buffer)
				layerId.insert(std::make_pair(mInterpreter->tensor(idx)->name, idx));
			return;
		}

		for (auto& layer: layers) {
			LOGI("Layer list [%s]", layer.first.c_str());
			for (unsigned int idx = 0; idx < mInterpreter->tensors_size(); ++idx) {
				if (mInterpreter->tensor(idx)->name == NULL)
					continue;
				if ((layer.first).compare(mInterpreter->tensor(idx)->name) == 0) {
					layerId.insert(std::make_pair(layer.first, idx));
					break;
				}
			}
		}
	}

	int InferenceTFLite::FillLayer(std::map<std::string, inference_engine_tensor_info>& layers,
			std::map<std::string, int>& layerId)
	{
		layers.clear();
		for (auto& layer : layerId) {

			std::vector<size_t> shape_nhwc;

			for (int idx = 0; idx < mInterpreter->tensor(layer.second)->dims->size; idx++)
				shape_nhwc.push_back(mInterpreter->tensor(layer.second)->dims->data[idx]);

			inference_engine_tensor_info tensor_info {
				shape_nhwc, INFERENCE_TENSOR_SHAPE_NHWC,
				INFERENCE_TENSOR_DATA_TYPE_NONE, 1
			};

			switch (mInterpreter->tensor(layer.second)->type) {
			case kTfLiteUInt8:
				LOGI("type is kTfLiteUInt8");
				tensor_info.data_type = INFERENCE_TENSOR_DATA_TYPE_UINT8;
				break;
			case kTfLiteFloat32:
				LOGI("type is kTfLiteFloat32");
				tensor_info.data_type = INFERENCE_TENSOR_DATA_TYPE_FLOAT32;
				break;
			default:
				LOGE("Not supported");
				return INFERENCE_ENGINE_ERROR_NOT_SUPPORTED_FORMAT;
			}

			for (auto& dim : tensor_info.shape)
				tensor_info.size *= dim;

			layers.insert(std::make_pair(mInterpreter->tensor(layer.second)->name, tensor_info));

		}
		return INFERENCE_ENGINE_ERROR_NONE;
	}

	extern "C"
	{
		class IInferenceEngineCommon *EngineCommonInit(void)
		{
			InferenceTFLite *engine = new InferenceTFLite();
			return engine;
		}

		void EngineCommonDestroy(class IInferenceEngineCommon *engine)
		{
			delete engine;
		}
	}
} /* TFLiteImpl */
} /* InferenceEngineImpl */