blob: b20bea247dc6ac38a93a012be1726d825c19642f [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>
keidav01222c7532019-03-14 17:12:10 +000016
telsoa01c577f2c2018-08-31 09:22:23 +010017#include "test/TensorHelpers.hpp"
18
Aron Virginas-Tard4f0fea2019-04-09 14:08:06 +010019#include <ResolveType.hpp>
telsoa01c577f2c2018-08-31 09:22:23 +010020#include "armnnTfLiteParser/ITfLiteParser.hpp"
21
Aron Virginas-Tarc9cc8042018-11-01 16:15:57 +000022#include <backendsCommon/BackendRegistry.hpp>
Aron Virginas-Tar54e95722018-10-25 11:47:31 +010023
telsoa01c577f2c2018-08-31 09:22:23 +010024#include "flatbuffers/idl.h"
25#include "flatbuffers/util.h"
keidav01222c7532019-03-14 17:12:10 +000026#include "flatbuffers/flexbuffers.h"
telsoa01c577f2c2018-08-31 09:22:23 +010027
28#include <schema_generated.h>
29#include <iostream>
30
31using armnnTfLiteParser::ITfLiteParser;
32using TensorRawPtr = const tflite::TensorT *;
33
34struct ParserFlatbuffersFixture
35{
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +000036 ParserFlatbuffersFixture() :
37 m_Parser(ITfLiteParser::Create()),
38 m_Runtime(armnn::IRuntime::Create(armnn::IRuntime::CreationOptions())),
39 m_NetworkIdentifier(-1)
telsoa01c577f2c2018-08-31 09:22:23 +010040 {
telsoa01c577f2c2018-08-31 09:22:23 +010041 }
42
43 std::vector<uint8_t> m_GraphBinary;
44 std::string m_JsonString;
45 std::unique_ptr<ITfLiteParser, void (*)(ITfLiteParser *parser)> m_Parser;
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +000046 armnn::IRuntimePtr m_Runtime;
telsoa01c577f2c2018-08-31 09:22:23 +010047 armnn::NetworkId m_NetworkIdentifier;
48
49 /// If the single-input-single-output overload of Setup() is called, these will store the input and output name
50 /// so they don't need to be passed to the single-input-single-output overload of RunTest().
51 std::string m_SingleInputName;
52 std::string m_SingleOutputName;
53
54 void Setup()
55 {
56 bool ok = ReadStringToBinary();
57 if (!ok) {
58 throw armnn::Exception("LoadNetwork failed while reading binary input");
59 }
60
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +000061 armnn::INetworkPtr network =
62 m_Parser->CreateNetworkFromBinary(m_GraphBinary);
63
64 if (!network) {
65 throw armnn::Exception("The parser failed to create an ArmNN network");
66 }
67
68 auto optimized = Optimize(*network, { armnn::Compute::CpuRef },
69 m_Runtime->GetDeviceSpec());
70 std::string errorMessage;
71
72 armnn::Status ret = m_Runtime->LoadNetwork(m_NetworkIdentifier, move(optimized), errorMessage);
73
74 if (ret != armnn::Status::Success)
telsoa01c577f2c2018-08-31 09:22:23 +010075 {
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +000076 throw armnn::Exception(
77 boost::str(
78 boost::format("The runtime failed to load the network. "
79 "Error was: %1%. in %2% [%3%:%4%]") %
80 errorMessage %
81 __func__ %
82 __FILE__ %
83 __LINE__));
telsoa01c577f2c2018-08-31 09:22:23 +010084 }
85 }
86
87 void SetupSingleInputSingleOutput(const std::string& inputName, const std::string& outputName)
88 {
89 // Store the input and output name so they don't need to be passed to the single-input-single-output RunTest().
90 m_SingleInputName = inputName;
91 m_SingleOutputName = outputName;
92 Setup();
93 }
94
95 bool ReadStringToBinary()
96 {
Matthew Bentham6c8e8e72019-01-15 17:57:00 +000097 std::string schemafile(&tflite_schema_start, &tflite_schema_end);
telsoa01c577f2c2018-08-31 09:22:23 +010098
99 // parse schema first, so we can use it to parse the data after
100 flatbuffers::Parser parser;
101
Matthew Bentham6c8e8e72019-01-15 17:57:00 +0000102 bool ok = parser.Parse(schemafile.c_str());
telsoa01c577f2c2018-08-31 09:22:23 +0100103 BOOST_ASSERT_MSG(ok, "Failed to parse schema file");
104
105 ok &= parser.Parse(m_JsonString.c_str());
106 BOOST_ASSERT_MSG(ok, "Failed to parse json input");
107
108 if (!ok)
109 {
110 return false;
111 }
112
113 {
114 const uint8_t * bufferPtr = parser.builder_.GetBufferPointer();
115 size_t size = static_cast<size_t>(parser.builder_.GetSize());
116 m_GraphBinary.assign(bufferPtr, bufferPtr+size);
117 }
118 return ok;
119 }
120
121 /// Executes the network with the given input tensor and checks the result against the given output tensor.
keidav011b3e2ea2019-02-21 10:07:37 +0000122 /// This assumes the network has a single input and a single output.
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000123 template <std::size_t NumOutputDimensions,
124 armnn::DataType ArmnnType,
125 typename DataType = armnn::ResolveType<ArmnnType>>
telsoa01c577f2c2018-08-31 09:22:23 +0100126 void RunTest(size_t subgraphId,
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000127 const std::vector<DataType>& inputData,
128 const std::vector<DataType>& expectedOutputData);
telsoa01c577f2c2018-08-31 09:22:23 +0100129
130 /// Executes the network with the given input tensors and checks the results against the given output tensors.
131 /// This overload supports multiple inputs and multiple outputs, identified by name.
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000132 template <std::size_t NumOutputDimensions,
133 armnn::DataType ArmnnType,
134 typename DataType = armnn::ResolveType<ArmnnType>>
telsoa01c577f2c2018-08-31 09:22:23 +0100135 void RunTest(size_t subgraphId,
136 const std::map<std::string, std::vector<DataType>>& inputData,
137 const std::map<std::string, std::vector<DataType>>& expectedOutputData);
138
keidav011b3e2ea2019-02-21 10:07:37 +0000139 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
140 /// Executes the network with the given input tensors and checks the results against the given output tensors.
141 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
142 /// the input datatype to be different to the output
143 template <std::size_t NumOutputDimensions,
144 armnn::DataType ArmnnType1,
145 armnn::DataType ArmnnType2,
146 typename DataType1 = armnn::ResolveType<ArmnnType1>,
147 typename DataType2 = armnn::ResolveType<ArmnnType2>>
148 void RunTest(size_t subgraphId,
149 const std::map<std::string, std::vector<DataType1>>& inputData,
150 const std::map<std::string, std::vector<DataType2>>& expectedOutputData);
151
152
153 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
154 /// Executes the network with the given input tensors and checks the results against the given output tensors.
155 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
156 /// the input datatype to be different to the output
157 template<armnn::DataType ArmnnType1,
158 armnn::DataType ArmnnType2,
159 typename DataType1 = armnn::ResolveType<ArmnnType1>,
160 typename DataType2 = armnn::ResolveType<ArmnnType2>>
161 void RunTest(std::size_t subgraphId,
162 const std::map<std::string, std::vector<DataType1>>& inputData,
163 const std::map<std::string, std::vector<DataType2>>& expectedOutputData);
164
keidav01222c7532019-03-14 17:12:10 +0000165 static inline std::string GenerateDetectionPostProcessJsonString(
166 const armnn::DetectionPostProcessDescriptor& descriptor)
167 {
168 flexbuffers::Builder detectPostProcess;
169 detectPostProcess.Map([&]() {
170 detectPostProcess.Bool("use_regular_nms", descriptor.m_UseRegularNms);
171 detectPostProcess.Int("max_detections", descriptor.m_MaxDetections);
172 detectPostProcess.Int("max_classes_per_detection", descriptor.m_MaxClassesPerDetection);
173 detectPostProcess.Int("detections_per_class", descriptor.m_DetectionsPerClass);
174 detectPostProcess.Int("num_classes", descriptor.m_NumClasses);
175 detectPostProcess.Float("nms_score_threshold", descriptor.m_NmsScoreThreshold);
176 detectPostProcess.Float("nms_iou_threshold", descriptor.m_NmsIouThreshold);
177 detectPostProcess.Float("h_scale", descriptor.m_ScaleH);
178 detectPostProcess.Float("w_scale", descriptor.m_ScaleW);
179 detectPostProcess.Float("x_scale", descriptor.m_ScaleX);
180 detectPostProcess.Float("y_scale", descriptor.m_ScaleY);
181 });
182 detectPostProcess.Finish();
183
184 // Create JSON string
185 std::stringstream strStream;
186 std::vector<uint8_t> buffer = detectPostProcess.GetBuffer();
187 std::copy(buffer.begin(), buffer.end(),std::ostream_iterator<int>(strStream,","));
188
189 return strStream.str();
190 }
191
telsoa01c577f2c2018-08-31 09:22:23 +0100192 void CheckTensors(const TensorRawPtr& tensors, size_t shapeSize, const std::vector<int32_t>& shape,
193 tflite::TensorType tensorType, uint32_t buffer, const std::string& name,
194 const std::vector<float>& min, const std::vector<float>& max,
195 const std::vector<float>& scale, const std::vector<int64_t>& zeroPoint)
196 {
197 BOOST_CHECK(tensors);
198 BOOST_CHECK_EQUAL(shapeSize, tensors->shape.size());
199 BOOST_CHECK_EQUAL_COLLECTIONS(shape.begin(), shape.end(), tensors->shape.begin(), tensors->shape.end());
200 BOOST_CHECK_EQUAL(tensorType, tensors->type);
201 BOOST_CHECK_EQUAL(buffer, tensors->buffer);
202 BOOST_CHECK_EQUAL(name, tensors->name);
203 BOOST_CHECK(tensors->quantization);
204 BOOST_CHECK_EQUAL_COLLECTIONS(min.begin(), min.end(), tensors->quantization.get()->min.begin(),
205 tensors->quantization.get()->min.end());
206 BOOST_CHECK_EQUAL_COLLECTIONS(max.begin(), max.end(), tensors->quantization.get()->max.begin(),
207 tensors->quantization.get()->max.end());
208 BOOST_CHECK_EQUAL_COLLECTIONS(scale.begin(), scale.end(), tensors->quantization.get()->scale.begin(),
209 tensors->quantization.get()->scale.end());
210 BOOST_CHECK_EQUAL_COLLECTIONS(zeroPoint.begin(), zeroPoint.end(),
211 tensors->quantization.get()->zero_point.begin(),
212 tensors->quantization.get()->zero_point.end());
213 }
214};
215
keidav011b3e2ea2019-02-21 10:07:37 +0000216/// Single Input, Single Output
217/// Executes the network with the given input tensor and checks the result against the given output tensor.
218/// This overload assumes the network has a single input and a single output.
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000219template <std::size_t NumOutputDimensions,
keidav011b3e2ea2019-02-21 10:07:37 +0000220 armnn::DataType armnnType,
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000221 typename DataType>
telsoa01c577f2c2018-08-31 09:22:23 +0100222void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
223 const std::vector<DataType>& inputData,
224 const std::vector<DataType>& expectedOutputData)
225{
keidav011b3e2ea2019-02-21 10:07:37 +0000226 RunTest<NumOutputDimensions, armnnType>(subgraphId,
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000227 { { m_SingleInputName, inputData } },
228 { { m_SingleOutputName, expectedOutputData } });
telsoa01c577f2c2018-08-31 09:22:23 +0100229}
230
keidav011b3e2ea2019-02-21 10:07:37 +0000231/// 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.
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000234template <std::size_t NumOutputDimensions,
keidav011b3e2ea2019-02-21 10:07:37 +0000235 armnn::DataType armnnType,
Nattapat Chaimanowong649dd952019-01-22 16:10:44 +0000236 typename DataType>
237void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
238 const std::map<std::string, std::vector<DataType>>& inputData,
239 const std::map<std::string, std::vector<DataType>>& expectedOutputData)
telsoa01c577f2c2018-08-31 09:22:23 +0100240{
keidav011b3e2ea2019-02-21 10:07:37 +0000241 RunTest<NumOutputDimensions, armnnType, armnnType>(subgraphId, inputData, expectedOutputData);
242}
243
244/// Multiple Inputs, Multiple Outputs w/ Variable Datatypes
245/// Executes the network with the given input tensors and checks the results against the given output tensors.
246/// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
247/// the input datatype to be different to the output
248template <std::size_t NumOutputDimensions,
249 armnn::DataType armnnType1,
250 armnn::DataType armnnType2,
251 typename DataType1,
252 typename DataType2>
253void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
254 const std::map<std::string, std::vector<DataType1>>& inputData,
255 const std::map<std::string, std::vector<DataType2>>& expectedOutputData)
256{
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000257 // Setup the armnn input tensors from the given vectors.
258 armnn::InputTensors inputTensors;
259 for (auto&& it : inputData)
telsoa01c577f2c2018-08-31 09:22:23 +0100260 {
Jim Flynnb4d7eae2019-05-01 14:44:27 +0100261 armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
keidav011b3e2ea2019-02-21 10:07:37 +0000262 armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType1);
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000263 inputTensors.push_back({ bindingInfo.first, armnn::ConstTensor(bindingInfo.second, it.second.data()) });
264 }
telsoa01c577f2c2018-08-31 09:22:23 +0100265
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000266 // Allocate storage for the output tensors to be written to and setup the armnn output tensors.
keidav011b3e2ea2019-02-21 10:07:37 +0000267 std::map<std::string, boost::multi_array<DataType2, NumOutputDimensions>> outputStorage;
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000268 armnn::OutputTensors outputTensors;
269 for (auto&& it : expectedOutputData)
270 {
Narumol Prangnawarat386681a2019-04-29 16:40:55 +0100271 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 boost::str(boost::format("Number of dimensions expected %1%, but got %2% for output layer %3%")
278 % NumOutputDimensions
279 % outputNumDimensions
280 % it.first));
281
282 armnn::VerifyTensorInfoDataType(outputTensorInfo, armnnType2);
283 outputStorage.emplace(it.first, MakeTensor<DataType2, NumOutputDimensions>(outputTensorInfo));
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000284 outputTensors.push_back(
Narumol Prangnawarat386681a2019-04-29 16:40:55 +0100285 { outputBindingId, armnn::Tensor(outputTensorInfo, outputStorage.at(it.first).data()) });
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000286 }
telsoa01c577f2c2018-08-31 09:22:23 +0100287
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000288 m_Runtime->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
telsoa01c577f2c2018-08-31 09:22:23 +0100289
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000290 // Compare each output tensor to the expected values
291 for (auto&& it : expectedOutputData)
292 {
Jim Flynnb4d7eae2019-05-01 14:44:27 +0100293 armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
keidav011b3e2ea2019-02-21 10:07:37 +0000294 auto outputExpected = MakeTensor<DataType2, NumOutputDimensions>(bindingInfo.second, it.second);
Aron Virginas-Tar1d67a6902018-11-19 10:58:30 +0000295 BOOST_TEST(CompareTensors(outputExpected, outputStorage[it.first]));
telsoa01c577f2c2018-08-31 09:22:23 +0100296 }
297}
keidav011b3e2ea2019-02-21 10:07:37 +0000298
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.
303template <armnn::DataType armnnType1,
304 armnn::DataType armnnType2,
305 typename DataType1,
306 typename DataType2>
307void ParserFlatbuffersFixture::RunTest(std::size_t subgraphId,
308 const std::map<std::string, std::vector<DataType1>>& inputData,
309 const std::map<std::string, std::vector<DataType2>>& expectedOutputData)
310{
keidav011b3e2ea2019-02-21 10:07:37 +0000311 // Setup the armnn input tensors from the given vectors.
312 armnn::InputTensors inputTensors;
313 for (auto&& it : inputData)
314 {
Jim Flynnb4d7eae2019-05-01 14:44:27 +0100315 armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
keidav011b3e2ea2019-02-21 10:07:37 +0000316 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 {
Jim Flynnb4d7eae2019-05-01 14:44:27 +0100326 armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
keidav011b3e2ea2019-02-21 10:07:37 +0000327 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<DataType2> 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 }
keidav01222c7532019-03-14 17:12:10 +0000349}