ArmNN
 20.05
InferenceTest.inl
Go to the documentation of this file.
1 //
2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 #include "InferenceTest.hpp"
6 
8 #include <boost/numeric/conversion/cast.hpp>
9 #include <boost/filesystem/path.hpp>
10 #include <boost/format.hpp>
11 #include <boost/program_options.hpp>
12 #include <boost/filesystem/operations.hpp>
13 
14 #include <fstream>
15 #include <iostream>
16 #include <iomanip>
17 #include <array>
18 #include <chrono>
19 
20 using namespace std;
21 using namespace std::chrono;
22 using namespace armnn::test;
23 
24 namespace armnn
25 {
26 namespace test
27 {
28 
29 using TContainer = boost::variant<std::vector<float>, std::vector<int>, std::vector<unsigned char>>;
30 
31 template <typename TTestCaseDatabase, typename TModel>
33  int& numInferencesRef,
34  int& numCorrectInferencesRef,
35  const std::vector<unsigned int>& validationPredictions,
36  std::vector<unsigned int>* validationPredictionsOut,
37  TModel& model,
38  unsigned int testCaseId,
39  unsigned int label,
40  std::vector<typename TModel::DataType> modelInput)
41  : InferenceModelTestCase<TModel>(
42  model, testCaseId, std::vector<TContainer>{ modelInput }, { model.GetOutputSize() })
43  , m_Label(label)
44  , m_QuantizationParams(model.GetQuantizationParams())
45  , m_NumInferencesRef(numInferencesRef)
46  , m_NumCorrectInferencesRef(numCorrectInferencesRef)
47  , m_ValidationPredictions(validationPredictions)
48  , m_ValidationPredictionsOut(validationPredictionsOut)
49 {
50 }
51 
52 struct ClassifierResultProcessor : public boost::static_visitor<>
53 {
54  using ResultMap = std::map<float,int>;
55 
56  ClassifierResultProcessor(float scale, int offset)
57  : m_Scale(scale)
58  , m_Offset(offset)
59  {}
60 
61  void operator()(const std::vector<float>& values)
62  {
63  SortPredictions(values, [](float value)
64  {
65  return value;
66  });
67  }
68 
69  void operator()(const std::vector<uint8_t>& values)
70  {
71  auto& scale = m_Scale;
72  auto& offset = m_Offset;
73  SortPredictions(values, [&scale, &offset](uint8_t value)
74  {
75  return armnn::Dequantize(value, scale, offset);
76  });
77  }
78 
79  void operator()(const std::vector<int>& values)
80  {
81  IgnoreUnused(values);
82  ARMNN_ASSERT_MSG(false, "Non-float predictions output not supported.");
83  }
84 
85  ResultMap& GetResultMap() { return m_ResultMap; }
86 
87 private:
88  template<typename Container, typename Delegate>
89  void SortPredictions(const Container& c, Delegate delegate)
90  {
91  int index = 0;
92  for (const auto& value : c)
93  {
94  int classification = index++;
95  // Take the first class with each probability
96  // This avoids strange results when looping over batched results produced
97  // with identical test data.
98  ResultMap::iterator lb = m_ResultMap.lower_bound(value);
99 
100  if (lb == m_ResultMap.end() || !m_ResultMap.key_comp()(value, lb->first))
101  {
102  // If the key is not already in the map, insert it.
103  m_ResultMap.insert(lb, ResultMap::value_type(delegate(value), classification));
104  }
105  }
106  }
107 
108  ResultMap m_ResultMap;
109 
110  float m_Scale=0.0f;
111  int m_Offset=0;
112 };
113 
114 template <typename TTestCaseDatabase, typename TModel>
116 {
117  auto& output = this->GetOutputs()[0];
118  const auto testCaseId = this->GetTestCaseId();
119 
120  ClassifierResultProcessor resultProcessor(m_QuantizationParams.first, m_QuantizationParams.second);
121  boost::apply_visitor(resultProcessor, output);
122 
123  ARMNN_LOG(info) << "= Prediction values for test #" << testCaseId;
124  auto it = resultProcessor.GetResultMap().rbegin();
125  for (int i=0; i<5 && it != resultProcessor.GetResultMap().rend(); ++i)
126  {
127  ARMNN_LOG(info) << "Top(" << (i+1) << ") prediction is " << it->second <<
128  " with value: " << (it->first);
129  ++it;
130  }
131 
132  unsigned int prediction = 0;
133  boost::apply_visitor([&](auto&& value)
134  {
135  prediction = boost::numeric_cast<unsigned int>(
136  std::distance(value.begin(), std::max_element(value.begin(), value.end())));
137  },
138  output);
139 
140  // If we're just running the defaultTestCaseIds, each one must be classified correctly.
141  if (params.m_IterationCount == 0 && prediction != m_Label)
142  {
143  ARMNN_LOG(error) << "Prediction for test case " << testCaseId << " (" << prediction << ")" <<
144  " is incorrect (should be " << m_Label << ")";
145  return TestCaseResult::Failed;
146  }
147 
148  // If a validation file was provided as input, it checks that the prediction matches.
149  if (!m_ValidationPredictions.empty() && prediction != m_ValidationPredictions[testCaseId])
150  {
151  ARMNN_LOG(error) << "Prediction for test case " << testCaseId << " (" << prediction << ")" <<
152  " doesn't match the prediction in the validation file (" << m_ValidationPredictions[testCaseId] << ")";
153  return TestCaseResult::Failed;
154  }
155 
156  // If a validation file was requested as output, it stores the predictions.
157  if (m_ValidationPredictionsOut)
158  {
159  m_ValidationPredictionsOut->push_back(prediction);
160  }
161 
162  // Updates accuracy stats.
163  m_NumInferencesRef++;
164  if (prediction == m_Label)
165  {
166  m_NumCorrectInferencesRef++;
167  }
168 
169  return TestCaseResult::Ok;
170 }
171 
172 template <typename TDatabase, typename InferenceModel>
173 template <typename TConstructDatabaseCallable, typename TConstructModelCallable>
175  TConstructDatabaseCallable constructDatabase, TConstructModelCallable constructModel)
176  : m_ConstructModel(constructModel)
177  , m_ConstructDatabase(constructDatabase)
178  , m_NumInferences(0)
179  , m_NumCorrectInferences(0)
180 {
181 }
182 
183 template <typename TDatabase, typename InferenceModel>
185  boost::program_options::options_description& options)
186 {
187  namespace po = boost::program_options;
188 
189  options.add_options()
190  ("validation-file-in", po::value<std::string>(&m_ValidationFileIn)->default_value(""),
191  "Reads expected predictions from the given file and confirms they match the actual predictions.")
192  ("validation-file-out", po::value<std::string>(&m_ValidationFileOut)->default_value(""),
193  "Predictions are saved to the given file for later use via --validation-file-in.")
194  ("data-dir,d", po::value<std::string>(&m_DataDir)->required(),
195  "Path to directory containing test data");
196 
197  InferenceModel::AddCommandLineOptions(options, m_ModelCommandLineOptions);
198 }
199 
200 template <typename TDatabase, typename InferenceModel>
202  const InferenceTestOptions& commonOptions)
203 {
204  if (!ValidateDirectory(m_DataDir))
205  {
206  return false;
207  }
208 
209  ReadPredictions();
210 
211  m_Model = m_ConstructModel(commonOptions, m_ModelCommandLineOptions);
212  if (!m_Model)
213  {
214  return false;
215  }
216 
217  m_Database = std::make_unique<TDatabase>(m_ConstructDatabase(m_DataDir.c_str(), *m_Model));
218  if (!m_Database)
219  {
220  return false;
221  }
222 
223  return true;
224 }
225 
226 template <typename TDatabase, typename InferenceModel>
227 std::unique_ptr<IInferenceTestCase>
229 {
230  std::unique_ptr<typename TDatabase::TTestCaseData> testCaseData = m_Database->GetTestCaseData(testCaseId);
231  if (testCaseData == nullptr)
232  {
233  return nullptr;
234  }
235 
236  return std::make_unique<ClassifierTestCase<TDatabase, InferenceModel>>(
237  m_NumInferences,
238  m_NumCorrectInferences,
239  m_ValidationPredictions,
240  m_ValidationFileOut.empty() ? nullptr : &m_ValidationPredictionsOut,
241  *m_Model,
242  testCaseId,
243  testCaseData->m_Label,
244  std::move(testCaseData->m_InputImage));
245 }
246 
247 template <typename TDatabase, typename InferenceModel>
249 {
250  const double accuracy = boost::numeric_cast<double>(m_NumCorrectInferences) /
251  boost::numeric_cast<double>(m_NumInferences);
252  ARMNN_LOG(info) << std::fixed << std::setprecision(3) << "Overall accuracy: " << accuracy;
253 
254  // If a validation file was requested as output, the predictions are saved to it.
255  if (!m_ValidationFileOut.empty())
256  {
257  std::ofstream validationFileOut(m_ValidationFileOut.c_str(), std::ios_base::trunc | std::ios_base::out);
258  if (validationFileOut.good())
259  {
260  for (const unsigned int prediction : m_ValidationPredictionsOut)
261  {
262  validationFileOut << prediction << std::endl;
263  }
264  }
265  else
266  {
267  ARMNN_LOG(error) << "Failed to open output validation file: " << m_ValidationFileOut;
268  return false;
269  }
270  }
271 
272  return true;
273 }
274 
275 template <typename TDatabase, typename InferenceModel>
277 {
278  // Reads the expected predictions from the input validation file (if provided).
279  if (!m_ValidationFileIn.empty())
280  {
281  std::ifstream validationFileIn(m_ValidationFileIn.c_str(), std::ios_base::in);
282  if (validationFileIn.good())
283  {
284  while (!validationFileIn.eof())
285  {
286  unsigned int i;
287  validationFileIn >> i;
288  m_ValidationPredictions.emplace_back(i);
289  }
290  }
291  else
292  {
293  throw armnn::Exception(boost::str(boost::format("Failed to open input validation file: %1%")
294  % m_ValidationFileIn));
295  }
296  }
297 }
298 
299 template<typename TConstructTestCaseProvider>
300 int InferenceTestMain(int argc,
301  char* argv[],
302  const std::vector<unsigned int>& defaultTestCaseIds,
303  TConstructTestCaseProvider constructTestCaseProvider)
304 {
305  // Configures logging for both the ARMNN library and this test program.
306 #ifdef NDEBUG
308 #else
310 #endif
311  armnn::ConfigureLogging(true, true, level);
312 
313  try
314  {
315  std::unique_ptr<IInferenceTestCaseProvider> testCaseProvider = constructTestCaseProvider();
316  if (!testCaseProvider)
317  {
318  return 1;
319  }
320 
321  InferenceTestOptions inferenceTestOptions;
322  if (!ParseCommandLine(argc, argv, *testCaseProvider, inferenceTestOptions))
323  {
324  return 1;
325  }
326 
327  const bool success = InferenceTest(inferenceTestOptions, defaultTestCaseIds, *testCaseProvider);
328  return success ? 0 : 1;
329  }
330  catch (armnn::Exception const& e)
331  {
332  ARMNN_LOG(fatal) << "Armnn Error: " << e.what();
333  return 1;
334  }
335 }
336 
337 //
338 // This function allows us to create a classifier inference test based on:
339 // - a model file name
340 // - which can be a binary or a text file for protobuf formats
341 // - an input tensor name
342 // - an output tensor name
343 // - a set of test case ids
344 // - a callback method which creates an object that can return images
345 // called 'Database' in these tests
346 // - and an input tensor shape
347 //
348 template<typename TDatabase,
349  typename TParser,
350  typename TConstructDatabaseCallable>
352  char* argv[],
353  const char* modelFilename,
354  bool isModelBinary,
355  const char* inputBindingName,
356  const char* outputBindingName,
357  const std::vector<unsigned int>& defaultTestCaseIds,
358  TConstructDatabaseCallable constructDatabase,
359  const armnn::TensorShape* inputTensorShape)
360 
361 {
362  ARMNN_ASSERT(modelFilename);
363  ARMNN_ASSERT(inputBindingName);
364  ARMNN_ASSERT(outputBindingName);
365 
366  return InferenceTestMain(argc, argv, defaultTestCaseIds,
367  [=]
368  ()
369  {
372 
373  return make_unique<TestCaseProvider>(constructDatabase,
374  [&]
375  (const InferenceTestOptions &commonOptions,
376  typename InferenceModel::CommandLineOptions modelOptions)
377  {
378  if (!ValidateDirectory(modelOptions.m_ModelDir))
379  {
380  return std::unique_ptr<InferenceModel>();
381  }
382 
383  typename InferenceModel::Params modelParams;
384  modelParams.m_ModelPath = modelOptions.m_ModelDir + modelFilename;
385  modelParams.m_InputBindings = { inputBindingName };
386  modelParams.m_OutputBindings = { outputBindingName };
387 
388  if (inputTensorShape)
389  {
390  modelParams.m_InputShapes.push_back(*inputTensorShape);
391  }
392 
393  modelParams.m_IsModelBinary = isModelBinary;
394  modelParams.m_ComputeDevices = modelOptions.GetComputeDevicesAsBackendIds();
395  modelParams.m_VisualizePostOptimizationModel = modelOptions.m_VisualizePostOptimizationModel;
396  modelParams.m_EnableFp16TurboMode = modelOptions.m_EnableFp16TurboMode;
397 
398  return std::make_unique<InferenceModel>(modelParams,
399  commonOptions.m_EnableProfiling,
400  commonOptions.m_DynamicBackendsPath);
401  });
402  });
403 }
404 
405 } // namespace test
406 } // namespace armnn
bool ParseCommandLine(int argc, char **argv, IInferenceTestCaseProvider &testCaseProvider, InferenceTestOptions &outParams)
Parse the command line of an ArmNN (or referencetests) inference test program.
void ConfigureLogging(bool printToStandardOutput, bool printToDebugOutput, LogSeverity severity)
Configures the logging behaviour of the ARMNN library.
Definition: Utils.cpp:10
const std::vector< TContainer > & GetOutputs() const
virtual const char * what() const noexcept override
Definition: Exceptions.cpp:32
#define ARMNN_LOG(severity)
Definition: Logging.hpp:163
ClassifierTestCaseProvider(TConstructDatabaseCallable constructDatabase, TConstructModelCallable constructModel)
Copyright (c) 2020 ARM Limited.
void IgnoreUnused(Ts &&...)
virtual bool ProcessCommandLineOptions(const InferenceTestOptions &commonOptions) override
virtual bool OnInferenceTestFinished() override
#define ARMNN_ASSERT_MSG(COND, MSG)
Definition: Assert.hpp:15
virtual TestCaseResult ProcessResult(const InferenceTestOptions &params) override
#define ARMNN_ASSERT(COND)
Definition: Assert.hpp:14
std::enable_if_t< std::is_unsigned< Source >::value &&std::is_unsigned< Dest >::value, Dest > numeric_cast(Source source)
Definition: NumericCast.hpp:33
int ClassifierInferenceTestMain(int argc, char *argv[], const char *modelFilename, bool isModelBinary, const char *inputBindingName, const char *outputBindingName, const std::vector< unsigned int > &defaultTestCaseIds, TConstructDatabaseCallable constructDatabase, const armnn::TensorShape *inputTensorShape=nullptr)
bool InferenceTest(const InferenceTestOptions &params, const std::vector< unsigned int > &defaultTestCaseIds, IInferenceTestCaseProvider &testCaseProvider)
boost::variant< std::vector< float >, std::vector< int >, std::vector< unsigned char > > TContainer
Base class for all ArmNN exceptions so that users can filter to just those.
Definition: Exceptions.hpp:46
virtual std::unique_ptr< IInferenceTestCase > GetTestCase(unsigned int testCaseId) override
virtual void AddCommandLineOptions(boost::program_options::options_description &options) override
static void AddCommandLineOptions(boost::program_options::options_description &desc, CommandLineOptions &options)
bool ValidateDirectory(std::string &dir)
boost::variant< std::vector< float >, std::vector< int >, std::vector< unsigned char > > TContainer
armnn::Runtime::CreationOptions::ExternalProfilingOptions options
LogSeverity
Definition: Utils.hpp:12
int InferenceTestMain(int argc, char *argv[], const std::vector< unsigned int > &defaultTestCaseIds, TConstructTestCaseProvider constructTestCaseProvider)
The test completed without any errors.