2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // See LICENSE file in the project root for full license information.
5 #include "InferenceTest.hpp"
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>
23 using namespace std::chrono;
24 using namespace armnn::test;
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)
35 namespace po = boost::program_options;
37 std::string computeDeviceStr;
39 po::options_description desc("Options");
43 // Adds generic options needed for all inference tests.
45 ("help", "Display help messages")
46 ("iterations,i", po::value<unsigned int>(&outParams.m_IterationCount)->default_value(0),
47 "Sets the number number of inferences to perform. If unset, a default number will be ran.")
48 ("inference-times-file", po::value<std::string>(&outParams.m_InferenceTimesFile)->default_value(""),
49 "If non-empty, each individual inference time will be recorded and output to this file")
50 ("event-based-profiling,e", po::value<bool>(&outParams.m_EnableProfiling)->default_value(0),
51 "Enables built in profiler. If unset, defaults to off.");
53 // Adds options specific to the ITestCaseProvider.
54 testCaseProvider.AddCommandLineOptions(desc);
56 catch (const std::exception& e)
58 // Coverity points out that default_value(...) can throw a bad_lexical_cast,
59 // and that desc.add_options() can throw boost::io::too_few_args.
60 // They really won't in any of these cases.
61 BOOST_ASSERT_MSG(false, "Caught unexpected exception");
62 std::cerr << "Fatal internal error: " << e.what() << std::endl;
70 po::store(po::parse_command_line(argc, argv, desc), vm);
74 std::cout << desc << std::endl;
82 std::cerr << e.what() << std::endl << std::endl;
83 std::cerr << desc << std::endl;
87 if (!testCaseProvider.ProcessCommandLineOptions())
95 bool ValidateDirectory(std::string& dir)
97 if (dir[dir.length() - 1] != '/')
102 if (!boost::filesystem::exists(dir))
104 std::cerr << "Given directory " << dir << " does not exist" << std::endl;
111 bool InferenceTest(const InferenceTestOptions& params,
112 const std::vector<unsigned int>& defaultTestCaseIds,
113 IInferenceTestCaseProvider& testCaseProvider)
115 #if !defined (NDEBUG)
116 if (params.m_IterationCount > 0) // If just running a few select images then don't bother to warn.
118 BOOST_LOG_TRIVIAL(warning) << "Performance test running in DEBUG build - results may be inaccurate.";
122 double totalTime = 0;
123 unsigned int nbProcessed = 0;
126 // Opens the file to write inference times too, if needed.
127 ofstream inferenceTimesFile;
128 const bool recordInferenceTimes = !params.m_InferenceTimesFile.empty();
129 if (recordInferenceTimes)
131 inferenceTimesFile.open(params.m_InferenceTimesFile.c_str(), ios_base::trunc | ios_base::out);
132 if (!inferenceTimesFile.good())
134 BOOST_LOG_TRIVIAL(error) << "Failed to open inference times file for writing: "
135 << params.m_InferenceTimesFile;
140 // Create a profiler and register it for the current thread.
141 std::unique_ptr<Profiler> profiler = std::make_unique<Profiler>();
142 ProfilerManager::GetInstance().RegisterProfiler(profiler.get());
144 // Enable profiling if requested.
145 profiler->EnableProfiling(params.m_EnableProfiling);
147 // Run a single test case to 'warm-up' the model. The first one can sometimes take up to 10x longer
148 std::unique_ptr<IInferenceTestCase> warmupTestCase = testCaseProvider.GetTestCase(0);
149 if (warmupTestCase == nullptr)
151 BOOST_LOG_TRIVIAL(error) << "Failed to load test case";
157 warmupTestCase->Run();
159 catch (const TestFrameworkException& testError)
161 BOOST_LOG_TRIVIAL(error) << testError.what();
165 const unsigned int nbTotalToProcess = params.m_IterationCount > 0 ? params.m_IterationCount
166 : static_cast<unsigned int>(defaultTestCaseIds.size());
168 for (; nbProcessed < nbTotalToProcess; nbProcessed++)
170 const unsigned int testCaseId = params.m_IterationCount > 0 ? nbProcessed : defaultTestCaseIds[nbProcessed];
171 std::unique_ptr<IInferenceTestCase> testCase = testCaseProvider.GetTestCase(testCaseId);
173 if (testCase == nullptr)
175 BOOST_LOG_TRIVIAL(error) << "Failed to load test case";
179 time_point<high_resolution_clock> predictStart;
180 time_point<high_resolution_clock> predictEnd;
182 TestCaseResult result = TestCaseResult::Ok;
186 predictStart = high_resolution_clock::now();
190 predictEnd = high_resolution_clock::now();
192 // duration<double> will convert the time difference into seconds as a double by default.
193 double timeTakenS = duration<double>(predictEnd - predictStart).count();
194 totalTime += timeTakenS;
196 // Outputss inference times, if needed.
197 if (recordInferenceTimes)
199 inferenceTimesFile << testCaseId << " " << (timeTakenS * 1000.0) << std::endl;
202 result = testCase->ProcessResult(params);
205 catch (const TestFrameworkException& testError)
207 BOOST_LOG_TRIVIAL(error) << testError.what();
208 result = TestCaseResult::Abort;
213 case TestCaseResult::Ok:
215 case TestCaseResult::Abort:
217 case TestCaseResult::Failed:
218 // This test failed so we will fail the entire program eventually, but keep going for now.
222 BOOST_ASSERT_MSG(false, "Unexpected TestCaseResult");
227 const double averageTimePerTestCaseMs = totalTime / nbProcessed * 1000.0f;
229 BOOST_LOG_TRIVIAL(info) << std::fixed << std::setprecision(3) <<
230 "Total time for " << nbProcessed << " test cases: " << totalTime << " seconds";
231 BOOST_LOG_TRIVIAL(info) << std::fixed << std::setprecision(3) <<
232 "Average time per test case: " << averageTimePerTestCaseMs << " ms";
236 BOOST_LOG_TRIVIAL(error) << "One or more test cases failed";
240 return testCaseProvider.OnInferenceTestFinished();