blob: f5f5cc380920e3e25211dc7465874b0c8634d93c [file] [log] [blame]
Ryan OShea57480cd2022-06-10 14:49:11 +01001//
2// Copyright © 2022 Arm Ltd and Contributors. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
6#pragma once
7
8#include "TestUtils.hpp"
9
10#include <armnn_delegate.hpp>
11
12#include <flatbuffers/flatbuffers.h>
13#include <flatbuffers/flexbuffers.h>
14#include <tensorflow/lite/interpreter.h>
15#include <tensorflow/lite/kernels/custom_ops_register.h>
16#include <tensorflow/lite/kernels/register.h>
17#include <tensorflow/lite/model.h>
18#include <tensorflow/lite/schema/schema_generated.h>
19#include <tensorflow/lite/version.h>
20
21#include <doctest/doctest.h>
22
23namespace
24{
25#if defined(ARMNN_POST_TFLITE_2_5)
26
27std::vector<uint8_t> CreateCustomOptions(int, int, int, int, int, int, TfLitePadding);
28
29std::vector<char> CreatePooling3dTfLiteModel(
30 std::string poolType,
31 tflite::TensorType tensorType,
32 const std::vector<int32_t>& inputTensorShape,
33 const std::vector<int32_t>& outputTensorShape,
34 TfLitePadding padding = kTfLitePaddingSame,
35 int32_t strideWidth = 0,
36 int32_t strideHeight = 0,
37 int32_t strideDepth = 0,
38 int32_t filterWidth = 0,
39 int32_t filterHeight = 0,
40 int32_t filterDepth = 0,
41 tflite::ActivationFunctionType fusedActivation = tflite::ActivationFunctionType_NONE,
42 float quantScale = 1.0f,
43 int quantOffset = 0)
44{
45 using namespace tflite;
46 flatbuffers::FlatBufferBuilder flatBufferBuilder;
47
48 std::vector<flatbuffers::Offset<tflite::Buffer>> buffers;
49 buffers.push_back(CreateBuffer(flatBufferBuilder, flatBufferBuilder.CreateVector({})));
50
51 auto quantizationParameters =
52 CreateQuantizationParameters(flatBufferBuilder,
53 0,
54 0,
55 flatBufferBuilder.CreateVector<float>({ quantScale }),
56 flatBufferBuilder.CreateVector<int64_t>({ quantOffset }));
57
58 // Create the input and output tensors
59 std::array<flatbuffers::Offset<Tensor>, 2> tensors;
60 tensors[0] = CreateTensor(flatBufferBuilder,
61 flatBufferBuilder.CreateVector<int32_t>(inputTensorShape.data(),
62 inputTensorShape.size()),
63 tensorType,
64 0,
65 flatBufferBuilder.CreateString("input"),
66 quantizationParameters);
67
68 tensors[1] = CreateTensor(flatBufferBuilder,
69 flatBufferBuilder.CreateVector<int32_t>(outputTensorShape.data(),
70 outputTensorShape.size()),
71 tensorType,
72 0,
73 flatBufferBuilder.CreateString("output"),
74 quantizationParameters);
75
76 // Create the custom options from the function below
77 std::vector<uint8_t> customOperatorOptions = CreateCustomOptions(strideHeight, strideWidth, strideDepth,
78 filterHeight, filterWidth, filterDepth, padding);
79 // opCodeIndex is created as a uint8_t to avoid map lookup
80 uint8_t opCodeIndex = 0;
81 // Set the operator name based on the PoolType passed in from the test case
82 std::string opName = "";
83 if (poolType == "kMax")
84 {
85 opName = "MaxPool3D";
86 }
87 else
88 {
89 opName = "AveragePool3D";
90 }
91 // To create a custom operator code you pass in the builtin code for custom operators and the name of the custom op
92 flatbuffers::Offset<OperatorCode> operatorCode = CreateOperatorCodeDirect(flatBufferBuilder,
93 tflite::BuiltinOperator_CUSTOM,
94 opName.c_str());
95
96 // Create the Operator using the opCodeIndex and custom options. Also sets builtin options to none.
97 const std::vector<int32_t> operatorInputs{ 0 };
98 const std::vector<int32_t> operatorOutputs{ 1 };
99 flatbuffers::Offset<Operator> poolingOperator =
100 CreateOperator(flatBufferBuilder,
101 opCodeIndex,
102 flatBufferBuilder.CreateVector<int32_t>(operatorInputs.data(), operatorInputs.size()),
103 flatBufferBuilder.CreateVector<int32_t>(operatorOutputs.data(), operatorOutputs.size()),
104 tflite::BuiltinOptions_NONE,
105 0,
106 flatBufferBuilder.CreateVector<uint8_t>(customOperatorOptions),
107 tflite::CustomOptionsFormat_FLEXBUFFERS);
108
109 // Create the subgraph using the operator created above.
110 const std::vector<int> subgraphInputs{ 0 };
111 const std::vector<int> subgraphOutputs{ 1 };
112 flatbuffers::Offset<SubGraph> subgraph =
113 CreateSubGraph(flatBufferBuilder,
114 flatBufferBuilder.CreateVector(tensors.data(), tensors.size()),
115 flatBufferBuilder.CreateVector<int32_t>(subgraphInputs.data(), subgraphInputs.size()),
116 flatBufferBuilder.CreateVector<int32_t>(subgraphOutputs.data(), subgraphOutputs.size()),
117 flatBufferBuilder.CreateVector(&poolingOperator, 1));
118
119 flatbuffers::Offset<flatbuffers::String> modelDescription =
120 flatBufferBuilder.CreateString("ArmnnDelegate: Pooling3d Operator Model");
121
122 // Create the model using operatorCode and the subgraph.
123 flatbuffers::Offset<Model> flatbufferModel =
124 CreateModel(flatBufferBuilder,
125 TFLITE_SCHEMA_VERSION,
126 flatBufferBuilder.CreateVector(&operatorCode, 1),
127 flatBufferBuilder.CreateVector(&subgraph, 1),
128 modelDescription,
129 flatBufferBuilder.CreateVector(buffers.data(), buffers.size()));
130
131 flatBufferBuilder.Finish(flatbufferModel);
132
133 return std::vector<char>(flatBufferBuilder.GetBufferPointer(),
134 flatBufferBuilder.GetBufferPointer() + flatBufferBuilder.GetSize());
135}
136
137template<typename T>
138void Pooling3dTest(std::string poolType,
139 tflite::TensorType tensorType,
140 std::vector<armnn::BackendId>& backends,
141 std::vector<int32_t>& inputShape,
142 std::vector<int32_t>& outputShape,
143 std::vector<T>& inputValues,
144 std::vector<T>& expectedOutputValues,
145 TfLitePadding padding = kTfLitePaddingSame,
146 int32_t strideWidth = 0,
147 int32_t strideHeight = 0,
148 int32_t strideDepth = 0,
149 int32_t filterWidth = 0,
150 int32_t filterHeight = 0,
151 int32_t filterDepth = 0,
152 tflite::ActivationFunctionType fusedActivation = tflite::ActivationFunctionType_NONE,
153 float quantScale = 1.0f,
154 int quantOffset = 0)
155{
156 using namespace tflite;
157 // Create the single op model buffer
158 std::vector<char> modelBuffer = CreatePooling3dTfLiteModel(poolType,
159 tensorType,
160 inputShape,
161 outputShape,
162 padding,
163 strideWidth,
164 strideHeight,
165 strideDepth,
166 filterWidth,
167 filterHeight,
168 filterDepth,
169 fusedActivation,
170 quantScale,
171 quantOffset);
172
173 const Model* tfLiteModel = GetModel(modelBuffer.data());
174 CHECK(tfLiteModel != nullptr);
175 // Create TfLite Interpreters
176 std::unique_ptr<Interpreter> armnnDelegateInterpreter;
177
178 // Custom ops need to be added to the BuiltinOp resolver before the interpreter is created
179 // Based on the poolType from the test case add the custom operator using the name and the tflite
180 // registration function
181 tflite::ops::builtin::BuiltinOpResolver armnn_op_resolver;
182 if (poolType == "kMax")
183 {
184 armnn_op_resolver.AddCustom("MaxPool3D", tflite::ops::custom::Register_MAX_POOL_3D());
185 }
186 else
187 {
188 armnn_op_resolver.AddCustom("AveragePool3D", tflite::ops::custom::Register_AVG_POOL_3D());
189 }
190
191 CHECK(InterpreterBuilder(tfLiteModel, armnn_op_resolver)
192 (&armnnDelegateInterpreter) == kTfLiteOk);
193 CHECK(armnnDelegateInterpreter != nullptr);
194 CHECK(armnnDelegateInterpreter->AllocateTensors() == kTfLiteOk);
195
196 std::unique_ptr<Interpreter> tfLiteInterpreter;
197
198 // Custom ops need to be added to the BuiltinOp resolver before the interpreter is created
199 // Based on the poolType from the test case add the custom operator using the name and the tflite
200 // registration function
201 tflite::ops::builtin::BuiltinOpResolver tflite_op_resolver;
202 if (poolType == "kMax")
203 {
204 tflite_op_resolver.AddCustom("MaxPool3D", tflite::ops::custom::Register_MAX_POOL_3D());
205 }
206 else
207 {
208 tflite_op_resolver.AddCustom("AveragePool3D", tflite::ops::custom::Register_AVG_POOL_3D());
209 }
210
211 CHECK(InterpreterBuilder(tfLiteModel, tflite_op_resolver)
212 (&tfLiteInterpreter) == kTfLiteOk);
213 CHECK(tfLiteInterpreter != nullptr);
214 CHECK(tfLiteInterpreter->AllocateTensors() == kTfLiteOk);
215
216 // Create the ArmNN Delegate
217 armnnDelegate::DelegateOptions delegateOptions(backends);
218 std::unique_ptr<TfLiteDelegate, decltype(&armnnDelegate::TfLiteArmnnDelegateDelete)>
219 theArmnnDelegate(armnnDelegate::TfLiteArmnnDelegateCreate(delegateOptions),
220 armnnDelegate::TfLiteArmnnDelegateDelete);
221 CHECK(theArmnnDelegate != nullptr);
222
223 // Modify armnnDelegateInterpreter to use armnnDelegate
224 CHECK(armnnDelegateInterpreter->ModifyGraphWithDelegate(theArmnnDelegate.get()) == kTfLiteOk);
225
226 // Set input data
227 auto tfLiteDelegateInputId = tfLiteInterpreter->inputs()[0];
228 auto tfLiteDelegateInputData = tfLiteInterpreter->typed_tensor<T>(tfLiteDelegateInputId);
229 for (unsigned int i = 0; i < inputValues.size(); ++i)
230 {
231 tfLiteDelegateInputData[i] = inputValues[i];
232 }
233
234 auto armnnDelegateInputId = armnnDelegateInterpreter->inputs()[0];
235 auto armnnDelegateInputData = armnnDelegateInterpreter->typed_tensor<T>(armnnDelegateInputId);
236 for (unsigned int i = 0; i < inputValues.size(); ++i)
237 {
238 armnnDelegateInputData[i] = inputValues[i];
239 }
240
241 // Run EnqueueWorkload
242 CHECK(tfLiteInterpreter->Invoke() == kTfLiteOk);
243 CHECK(armnnDelegateInterpreter->Invoke() == kTfLiteOk);
244
245 armnnDelegate::CompareOutputData(tfLiteInterpreter, armnnDelegateInterpreter, outputShape, expectedOutputValues);
246}
247
248// Function to create the flexbuffer custom options for the custom pooling3d operator.
249std::vector<uint8_t> CreateCustomOptions(int strideHeight, int strideWidth, int strideDepth,
250 int filterHeight, int filterWidth, int filterDepth, TfLitePadding padding)
251{
252 auto flex_builder = std::make_unique<flexbuffers::Builder>();
253 size_t map_start = flex_builder->StartMap();
254 flex_builder->String("data_format", "NDHWC");
255 // Padding is created as a key and padding type. Only VALID and SAME supported
256 if (padding == kTfLitePaddingValid)
257 {
258 flex_builder->String("padding", "VALID");
259 }
260 else
261 {
262 flex_builder->String("padding", "SAME");
263 }
264
265 // Vector of filter dimensions in order ( 1, Depth, Height, Width, 1 )
266 auto start = flex_builder->StartVector("ksize");
267 flex_builder->Add(1);
268 flex_builder->Add(filterDepth);
269 flex_builder->Add(filterHeight);
270 flex_builder->Add(filterWidth);
271 flex_builder->Add(1);
272 // EndVector( start, bool typed, bool fixed)
273 flex_builder->EndVector(start, true, false);
274
275 // Vector of stride dimensions in order ( 1, Depth, Height, Width, 1 )
276 auto stridesStart = flex_builder->StartVector("strides");
277 flex_builder->Add(1);
278 flex_builder->Add(strideDepth);
279 flex_builder->Add(strideHeight);
280 flex_builder->Add(strideWidth);
281 flex_builder->Add(1);
282 // EndVector( stridesStart, bool typed, bool fixed)
283 flex_builder->EndVector(stridesStart, true, false);
284
285 flex_builder->EndMap(map_start);
286 flex_builder->Finish();
287
288 return flex_builder->GetBuffer();
289}
290#endif
291} // anonymous namespace
292
293
294
295