1 | """ |
---|
2 | GPU driver for C kernels |
---|
3 | |
---|
4 | There should be a single GPU environment running on the system. This |
---|
5 | environment is constructed on the first call to :func:`env`, and the |
---|
6 | same environment is returned on each call. |
---|
7 | |
---|
8 | After retrieving the environment, the next step is to create the kernel. |
---|
9 | This is done with a call to :meth:`GpuEnvironment.make_kernel`, which |
---|
10 | returns the type of data used by the kernel. |
---|
11 | |
---|
12 | Next a :class:`GpuData` object should be created with the correct kind |
---|
13 | of data. This data object can be used by multiple kernels, for example, |
---|
14 | if the target model is a weighted sum of multiple kernels. The data |
---|
15 | should include any extra evaluation points required to compute the proper |
---|
16 | data smearing. This need not match the square grid for 2D data if there |
---|
17 | is an index saying which q points are active. |
---|
18 | |
---|
19 | Together the GpuData, the program, and a device form a :class:`GpuKernel`. |
---|
20 | This kernel is used during fitting, receiving new sets of parameters and |
---|
21 | evaluating them. The output value is stored in an output buffer on the |
---|
22 | devices, where it can be combined with other structure factors and form |
---|
23 | factors and have instrumental resolution effects applied. |
---|
24 | |
---|
25 | In order to use OpenCL for your models, you will need OpenCL drivers for |
---|
26 | your machine. These should be available from your graphics card vendor. |
---|
27 | Intel provides OpenCL drivers for CPUs as well as their integrated HD |
---|
28 | graphics chipsets. AMD also provides drivers for Intel CPUs, but as of |
---|
29 | this writing the performance is lacking compared to the Intel drivers. |
---|
30 | NVidia combines drivers for CUDA and OpenCL in one package. The result |
---|
31 | is a bit messy if you have multiple drivers installed. You can see which |
---|
32 | drivers are available by starting python and running: |
---|
33 | |
---|
34 | import pyopencl as cl |
---|
35 | cl.create_some_context(interactive=True) |
---|
36 | |
---|
37 | Once you have done that, it will show the available drivers which you |
---|
38 | can select. It will then tell you that you can use these drivers |
---|
39 | automatically by setting the PYOPENCL_CTX environment variable. |
---|
40 | |
---|
41 | Some graphics cards have multiple devices on the same card. You cannot |
---|
42 | yet use both of them concurrently to evaluate models, but you can run |
---|
43 | the program twice using a different device for each session. |
---|
44 | |
---|
45 | OpenCL kernels are compiled when needed by the device driver. Some |
---|
46 | drivers produce compiler output even when there is no error. You |
---|
47 | can see the output by setting PYOPENCL_COMPILER_OUTPUT=1. It should be |
---|
48 | harmless, albeit annoying. |
---|
49 | """ |
---|
50 | import os |
---|
51 | import warnings |
---|
52 | |
---|
53 | import numpy as np |
---|
54 | |
---|
55 | try: |
---|
56 | import pyopencl as cl |
---|
57 | # Ask OpenCL for the default context so that we know that one exists |
---|
58 | cl.create_some_context(interactive=False) |
---|
59 | except Exception as exc: |
---|
60 | warnings.warn(str(exc)) |
---|
61 | raise RuntimeError("OpenCL not available") |
---|
62 | |
---|
63 | from pyopencl import mem_flags as mf |
---|
64 | from pyopencl.characterize import get_fast_inaccurate_build_options |
---|
65 | |
---|
66 | from . import generate |
---|
67 | |
---|
68 | # The max loops number is limited by the amount of local memory available |
---|
69 | # on the device. You don't want to make this value too big because it will |
---|
70 | # waste resources, nor too small because it may interfere with users trying |
---|
71 | # to do their polydispersity calculations. A value of 1024 should be much |
---|
72 | # larger than necessary given that cost grows as npts^k where k is the number |
---|
73 | # of polydisperse parameters. |
---|
74 | MAX_LOOPS = 2048 |
---|
75 | |
---|
76 | |
---|
77 | ENV = None |
---|
78 | def environment(): |
---|
79 | """ |
---|
80 | Returns a singleton :class:`GpuEnvironment`. |
---|
81 | |
---|
82 | This provides an OpenCL context and one queue per device. |
---|
83 | """ |
---|
84 | global ENV |
---|
85 | if ENV is None: |
---|
86 | ENV = GpuEnvironment() |
---|
87 | return ENV |
---|
88 | |
---|
89 | def has_type(device, dtype): |
---|
90 | """ |
---|
91 | Return true if device supports the requested precision. |
---|
92 | """ |
---|
93 | if dtype == generate.F32: |
---|
94 | return True |
---|
95 | elif dtype == generate.F64: |
---|
96 | return "cl_khr_fp64" in device.extensions |
---|
97 | elif dtype == generate.F16: |
---|
98 | return "cl_khr_fp16" in device.extensions |
---|
99 | else: |
---|
100 | return False |
---|
101 | |
---|
102 | def get_warp(kernel, queue): |
---|
103 | """ |
---|
104 | Return the size of an execution batch for *kernel* running on *queue*. |
---|
105 | """ |
---|
106 | return kernel.get_work_group_info( |
---|
107 | cl.kernel_work_group_info.PREFERRED_WORK_GROUP_SIZE_MULTIPLE, |
---|
108 | queue.device) |
---|
109 | |
---|
110 | def _stretch_input(vector, dtype, extra=1e-3, boundary=32): |
---|
111 | """ |
---|
112 | Stretch an input vector to the correct boundary. |
---|
113 | |
---|
114 | Performance on the kernels can drop by a factor of two or more if the |
---|
115 | number of values to compute does not fall on a nice power of two |
---|
116 | boundary. The trailing additional vector elements are given a |
---|
117 | value of *extra*, and so f(*extra*) will be computed for each of |
---|
118 | them. The returned array will thus be a subset of the computed array. |
---|
119 | |
---|
120 | *boundary* should be a power of 2 which is at least 32 for good |
---|
121 | performance on current platforms (as of Jan 2015). It should |
---|
122 | probably be the max of get_warp(kernel,queue) and |
---|
123 | device.min_data_type_align_size//4. |
---|
124 | """ |
---|
125 | remainder = vector.size % boundary |
---|
126 | if remainder != 0: |
---|
127 | size = vector.size + (boundary - remainder) |
---|
128 | vector = np.hstack((vector, [extra] * (size - vector.size))) |
---|
129 | return np.ascontiguousarray(vector, dtype=dtype) |
---|
130 | |
---|
131 | |
---|
132 | def compile_model(context, source, dtype, fast=False): |
---|
133 | """ |
---|
134 | Build a model to run on the gpu. |
---|
135 | |
---|
136 | Returns the compiled program and its type. The returned type will |
---|
137 | be float32 even if the desired type is float64 if any of the |
---|
138 | devices in the context do not support the cl_khr_fp64 extension. |
---|
139 | """ |
---|
140 | dtype = np.dtype(dtype) |
---|
141 | if not all(has_type(d, dtype) for d in context.devices): |
---|
142 | raise RuntimeError("%s not supported for devices"%dtype) |
---|
143 | |
---|
144 | source = generate.convert_type(source, dtype) |
---|
145 | # Note: USE_SINCOS makes the intel cpu slower under opencl |
---|
146 | if context.devices[0].type == cl.device_type.GPU: |
---|
147 | source = "#define USE_SINCOS\n" + source |
---|
148 | options = (get_fast_inaccurate_build_options(context.devices[0]) |
---|
149 | if fast else []) |
---|
150 | program = cl.Program(context, source).build(options=options) |
---|
151 | return program |
---|
152 | |
---|
153 | |
---|
154 | # for now, this returns one device in the context |
---|
155 | # TODO: create a context that contains all devices on all platforms |
---|
156 | class GpuEnvironment(object): |
---|
157 | """ |
---|
158 | GPU context, with possibly many devices, and one queue per device. |
---|
159 | """ |
---|
160 | def __init__(self): |
---|
161 | # find gpu context |
---|
162 | #self.context = cl.create_some_context() |
---|
163 | |
---|
164 | self.context = None |
---|
165 | if 'PYOPENCL_CTX' in os.environ: |
---|
166 | self._create_some_context() |
---|
167 | |
---|
168 | if not self.context: |
---|
169 | self.context = _get_default_context() |
---|
170 | |
---|
171 | # Byte boundary for data alignment |
---|
172 | #self.data_boundary = max(d.min_data_type_align_size |
---|
173 | # for d in self.context.devices) |
---|
174 | self.queues = [cl.CommandQueue(context, context.devices[0]) |
---|
175 | for context in self.context] |
---|
176 | self.compiled = {} |
---|
177 | |
---|
178 | def has_type(self, dtype): |
---|
179 | """ |
---|
180 | Return True if all devices support a given type. |
---|
181 | """ |
---|
182 | dtype = generate.F32 if dtype == 'fast' else np.dtype(dtype) |
---|
183 | return any(has_type(d, dtype) |
---|
184 | for context in self.context |
---|
185 | for d in context.devices) |
---|
186 | |
---|
187 | def get_queue(self, dtype): |
---|
188 | """ |
---|
189 | Return a command queue for the kernels of type dtype. |
---|
190 | """ |
---|
191 | for context, queue in zip(self.context, self.queues): |
---|
192 | if all(has_type(d, dtype) for d in context.devices): |
---|
193 | return queue |
---|
194 | |
---|
195 | def get_context(self, dtype): |
---|
196 | """ |
---|
197 | Return a OpenCL context for the kernels of type dtype. |
---|
198 | """ |
---|
199 | for context, queue in zip(self.context, self.queues): |
---|
200 | if all(has_type(d, dtype) for d in context.devices): |
---|
201 | return context |
---|
202 | |
---|
203 | def _create_some_context(self): |
---|
204 | """ |
---|
205 | Protected call to cl.create_some_context without interactivity. Use |
---|
206 | this if PYOPENCL_CTX is set in the environment. Sets the *context* |
---|
207 | attribute. |
---|
208 | """ |
---|
209 | try: |
---|
210 | self.context = [cl.create_some_context(interactive=False)] |
---|
211 | except Exception as exc: |
---|
212 | warnings.warn(str(exc)) |
---|
213 | warnings.warn("pyopencl.create_some_context() failed") |
---|
214 | warnings.warn("the environment variable 'PYOPENCL_CTX' might not be set correctly") |
---|
215 | |
---|
216 | def compile_program(self, name, source, dtype, fast=False): |
---|
217 | """ |
---|
218 | Compile the program for the device in the given context. |
---|
219 | """ |
---|
220 | key = "%s-%s-%s"%(name, dtype, fast) |
---|
221 | if key not in self.compiled: |
---|
222 | #print("compiling",name) |
---|
223 | dtype = np.dtype(dtype) |
---|
224 | program = compile_model(self.get_context(dtype), source, dtype, fast) |
---|
225 | self.compiled[key] = program |
---|
226 | return self.compiled[key] |
---|
227 | |
---|
228 | def release_program(self, name): |
---|
229 | """ |
---|
230 | Free memory associated with the program on the device. |
---|
231 | """ |
---|
232 | if name in self.compiled: |
---|
233 | self.compiled[name].release() |
---|
234 | del self.compiled[name] |
---|
235 | |
---|
236 | def _get_default_context(): |
---|
237 | """ |
---|
238 | Get an OpenCL context, preferring GPU over CPU, and preferring Intel |
---|
239 | drivers over AMD drivers. |
---|
240 | """ |
---|
241 | # Note: on mobile devices there is automatic clock scaling if either the |
---|
242 | # CPU or the GPU is underutilized; probably doesn't affect us, but we if |
---|
243 | # it did, it would mean that putting a busy loop on the CPU while the GPU |
---|
244 | # is running may increase throughput. |
---|
245 | # |
---|
246 | # Macbook pro, base install: |
---|
247 | # {'Apple': [Intel CPU, NVIDIA GPU]} |
---|
248 | # Macbook pro, base install: |
---|
249 | # {'Apple': [Intel CPU, Intel GPU]} |
---|
250 | # 2 x nvidia 295 with Intel and NVIDIA opencl drivers installed |
---|
251 | # {'Intel': [CPU], 'NVIDIA': [GPU, GPU, GPU, GPU]} |
---|
252 | gpu, cpu = None, None |
---|
253 | for platform in cl.get_platforms(): |
---|
254 | # AMD provides a much weaker CPU driver than Intel/Apple, so avoid it. |
---|
255 | # If someone has bothered to install the AMD/NVIDIA drivers, prefer them over the integrated |
---|
256 | # graphics driver that may have been supplied with the CPU chipset. |
---|
257 | preferred_cpu = platform.vendor.startswith('Intel') or platform.vendor.startswith('Apple') |
---|
258 | preferred_gpu = platform.vendor.startswith('Advanced') or platform.vendor.startswith('NVIDIA') |
---|
259 | for device in platform.get_devices(): |
---|
260 | if device.type == cl.device_type.GPU: |
---|
261 | # If the existing type is not GPU then it will be CUSTOM or ACCELERATOR, |
---|
262 | # so don't override it. |
---|
263 | if gpu is None or (preferred_gpu and gpu.type == cl.device_type.GPU): |
---|
264 | gpu = device |
---|
265 | elif device.type == cl.device_type.CPU: |
---|
266 | if cpu is None or preferred_cpu: |
---|
267 | cpu = device |
---|
268 | else: |
---|
269 | # System has cl.device_type.ACCELERATOR or cl.device_type.CUSTOM |
---|
270 | # Intel Phi for example registers as an accelerator |
---|
271 | # Since the user installed a custom device on their system and went through the |
---|
272 | # pain of sorting out OpenCL drivers for it, lets assume they really do want to |
---|
273 | # use it as their primary compute device. |
---|
274 | gpu = device |
---|
275 | |
---|
276 | # order the devices by gpu then by cpu; when searching for an available device by data type they |
---|
277 | # will be checked in this order, which means that if the gpu supports double then the cpu will never |
---|
278 | # be used (though we may make it possible to explicitly request the cpu at some point). |
---|
279 | devices = [] |
---|
280 | if gpu is not None: |
---|
281 | devices.append(gpu) |
---|
282 | if cpu is not None: |
---|
283 | devices.append(cpu) |
---|
284 | return [cl.Context([d]) for d in devices] |
---|
285 | |
---|
286 | |
---|
287 | class GpuModel(object): |
---|
288 | """ |
---|
289 | GPU wrapper for a single model. |
---|
290 | |
---|
291 | *source* and *info* are the model source and interface as returned |
---|
292 | from :func:`gen.make`. |
---|
293 | |
---|
294 | *dtype* is the desired model precision. Any numpy dtype for single |
---|
295 | or double precision floats will do, such as 'f', 'float32' or 'single' |
---|
296 | for single and 'd', 'float64' or 'double' for double. Double precision |
---|
297 | is an optional extension which may not be available on all devices. |
---|
298 | Half precision ('float16','half') may be available on some devices. |
---|
299 | Fast precision ('fast') is a loose version of single precision, indicating |
---|
300 | that the compiler is allowed to take shortcuts. |
---|
301 | """ |
---|
302 | def __init__(self, source, info, dtype=generate.F32): |
---|
303 | self.info = info |
---|
304 | self.source = source |
---|
305 | self.dtype = generate.F32 if dtype == 'fast' else np.dtype(dtype) |
---|
306 | self.fast = (dtype == 'fast') |
---|
307 | self.program = None # delay program creation |
---|
308 | |
---|
309 | def __getstate__(self): |
---|
310 | return self.info, self.source, self.dtype, self.fast |
---|
311 | |
---|
312 | def __setstate__(self, state): |
---|
313 | self.info, self.source, self.dtype, self.fast = state |
---|
314 | self.program = None |
---|
315 | |
---|
316 | def __call__(self, q_vectors): |
---|
317 | if self.program is None: |
---|
318 | compiler = environment().compile_program |
---|
319 | self.program = compiler(self.info['name'], self.source, self.dtype, |
---|
320 | self.fast) |
---|
321 | is_2d = len(q_vectors) == 2 |
---|
322 | kernel_name = generate.kernel_name(self.info, is_2d) |
---|
323 | kernel = getattr(self.program, kernel_name) |
---|
324 | return GpuKernel(kernel, self.info, q_vectors, self.dtype) |
---|
325 | |
---|
326 | def release(self): |
---|
327 | """ |
---|
328 | Free the resources associated with the model. |
---|
329 | """ |
---|
330 | if self.program is not None: |
---|
331 | environment().release_program(self.info['name']) |
---|
332 | self.program = None |
---|
333 | |
---|
334 | def __del__(self): |
---|
335 | self.release() |
---|
336 | |
---|
337 | # TODO: check that we don't need a destructor for buffers which go out of scope |
---|
338 | class GpuInput(object): |
---|
339 | """ |
---|
340 | Make q data available to the gpu. |
---|
341 | |
---|
342 | *q_vectors* is a list of q vectors, which will be *[q]* for 1-D data, |
---|
343 | and *[qx, qy]* for 2-D data. Internally, the vectors will be reallocated |
---|
344 | to get the best performance on OpenCL, which may involve shifting and |
---|
345 | stretching the array to better match the memory architecture. Additional |
---|
346 | points will be evaluated with *q=1e-3*. |
---|
347 | |
---|
348 | *dtype* is the data type for the q vectors. The data type should be |
---|
349 | set to match that of the kernel, which is an attribute of |
---|
350 | :class:`GpuProgram`. Note that not all kernels support double |
---|
351 | precision, so even if the program was created for double precision, |
---|
352 | the *GpuProgram.dtype* may be single precision. |
---|
353 | |
---|
354 | Call :meth:`release` when complete. Even if not called directly, the |
---|
355 | buffer will be released when the data object is freed. |
---|
356 | """ |
---|
357 | def __init__(self, q_vectors, dtype=generate.F32): |
---|
358 | env = environment() |
---|
359 | self.nq = q_vectors[0].size |
---|
360 | self.dtype = np.dtype(dtype) |
---|
361 | self.is_2d = (len(q_vectors) == 2) |
---|
362 | # TODO: stretch input based on get_warp() |
---|
363 | # not doing it now since warp depends on kernel, which is not known |
---|
364 | # at this point, so instead using 32, which is good on the set of |
---|
365 | # architectures tested so far. |
---|
366 | self.q_vectors = [_stretch_input(q, self.dtype, 32) for q in q_vectors] |
---|
367 | context = env.get_context(self.dtype) |
---|
368 | self.q_buffers = [ |
---|
369 | cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=q) |
---|
370 | for q in self.q_vectors |
---|
371 | ] |
---|
372 | self.global_size = [self.q_vectors[0].size] |
---|
373 | |
---|
374 | def release(self): |
---|
375 | """ |
---|
376 | Free the memory. |
---|
377 | """ |
---|
378 | for b in self.q_buffers: |
---|
379 | b.release() |
---|
380 | self.q_buffers = [] |
---|
381 | |
---|
382 | def __del__(self): |
---|
383 | self.release() |
---|
384 | |
---|
385 | class GpuKernel(object): |
---|
386 | """ |
---|
387 | Callable SAS kernel. |
---|
388 | |
---|
389 | *kernel* is the GpuKernel object to call |
---|
390 | |
---|
391 | *info* is the module information |
---|
392 | |
---|
393 | *q_vectors* is the q vectors at which the kernel should be evaluated |
---|
394 | |
---|
395 | *dtype* is the kernel precision |
---|
396 | |
---|
397 | The resulting call method takes the *pars*, a list of values for |
---|
398 | the fixed parameters to the kernel, and *pd_pars*, a list of (value,weight) |
---|
399 | vectors for the polydisperse parameters. *cutoff* determines the |
---|
400 | integration limits: any points with combined weight less than *cutoff* |
---|
401 | will not be calculated. |
---|
402 | |
---|
403 | Call :meth:`release` when done with the kernel instance. |
---|
404 | """ |
---|
405 | def __init__(self, kernel, info, q_vectors, dtype): |
---|
406 | q_input = GpuInput(q_vectors, dtype) |
---|
407 | self.kernel = kernel |
---|
408 | self.info = info |
---|
409 | self.res = np.empty(q_input.nq, q_input.dtype) |
---|
410 | dim = '2d' if q_input.is_2d else '1d' |
---|
411 | self.fixed_pars = info['partype']['fixed-' + dim] |
---|
412 | self.pd_pars = info['partype']['pd-' + dim] |
---|
413 | |
---|
414 | # Inputs and outputs for each kernel call |
---|
415 | # Note: res may be shorter than res_b if global_size != nq |
---|
416 | env = environment() |
---|
417 | self.queue = env.get_queue(dtype) |
---|
418 | self.loops_b = cl.Buffer(self.queue.context, mf.READ_WRITE, |
---|
419 | 2 * MAX_LOOPS * q_input.dtype.itemsize) |
---|
420 | self.res_b = cl.Buffer(self.queue.context, mf.READ_WRITE, |
---|
421 | q_input.global_size[0] * q_input.dtype.itemsize) |
---|
422 | self.q_input = q_input |
---|
423 | |
---|
424 | self._need_release = [self.loops_b, self.res_b, self.q_input] |
---|
425 | |
---|
426 | def __call__(self, fixed_pars, pd_pars, cutoff=1e-5): |
---|
427 | real = (np.float32 if self.q_input.dtype == generate.F32 |
---|
428 | else np.float64 if self.q_input.dtype == generate.F64 |
---|
429 | else np.float16 if self.q_input.dtype == generate.F16 |
---|
430 | else np.float32) # will never get here, so use np.float32 |
---|
431 | |
---|
432 | res_bi = self.res_b |
---|
433 | nq = np.uint32(self.q_input.nq) |
---|
434 | if pd_pars: |
---|
435 | cutoff = real(cutoff) |
---|
436 | loops_N = [np.uint32(len(p[0])) for p in pd_pars] |
---|
437 | loops = np.hstack(pd_pars) \ |
---|
438 | if pd_pars else np.empty(0, dtype=self.q_input.dtype) |
---|
439 | loops = np.ascontiguousarray(loops.T, self.q_input.dtype).flatten() |
---|
440 | #print("loops",Nloops, loops) |
---|
441 | |
---|
442 | #import sys; print("opencl eval",pars) |
---|
443 | #print("opencl eval",pars) |
---|
444 | if len(loops) > 2 * MAX_LOOPS: |
---|
445 | raise ValueError("too many polydispersity points") |
---|
446 | |
---|
447 | loops_bi = self.loops_b |
---|
448 | cl.enqueue_copy(self.queue, loops_bi, loops) |
---|
449 | loops_l = cl.LocalMemory(len(loops.data)) |
---|
450 | #ctx = environment().context |
---|
451 | #loops_bi = cl.Buffer(ctx, mf.READ_ONLY|mf.COPY_HOST_PTR, hostbuf=loops) |
---|
452 | dispersed = [loops_bi, loops_l, cutoff] + loops_N |
---|
453 | else: |
---|
454 | dispersed = [] |
---|
455 | fixed = [real(p) for p in fixed_pars] |
---|
456 | args = self.q_input.q_buffers + [res_bi, nq] + dispersed + fixed |
---|
457 | self.kernel(self.queue, self.q_input.global_size, None, *args) |
---|
458 | cl.enqueue_copy(self.queue, self.res, res_bi) |
---|
459 | |
---|
460 | return self.res |
---|
461 | |
---|
462 | def release(self): |
---|
463 | """ |
---|
464 | Release resources associated with the kernel. |
---|
465 | """ |
---|
466 | for v in self._need_release: |
---|
467 | v.release() |
---|
468 | self._need_release = [] |
---|
469 | |
---|
470 | def __del__(self): |
---|
471 | self.release() |
---|