ArmNN
 21.02
ParserFlatbuffersFixture.hpp
Go to the documentation of this file.
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>
14 #include <armnn/utility/Assert.hpp>
15 
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 
34 
35 using TensorRawPtr = const tflite::TensorT *;
37 {
39  m_Parser(nullptr, &ITfLiteParser::Destroy),
40  m_Runtime(armnn::IRuntime::Create(armnn::IRuntime::CreationOptions())),
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;
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 
61  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 
93  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 
102  {
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  /// Multiple Inputs with different DataTypes, Multiple Outputs w/ Variable DataTypes
156  /// Executes the network with the given input tensors and checks the results against the given output tensors.
157  /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
158  /// the input datatype to be different to the output
159  template <std::size_t NumOutputDimensions,
160  armnn::DataType inputType1,
161  armnn::DataType inputType2,
162  armnn::DataType outputType>
163  void RunTest(size_t subgraphId,
164  const std::map<std::string, std::vector<armnn::ResolveType<inputType1>>>& input1Data,
165  const std::map<std::string, std::vector<armnn::ResolveType<inputType2>>>& input2Data,
166  const std::map<std::string, std::vector<armnn::ResolveType<outputType>>>& expectedOutputData);
167 
168  /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
169  /// Executes the network with the given input tensors and checks the results against the given output tensors.
170  /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
171  /// the input datatype to be different to the output
172  template<armnn::DataType ArmnnType1,
173  armnn::DataType ArmnnType2>
174  void RunTest(std::size_t subgraphId,
175  const std::map<std::string, std::vector<armnn::ResolveType<ArmnnType1>>>& inputData,
176  const std::map<std::string, std::vector<armnn::ResolveType<ArmnnType2>>>& expectedOutputData);
177 
178  static inline std::string GenerateDetectionPostProcessJsonString(
179  const armnn::DetectionPostProcessDescriptor& descriptor)
180  {
181  flexbuffers::Builder detectPostProcess;
182  detectPostProcess.Map([&]() {
183  detectPostProcess.Bool("use_regular_nms", descriptor.m_UseRegularNms);
184  detectPostProcess.Int("max_detections", descriptor.m_MaxDetections);
185  detectPostProcess.Int("max_classes_per_detection", descriptor.m_MaxClassesPerDetection);
186  detectPostProcess.Int("detections_per_class", descriptor.m_DetectionsPerClass);
187  detectPostProcess.Int("num_classes", descriptor.m_NumClasses);
188  detectPostProcess.Float("nms_score_threshold", descriptor.m_NmsScoreThreshold);
189  detectPostProcess.Float("nms_iou_threshold", descriptor.m_NmsIouThreshold);
190  detectPostProcess.Float("h_scale", descriptor.m_ScaleH);
191  detectPostProcess.Float("w_scale", descriptor.m_ScaleW);
192  detectPostProcess.Float("x_scale", descriptor.m_ScaleX);
193  detectPostProcess.Float("y_scale", descriptor.m_ScaleY);
194  });
195  detectPostProcess.Finish();
196 
197  // Create JSON string
198  std::stringstream strStream;
199  std::vector<uint8_t> buffer = detectPostProcess.GetBuffer();
200  std::copy(buffer.begin(), buffer.end(),std::ostream_iterator<int>(strStream,","));
201 
202  return strStream.str();
203  }
204 
205  void CheckTensors(const TensorRawPtr& tensors, size_t shapeSize, const std::vector<int32_t>& shape,
206  tflite::TensorType tensorType, uint32_t buffer, const std::string& name,
207  const std::vector<float>& min, const std::vector<float>& max,
208  const std::vector<float>& scale, const std::vector<int64_t>& zeroPoint)
209  {
210  BOOST_CHECK(tensors);
211  BOOST_CHECK_EQUAL(shapeSize, tensors->shape.size());
212  BOOST_CHECK_EQUAL_COLLECTIONS(shape.begin(), shape.end(), tensors->shape.begin(), tensors->shape.end());
213  BOOST_CHECK_EQUAL(tensorType, tensors->type);
214  BOOST_CHECK_EQUAL(buffer, tensors->buffer);
215  BOOST_CHECK_EQUAL(name, tensors->name);
216  BOOST_CHECK(tensors->quantization);
217  BOOST_CHECK_EQUAL_COLLECTIONS(min.begin(), min.end(), tensors->quantization.get()->min.begin(),
218  tensors->quantization.get()->min.end());
219  BOOST_CHECK_EQUAL_COLLECTIONS(max.begin(), max.end(), tensors->quantization.get()->max.begin(),
220  tensors->quantization.get()->max.end());
221  BOOST_CHECK_EQUAL_COLLECTIONS(scale.begin(), scale.end(), tensors->quantization.get()->scale.begin(),
222  tensors->quantization.get()->scale.end());
223  BOOST_CHECK_EQUAL_COLLECTIONS(zeroPoint.begin(), zeroPoint.end(),
224  tensors->quantization.get()->zero_point.begin(),
225  tensors->quantization.get()->zero_point.end());
226  }
227 
228 private:
229  /// Fills the InputTensors with given input data
230  template <armnn::DataType dataType>
231  void FillInputTensors(armnn::InputTensors& inputTensors,
232  const std::map<std::string, std::vector<armnn::ResolveType<dataType>>>& inputData,
233  size_t subgraphId);
234 };
235 
236 /// Fills the InputTensors with given input data
237 template <armnn::DataType dataType>
238 void ParserFlatbuffersFixture::FillInputTensors(
239  armnn::InputTensors& inputTensors,
240  const std::map<std::string, std::vector<armnn::ResolveType<dataType>>>& inputData,
241  size_t subgraphId)
242 {
243  for (auto&& it : inputData)
244  {
245  armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
246  armnn::VerifyTensorInfoDataType(bindingInfo.second, dataType);
247  inputTensors.push_back({ bindingInfo.first, armnn::ConstTensor(bindingInfo.second, it.second.data()) });
248  }
249 }
250 
251 /// Single Input, Single Output
252 /// Executes the network with the given input tensor and checks the result against the given output tensor.
253 /// This overload assumes the network has a single input and a single output.
254 template <std::size_t NumOutputDimensions,
255  armnn::DataType armnnType>
256 void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
257  const std::vector<armnn::ResolveType<armnnType>>& inputData,
258  const std::vector<armnn::ResolveType<armnnType>>& expectedOutputData)
259 {
260  RunTest<NumOutputDimensions, armnnType>(subgraphId,
261  { { m_SingleInputName, inputData } },
262  { { m_SingleOutputName, expectedOutputData } });
263 }
264 
265 /// Multiple Inputs, Multiple Outputs
266 /// Executes the network with the given input tensors and checks the results against the given output tensors.
267 /// This overload supports multiple inputs and multiple outputs, identified by name.
268 template <std::size_t NumOutputDimensions,
269  armnn::DataType armnnType>
270 void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
271  const std::map<std::string, std::vector<armnn::ResolveType<armnnType>>>& inputData,
272  const std::map<std::string, std::vector<armnn::ResolveType<armnnType>>>& expectedOutputData)
273 {
274  RunTest<NumOutputDimensions, armnnType, armnnType>(subgraphId, inputData, expectedOutputData);
275 }
276 
277 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes
278 /// Executes the network with the given input tensors and checks the results against the given output tensors.
279 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
280 /// the input datatype to be different to the output
281 template <std::size_t NumOutputDimensions,
282  armnn::DataType armnnType1,
283  armnn::DataType armnnType2>
284 void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
285  const std::map<std::string, std::vector<armnn::ResolveType<armnnType1>>>& inputData,
286  const std::map<std::string, std::vector<armnn::ResolveType<armnnType2>>>& expectedOutputData,
287  bool isDynamic)
288 {
289  using DataType2 = armnn::ResolveType<armnnType2>;
290 
291  // Setup the armnn input tensors from the given vectors.
292  armnn::InputTensors inputTensors;
293  FillInputTensors<armnnType1>(inputTensors, inputData, subgraphId);
294 
295  // Allocate storage for the output tensors to be written to and setup the armnn output tensors.
296  std::map<std::string, boost::multi_array<DataType2, NumOutputDimensions>> outputStorage;
297  armnn::OutputTensors outputTensors;
298  for (auto&& it : expectedOutputData)
299  {
300  armnn::LayerBindingId outputBindingId = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first).first;
301  armnn::TensorInfo outputTensorInfo = m_Runtime->GetOutputTensorInfo(m_NetworkIdentifier, outputBindingId);
302 
303  // Check that output tensors have correct number of dimensions (NumOutputDimensions specified in test)
304  auto outputNumDimensions = outputTensorInfo.GetNumDimensions();
305  BOOST_CHECK_MESSAGE((outputNumDimensions == NumOutputDimensions),
306  fmt::format("Number of dimensions expected {}, but got {} for output layer {}",
307  NumOutputDimensions,
308  outputNumDimensions,
309  it.first));
310 
311  armnn::VerifyTensorInfoDataType(outputTensorInfo, armnnType2);
312  outputStorage.emplace(it.first, MakeTensor<DataType2, NumOutputDimensions>(outputTensorInfo));
313  outputTensors.push_back(
314  { outputBindingId, armnn::Tensor(outputTensorInfo, outputStorage.at(it.first).data()) });
315  }
316 
317  m_Runtime->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
318 
319  // Compare each output tensor to the expected values
320  for (auto&& it : expectedOutputData)
321  {
322  armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
323  auto outputExpected = MakeTensor<DataType2, NumOutputDimensions>(bindingInfo.second, it.second, isDynamic);
324  BOOST_TEST(CompareTensors(outputExpected, outputStorage[it.first], false, isDynamic));
325  }
326 }
327 
328 /// Multiple Inputs, Multiple Outputs w/ Variable Datatypes and different dimension sizes.
329 /// Executes the network with the given input tensors and checks the results against the given output tensors.
330 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
331 /// the input datatype to be different to the output.
332 template <armnn::DataType armnnType1,
333  armnn::DataType armnnType2>
334 void ParserFlatbuffersFixture::RunTest(std::size_t subgraphId,
335  const std::map<std::string, std::vector<armnn::ResolveType<armnnType1>>>& inputData,
336  const std::map<std::string, std::vector<armnn::ResolveType<armnnType2>>>& expectedOutputData)
337 {
338  using DataType2 = armnn::ResolveType<armnnType2>;
339 
340  // Setup the armnn input tensors from the given vectors.
341  armnn::InputTensors inputTensors;
342  FillInputTensors<armnnType1>(inputTensors, inputData, subgraphId);
343 
344  armnn::OutputTensors outputTensors;
345  outputTensors.reserve(expectedOutputData.size());
346  std::map<std::string, std::vector<DataType2>> outputStorage;
347  for (auto&& it : expectedOutputData)
348  {
349  armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
350  armnn::VerifyTensorInfoDataType(bindingInfo.second, armnnType2);
351 
352  std::vector<DataType2> out(it.second.size());
353  outputStorage.emplace(it.first, out);
354  outputTensors.push_back({ bindingInfo.first,
355  armnn::Tensor(bindingInfo.second,
356  outputStorage.at(it.first).data()) });
357  }
358 
359  m_Runtime->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
360 
361  // Checks the results.
362  for (auto&& it : expectedOutputData)
363  {
364  std::vector<armnn::ResolveType<armnnType2>> out = outputStorage.at(it.first);
365  {
366  for (unsigned int i = 0; i < out.size(); ++i)
367  {
368  BOOST_TEST(it.second[i] == out[i], boost::test_tools::tolerance(0.000001f));
369  }
370  }
371  }
372 }
373 
374 /// Multiple Inputs with different DataTypes, Multiple Outputs w/ Variable DataTypes
375 /// Executes the network with the given input tensors and checks the results against the given output tensors.
376 /// This overload supports multiple inputs and multiple outputs, identified by name along with the allowance for
377 /// the input datatype to be different to the output
378 template <std::size_t NumOutputDimensions,
379  armnn::DataType inputType1,
380  armnn::DataType inputType2,
381  armnn::DataType outputType>
382 void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
383  const std::map<std::string, std::vector<armnn::ResolveType<inputType1>>>& input1Data,
384  const std::map<std::string, std::vector<armnn::ResolveType<inputType2>>>& input2Data,
385  const std::map<std::string, std::vector<armnn::ResolveType<outputType>>>& expectedOutputData)
386 {
387  using DataType2 = armnn::ResolveType<outputType>;
388 
389  // Setup the armnn input tensors from the given vectors.
390  armnn::InputTensors inputTensors;
391  FillInputTensors<inputType1>(inputTensors, input1Data, subgraphId);
392  FillInputTensors<inputType2>(inputTensors, input2Data, subgraphId);
393 
394  // Allocate storage for the output tensors to be written to and setup the armnn output tensors.
395  std::map<std::string, boost::multi_array<DataType2, NumOutputDimensions>> outputStorage;
396  armnn::OutputTensors outputTensors;
397  for (auto&& it : expectedOutputData)
398  {
399  armnn::LayerBindingId outputBindingId = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first).first;
400  armnn::TensorInfo outputTensorInfo = m_Runtime->GetOutputTensorInfo(m_NetworkIdentifier, outputBindingId);
401 
402  // Check that output tensors have correct number of dimensions (NumOutputDimensions specified in test)
403  auto outputNumDimensions = outputTensorInfo.GetNumDimensions();
404  BOOST_CHECK_MESSAGE((outputNumDimensions == NumOutputDimensions),
405  fmt::format("Number of dimensions expected {}, but got {} for output layer {}",
406  NumOutputDimensions,
407  outputNumDimensions,
408  it.first));
409 
410  armnn::VerifyTensorInfoDataType(outputTensorInfo, outputType);
411  outputStorage.emplace(it.first, MakeTensor<DataType2, NumOutputDimensions>(outputTensorInfo));
412  outputTensors.push_back(
413  { outputBindingId, armnn::Tensor(outputTensorInfo, outputStorage.at(it.first).data()) });
414  }
415 
416  m_Runtime->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
417 
418  // Compare each output tensor to the expected values
419  for (auto&& it : expectedOutputData)
420  {
421  armnn::BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
422  auto outputExpected = MakeTensor<DataType2, NumOutputDimensions>(bindingInfo.second, it.second);
423  BOOST_TEST(CompareTensors(outputExpected, outputStorage[it.first], false));
424  }
425 }
float m_ScaleW
Center size encoding scale weight.
static std::string GenerateDetectionPostProcessJsonString(const armnn::DetectionPostProcessDescriptor &descriptor)
CPU Execution: Reference C++ kernels.
float m_ScaleX
Center size encoding scale x.
boost::test_tools::predicate_result CompareTensors(const boost::multi_array< T, n > &a, const boost::multi_array< T, n > &b, bool compareBoolean=false, bool isDynamic=false)
void CheckTensors(const TensorRawPtr &tensors, size_t shapeSize, const std::vector< int32_t > &shape, tflite::TensorType tensorType, uint32_t buffer, const std::string &name, const std::vector< float > &min, const std::vector< float > &max, const std::vector< float > &scale, const std::vector< int64_t > &zeroPoint)
std::unique_ptr< IRuntime, void(*)(IRuntime *runtime)> IRuntimePtr
Definition: IRuntime.hpp:26
uint32_t m_DetectionsPerClass
Detections per classes, used in Regular NMS.
typename ResolveTypeImpl< DT >::Type ResolveType
Definition: ResolveType.hpp:73
std::vector< std::pair< LayerBindingId, class ConstTensor > > InputTensors
Definition: Tensor.hpp:340
int NetworkId
Definition: IRuntime.hpp:20
std::unique_ptr< ITfLiteParser, void(*)(ITfLiteParser *parser)> ITfLiteParserPtr
Copyright (c) 2021 ARM Limited and Contributors.
void RunTest(size_t subgraphId, const std::vector< armnn::ResolveType< ArmnnType >> &inputData, const std::vector< armnn::ResolveType< ArmnnType >> &expectedOutputData)
Executes the network with the given input tensor and checks the result against the given output tenso...
int LayerBindingId
Type of identifiers for bindable layers (inputs, outputs).
Definition: Types.hpp:210
uint32_t m_MaxClassesPerDetection
Maximum numbers of classes per detection, used in Fast NMS.
A tensor defined by a TensorInfo (shape and data type) and a mutable backing store.
Definition: Tensor.hpp:306
uint32_t m_MaxDetections
Maximum numbers of detections.
DataType
Definition: Types.hpp:32
float m_NmsIouThreshold
Intersection over union threshold.
IOptimizedNetworkPtr Optimize(const INetwork &network, const std::vector< BackendId > &backendPreferences, const IDeviceSpec &deviceSpec, const OptimizerOptions &options=OptimizerOptions(), Optional< std::vector< std::string > &> messages=EmptyOptional())
Create an optimized version of the network.
Definition: Network.cpp:1502
#define ARMNN_ASSERT_MSG(COND, MSG)
Definition: Assert.hpp:15
armnnSerializer::TensorInfo * TensorRawPtr
A tensor defined by a TensorInfo (shape and data type) and an immutable backing store.
Definition: Tensor.hpp:314
std::vector< std::pair< LayerBindingId, class Tensor > > OutputTensors
Definition: Tensor.hpp:341
Status
enumeration
Definition: Types.hpp:26
uint32_t m_NumClasses
Number of classes.
bool m_UseRegularNms
Use Regular NMS.
std::vector< uint8_t > m_GraphBinary
float m_ScaleH
Center size encoding scale height.
std::pair< armnn::LayerBindingId, armnn::TensorInfo > BindingPointInfo
Definition: Tensor.hpp:261
void SetupSingleInputSingleOutput(const std::string &inputName, const std::string &outputName)
Base class for all ArmNN exceptions so that users can filter to just those.
Definition: Exceptions.hpp:46
void VerifyTensorInfoDataType(const armnn::TensorInfo &info, armnn::DataType dataType)
Definition: TypesUtils.hpp:309
float m_ScaleY
Center size encoding scale y.
unsigned char g_TfLiteSchemaText[]
float m_NmsScoreThreshold
NMS score threshold.
std::unique_ptr< INetwork, void(*)(INetwork *network)> INetworkPtr
Definition: INetwork.hpp:173
std::string m_SingleInputName
If the single-input-single-output overload of Setup() is called, these will store the input and outpu...
unsigned int GetNumDimensions() const
Definition: Tensor.hpp:191
unsigned int g_TfLiteSchemaText_len