1 //
2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5
6 #pragma once
7
8 #include "Schema.hpp"
9
10 #include <armnn/Descriptors.hpp>
11 #include <armnn/IRuntime.hpp>
12 #include <armnn/TypesUtils.hpp>
13 #include <armnn/BackendRegistry.hpp>
14 #include <armnn/utility/Assert.hpp>
15
16 #include <armnnTfLiteParser/ITfLiteParser.hpp>
17
18 #include <ResolveType.hpp>
19
20 #include <test/TensorHelpers.hpp>
21
22 #include <fmt/format.h>
23
24 #include "flatbuffers/idl.h"
25 #include "flatbuffers/util.h"
26 #include "flatbuffers/flexbuffers.h"
27
28 #include <schema_generated.h>
29
30 #include <iostream>
31
32 using armnnTfLiteParser::ITfLiteParser;
33 using armnnTfLiteParser::ITfLiteParserPtr;
34
35 using TensorRawPtr = const tflite::TensorT *;
36 struct ParserFlatbuffersFixture
37 {
ParserFlatbuffersFixtureParserFlatbuffersFixture38 ParserFlatbuffersFixture() :
39 m_Parser(nullptr, &ITfLiteParser::Destroy),
40 m_Runtime(armnn::IRuntime::Create(armnn::IRuntime::CreationOptions())),
41 m_NetworkIdentifier(-1)
42 {
43 ITfLiteParser::TfLiteParserOptions options;
44 options.m_StandInLayerForUnsupported = true;
45 options.m_InferAndValidate = true;
46
47 m_Parser.reset(ITfLiteParser::CreateRaw(armnn::Optional<ITfLiteParser::TfLiteParserOptions>(options)));
48 }
49
50 std::vector<uint8_t> m_GraphBinary;
51 std::string m_JsonString;
52 ITfLiteParserPtr m_Parser;
53 armnn::IRuntimePtr m_Runtime;
54 armnn::NetworkId m_NetworkIdentifier;
55
56 /// If the single-input-single-output overload of Setup() is called, these will store the input and output name
57 /// so they don't need to be passed to the single-input-single-output overload of RunTest().
58 std::string m_SingleInputName;
59 std::string m_SingleOutputName;
60
SetupParserFlatbuffersFixture61 void Setup()
62 {
63 bool ok = ReadStringToBinary();
64 if (!ok) {
65 throw armnn::Exception("LoadNetwork failed while reading binary input");
66 }
67
68 armnn::INetworkPtr network =
69 m_Parser->CreateNetworkFromBinary(m_GraphBinary);
70
71 if (!network) {
72 throw armnn::Exception("The parser failed to create an ArmNN network");
73 }
74
75 auto optimized = Optimize(*network, { armnn::Compute::CpuRef },
76 m_Runtime->GetDeviceSpec());
77 std::string errorMessage;
78
79 armnn::Status ret = m_Runtime->LoadNetwork(m_NetworkIdentifier, move(optimized), errorMessage);
80
81 if (ret != armnn::Status::Success)
82 {
83 throw armnn::Exception(
84 fmt::format("The runtime failed to load the network. "
85 "Error was: {}. in {} [{}:{}]",
86 errorMessage,
87 __func__,
88 __FILE__,
89 __LINE__));
90 }
91 }
92
SetupSingleInputSingleOutputParserFlatbuffersFixture93 void SetupSingleInputSingleOutput(const std::string& inputName, const std::string& outputName)
94 {
95 // Store the input and output name so they don't need to be passed to the single-input-single-output RunTest().
96 m_SingleInputName = inputName;
97 m_SingleOutputName = outputName;
98 Setup();
99 }
100
ReadStringToBinaryParserFlatbuffersFixture101 bool ReadStringToBinary()
102 {
103 std::string schemafile(g_TfLiteSchemaText, g_TfLiteSchemaText + g_TfLiteSchemaText_len);
104
105 // parse schema first, so we can use it to parse the data after
106 flatbuffers::Parser parser;
107
108 bool ok = parser.Parse(schemafile.c_str());
109 ARMNN_ASSERT_MSG(ok, "Failed to parse schema file");
110
111 ok &= parser.Parse(m_JsonString.c_str());
112 ARMNN_ASSERT_MSG(ok, "Failed to parse json input");
113
114 if (!ok)
115 {
116 return false;
117 }
118
119 {
120 const uint8_t * bufferPtr = parser.builder_.GetBufferPointer();
121 size_t size = static_cast<size_t>(parser.builder_.GetSize());
122 m_GraphBinary.assign(bufferPtr, bufferPtr+size);
123 }
124 return ok;
125 }
126
127 /// Executes the network with the given input tensor and checks the result against the given output tensor.
128 /// This assumes the network has a single input and a single output.
129 template <std::size_t NumOutputDimensions,
130 armnn::DataType ArmnnType>
131 void RunTest(size_t subgraphId,
132 const std::vector<armnn::ResolveType<ArmnnType>>& inputData,
133 const std::vector<armnn::ResolveType<ArmnnType>>& expectedOutputData);
134
135 /// Executes the network with the given input tensors and checks the results against the given output tensors.
136 /// This overload supports multiple inputs and multiple outputs, identified by name.
137 template <std::size_t NumOutputDimensions,
138 armnn::DataType ArmnnType>
139 void RunTest(size_t subgraphId,
140 const std::map<std::string, std::vector<armnn::ResolveType<ArmnnType>>>& inputData,
141 const std::map<std::string, std::vector<armnn::ResolveType<ArmnnType>>>& expectedOutputData);
142
143 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
144 /// Executes the network with the given input tensors and checks the results against the given output tensors.
145 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
146 /// the input datatype to be different to the output
147 template <std::size_t NumOutputDimensions,
148 armnn::DataType ArmnnType1,
149 armnn::DataType ArmnnType2>
150 void RunTest(size_t subgraphId,
151 const std::map<std::string, std::vector<armnn::ResolveType<ArmnnType1>>>& inputData,
152 const std::map<std::string, std::vector<armnn::ResolveType<ArmnnType2>>>& expectedOutputData,
153 bool isDynamic = false);
154
155
156 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
157 /// Executes the network with the given input tensors and checks the results against the given output tensors.
158 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
159 /// the input datatype to be different to the output
160 template<armnn::DataType ArmnnType1,
161 armnn::DataType ArmnnType2>
162 void RunTest(std::size_t subgraphId,
163 const std::map<std::string, std::vector<armnn::ResolveType<ArmnnType1>>>& inputData,
164 const std::map<std::string, std::vector<armnn::ResolveType<ArmnnType2>>>& expectedOutputData);
165
GenerateDetectionPostProcessJsonStringParserFlatbuffersFixture166 static inline std::string GenerateDetectionPostProcessJsonString(
167 const armnn::DetectionPostProcessDescriptor& descriptor)
168 {
169 flexbuffers::Builder detectPostProcess;
170 detectPostProcess.Map([&]() {
171 detectPostProcess.Bool("use_regular_nms", descriptor.m_UseRegularNms);
172 detectPostProcess.Int("max_detections", descriptor.m_MaxDetections);
173 detectPostProcess.Int("max_classes_per_detection", descriptor.m_MaxClassesPerDetection);
174 detectPostProcess.Int("detections_per_class", descriptor.m_DetectionsPerClass);
175 detectPostProcess.Int("num_classes", descriptor.m_NumClasses);
176 detectPostProcess.Float("nms_score_threshold", descriptor.m_NmsScoreThreshold);
177 detectPostProcess.Float("nms_iou_threshold", descriptor.m_NmsIouThreshold);
178 detectPostProcess.Float("h_scale", descriptor.m_ScaleH);
179 detectPostProcess.Float("w_scale", descriptor.m_ScaleW);
180 detectPostProcess.Float("x_scale", descriptor.m_ScaleX);
181 detectPostProcess.Float("y_scale", descriptor.m_ScaleY);
182 });
183 detectPostProcess.Finish();
184
185 // Create JSON string
186 std::stringstream strStream;
187 std::vector<uint8_t> buffer = detectPostProcess.GetBuffer();
188 std::copy(buffer.begin(), buffer.end(),std::ostream_iterator<int>(strStream,","));
189
190 return strStream.str();
191 }
192
CheckTensorsParserFlatbuffersFixture193 void CheckTensors(const TensorRawPtr& tensors, size_t shapeSize, const std::vector<int32_t>& shape,
194 tflite::TensorType tensorType, uint32_t buffer, const std::string& name,
195 const std::vector<float>& min, const std::vector<float>& max,
196 const std::vector<float>& scale, const std::vector<int64_t>& zeroPoint)
197 {
198 BOOST_CHECK(tensors);
199 BOOST_CHECK_EQUAL(shapeSize, tensors->shape.size());
200 BOOST_CHECK_EQUAL_COLLECTIONS(shape.begin(), shape.end(), tensors->shape.begin(), tensors->shape.end());
201 BOOST_CHECK_EQUAL(tensorType, tensors->type);
202 BOOST_CHECK_EQUAL(buffer, tensors->buffer);
203 BOOST_CHECK_EQUAL(name, tensors->name);
204 BOOST_CHECK(tensors->quantization);
205 BOOST_CHECK_EQUAL_COLLECTIONS(min.begin(), min.end(), tensors->quantization.get()->min.begin(),
206 tensors->quantization.get()->min.end());
207 BOOST_CHECK_EQUAL_COLLECTIONS(max.begin(), max.end(), tensors->quantization.get()->max.begin(),
208 tensors->quantization.get()->max.end());
209 BOOST_CHECK_EQUAL_COLLECTIONS(scale.begin(), scale.end(), tensors->quantization.get()->scale.begin(),
210 tensors->quantization.get()->scale.end());
211 BOOST_CHECK_EQUAL_COLLECTIONS(zeroPoint.begin(), zeroPoint.end(),
212 tensors->quantization.get()->zero_point.begin(),
213 tensors->quantization.get()->zero_point.end());
214 }
215 };
216
217 /// Single Input, Single Output
218 /// Executes the network with the given input tensor and checks the result against the given output tensor.
219 /// This overload assumes the network has a single input and a single output.
220 template <std::size_t NumOutputDimensions,
221 armnn::DataType armnnType>
RunTest(size_t subgraphId,const std::vector<armnn::ResolveType<armnnType>> & inputData,const std::vector<armnn::ResolveType<armnnType>> & expectedOutputData)222 void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
223 const std::vector<armnn::ResolveType<armnnType>>& inputData,
224 const std::vector<armnn::ResolveType<armnnType>>& expectedOutputData)
225 {
226 RunTest<NumOutputDimensions, armnnType>(subgraphId,
227 { { m_SingleInputName, inputData } },
228 { { m_SingleOutputName, expectedOutputData } });
229 }
230
231 /// Multiple Inputs, Multiple Outputs
232 /// Executes the network with the given input tensors and checks the results against the given output tensors.
233 /// This overload supports multiple inputs and multiple outputs, identified by name.
234 template <std::size_t NumOutputDimensions,
235 armnn::DataType armnnType>
RunTest(size_t subgraphId,const std::map<std::string,std::vector<armnn::ResolveType<armnnType>>> & inputData,const std::map<std::string,std::vector<armnn::ResolveType<armnnType>>> & expectedOutputData)236 void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
237 const std::map<std::string, std::vector<armnn::ResolveType<armnnType>>>& inputData,
238 const std::map<std::string, std::vector<armnn::ResolveType<armnnType>>>& expectedOutputData)
239 {
240 RunTest<NumOutputDimensions, armnnType, armnnType>(subgraphId, inputData, expectedOutputData);
241 }
242
243 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes
244 /// Executes the network with the given input tensors and checks the results against the given output tensors.
245 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
246 /// the input datatype to be different to the output
247 template <std::size_t NumOutputDimensions,
248 armnn::DataType armnnType1,
249 armnn::DataType armnnType2>
RunTest(size_t subgraphId,const std::map<std::string,std::vector<armnn::ResolveType<armnnType1>>> & inputData,const std::map<std::string,std::vector<armnn::ResolveType<armnnType2>>> & expectedOutputData,bool isDynamic)250 void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
251 const std::map<std::string, std::vector<armnn::ResolveType<armnnType1>>>& inputData,
252 const std::map<std::string, std::vector<armnn::ResolveType<armnnType2>>>& expectedOutputData,
253 bool isDynamic)
254 {
255 using DataType2 = armnn::ResolveType<armnnType2>;
256
257 // Setup the armnn input tensors from the given vectors.
258 armnn::InputTensors inputTensors;
259 for (auto&& it : inputData)
260 {
261 armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
262 armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType1);
263 inputTensors.push_back({ bindingInfo.first, armnn::ConstTensor(bindingInfo.second, it.second.data()) });
264 }
265
266 // Allocate storage for the output tensors to be written to and setup the armnn output tensors.
267 std::map<std::string, boost::multi_array<DataType2, NumOutputDimensions>> outputStorage;
268 armnn::OutputTensors outputTensors;
269 for (auto&& it : expectedOutputData)
270 {
271 armnn::LayerBindingId outputBindingId = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first).first;
272 armnn::TensorInfo outputTensorInfo = m_Runtime->GetOutputTensorInfo(m_NetworkIdentifier, outputBindingId);
273
274 // Check that output tensors have correct number of dimensions (NumOutputDimensions specified in test)
275 auto outputNumDimensions = outputTensorInfo.GetNumDimensions();
276 BOOST_CHECK_MESSAGE((outputNumDimensions == NumOutputDimensions),
277 fmt::format("Number of dimensions expected {}, but got {} for output layer {}",
278 NumOutputDimensions,
279 outputNumDimensions,
280 it.first));
281
282 armnn::VerifyTensorInfoDataType(outputTensorInfo, armnnType2);
283 outputStorage.emplace(it.first, MakeTensor<DataType2, NumOutputDimensions>(outputTensorInfo));
284 outputTensors.push_back(
285 { outputBindingId, armnn::Tensor(outputTensorInfo, outputStorage.at(it.first).data()) });
286 }
287
288 m_Runtime->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
289
290 // Compare each output tensor to the expected values
291 for (auto&& it : expectedOutputData)
292 {
293 armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
294 auto outputExpected = MakeTensor<DataType2, NumOutputDimensions>(bindingInfo.second, it.second, isDynamic);
295 BOOST_TEST(CompareTensors(outputExpected, outputStorage[it.first], false, isDynamic));
296 }
297 }
298
299 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
300 /// Executes the network with the given input tensors and checks the results against the given output tensors.
301 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
302 /// the input datatype to be different to the output.
303 template <armnn::DataType armnnType1,
304 armnn::DataType armnnType2>
RunTest(std::size_t subgraphId,const std::map<std::string,std::vector<armnn::ResolveType<armnnType1>>> & inputData,const std::map<std::string,std::vector<armnn::ResolveType<armnnType2>>> & expectedOutputData)305 void ParserFlatbuffersFixture::RunTest(std::size_t subgraphId,
306 const std::map<std::string, std::vector<armnn::ResolveType<armnnType1>>>& inputData,
307 const std::map<std::string, std::vector<armnn::ResolveType<armnnType2>>>& expectedOutputData)
308 {
309 using DataType2 = armnn::ResolveType<armnnType2>;
310
311 // Setup the armnn input tensors from the given vectors.
312 armnn::InputTensors inputTensors;
313 for (auto&& it : inputData)
314 {
315 armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
316 armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType1);
317
318 inputTensors.push_back({ bindingInfo.first, armnn::ConstTensor(bindingInfo.second, it.second.data()) });
319 }
320
321 armnn::OutputTensors outputTensors;
322 outputTensors.reserve(expectedOutputData.size());
323 std::map<std::string, std::vector<DataType2>> outputStorage;
324 for (auto&& it : expectedOutputData)
325 {
326 armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
327 armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType2);
328
329 std::vector<DataType2> out(it.second.size());
330 outputStorage.emplace(it.first, out);
331 outputTensors.push_back({ bindingInfo.first,
332 armnn::Tensor(bindingInfo.second,
333 outputStorage.at(it.first).data()) });
334 }
335
336 m_Runtime->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
337
338 // Checks the results.
339 for (auto&& it : expectedOutputData)
340 {
341 std::vector<armnn::ResolveType<armnnType2>> out = outputStorage.at(it.first);
342 {
343 for (unsigned int i = 0; i < out.size(); ++i)
344 {
345 BOOST_TEST(it.second[i] == out[i], boost::test_tools::tolerance(0.000001f));
346 }
347 }
348 }
349 }
350