Compute Library
 21.05
main.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2017-2021 Arm Limited.
3  *
4  * SPDX-License-Identifier: MIT
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to
8  * deal in the Software without restriction, including without limitation the
9  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10  * sell copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #include "support/StringSupport.h"
25 #include "tests/AssetsLibrary.h"
29 #include "tests/framework/Macros.h"
38 
39 #ifdef ARM_COMPUTE_CL
45 #include "utils/TypePrinter.h"
46 #endif /* ARM_COMPUTE_CL */
48 
49 #include <fstream>
50 #include <initializer_list>
51 #include <iostream>
52 #include <memory>
53 #include <random>
54 #include <utility>
55 
56 using namespace arm_compute;
57 using namespace arm_compute::test;
58 
59 namespace
60 {
61 std::string command_line(int argc, char **argv)
62 {
63  std::stringstream ss;
64  for(int i = 0; i < argc; i++)
65  {
66  ss << argv[i] << " ";
67  }
68  return ss.str();
69 }
70 } // namespace
71 namespace arm_compute
72 {
73 namespace test
74 {
75 std::unique_ptr<AssetsLibrary> library;
76 
77 static constexpr uint32_t fixed_seed = 1;
78 std::unique_ptr<AssetsLibrary> fixed_library;
79 
80 extern std::unique_ptr<ParametersLibrary> parameters;
81 } // namespace test
82 } // namespace arm_compute
83 
84 namespace
85 {
86 #ifdef ARM_COMPUTE_CL
87 bool file_exists(const std::string &filename)
88 {
89  std::ifstream file(filename);
90  return file.good();
91 }
92 #endif /* ARM_COMPUTE_CL */
93 } //namespace
94 
95 int main(int argc, char **argv)
96 {
98 
100 
101  std::set<framework::DatasetMode> allowed_modes
102  {
107  };
108 
110 
111  auto dataset_mode = parser.add_option<utils::EnumOption<framework::DatasetMode>>("mode", allowed_modes, framework::DatasetMode::PRECOMMIT);
112  dataset_mode->set_help("For managed datasets select which group to use");
113  auto filter = parser.add_option<utils::SimpleOption<std::string>>("filter", ".*");
114  filter->set_help("Regular expression to select test cases");
115  auto filter_id = parser.add_option<utils::SimpleOption<std::string>>("filter-id");
116  filter_id->set_help("List of test ids. ... can be used to define a range.");
117  auto stop_on_error = parser.add_option<utils::ToggleOption>("stop-on-error");
118  stop_on_error->set_help("Abort execution after the first failed test (useful for debugging)");
119  auto seed = parser.add_option<utils::SimpleOption<std::random_device::result_type>>("seed", std::random_device()());
120  seed->set_help("Global seed for random number generation");
121  auto list_tests = parser.add_option<utils::ToggleOption>("list-tests", false);
122  list_tests->set_help("List all test names");
123  auto test_instruments = parser.add_option<utils::ToggleOption>("test-instruments", false);
124  test_instruments->set_help("Test if the instruments work on the platform");
125  auto error_on_missing_assets = parser.add_option<utils::ToggleOption>("error-on-missing-assets", false);
126  error_on_missing_assets->set_help("Mark a test as failed instead of skipping it when assets are missing");
127  auto assets = parser.add_positional_option<utils::SimpleOption<std::string>>("assets");
128  assets->set_help("Path to the assets directory");
129 #ifdef ARM_COMPUTE_CL
130  auto enable_tuner = parser.add_option<utils::ToggleOption>("enable-tuner");
131  enable_tuner->set_help("Enable OpenCL dynamic tuner");
132 
133  const std::set<CLTunerMode> supported_tuner_modes
134  {
138  };
139  auto tuner_mode = parser.add_option<utils::EnumOption<CLTunerMode>>("tuner-mode", supported_tuner_modes, CLTunerMode::NORMAL);
140  tuner_mode->set_help("Configures the time taken by the tuner to tune. Slow tuner produces the most performant LWS configuration");
141 
142  auto tuner_file = parser.add_option<utils::SimpleOption<std::string>>("tuner-file", "");
143  tuner_file->set_help("File to load/save CLTuner values");
144 
145  auto mlgo_file = parser.add_option<utils::SimpleOption<std::string>>("mlgo-file", "");
146  mlgo_file->set_help("File to load MLGO heuristics");
147 #endif /* ARM_COMPUTE_CL */
148  auto threads = parser.add_option<utils::SimpleOption<int>>("threads", 1);
149  threads->set_help("Number of threads to use");
150  auto cooldown_sec = parser.add_option<utils::SimpleOption<float>>("delay", -1.f);
151  cooldown_sec->set_help("Delay to add between test executions in seconds");
152  auto configure_only = parser.add_option<utils::ToggleOption>("configure-only", false);
153  configure_only->set_help("Only configures kernels, without allocating, running or validating. Needed in order to validate OpenCL kernel run-time compilation, without necessarily running or validating the kernels' execution");
154 
155  try
156  {
157  parser.parse(argc, argv);
158 
159  if(options.help->is_set() && options.help->value())
160  {
161  parser.print_help(argv[0]);
162  return 0;
163  }
164 
165  std::vector<std::unique_ptr<framework::Printer>> printers = options.create_printers();
166 
167  // Setup CPU Scheduler
168  Scheduler::get().set_num_threads(threads->value());
169 
170  // Create CPU context
171  auto cpu_ctx = std::make_unique<RuntimeContext>();
172  cpu_ctx->set_scheduler(&Scheduler::get());
173 
174  // Track CPU context
175  auto cpu_ctx_track = std::make_unique<ContextSchedulerUser>(cpu_ctx.get());
176 
177  // Create parameters
178  parameters = std::make_unique<ParametersLibrary>();
179  parameters->set_cpu_ctx(std::move(cpu_ctx));
180 
181 #ifdef ARM_COMPUTE_CL
182  CLTuner cl_tuner(false);
183  CLGEMMHeuristicsHandle gemm_heuristics;
184  if(opencl_is_available())
185  {
187  ARM_COMPUTE_ERROR_ON_MSG(std::get<2>(ctx_dev_err) != CL_SUCCESS, "Failed to create OpenCL context");
188  gemm_heuristics.reload_from_file(mlgo_file->value());
189  CLScheduler::get().default_init_with_context(std::get<1>(ctx_dev_err), std::get<0>(ctx_dev_err), &cl_tuner, &gemm_heuristics);
190  }
191 
192  if(enable_tuner->is_set())
193  {
194  cl_tuner.set_tune_new_kernels(enable_tuner->value());
195 
196  //set tuner mode
197  cl_tuner.set_tuner_mode(tuner_mode->value());
198 
199  // If that's the first run then the file won't exist yet
200  if(file_exists(tuner_file->value()))
201  {
202  cl_tuner.load_from_file(tuner_file->value());
203  }
204  }
205  else if(!tuner_file->value().empty())
206  {
207  //If we're not tuning and the file doesn't exist then we should raise an error:
208  cl_tuner.load_from_file(tuner_file->value());
209  }
210 #endif /* ARM_COMPUTE_CL */
211  if(options.log_level->value() > framework::LogLevel::NONE)
212  {
213  for(auto &p : printers)
214  {
215  p->print_global_header();
216  }
217  }
218 
220  {
221  for(auto &p : printers)
222  {
223  p->print_entry("Version", build_information());
224  p->print_entry("CommandLine", command_line(argc, argv));
225  p->print_entry("Seed", support::cpp11::to_string(seed->value()));
226 #ifdef ARM_COMPUTE_CL
227  if(opencl_is_available())
228  {
229  p->print_entry("CL_DEVICE_VERSION", CLKernelLibrary::get().get_device_version());
230  }
231  else
232  {
233  p->print_entry("CL_DEVICE_VERSION", "Unavailable");
234  }
235 #endif /* ARM_COMPUTE_CL */
236  const arm_compute::CPUInfo &cpu_info = Scheduler::get().cpu_info();
237  const unsigned int num_cpus = cpu_info.get_cpu_num();
238  p->print_entry("cpu_has_fp16", support::cpp11::to_string(cpu_info.has_fp16()));
239  p->print_entry("cpu_has_dotprod", support::cpp11::to_string(cpu_info.has_dotprod()));
240 
241  for(unsigned int j = 0; j < num_cpus; ++j)
242  {
243  const CPUModel model = cpu_info.get_cpu_model(j);
244  p->print_entry("CPU" + support::cpp11::to_string(j), cpu_model_to_string(model));
245  }
246  p->print_entry("Iterations", support::cpp11::to_string(options.iterations->value()));
247  p->print_entry("Threads", support::cpp11::to_string(threads->value()));
248  {
250  p->print_entry("Dataset mode", to_string(dataset_mode->value()));
251  }
252  }
253  }
254 
255  // Setup instruments meta-data
257  instruments_info._scheduler_users.push_back(cpu_ctx_track.get());
259 
260  // Initialize framework
262  fconfig.instruments = options.instruments->value();
263  fconfig.name_filter = filter->value();
264  fconfig.id_filter = filter_id->value();
265  fconfig.num_iterations = options.iterations->value();
266  fconfig.mode = dataset_mode->value();
267  fconfig.log_level = options.log_level->value();
268  fconfig.cooldown_sec = cooldown_sec->value();
269  fconfig.configure_only = configure_only->value();
270  framework.init(fconfig);
271 
272  for(auto &p : printers)
273  {
274  framework.add_printer(p.get());
275  }
276  framework.set_throw_errors(options.throw_errors->value());
277  framework.set_stop_on_error(stop_on_error->value());
278  framework.set_error_on_missing_assets(error_on_missing_assets->value());
279 
280  bool success = true;
281 
282  if(list_tests->value())
283  {
284  for(auto &p : printers)
285  {
286  p->print_list_tests(framework.test_infos());
287  p->print_global_footer();
288  }
289 
290  return 0;
291  }
292 
293  if(test_instruments->value())
294  {
295  framework::Profiler profiler = framework.get_profiler();
296  profiler.start();
297  profiler.stop();
298  for(auto &p : printers)
299  {
300  p->print_measurements(profiler.measurements());
301  }
302 
303  return 0;
304  }
305 
306  library = std::make_unique<AssetsLibrary>(assets->value(), seed->value());
307  fixed_library = std::make_unique<AssetsLibrary>(assets->value(), fixed_seed);
308 
309  if(!parser.validate())
310  {
311  return 1;
312  }
313 
314  success = framework.run();
315 
316  if(options.log_level->value() > framework::LogLevel::NONE)
317  {
318  for(auto &p : printers)
319  {
320  p->print_global_footer();
321  }
322  }
323 
324 #ifdef ARM_COMPUTE_CL
325  if(opencl_is_available())
326  {
328  if(enable_tuner->is_set() && enable_tuner->value() && tuner_file->is_set())
329  {
330  cl_tuner.save_to_file(tuner_file->value());
331  }
332  }
333 #endif /* ARM_COMPUTE_CL */
334 
335  return (success ? 0 : 1);
336  }
337  catch(const std::exception &error)
338  {
339  std::cerr << error.what() << "\n";
340 
341  if(options.throw_errors->value())
342  {
343  throw;
344  }
345 
346  return 1;
347  }
348  return 0;
349 }
Basic implementation of the OpenCL tuner interface.
Definition: CLTuner.h:40
Framework configuration structure.
Definition: Framework.h:57
void set_tuner_mode(CLTunerMode mode)
Set OpenCL tuner mode.
Definition: CLTuner.cpp:61
arm_compute::utils::ToggleOption * help
Show help option.
Definition: CommonOptions.h:74
int main(int argc, char **argv)
Definition: main.cpp:95
int num_iterations
Number of iterations per test.
Definition: Framework.h:63
static CLScheduler & get()
Access the scheduler singleton.
Profiler class to collect benchmark numbers.
Definition: Profiler.h:45
virtual void set_num_threads(unsigned int num_threads)=0
Sets the number of threads the scheduler will use to run the kernels.
void default_init_with_context(cl::Device &device, cl::Context &ctx, ICLTuner *cl_tuner=nullptr, CLGEMMHeuristicsHandle *gemm_h=nullptr)
Initialises the scheduler with context and device provided by the user.
std::string to_string(T &&value)
Convert integer and float values to string.
void load_from_file(const std::string &filename)
Load the tuning parameters table from file.
Definition: CLTuner.cpp:280
bool has_fp16() const
Checks if the cpu model supports fp16.
Definition: CPPTypes.cpp:69
void set_throw_errors(bool throw_errors)
Set whether errors are caught or thrown by the framework.
Definition: Framework.cpp:264
Implementation of an option that can be either true or false.
Definition: ToggleOption.h:36
const std::vector< T > & value() const
Get the values of the option.
void set_instruments_info(InstrumentsInfo instr_info)
Sets instruments info.
Definition: Framework.cpp:700
std::unique_ptr< InstrumentsInfo > instruments_info
Definition: Framework.cpp:50
std::stringstream ss(mlgo_str)
static CLKernelLibrary & get()
Access the KernelLibrary singleton.
CPUModel
CPU models - we only need to detect CPUs we have microarchitecture-specific code for.
Definition: CPPTypes.h:40
CPUInfo & cpu_info()
Get CPU info.
Definition: IScheduler.cpp:42
std::tuple< cl::Context, cl::Device, cl_int > create_opencl_context_and_device(CLBackendType cl_backend_type)
This function creates an OpenCL context and a device.
Definition: CLHelpers.cpp:126
void set_error_on_missing_assets(bool error_on_missing_assets)
Set whether a test should be considered as failed if its assets cannot be found.
Definition: Framework.cpp:284
Class to parse command line arguments.
Copyright (c) 2017-2021 Arm Limited.
CPUModel get_cpu_model(unsigned int cpuid) const
Gets the cpu model for a given cpuid.
Definition: CPPTypes.cpp:79
float cooldown_sec
Delay between tests in seconds.
Definition: Framework.h:64
static Framework & get()
Access to the singleton.
Definition: Framework.cpp:124
Searches a minimal subset of LWS configurations while tuning.
std::string cpu_model_to_string(CPUModel val)
Convert a cpumodel value to a string.
Definition: CPPTypes.h:73
Interface to enqueue OpenCL kernels and get/set the OpenCL CommandQueue and ICLTuner.
std::string to_string(const ROIPoolingLayerInfo &pool_info)
Formatted output of the ROIPoolingInfo type.
Definition: TypePrinter.h:149
LogLevel log_level
Verbosity of the output.
Definition: Framework.h:65
bool run()
Run all enabled test cases.
Definition: Framework.cpp:541
std::vector< framework::InstrumentsDescription > instruments
Instrument types that will be used for benchmarking.
Definition: Framework.h:59
bool save_to_file(const std::string &filename) const
Save the content of the tuning parameters table to file.
Definition: CLTuner.cpp:332
std::vector< std::unique_ptr< Printer > > create_printers()
Create the printers based on parsed command line options.
std::vector< TestInfo > test_infos() const
List of TestInfo's.
Definition: Framework.cpp:674
std::string name_filter
Regular expression to filter tests by name.
Definition: Framework.h:60
std::unique_ptr< AssetsLibrary > library
Definition: main.cpp:75
bool reload_from_file(const std::string &filename)
(Re)Load the heuristics from reading a dotmlgo file
std::unique_ptr< ParametersLibrary > parameters
Definition: Framework.cpp:46
#define ARM_COMPUTE_ERROR_ON_MSG(cond, msg)
Definition: Error.h:456
void set_tune_new_kernels(bool tune_new_kernels)
Setter for tune_new_kernels option.
Definition: CLTuner.cpp:52
bool has_dotprod() const
Checks if the cpu model supports dot product.
Definition: CPPTypes.cpp:74
Profiler get_profiler() const
Factory method to obtain a configured profiler.
Definition: Framework.cpp:640
const T & value() const
Get the option value.
Definition: SimpleOption.h:112
const MeasurementsMap & measurements() const
Return measurements for all instruments.
Definition: Profiler.cpp:87
unsigned int get_cpu_num() const
Return the maximum number of CPUs present.
Definition: CPPTypes.cpp:59
arm_compute::utils::SimpleOption< int > * iterations
Number of iterations option.
Definition: CommonOptions.h:76
const T & value() const
Get the selected value.
Definition: EnumOption.h:130
arm_compute::utils::EnumListOption< InstrumentsDescription > * instruments
Instruments option.
Definition: CommonOptions.h:75
void sync()
Blocks until all commands in the associated command queue have finished.
Definition: CLScheduler.cpp:70
Handle for loading and retrieving GEMM heuristics.
arm_compute::utils::EnumOption< LogLevel > * log_level
Logging level option.
Definition: CommonOptions.h:79
std::string id_filter
String to match selected test ids.
Definition: Framework.h:61
Implementation of a simple option that accepts a value from a fixed set.
Definition: EnumOption.h:40
void start()
Call start() on all the added instruments.
Definition: Profiler.cpp:48
Wrapper to configure the Khronos OpenCL C++ header.
std::string build_information()
Returns the arm_compute library build information.
bool configure_only
Only configure kernels.
Definition: Framework.h:66
void add_printer(Printer *printer)
Set the printer used for the output of test results.
Definition: Framework.cpp:669
void stop()
Call stop() on all the added instruments.
Definition: Profiler.cpp:56
bool is_set() const
Has a value been assigned to the option?
Definition: Option.h:135
Common command line options used to configure the framework.
Definition: CommonOptions.h:54
Searches all possible LWS configurations while tuning.
void set_stop_on_error(bool stop_on_error)
Set whether to abort execution after the first failed test.
Definition: Framework.cpp:274
void set_help(std::string help)
Set the help message for the option.
Definition: Option.h:125
void init(const FrameworkConfig &config)
Init the framework.
Definition: Framework.cpp:130
bool opencl_is_available()
Check if OpenCL is available.
Definition: OpenCL.cpp:154
static IScheduler & get()
Access the scheduler singleton.
Definition: Scheduler.cpp:94
std::unique_ptr< AssetsLibrary > fixed_library
Definition: main.cpp:78
arm_compute::utils::ToggleOption * throw_errors
Throw errors option.
Definition: CommonOptions.h:80