1 /*
2 * Copyright (c) 2017-2020 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/CLLWSList.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 <iostream>
35 #include <limits>
36 #include <memory>
37 #include <string>
38
39 namespace arm_compute
40 {
CLTuner(bool tune_new_kernels)41 CLTuner::CLTuner(bool tune_new_kernels)
42 : real_clEnqueueNDRangeKernel(nullptr), _lws_table(), _kernel_event(), _tune_new_kernels(tune_new_kernels), _tuner_mode(CLTunerMode::NORMAL)
43 {
44 }
45
kernel_event_is_set() const46 bool CLTuner::kernel_event_is_set() const
47 {
48 return _kernel_event() != nullptr;
49 }
set_cl_kernel_event(cl_event kernel_event)50 void CLTuner::set_cl_kernel_event(cl_event kernel_event)
51 {
52 _kernel_event = kernel_event;
53 }
54
set_tune_new_kernels(bool tune_new_kernels)55 void CLTuner::set_tune_new_kernels(bool tune_new_kernels)
56 {
57 _tune_new_kernels = tune_new_kernels;
58 }
tune_new_kernels() const59 bool CLTuner::tune_new_kernels() const
60 {
61 return _tune_new_kernels;
62 }
63
set_tuner_mode(CLTunerMode mode)64 void CLTuner::set_tuner_mode(CLTunerMode mode)
65 {
66 _tuner_mode = mode;
67 }
get_tuner_mode() const68 CLTunerMode CLTuner::get_tuner_mode() const
69 {
70 return _tuner_mode;
71 }
72
tune_kernel_static(ICLKernel & kernel)73 void CLTuner::tune_kernel_static(ICLKernel &kernel)
74 {
75 ARM_COMPUTE_UNUSED(kernel);
76 }
77
tune_kernel_dynamic(ICLKernel & kernel)78 void CLTuner::tune_kernel_dynamic(ICLKernel &kernel)
79 {
80 ITensorPack pack;
81 tune_kernel_dynamic(kernel, pack);
82 }
83
tune_kernel_dynamic(ICLKernel & kernel,ITensorPack & tensors)84 void CLTuner::tune_kernel_dynamic(ICLKernel &kernel, ITensorPack &tensors)
85 {
86 // Get the configuration ID from the kernel and append GPU target name and number of available compute units
87 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());
88
89 // 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
90 if(kernel.config_id() != arm_compute::default_config_id)
91 {
92 auto p = _lws_table.find(config_id);
93
94 if(p == _lws_table.end())
95 {
96 if(_tune_new_kernels)
97 {
98 // Find the optimal LWS for the kernel
99 cl::NDRange opt_lws = find_optimal_lws(kernel, tensors);
100
101 // Insert the optimal LWS in the table
102 add_lws_to_table(config_id, opt_lws);
103
104 // Set Local-Workgroup-Size
105 kernel.set_lws_hint(opt_lws);
106 }
107 }
108 else
109 {
110 // Set Local-Workgroup-Size
111 kernel.set_lws_hint(p->second);
112 }
113 }
114 }
115
add_lws_to_table(const std::string & kernel_id,cl::NDRange optimal_lws)116 void CLTuner::add_lws_to_table(const std::string &kernel_id, cl::NDRange optimal_lws)
117 {
118 _lws_table.emplace(kernel_id, optimal_lws);
119 }
120
find_optimal_lws(ICLKernel & kernel,ITensorPack & tensors)121 cl::NDRange CLTuner::find_optimal_lws(ICLKernel &kernel, ITensorPack &tensors)
122 {
123 // Profiling queue
124 cl::CommandQueue queue_profiler;
125
126 // Extract real OpenCL function to intercept
127 if(real_clEnqueueNDRangeKernel == nullptr)
128 {
129 real_clEnqueueNDRangeKernel = CLSymbols::get().clEnqueueNDRangeKernel_ptr;
130 }
131
132 // Get the default queue
133 cl::CommandQueue default_queue = CLScheduler::get().queue();
134
135 // Check if we can use the OpenCL timer with the default queue
136 cl_command_queue_properties props = default_queue.getInfo<CL_QUEUE_PROPERTIES>();
137
138 if((props & CL_QUEUE_PROFILING_ENABLE) == 0)
139 {
140 // Set the queue for profiling
141 queue_profiler = cl::CommandQueue(CLScheduler::get().context(), props | CL_QUEUE_PROFILING_ENABLE);
142 }
143 else
144 {
145 queue_profiler = default_queue;
146 }
147
148 // Start intercepting enqueues:
149 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,
150 const cl_event * event_wait_list, cl_event * event)
151 {
152 if(this->kernel_event_is_set())
153 {
154 // 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.
155 return CL_SUCCESS;
156 }
157 cl_event tmp;
158 cl_int retval = this->real_clEnqueueNDRangeKernel(command_queue, kernel, work_dim, gwo, gws, lws, num_events_in_wait_list, event_wait_list, &tmp);
159
160 // Set OpenCL event
161 this->set_cl_kernel_event(tmp);
162
163 if(event != nullptr)
164 {
165 //return cl_event from the intercepted call
166 clRetainEvent(tmp);
167 *event = tmp;
168 }
169 return retval;
170 };
171 CLSymbols::get().clEnqueueNDRangeKernel_ptr = interceptor;
172
173 cl::NDRange gws = ICLKernel::gws_from_window(kernel.window());
174
175 // Run the kernel with default lws to be used as baseline
176 const bool inject_memory = !tensors.empty();
177 inject_memory ? kernel.run_op(tensors, kernel.window(), queue_profiler) : kernel.run(kernel.window(), queue_profiler);
178
179 queue_profiler.finish();
180
181 const cl_ulong start = _kernel_event.getProfilingInfo<CL_PROFILING_COMMAND_START>();
182 const cl_ulong end = _kernel_event.getProfilingInfo<CL_PROFILING_COMMAND_END>();
183 cl_ulong min_exec_time = end - start;
184 _kernel_event = nullptr;
185
186 cl::NDRange opt_lws = cl::NullRange;
187
188 // Construct the list of LWS values to be tested based on the tuner mode.
189 auto lws_list = cl_tuner::CLLWSListFactory::get_lws_list(_tuner_mode, gws);
190 for(size_t i = 0; i < lws_list->size(); ++i)
191 {
192 cl::NDRange lws_test = (*lws_list)[i];
193 auto x = lws_test[0];
194 auto y = lws_test[1];
195 auto z = lws_test[2];
196 const bool invalid_lws = (x * y * z > kernel.get_max_workgroup_size()) || (x == 1 && y == 1 && z == 1);
197
198 if(invalid_lws)
199 {
200 continue;
201 }
202
203 //Set the Local-Workgroup-Size
204 kernel.set_lws_hint(lws_test);
205
206 // Run the kernel
207 inject_memory ? kernel.run_op(tensors, kernel.window(), queue_profiler) : kernel.run(kernel.window(), queue_profiler);
208
209 queue_profiler.finish();
210
211 const cl_ulong start = _kernel_event.getProfilingInfo<CL_PROFILING_COMMAND_START>();
212 const cl_ulong end = _kernel_event.getProfilingInfo<CL_PROFILING_COMMAND_END>();
213 const cl_ulong diff = end - start;
214 _kernel_event = nullptr;
215
216 // Check the execution time
217 if(diff < min_exec_time)
218 {
219 min_exec_time = diff;
220 opt_lws = cl::NDRange(x, y, z);
221 }
222 }
223
224 // Restore real function
225 CLSymbols::get().clEnqueueNDRangeKernel_ptr = real_clEnqueueNDRangeKernel;
226
227 return opt_lws;
228 }
229
import_lws_table(const std::unordered_map<std::string,cl::NDRange> & lws_table)230 void CLTuner::import_lws_table(const std::unordered_map<std::string, cl::NDRange> &lws_table)
231 {
232 _lws_table.clear();
233 _lws_table = lws_table;
234 }
235
lws_table() const236 const std::unordered_map<std::string, cl::NDRange> &CLTuner::lws_table() const
237 {
238 return _lws_table;
239 }
240
load_from_file(const std::string & filename)241 void CLTuner::load_from_file(const std::string &filename)
242 {
243 std::ifstream fs;
244 fs.exceptions(std::ifstream::badbit);
245 fs.open(filename, std::ios::in);
246 if(!fs.is_open())
247 {
248 ARM_COMPUTE_ERROR_VAR("Failed to open '%s' (%s [%d])", filename.c_str(), strerror(errno), errno);
249 }
250 std::string line;
251 while(!std::getline(fs, line).fail())
252 {
253 std::istringstream ss(line);
254 std::string token;
255 if(std::getline(ss, token, ';').fail())
256 {
257 ARM_COMPUTE_ERROR_VAR("Malformed row '%s' in %s (Should be of the form 'kernel_id;lws[0];lws[1];lws[2]')", ss.str().c_str(), filename.c_str());
258 }
259 std::string kernel_id = token;
260 cl::NDRange lws(1, 1, 1);
261 for(int i = 0; i < 3; i++)
262 {
263 if(std::getline(ss, token, ';').fail())
264 {
265 ARM_COMPUTE_ERROR_VAR("Malformed row '%s' in %s (Should be of the form 'kernel_id;lws[0];lws[1];lws[2]')", ss.str().c_str(), filename.c_str());
266 }
267 lws.get()[i] = support::cpp11::stoi(token);
268 }
269
270 // If all dimensions are 0: reset to NullRange (i.e nullptr)
271 if(lws[0] == 0 && lws[1] == 0 && lws[2] == 0)
272 {
273 lws = cl::NullRange;
274 }
275 add_lws_to_table(kernel_id, lws);
276 }
277 fs.close();
278 }
279
save_to_file(const std::string & filename) const280 void CLTuner::save_to_file(const std::string &filename) const
281 {
282 std::ofstream fs;
283 fs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
284 fs.open(filename, std::ios::out);
285 for(auto const &kernel_data : _lws_table)
286 {
287 fs << kernel_data.first << ";" << kernel_data.second[0] << ";" << kernel_data.second[1] << ";" << kernel_data.second[2] << std::endl;
288 }
289 fs.close();
290 }
291 } // namespace arm_compute
292