blob: 9b443c383df2e89948d36397eece7ac211dfac8c [file] [log] [blame]
telsoa01c577f2c2018-08-31 09:22:23 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa01c577f2c2018-08-31 09:22:23 +01004//
5
6#pragma once
7
keidav01222c7532019-03-14 17:12:10 +00008#include <armnn/Descriptors.hpp>
9#include <armnn/IRuntime.hpp>
10#include <armnn/TypesUtils.hpp>
11
Matthew Bentham6c8e8e72019-01-15 17:57:00 +000012#include "Schema.hpp"
telsoa01c577f2c2018-08-31 09:22:23 +010013#include <boost/filesystem.hpp>
14#include <boost/assert.hpp>
15#include <boost/format.hpp>
16#include <experimental/filesystem>
keidav01222c7532019-03-14 17:12:10 +000017
telsoa01c577f2c2018-08-31 09:22:23 +010018#include "test/TensorHelpers.hpp"
19
Aron Virginas-Tard4f0fea2019-04-09 14:08:06 +010020#include <ResolveType.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010021#include "armnnTfLiteParser/ITfLiteParser.hpp"
22
Aron Virginas-Tarc9cc8042018-11-01 16:15:57 +000023#include <backendsCommon/BackendRegistry.hpp>
Aron Virginas-Tar54e95722018-10-25 11:47:31 +010024
telsoa01c577f2c2018-08-31 09:22:23 +010025#include "flatbuffers/idl.h"
26#include "flatbuffers/util.h"
keidav01222c7532019-03-14 17:12:10 +000027#include "flatbuffers/flexbuffers.h"
telsoa01c577f2c2018-08-31 09:22:23 +010028
29#include <schema_generated.h>
30#include <iostream>
31
32using armnnTfLiteParser::ITfLiteParser;
33using TensorRawPtr = const tflite::TensorT *;
34
35struct ParserFlatbuffersFixture
36{
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +000037 ParserFlatbuffersFixture() :
38 m_Parser(ITfLiteParser::Create()),
39 m_Runtime(armnn::IRuntime::Create(armnn::IRuntime::CreationOptions())),
40 m_NetworkIdentifier(-1)
telsoa01c577f2c2018-08-31 09:22:23 +010041 {
telsoa01c577f2c2018-08-31 09:22:23 +010042 }
43
44 std::vector<uint8_t> m_GraphBinary;
45 std::string m_JsonString;
46 std::unique_ptr<ITfLiteParser, void (*)(ITfLiteParser *parser)> m_Parser;
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +000047 armnn::IRuntimePtr m_Runtime;
telsoa01c577f2c2018-08-31 09:22:23 +010048 armnn::NetworkId m_NetworkIdentifier;
49
50 /// If the single-input-single-output overload of Setup() is called, these will store the input and output name
51 /// so they don't need to be passed to the single-input-single-output overload of RunTest().
52 std::string m_SingleInputName;
53 std::string m_SingleOutputName;
54
55 void Setup()
56 {
57 bool ok = ReadStringToBinary();
58 if (!ok) {
59 throw armnn::Exception("LoadNetwork failed while reading binary input");
60 }
61
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +000062 armnn::INetworkPtr network =
63 m_Parser->CreateNetworkFromBinary(m_GraphBinary);
64
65 if (!network) {
66 throw armnn::Exception("The parser failed to create an ArmNN network");
67 }
68
69 auto optimized = Optimize(*network, { armnn::Compute::CpuRef },
70 m_Runtime->GetDeviceSpec());
71 std::string errorMessage;
72
73 armnn::Status ret = m_Runtime->LoadNetwork(m_NetworkIdentifier, move(optimized), errorMessage);
74
75 if (ret != armnn::Status::Success)
telsoa01c577f2c2018-08-31 09:22:23 +010076 {
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +000077 throw armnn::Exception(
78 boost::str(
79 boost::format("The runtime failed to load the network. "
80 "Error was: %1%. in %2% [%3%:%4%]") %
81 errorMessage %
82 __func__ %
83 __FILE__ %
84 __LINE__));
telsoa01c577f2c2018-08-31 09:22:23 +010085 }
86 }
87
88 void SetupSingleInputSingleOutput(const std::string& inputName, const std::string& outputName)
89 {
90 // Store the input and output name so they don't need to be passed to the single-input-single-output RunTest().
91 m_SingleInputName = inputName;
92 m_SingleOutputName = outputName;
93 Setup();
94 }
95
96 bool ReadStringToBinary()
97 {
Matthew Bentham6c8e8e72019-01-15 17:57:00 +000098 std::string schemafile(&tflite_schema_start, &tflite_schema_end);
telsoa01c577f2c2018-08-31 09:22:23 +010099
100 // parse schema first, so we can use it to parse the data after
101 flatbuffers::Parser parser;
102
Matthew Bentham6c8e8e72019-01-15 17:57:00 +0000103 bool ok = parser.Parse(schemafile.c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100104 BOOST_ASSERT_MSG(ok, "Failed to parse schema file");
105
106 ok &= parser.Parse(m_JsonString.c_str());
107 BOOST_ASSERT_MSG(ok, "Failed to parse json input");
108
109 if (!ok)
110 {
111 return false;
112 }
113
114 {
115 const uint8_t * bufferPtr = parser.builder_.GetBufferPointer();
116 size_t size = static_cast<size_t>(parser.builder_.GetSize());
117 m_GraphBinary.assign(bufferPtr, bufferPtr+size);
118 }
119 return ok;
120 }
121
122 /// Executes the network with the given input tensor and checks the result against the given output tensor.
keidav011b3e2ea2019-02-21 10:07:37 +0000123 /// This assumes the network has a single input and a single output.
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000124 template <std::size_t NumOutputDimensions,
125 armnn::DataType ArmnnType,
126 typename DataType = armnn::ResolveType<ArmnnType>>
telsoa01c577f2c2018-08-31 09:22:23 +0100127 void RunTest(size_t subgraphId,
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000128 const std::vector<DataType>& inputData,
129 const std::vector<DataType>& expectedOutputData);
telsoa01c577f2c2018-08-31 09:22:23 +0100130
131 /// Executes the network with the given input tensors and checks the results against the given output tensors.
132 /// This overload supports multiple inputs and multiple outputs, identified by name.
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000133 template <std::size_t NumOutputDimensions,
134 armnn::DataType ArmnnType,
135 typename DataType = armnn::ResolveType<ArmnnType>>
telsoa01c577f2c2018-08-31 09:22:23 +0100136 void RunTest(size_t subgraphId,
137 const std::map<std::string, std::vector<DataType>>& inputData,
138 const std::map<std::string, std::vector<DataType>>& expectedOutputData);
139
keidav011b3e2ea2019-02-21 10:07:37 +0000140 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
141 /// Executes the network with the given input tensors and checks the results against the given output tensors.
142 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
143 /// the input datatype to be different to the output
144 template <std::size_t NumOutputDimensions,
145 armnn::DataType ArmnnType1,
146 armnn::DataType ArmnnType2,
147 typename DataType1 = armnn::ResolveType<ArmnnType1>,
148 typename DataType2 = armnn::ResolveType<ArmnnType2>>
149 void RunTest(size_t subgraphId,
150 const std::map<std::string, std::vector<DataType1>>& inputData,
151 const std::map<std::string, std::vector<DataType2>>& expectedOutputData);
152
153
154 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
155 /// Executes the network with the given input tensors and checks the results against the given output tensors.
156 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
157 /// the input datatype to be different to the output
158 template<armnn::DataType ArmnnType1,
159 armnn::DataType ArmnnType2,
160 typename DataType1 = armnn::ResolveType<ArmnnType1>,
161 typename DataType2 = armnn::ResolveType<ArmnnType2>>
162 void RunTest(std::size_t subgraphId,
163 const std::map<std::string, std::vector<DataType1>>& inputData,
164 const std::map<std::string, std::vector<DataType2>>& expectedOutputData);
165
keidav01222c7532019-03-14 17:12:10 +0000166 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
telsoa01c577f2c2018-08-31 09:22:23 +0100193 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
keidav011b3e2ea2019-02-21 10:07:37 +0000217/// 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.
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000220template <std::size_t NumOutputDimensions,
keidav011b3e2ea2019-02-21 10:07:37 +0000221 armnn::DataType armnnType,
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000222 typename DataType>
telsoa01c577f2c2018-08-31 09:22:23 +0100223void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
224 const std::vector<DataType>& inputData,
225 const std::vector<DataType>& expectedOutputData)
226{
keidav011b3e2ea2019-02-21 10:07:37 +0000227 RunTest<NumOutputDimensions, armnnType>(subgraphId,
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000228 { { m_SingleInputName, inputData } },
229 { { m_SingleOutputName, expectedOutputData } });
telsoa01c577f2c2018-08-31 09:22:23 +0100230}
231
keidav011b3e2ea2019-02-21 10:07:37 +0000232/// Multiple Inputs, Multiple Outputs
233/// Executes the network with the given input tensors and checks the results against the given output tensors.
234/// This overload supports multiple inputs and multiple outputs, identified by name.
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000235template <std::size_t NumOutputDimensions,
keidav011b3e2ea2019-02-21 10:07:37 +0000236 armnn::DataType armnnType,
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000237 typename DataType>
238void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
239 const std::map<std::string, std::vector<DataType>>& inputData,
240 const std::map<std::string, std::vector<DataType>>& expectedOutputData)
telsoa01c577f2c2018-08-31 09:22:23 +0100241{
keidav011b3e2ea2019-02-21 10:07:37 +0000242 RunTest<NumOutputDimensions, armnnType, armnnType>(subgraphId, inputData, expectedOutputData);
243}
244
245/// Multiple Inputs, Multiple Outputs w/ Variable Datatypes
246/// Executes the network with the given input tensors and checks the results against the given output tensors.
247/// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
248/// the input datatype to be different to the output
249template <std::size_t NumOutputDimensions,
250 armnn::DataType armnnType1,
251 armnn::DataType armnnType2,
252 typename DataType1,
253 typename DataType2>
254void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
255 const std::map<std::string, std::vector<DataType1>>& inputData,
256 const std::map<std::string, std::vector<DataType2>>& expectedOutputData)
257{
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000258 using BindingPointInfo = std::pair<armnn::LayerBindingId, armnn::TensorInfo>;
259
260 // Setup the armnn input tensors from the given vectors.
261 armnn::InputTensors inputTensors;
262 for (auto&& it : inputData)
telsoa01c577f2c2018-08-31 09:22:23 +0100263 {
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000264 BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
keidav011b3e2ea2019-02-21 10:07:37 +0000265 armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType1);
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000266 inputTensors.push_back({ bindingInfo.first, armnn::ConstTensor(bindingInfo.second, it.second.data()) });
267 }
telsoa01c577f2c2018-08-31 09:22:23 +0100268
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000269 // Allocate storage for the output tensors to be written to and setup the armnn output tensors.
keidav011b3e2ea2019-02-21 10:07:37 +0000270 std::map<std::string, boost::multi_array<DataType2, NumOutputDimensions>> outputStorage;
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000271 armnn::OutputTensors outputTensors;
272 for (auto&& it : expectedOutputData)
273 {
274 BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
keidav011b3e2ea2019-02-21 10:07:37 +0000275 armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType2);
276 outputStorage.emplace(it.first, MakeTensor<DataType2, NumOutputDimensions>(bindingInfo.second));
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000277 outputTensors.push_back(
278 { bindingInfo.first, armnn::Tensor(bindingInfo.second, outputStorage.at(it.first).data()) });
279 }
telsoa01c577f2c2018-08-31 09:22:23 +0100280
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000281 m_Runtime->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
telsoa01c577f2c2018-08-31 09:22:23 +0100282
Nina Drozdd49b70f2019-04-24 15:49:12 +0100283 // Check that output tensors have correct number of dimensions (NumOutputDimensions specified in test)
284 // after running the workload
285 for (auto&& it : expectedOutputData)
286 {
287 armnn::LayerBindingId outputBindingId = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first).first;
288 auto outputNumDimensions = m_Runtime->GetOutputTensorInfo(
289 m_NetworkIdentifier, outputBindingId).GetNumDimensions();
290
291 BOOST_CHECK_MESSAGE((outputNumDimensions == NumOutputDimensions),
292 boost::str(boost::format("Number of dimensions expected %1%, but got %2% for output layer %3%")
293 % NumOutputDimensions
294 % outputNumDimensions
295 % it.first));
296 }
297
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000298 // Compare each output tensor to the expected values
299 for (auto&& it : expectedOutputData)
300 {
301 BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
keidav011b3e2ea2019-02-21 10:07:37 +0000302 auto outputExpected = MakeTensor<DataType2, NumOutputDimensions>(bindingInfo.second, it.second);
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000303 BOOST_TEST(CompareTensors(outputExpected, outputStorage[it.first]));
telsoa01c577f2c2018-08-31 09:22:23 +0100304 }
305}
keidav011b3e2ea2019-02-21 10:07:37 +0000306
307/// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
308/// Executes the network with the given input tensors and checks the results against the given output tensors.
309/// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
310/// the input datatype to be different to the output.
311template <armnn::DataType armnnType1,
312 armnn::DataType armnnType2,
313 typename DataType1,
314 typename DataType2>
315void ParserFlatbuffersFixture::RunTest(std::size_t subgraphId,
316 const std::map<std::string, std::vector<DataType1>>& inputData,
317 const std::map<std::string, std::vector<DataType2>>& expectedOutputData)
318{
319 using BindingPointInfo = std::pair<armnn::LayerBindingId, armnn::TensorInfo>;
320
321 // Setup the armnn input tensors from the given vectors.
322 armnn::InputTensors inputTensors;
323 for (auto&& it : inputData)
324 {
325 BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
326 armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType1);
327
328 inputTensors.push_back({ bindingInfo.first, armnn::ConstTensor(bindingInfo.second, it.second.data()) });
329 }
330
331 armnn::OutputTensors outputTensors;
332 outputTensors.reserve(expectedOutputData.size());
333 std::map<std::string, std::vector<DataType2>> outputStorage;
334 for (auto&& it : expectedOutputData)
335 {
336 BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
337 armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType2);
338
339 std::vector<DataType2> out(it.second.size());
340 outputStorage.emplace(it.first, out);
341 outputTensors.push_back({ bindingInfo.first,
342 armnn::Tensor(bindingInfo.second,
343 outputStorage.at(it.first).data()) });
344 }
345
346 m_Runtime->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
347
348 // Checks the results.
349 for (auto&& it : expectedOutputData)
350 {
351 std::vector<DataType2> out = outputStorage.at(it.first);
352 {
353 for (unsigned int i = 0; i < out.size(); ++i)
354 {
355 BOOST_TEST(it.second[i] == out[i], boost::test_tools::tolerance(0.000001f));
356 }
357 }
358 }
keidav01222c7532019-03-14 17:12:10 +0000359}