source: sasmodels/sasmodels/kernelcl.py @ eafc9fa

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since eafc9fa was eafc9fa, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

refactor kernel wrappers to simplify q input handling

  • Property mode set to 100644
File size: 15.8 KB
Line 
1"""
2GPU driver for C kernels
3
4There should be a single GPU environment running on the system.  This
5environment is constructed on the first call to :func:`env`, and the
6same environment is returned on each call.
7
8After retrieving the environment, the next step is to create the kernel.
9This is done with a call to :meth:`GpuEnvironment.make_kernel`, which
10returns the type of data used by the kernel.
11
12Next a :class:`GpuData` object should be created with the correct kind
13of data.  This data object can be used by multiple kernels, for example,
14if the target model is a weighted sum of multiple kernels.  The data
15should include any extra evaluation points required to compute the proper
16data smearing.  This need not match the square grid for 2D data if there
17is an index saying which q points are active.
18
19Together the GpuData, the program, and a device form a :class:`GpuKernel`.
20This kernel is used during fitting, receiving new sets of parameters and
21evaluating them.  The output value is stored in an output buffer on the
22devices, where it can be combined with other structure factors and form
23factors and have instrumental resolution effects applied.
24
25In order to use OpenCL for your models, you will need OpenCL drivers for
26your machine.  These should be available from your graphics card vendor.
27Intel provides OpenCL drivers for CPUs as well as their integrated HD
28graphics chipsets.  AMD also provides drivers for Intel CPUs, but as of
29this writing the performance is lacking compared to the Intel drivers.
30NVidia combines drivers for CUDA and OpenCL in one package.  The result
31is a bit messy if you have multiple drivers installed.  You can see which
32drivers are available by starting python and running:
33
34    import pyopencl as cl
35    cl.create_some_context(interactive=True)
36
37Once you have done that, it will show the available drivers which you
38can select.  It will then tell you that you can use these drivers
39automatically by setting the PYOPENCL_CTX environment variable.
40
41Some graphics cards have multiple devices on the same card.  You cannot
42yet use both of them concurrently to evaluate models, but you can run
43the program twice using a different device for each session.
44
45OpenCL kernels are compiled when needed by the device driver.  Some
46drivers produce compiler output even when there is no error.  You
47can see the output by setting PYOPENCL_COMPILER_OUTPUT=1.  It should be
48harmless, albeit annoying.
49"""
50import os
51import warnings
52
53import numpy as np
54
55try:
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)
59except Exception as exc:
60    warnings.warn(str(exc))
61    raise RuntimeError("OpenCL not available")
62
63from pyopencl import mem_flags as mf
64from pyopencl.characterize import get_fast_inaccurate_build_options
65
66from . 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.
74MAX_LOOPS = 2048
75
76
77ENV = None
78def 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
89def 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
102def 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
110def _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
132def 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
156class 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(self.context, d)
175                       for d in self.context.devices]
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 all(has_type(d, dtype) for d in self.context.devices)
184
185    def _create_some_context(self):
186        """
187        Protected call to cl.create_some_context without interactivity.  Use
188        this if PYOPENCL_CTX is set in the environment.  Sets the *context*
189        attribute.
190        """
191        try:
192            self.context = cl.create_some_context(interactive=False)
193        except Exception as exc:
194            warnings.warn(str(exc))
195            warnings.warn("pyopencl.create_some_context() failed")
196            warnings.warn("the environment variable 'PYOPENCL_CTX' might not be set correctly")
197
198    def compile_program(self, name, source, dtype, fast=False):
199        """
200        Compile the program for the device in the given context.
201        """
202        key = "%s-%s-%s"%(name, dtype, fast)
203        if key not in self.compiled:
204            #print("compiling",name)
205            dtype = np.dtype(dtype)
206            program = compile_model(self.context, source, dtype, fast)
207            self.compiled[key] = program
208        return self.compiled[key]
209
210    def release_program(self, name):
211        """
212        Free memory associated with the program on the device.
213        """
214        if name in self.compiled:
215            self.compiled[name].release()
216            del self.compiled[name]
217
218def _get_default_context():
219    """
220    Get an OpenCL context, preferring GPU over CPU.
221    """
222    default = None
223    for platform in cl.get_platforms():
224        for device in platform.get_devices():
225            if device.type == cl.device_type.GPU:
226                return cl.Context([device])
227            if default is None:
228                default = device
229
230    if not default:
231        raise RuntimeError("OpenCL device not found")
232
233    return cl.Context([default])
234
235
236class GpuModel(object):
237    """
238    GPU wrapper for a single model.
239
240    *source* and *info* are the model source and interface as returned
241    from :func:`gen.make`.
242
243    *dtype* is the desired model precision.  Any numpy dtype for single
244    or double precision floats will do, such as 'f', 'float32' or 'single'
245    for single and 'd', 'float64' or 'double' for double.  Double precision
246    is an optional extension which may not be available on all devices.
247    Half precision ('float16','half') may be available on some devices.
248    Fast precision ('fast') is a loose version of single precision, indicating
249    that the compiler is allowed to take shortcuts.
250    """
251    def __init__(self, source, info, dtype=generate.F32):
252        self.info = info
253        self.source = source
254        self.dtype = generate.F32 if dtype == 'fast' else np.dtype(dtype)
255        self.fast = (dtype == 'fast')
256        self.program = None # delay program creation
257
258    def __getstate__(self):
259        return self.info, self.source, self.dtype, self.fast
260
261    def __setstate__(self, state):
262        self.info, self.source, self.dtype, self.fast = state
263        self.program = None
264
265    def __call__(self, q_vectors):
266        if self.program is None:
267            compiler = environment().compile_program
268            self.program = compiler(self.info['name'], self.source, self.dtype,
269                                    self.fast)
270        is_2d = len(q_vectors) == 2
271        kernel_name = generate.kernel_name(self.info, is_2d)
272        kernel = getattr(self.program, kernel_name)
273        return GpuKernel(kernel, self.info, q_vectors, self.dtype)
274
275    def release(self):
276        """
277        Free the resources associated with the model.
278        """
279        if self.program is not None:
280            environment().release_program(self.info['name'])
281            self.program = None
282
283    def __del__(self):
284        self.release()
285
286# TODO: check that we don't need a destructor for buffers which go out of scope
287class GpuInput(object):
288    """
289    Make q data available to the gpu.
290
291    *q_vectors* is a list of q vectors, which will be *[q]* for 1-D data,
292    and *[qx, qy]* for 2-D data.  Internally, the vectors will be reallocated
293    to get the best performance on OpenCL, which may involve shifting and
294    stretching the array to better match the memory architecture.  Additional
295    points will be evaluated with *q=1e-3*.
296
297    *dtype* is the data type for the q vectors. The data type should be
298    set to match that of the kernel, which is an attribute of
299    :class:`GpuProgram`.  Note that not all kernels support double
300    precision, so even if the program was created for double precision,
301    the *GpuProgram.dtype* may be single precision.
302
303    Call :meth:`release` when complete.  Even if not called directly, the
304    buffer will be released when the data object is freed.
305    """
306    def __init__(self, q_vectors, dtype=generate.F32):
307        env = environment()
308        self.nq = q_vectors[0].size
309        self.dtype = np.dtype(dtype)
310        self.is_2d = (len(q_vectors) == 2)
311        # TODO: stretch input based on get_warp()
312        # not doing it now since warp depends on kernel, which is not known
313        # at this point, so instead using 32, which is good on the set of
314        # architectures tested so far.
315        self.q_vectors = [_stretch_input(q, self.dtype, 32) for q in q_vectors]
316        self.q_buffers = [
317            cl.Buffer(env.context, mf.READ_ONLY | mf.COPY_HOST_PTR, hostbuf=q)
318            for q in self.q_vectors
319        ]
320        self.global_size = [self.q_vectors[0].size]
321
322    def release(self):
323        """
324        Free the memory.
325        """
326        for b in self.q_buffers:
327            b.release()
328        self.q_buffers = []
329
330    def __del__(self):
331        self.release()
332
333class GpuKernel(object):
334    """
335    Callable SAS kernel.
336
337    *kernel* is the GpuKernel object to call
338
339    *info* is the module information
340
341    *q_vectors* is the q vectors at which the kernel should be evaluated
342
343    *dtype* is the kernel precision
344
345    The resulting call method takes the *pars*, a list of values for
346    the fixed parameters to the kernel, and *pd_pars*, a list of (value,weight)
347    vectors for the polydisperse parameters.  *cutoff* determines the
348    integration limits: any points with combined weight less than *cutoff*
349    will not be calculated.
350
351    Call :meth:`release` when done with the kernel instance.
352    """
353    def __init__(self, kernel, info, q_vectors, dtype):
354        q_input = GpuInput(q_vectors, dtype)
355        self.kernel = kernel
356        self.info = info
357        self.res = np.empty(q_input.nq, q_input.dtype)
358        dim = '2d' if q_input.is_2d else '1d'
359        self.fixed_pars = info['partype']['fixed-' + dim]
360        self.pd_pars = info['partype']['pd-' + dim]
361
362        # Inputs and outputs for each kernel call
363        # Note: res may be shorter than res_b if global_size != nq
364        env = environment()
365        self.loops_b = [cl.Buffer(env.context, mf.READ_WRITE,
366                                  2 * MAX_LOOPS * q_input.dtype.itemsize)
367                        for _ in env.queues]
368        self.res_b = [cl.Buffer(env.context, mf.READ_WRITE,
369                                q_input.global_size[0] * q_input.dtype.itemsize)
370                      for _ in env.queues]
371        self.q_input = q_input
372
373    def __call__(self, fixed_pars, pd_pars, cutoff=1e-5):
374        real = (np.float32 if self.q_input.dtype == generate.F32
375                else np.float64 if self.q_input.dtype == generate.F64
376                else np.float16 if self.q_input.dtype == generate.F16
377                else np.float32)  # will never get here, so use np.float32
378
379        device_num = 0
380        queuei = environment().queues[device_num]
381        res_bi = self.res_b[device_num]
382        nq = np.uint32(self.q_input.nq)
383        if pd_pars:
384            cutoff = real(cutoff)
385            loops_N = [np.uint32(len(p[0])) for p in pd_pars]
386            loops = np.hstack(pd_pars) \
387                if pd_pars else np.empty(0, dtype=self.q_input.dtype)
388            loops = np.ascontiguousarray(loops.T, self.q_input.dtype).flatten()
389            #print("loops",Nloops, loops)
390
391            #import sys; print("opencl eval",pars)
392            #print("opencl eval",pars)
393            if len(loops) > 2 * MAX_LOOPS:
394                raise ValueError("too many polydispersity points")
395
396            loops_bi = self.loops_b[device_num]
397            cl.enqueue_copy(queuei, loops_bi, loops)
398            loops_l = cl.LocalMemory(len(loops.data))
399            #ctx = environment().context
400            #loops_bi = cl.Buffer(ctx, mf.READ_ONLY|mf.COPY_HOST_PTR, hostbuf=loops)
401            dispersed = [loops_bi, loops_l, cutoff] + loops_N
402        else:
403            dispersed = []
404        fixed = [real(p) for p in fixed_pars]
405        args = self.q_input.q_buffers + [res_bi, nq] + dispersed + fixed
406        self.kernel(queuei, self.q_input.global_size, None, *args)
407        cl.enqueue_copy(queuei, self.res, res_bi)
408
409        return self.res
410
411    def release(self):
412        """
413        Release resources associated with the kernel.
414        """
415        for b in self.loops_b:
416            b.release()
417        self.loops_b = []
418        for b in self.res_b:
419            b.release()
420        self.res_b = []
421        self.q_input.release()
422
423    def __del__(self):
424        self.release()
Note: See TracBrowser for help on using the repository browser.