IVGCVSW-2454 Merge together the pluggable backends work (was in a
[platform/upstream/armnn.git] / tests / InferenceTest.cpp
1 //
2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
4 //
5 #include "InferenceTest.hpp"
6
7 #include "../src/armnn/Profiling.hpp"
8 #include <boost/algorithm/string.hpp>
9 #include <boost/numeric/conversion/cast.hpp>
10 #include <boost/log/trivial.hpp>
11 #include <boost/filesystem/path.hpp>
12 #include <boost/assert.hpp>
13 #include <boost/format.hpp>
14 #include <boost/program_options.hpp>
15 #include <boost/filesystem/operations.hpp>
16
17 #include <fstream>
18 #include <iostream>
19 #include <iomanip>
20 #include <array>
21
22 using namespace std;
23 using namespace std::chrono;
24 using namespace armnn::test;
25
26 namespace armnn
27 {
28 namespace test
29 {
30 /// Parse the command line of an ArmNN (or referencetests) inference test program.
31 /// \return false if any error occurred during options processing, otherwise true
32 bool ParseCommandLine(int argc, char** argv, IInferenceTestCaseProvider& testCaseProvider,
33     InferenceTestOptions& outParams)
34 {
35     namespace po = boost::program_options;
36
37     po::options_description desc("Options");
38
39     try
40     {
41         // Adds generic options needed for all inference tests.
42         desc.add_options()
43             ("help", "Display help messages")
44             ("iterations,i", po::value<unsigned int>(&outParams.m_IterationCount)->default_value(0),
45                 "Sets the number number of inferences to perform. If unset, a default number will be ran.")
46             ("inference-times-file", po::value<std::string>(&outParams.m_InferenceTimesFile)->default_value(""),
47                 "If non-empty, each individual inference time will be recorded and output to this file")
48             ("event-based-profiling,e", po::value<bool>(&outParams.m_EnableProfiling)->default_value(0),
49                 "Enables built in profiler. If unset, defaults to off.");
50
51         // Adds options specific to the ITestCaseProvider.
52         testCaseProvider.AddCommandLineOptions(desc);
53     }
54     catch (const std::exception& e)
55     {
56         // Coverity points out that default_value(...) can throw a bad_lexical_cast,
57         // and that desc.add_options() can throw boost::io::too_few_args.
58         // They really won't in any of these cases.
59         BOOST_ASSERT_MSG(false, "Caught unexpected exception");
60         std::cerr << "Fatal internal error: " << e.what() << std::endl;
61         return false;
62     }
63
64     po::variables_map vm;
65
66     try
67     {
68         po::store(po::parse_command_line(argc, argv, desc), vm);
69
70         if (vm.count("help"))
71         {
72             std::cout << desc << std::endl;
73             return false;
74         }
75
76         po::notify(vm);
77     }
78     catch (po::error& e)
79     {
80         std::cerr << e.what() << std::endl << std::endl;
81         std::cerr << desc << std::endl;
82         return false;
83     }
84
85     if (!testCaseProvider.ProcessCommandLineOptions())
86     {
87         return false;
88     }
89
90     return true;
91 }
92
93 bool ValidateDirectory(std::string& dir)
94 {
95     if (dir[dir.length() - 1] != '/')
96     {
97         dir += "/";
98     }
99
100     if (!boost::filesystem::exists(dir))
101     {
102         std::cerr << "Given directory " << dir << " does not exist" << std::endl;
103         return false;
104     }
105
106     return true;
107 }
108
109 bool InferenceTest(const InferenceTestOptions& params,
110     const std::vector<unsigned int>& defaultTestCaseIds,
111     IInferenceTestCaseProvider& testCaseProvider)
112 {
113 #if !defined (NDEBUG)
114     if (params.m_IterationCount > 0) // If just running a few select images then don't bother to warn.
115     {
116         BOOST_LOG_TRIVIAL(warning) << "Performance test running in DEBUG build - results may be inaccurate.";
117     }
118 #endif
119
120     double totalTime = 0;
121     unsigned int nbProcessed = 0;
122     bool success = true;
123
124     // Opens the file to write inference times too, if needed.
125     ofstream inferenceTimesFile;
126     const bool recordInferenceTimes = !params.m_InferenceTimesFile.empty();
127     if (recordInferenceTimes)
128     {
129         inferenceTimesFile.open(params.m_InferenceTimesFile.c_str(), ios_base::trunc | ios_base::out);
130         if (!inferenceTimesFile.good())
131         {
132             BOOST_LOG_TRIVIAL(error) << "Failed to open inference times file for writing: "
133                 << params.m_InferenceTimesFile;
134             return false;
135         }
136     }
137
138     // Create a profiler and register it for the current thread.
139     std::unique_ptr<Profiler> profiler = std::make_unique<Profiler>();
140     ProfilerManager::GetInstance().RegisterProfiler(profiler.get());
141
142     // Enable profiling if requested.
143     profiler->EnableProfiling(params.m_EnableProfiling);
144
145     // Run a single test case to 'warm-up' the model. The first one can sometimes take up to 10x longer
146     std::unique_ptr<IInferenceTestCase> warmupTestCase = testCaseProvider.GetTestCase(0);
147     if (warmupTestCase == nullptr)
148     {
149         BOOST_LOG_TRIVIAL(error) << "Failed to load test case";
150         return false;
151     }
152
153     try
154     {
155         warmupTestCase->Run();
156     }
157     catch (const TestFrameworkException& testError)
158     {
159         BOOST_LOG_TRIVIAL(error) << testError.what();
160         return false;
161     }
162
163     const unsigned int nbTotalToProcess = params.m_IterationCount > 0 ? params.m_IterationCount
164         : static_cast<unsigned int>(defaultTestCaseIds.size());
165
166     for (; nbProcessed < nbTotalToProcess; nbProcessed++)
167     {
168         const unsigned int testCaseId = params.m_IterationCount > 0 ? nbProcessed : defaultTestCaseIds[nbProcessed];
169         std::unique_ptr<IInferenceTestCase> testCase = testCaseProvider.GetTestCase(testCaseId);
170
171         if (testCase == nullptr)
172         {
173             BOOST_LOG_TRIVIAL(error) << "Failed to load test case";
174             return false;
175         }
176
177         time_point<high_resolution_clock> predictStart;
178         time_point<high_resolution_clock> predictEnd;
179
180         TestCaseResult result = TestCaseResult::Ok;
181
182         try
183         {
184             predictStart = high_resolution_clock::now();
185
186             testCase->Run();
187
188             predictEnd = high_resolution_clock::now();
189
190             // duration<double> will convert the time difference into seconds as a double by default.
191             double timeTakenS = duration<double>(predictEnd - predictStart).count();
192             totalTime += timeTakenS;
193
194             // Outputss inference times, if needed.
195             if (recordInferenceTimes)
196             {
197                 inferenceTimesFile << testCaseId << " " << (timeTakenS * 1000.0) << std::endl;
198             }
199
200             result = testCase->ProcessResult(params);
201
202         }
203         catch (const TestFrameworkException& testError)
204         {
205             BOOST_LOG_TRIVIAL(error) << testError.what();
206             result = TestCaseResult::Abort;
207         }
208
209         switch (result)
210         {
211         case TestCaseResult::Ok:
212             break;
213         case TestCaseResult::Abort:
214             return false;
215         case TestCaseResult::Failed:
216             // This test failed so we will fail the entire program eventually, but keep going for now.
217             success = false;
218             break;
219         default:
220             BOOST_ASSERT_MSG(false, "Unexpected TestCaseResult");
221             return false;
222         }
223     }
224
225     const double averageTimePerTestCaseMs = totalTime / nbProcessed * 1000.0f;
226
227     BOOST_LOG_TRIVIAL(info) << std::fixed << std::setprecision(3) <<
228         "Total time for " << nbProcessed << " test cases: " << totalTime << " seconds";
229     BOOST_LOG_TRIVIAL(info) << std::fixed << std::setprecision(3) <<
230         "Average time per test case: " << averageTimePerTestCaseMs << " ms";
231
232     // if profiling is enabled print out the results
233     if (profiler && profiler->IsProfilingEnabled())
234     {
235         profiler->Print(std::cout);
236     }
237
238     if (!success)
239     {
240         BOOST_LOG_TRIVIAL(error) << "One or more test cases failed";
241         return false;
242     }
243
244     return testCaseProvider.OnInferenceTestFinished();
245 }
246
247 } // namespace test
248
249 } // namespace armnn