2 // Copyright © 2017 Arm Ltd. All rights reserved.
3 // SPDX-License-Identifier: MIT
5 #include "InferenceTest.hpp"
7 #include <armnn/utility/Assert.hpp>
8 #include <Filesystem.hpp>
10 #include "../src/armnn/Profiling.hpp"
11 #include <cxxopts/cxxopts.hpp>
19 using namespace std::chrono;
20 using namespace armnn::test;
26 /// Parse the command line of an ArmNN (or referencetests) inference test program.
27 /// \return false if any error occurred during options processing, otherwise true
28 bool ParseCommandLine(int argc, char** argv, IInferenceTestCaseProvider& testCaseProvider,
29 InferenceTestOptions& outParams)
31 cxxopts::Options options("InferenceTest", "Inference iteration parameters");
35 // Adds generic options needed for all inference tests.
37 .allow_unrecognised_options()
39 ("h,help", "Display help messages")
40 ("i,iterations", "Sets the number of inferences to perform. If unset, will only be run once.",
41 cxxopts::value<unsigned int>(outParams.m_IterationCount)->default_value("0"))
42 ("inference-times-file",
43 "If non-empty, each individual inference time will be recorded and output to this file",
44 cxxopts::value<std::string>(outParams.m_InferenceTimesFile)->default_value(""))
45 ("e,event-based-profiling", "Enables built in profiler. If unset, defaults to off.",
46 cxxopts::value<bool>(outParams.m_EnableProfiling)->default_value("0"));
48 std::vector<std::string> required; //to be passed as reference to derived inference tests
50 // Adds options specific to the ITestCaseProvider.
51 testCaseProvider.AddCommandLineOptions(options, required);
53 auto result = options.parse(argc, argv);
55 if (result.count("help"))
57 std::cout << options.help() << std::endl;
61 CheckRequiredOptions(result, required);
64 catch (const cxxopts::OptionException& e)
66 std::cerr << e.what() << std::endl << options.help() << std::endl;
69 catch (const std::exception& e)
71 // Coverity points out that default_value(...) can throw a bad_lexical_cast,
72 // and that desc.add_options() can throw boost::io::too_few_args.
73 // They really won't in any of these cases.
74 ARMNN_ASSERT_MSG(false, "Caught unexpected exception");
75 std::cerr << "Fatal internal error: " << e.what() << std::endl;
79 if (!testCaseProvider.ProcessCommandLineOptions(outParams))
87 bool ValidateDirectory(std::string& dir)
91 std::cerr << "No directory specified" << std::endl;
95 if (dir[dir.length() - 1] != '/')
100 if (!fs::exists(dir))
102 std::cerr << "Given directory " << dir << " does not exist" << std::endl;
106 if (!fs::is_directory(dir))
108 std::cerr << "Given directory [" << dir << "] is not a directory" << std::endl;
115 bool InferenceTest(const InferenceTestOptions& params,
116 const std::vector<unsigned int>& defaultTestCaseIds,
117 IInferenceTestCaseProvider& testCaseProvider)
119 #if !defined (NDEBUG)
120 if (params.m_IterationCount > 0) // If just running a few select images then don't bother to warn.
122 ARMNN_LOG(warning) << "Performance test running in DEBUG build - results may be inaccurate.";
126 double totalTime = 0;
127 unsigned int nbProcessed = 0;
130 // Opens the file to write inference times too, if needed.
131 ofstream inferenceTimesFile;
132 const bool recordInferenceTimes = !params.m_InferenceTimesFile.empty();
133 if (recordInferenceTimes)
135 inferenceTimesFile.open(params.m_InferenceTimesFile.c_str(), ios_base::trunc | ios_base::out);
136 if (!inferenceTimesFile.good())
138 ARMNN_LOG(error) << "Failed to open inference times file for writing: "
139 << params.m_InferenceTimesFile;
144 // Create a profiler and register it for the current thread.
145 std::unique_ptr<Profiler> profiler = std::make_unique<Profiler>();
146 ProfilerManager::GetInstance().RegisterProfiler(profiler.get());
148 // Enable profiling if requested.
149 profiler->EnableProfiling(params.m_EnableProfiling);
151 // Run a single test case to 'warm-up' the model. The first one can sometimes take up to 10x longer
152 std::unique_ptr<IInferenceTestCase> warmupTestCase = testCaseProvider.GetTestCase(0);
153 if (warmupTestCase == nullptr)
155 ARMNN_LOG(error) << "Failed to load test case";
161 warmupTestCase->Run();
163 catch (const TestFrameworkException& testError)
165 ARMNN_LOG(error) << testError.what();
169 const unsigned int nbTotalToProcess = params.m_IterationCount > 0 ? params.m_IterationCount
170 : static_cast<unsigned int>(defaultTestCaseIds.size());
172 for (; nbProcessed < nbTotalToProcess; nbProcessed++)
174 const unsigned int testCaseId = params.m_IterationCount > 0 ? nbProcessed : defaultTestCaseIds[nbProcessed];
175 std::unique_ptr<IInferenceTestCase> testCase = testCaseProvider.GetTestCase(testCaseId);
177 if (testCase == nullptr)
179 ARMNN_LOG(error) << "Failed to load test case";
183 time_point<high_resolution_clock> predictStart;
184 time_point<high_resolution_clock> predictEnd;
186 TestCaseResult result = TestCaseResult::Ok;
190 predictStart = high_resolution_clock::now();
194 predictEnd = high_resolution_clock::now();
196 // duration<double> will convert the time difference into seconds as a double by default.
197 double timeTakenS = duration<double>(predictEnd - predictStart).count();
198 totalTime += timeTakenS;
200 // Outputss inference times, if needed.
201 if (recordInferenceTimes)
203 inferenceTimesFile << testCaseId << " " << (timeTakenS * 1000.0) << std::endl;
206 result = testCase->ProcessResult(params);
209 catch (const TestFrameworkException& testError)
211 ARMNN_LOG(error) << testError.what();
212 result = TestCaseResult::Abort;
217 case TestCaseResult::Ok:
219 case TestCaseResult::Abort:
221 case TestCaseResult::Failed:
222 // This test failed so we will fail the entire program eventually, but keep going for now.
226 ARMNN_ASSERT_MSG(false, "Unexpected TestCaseResult");
231 const double averageTimePerTestCaseMs = totalTime / nbProcessed * 1000.0f;
233 ARMNN_LOG(info) << std::fixed << std::setprecision(3) <<
234 "Total time for " << nbProcessed << " test cases: " << totalTime << " seconds";
235 ARMNN_LOG(info) << std::fixed << std::setprecision(3) <<
236 "Average time per test case: " << averageTimePerTestCaseMs << " ms";
238 // if profiling is enabled print out the results
239 if (profiler && profiler->IsProfilingEnabled())
241 profiler->Print(std::cout);
246 ARMNN_LOG(error) << "One or more test cases failed";
250 return testCaseProvider.OnInferenceTestFinished();