1 /*
2 * Copyright (c) 2017-2022 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 "arm_compute/runtime/CL/CLTuner.h"
25 #include "arm_compute/runtime/CL/tuners/CLTuningParametersList.h"
26
27 #include "arm_compute/core/Error.h"
28 #include "arm_compute/runtime/CL/CLScheduler.h"
29 #include "src/core/CL/ICLKernel.h"
30 #include "support/StringSupport.h"
31
32 #include <cerrno>
33 #include <fstream>
34 #include <limits>
35
36 namespace arm_compute
37 {
CLTuner(bool tune_new_kernels,CLTuningInfo tuning_info)38 CLTuner::CLTuner(bool tune_new_kernels, CLTuningInfo tuning_info)
39 : real_clEnqueueNDRangeKernel(nullptr), _tuning_params_table(), _lws_table(), _kernel_event(), _tune_new_kernels(tune_new_kernels), _tuning_info(tuning_info)
40 {
41 }
42
43 struct CLTuner::IKernelData
44 {
45 virtual ~IKernelData() = default;
46 virtual void do_run(ICLKernel &kernel, cl::CommandQueue &queue) = 0;
47 };
48 struct DefaultKernelData : public CLTuner::IKernelData
49 {
DefaultKernelDataarm_compute::DefaultKernelData50 DefaultKernelData(ITensorPack &tensors)
51 : _tensors{ tensors }
52 {
53 }
54 ~DefaultKernelData() override = default;
do_runarm_compute::DefaultKernelData55 void do_run(ICLKernel &kernel, cl::CommandQueue &queue) override
56 {
57 const bool inject_memory = !_tensors.empty();
58 inject_memory ? kernel.run_op(_tensors, kernel.window(), queue) : kernel.run(kernel.window(), queue);
59 }
60
61 private:
62 ITensorPack &_tensors;
63 };
64
kernel_event_is_set() const65 bool CLTuner::kernel_event_is_set() const
66 {
67 return _kernel_event() != nullptr;
68 }
set_cl_kernel_event(cl_event kernel_event)69 void CLTuner::set_cl_kernel_event(cl_event kernel_event)
70 {
71 _kernel_event = kernel_event;
72 }
73
set_tune_new_kernels(bool tune_new_kernels)74 void CLTuner::set_tune_new_kernels(bool tune_new_kernels)
75 {
76 _tune_new_kernels = tune_new_kernels;
77 }
tune_new_kernels() const78 bool CLTuner::tune_new_kernels() const
79 {
80 return _tune_new_kernels;
81 }
82
set_tuner_mode(CLTunerMode mode)83 void CLTuner::set_tuner_mode(CLTunerMode mode)
84 {
85 _tuning_info.tuner_mode = mode;
86 }
87
tune_kernel_static(ICLKernel & kernel)88 void CLTuner::tune_kernel_static(ICLKernel &kernel)
89 {
90 ARM_COMPUTE_UNUSED(kernel);
91 }
92
tune_kernel_dynamic(ICLKernel & kernel)93 void CLTuner::tune_kernel_dynamic(ICLKernel &kernel)
94 {
95 ITensorPack pack;
96 tune_kernel_dynamic(kernel, pack);
97 }
98
do_tune_kernel_dynamic(ICLKernel & kernel,IKernelData * data)99 void CLTuner::do_tune_kernel_dynamic(ICLKernel &kernel, IKernelData *data)
100 {
101 // Get the configuration ID from the kernel and append GPU target name and number of available compute units
102 const std::string config_id = kernel.config_id() + "_" + string_from_target(kernel.get_target()) + "_MP" + support::cpp11::to_string(CLKernelLibrary::get().get_num_compute_units());
103
104 // Check if we need to find the Optimal LWS. If the kernel's config_id is equal to default_config_id, the kernel does not require to be tuned
105 if(kernel.config_id() != arm_compute::default_config_id)
106 {
107 auto p = _tuning_params_table.find(config_id);
108
109 if(p == _tuning_params_table.end())
110 {
111 if(_tune_new_kernels)
112 {
113 // Find the optimal LWS for the kernel
114 CLTuningParams opt_tuning_params = find_optimal_tuning_params(kernel, data);
115
116 // Insert the optimal LWS in the table
117 add_tuning_params(config_id, opt_tuning_params);
118
119 // Set Local-Workgroup-Size
120 kernel.set_lws_hint(opt_tuning_params.get_lws());
121 if(_tuning_info.tune_wbsm)
122 {
123 kernel.set_wbsm_hint(opt_tuning_params.get_wbsm());
124 }
125 }
126 }
127 else
128 {
129 // Set Local-Workgroup-Size
130 kernel.set_lws_hint(p->second.get_lws());
131 if(_tuning_info.tune_wbsm)
132 {
133 kernel.set_wbsm_hint(p->second.get_wbsm());
134 }
135 }
136 }
137 }
tune_kernel_dynamic(ICLKernel & kernel,ITensorPack & tensors)138 void CLTuner::tune_kernel_dynamic(ICLKernel &kernel, ITensorPack &tensors)
139 {
140 DefaultKernelData data{ tensors };
141
142 do_tune_kernel_dynamic(kernel, &data);
143 }
144
add_tuning_params(const std::string & kernel_id,CLTuningParams optimal_tuning_params)145 void CLTuner::add_tuning_params(const std::string &kernel_id, CLTuningParams optimal_tuning_params)
146 {
147 _tuning_params_table.emplace(kernel_id, optimal_tuning_params);
148 }
149
find_optimal_tuning_params(ICLKernel & kernel,IKernelData * data)150 CLTuningParams CLTuner::find_optimal_tuning_params(ICLKernel &kernel, IKernelData *data)
151 {
152 // Profiling queue
153 cl::CommandQueue queue_profiler;
154
155 // Extract real OpenCL function to intercept
156 if(real_clEnqueueNDRangeKernel == nullptr)
157 {
158 real_clEnqueueNDRangeKernel = CLSymbols::get().clEnqueueNDRangeKernel_ptr;
159 }
160
161 // Get the default queue
162 cl::CommandQueue default_queue = CLScheduler::get().queue();
163
164 // Check if we can use the OpenCL timer with the default queue
165 cl_command_queue_properties props = default_queue.getInfo<CL_QUEUE_PROPERTIES>();
166
167 if((props & CL_QUEUE_PROFILING_ENABLE) == 0)
168 {
169 // Set the queue for profiling
170 queue_profiler = cl::CommandQueue(CLScheduler::get().context(), props | CL_QUEUE_PROFILING_ENABLE);
171 }
172 else
173 {
174 queue_profiler = default_queue;
175 }
176
177 // Start intercepting enqueues:
178 auto interceptor = [this](cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, const size_t *gwo, const size_t *gws, const size_t *lws, cl_uint num_events_in_wait_list,
179 const cl_event * event_wait_list, cl_event * event)
180 {
181 if(this->kernel_event_is_set())
182 {
183 // If the event is already set it means the kernel enqueue is sliced: given that we only time the first slice we can save time by skipping the other enqueues.
184 return CL_SUCCESS;
185 }
186 cl_event tmp;
187 cl_int retval = this->real_clEnqueueNDRangeKernel(command_queue, kernel, work_dim, gwo, gws, lws, num_events_in_wait_list, event_wait_list, &tmp);
188
189 // Set OpenCL event
190 this->set_cl_kernel_event(tmp);
191
192 if(event != nullptr)
193 {
194 //return cl_event from the intercepted call
195 clRetainEvent(tmp);
196 *event = tmp;
197 }
198 return retval;
199 };
200 CLSymbols::get().clEnqueueNDRangeKernel_ptr = interceptor;
201
202 cl::NDRange gws = ICLKernel::gws_from_window(kernel.window());
203
204 // Run the kernel with default lws to be used as baseline
205 data->do_run(kernel, queue_profiler);
206
207 queue_profiler.finish();
208
209 const cl_ulong start = _kernel_event.getProfilingInfo<CL_PROFILING_COMMAND_START>();
210 const cl_ulong end = _kernel_event.getProfilingInfo<CL_PROFILING_COMMAND_END>();
211 cl_ulong min_exec_time = end - start;
212 _kernel_event = nullptr;
213
214 CLTuningParams opt_tuning_params(cl::NullRange, 0);
215
216 // Construct the list of tuning parameters values to be tested based on the tuner mode.
217 auto tuning_list = cl_tuner::get_tuning_parameters_list(_tuning_info, gws);
218 for(size_t i = 0; i < tuning_list->size(); ++i)
219 {
220 CLTuningParams tuning_test = (*tuning_list)[i];
221 // Setting the lws
222 cl::NDRange lws_test = tuning_test.get_lws();
223 auto x = lws_test[0];
224 auto y = lws_test[1];
225 auto z = lws_test[2];
226 const bool invalid_lws = (x * y * z > kernel.get_max_workgroup_size()) || (x == 1 && y == 1 && z == 1);
227
228 if(invalid_lws)
229 {
230 continue;
231 }
232
233 kernel.set_lws_hint(lws_test);
234 if(_tuning_info.tune_wbsm && CLKernelLibrary::get().is_wbsm_supported())
235 {
236 cl_int wbsm_test = tuning_test.get_wbsm();
237 kernel.set_wbsm_hint(wbsm_test);
238 }
239
240 // Run the kernel
241 data->do_run(kernel, queue_profiler);
242
243 queue_profiler.finish();
244
245 const cl_ulong start = _kernel_event.getProfilingInfo<CL_PROFILING_COMMAND_START>();
246 const cl_ulong end = _kernel_event.getProfilingInfo<CL_PROFILING_COMMAND_END>();
247 const cl_ulong diff = end - start;
248 _kernel_event = nullptr;
249
250 // Check the execution time
251 if(diff < min_exec_time)
252 {
253 min_exec_time = diff;
254 opt_tuning_params.set_lws(tuning_test.get_lws());
255 if(_tuning_info.tune_wbsm)
256 {
257 opt_tuning_params.set_wbsm(tuning_test.get_wbsm());
258 }
259 }
260 }
261
262 // Restore real function
263 CLSymbols::get().clEnqueueNDRangeKernel_ptr = real_clEnqueueNDRangeKernel;
264 return opt_tuning_params;
265 }
266
tuning_params_table() const267 const std::unordered_map<std::string, CLTuningParams> &CLTuner::tuning_params_table() const
268 {
269 return _tuning_params_table;
270 }
271
import_tuning_params(const std::unordered_map<std::string,CLTuningParams> & tuning_params_table)272 void CLTuner::import_tuning_params(const std::unordered_map<std::string, CLTuningParams> &tuning_params_table)
273 {
274 _tuning_params_table.clear();
275 _tuning_params_table = tuning_params_table;
276 }
277
load_from_file(const std::string & filename)278 void CLTuner::load_from_file(const std::string &filename)
279 {
280 std::ifstream fs;
281 fs.exceptions(std::ifstream::badbit);
282 fs.open(filename, std::ios::in);
283 if(!fs.is_open())
284 {
285 ARM_COMPUTE_ERROR_VAR("Failed to open '%s' (%s [%d])", filename.c_str(), strerror(errno), errno);
286 }
287 std::string line;
288 bool header_line = true;
289 while(!std::getline(fs, line).fail())
290 {
291 if(header_line)
292 {
293 header_line = false;
294 size_t pos_lws = line.find("lws");
295 size_t pos_wbsm = line.find("wbsm");
296 _tuning_info.tune_wbsm = false;
297 if(pos_lws != std::string::npos || pos_wbsm != std::string::npos)
298 {
299 // The file has in the first line the parameters it has been tuned on
300 if(pos_wbsm != std::string::npos)
301 {
302 _tuning_info.tune_wbsm = true;
303 }
304 // Once the line with the tuning parameter is read we can
305 // read the next one to start collecting the values
306 if(std::getline(fs, line).fail())
307 {
308 break;
309 }
310 }
311 }
312
313 CLTuningParams tuning_params;
314 size_t pos = line.find(";");
315 if(pos == std::string::npos)
316 {
317 ARM_COMPUTE_ERROR_VAR("Malformed row '%s' in %s", line.c_str(), filename.c_str());
318 }
319 std::string kernel_id = line.substr(0, pos);
320 line.erase(0, pos + 1);
321 if(!tuning_params.from_string(_tuning_info, line))
322 {
323 ARM_COMPUTE_ERROR_VAR("Malformed row '%s' in %s", line.c_str(), filename.c_str());
324 }
325 add_tuning_params(kernel_id, tuning_params);
326 }
327 fs.close();
328 }
329
save_to_file(const std::string & filename) const330 bool CLTuner::save_to_file(const std::string &filename) const
331 {
332 if(!_tune_new_kernels || _tuning_params_table.empty() || filename.empty())
333 {
334 return false;
335 }
336 std::ofstream fs;
337 fs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
338 fs.open(filename, std::ios::out);
339 std::string header_string = "";
340 header_string += "lws";
341 if(_tuning_info.tune_wbsm)
342 {
343 if(!header_string.empty())
344 {
345 header_string += " ";
346 }
347 header_string += "wbsm";
348 }
349 fs << header_string << std::endl;
350 for(auto const &kernel_data : _tuning_params_table)
351 {
352 CLTuningParams tun_pams(kernel_data.second);
353 fs << kernel_data.first << tun_pams.to_string(_tuning_info) << std::endl;
354 }
355 fs.close();
356 return true;
357 }
358 } // namespace arm_compute
359