blob: 7413de97ddb3d85544108fe9126ea69e63e2abc9 [file] [log] [blame]
telsoa014fcda012018-03-09 14:13:49 +00001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
David Beckecb56cd2018-09-05 12:52:57 +01003// SPDX-License-Identifier: MIT
telsoa014fcda012018-03-09 14:13:49 +00004//
5#include "InferenceTest.hpp"
6
telsoa01c577f2c2018-08-31 09:22:23 +01007#include "../src/armnn/Profiling.hpp"
telsoa014fcda012018-03-09 14:13:49 +00008#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
22using namespace std;
23using namespace std::chrono;
24using namespace armnn::test;
25
26namespace armnn
27{
28namespace test
29{
telsoa014fcda012018-03-09 14:13:49 +000030/// Parse the command line of an ArmNN (or referencetests) inference test program.
31/// \return false if any error occurred during options processing, otherwise true
32bool ParseCommandLine(int argc, char** argv, IInferenceTestCaseProvider& testCaseProvider,
33 InferenceTestOptions& outParams)
34{
35 namespace po = boost::program_options;
36
telsoa014fcda012018-03-09 14:13:49 +000037 po::options_description desc("Options");
38
39 try
40 {
telsoa01c577f2c2018-08-31 09:22:23 +010041 // Adds generic options needed for all inference tests.
telsoa014fcda012018-03-09 14:13:49 +000042 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(""),
telsoa01c577f2c2018-08-31 09:22:23 +010047 "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.");
telsoa014fcda012018-03-09 14:13:49 +000050
telsoa01c577f2c2018-08-31 09:22:23 +010051 // Adds options specific to the ITestCaseProvider.
telsoa014fcda012018-03-09 14:13:49 +000052 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
93bool 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
109bool InferenceTest(const InferenceTestOptions& params,
110 const std::vector<unsigned int>& defaultTestCaseIds,
111 IInferenceTestCaseProvider& testCaseProvider)
112{
113#if !defined (NDEBUG)
telsoa01c577f2c2018-08-31 09:22:23 +0100114 if (params.m_IterationCount > 0) // If just running a few select images then don't bother to warn.
telsoa014fcda012018-03-09 14:13:49 +0000115 {
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
telsoa01c577f2c2018-08-31 09:22:23 +0100124 // Opens the file to write inference times too, if needed.
telsoa014fcda012018-03-09 14:13:49 +0000125 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
telsoa01c577f2c2018-08-31 09:22:23 +0100138 // 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
telsoa014fcda012018-03-09 14:13:49 +0000145 // 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
surmeh013537c2c2018-05-18 16:31:43 +0100164 : static_cast<unsigned int>(defaultTestCaseIds.size());
telsoa014fcda012018-03-09 14:13:49 +0000165
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
telsoa01c577f2c2018-08-31 09:22:23 +0100194 // Outputss inference times, if needed.
telsoa014fcda012018-03-09 14:13:49 +0000195 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
Sadik Armagan2b7a1582018-09-05 16:33:58 +0100232 // if profiling is enabled print out the results
233 if (profiler && profiler->IsProfilingEnabled())
234 {
235 profiler->Print(std::cout);
236 }
237
telsoa014fcda012018-03-09 14:13:49 +0000238 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