[14de349] | 1 | """ |
---|
[eafc9fa] | 2 | GPU driver for C kernels |
---|
[14de349] | 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. |
---|
[92da231] | 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 |
---|
[880a2ed] | 39 | automatically by setting the SAS_OPENCL environment variable, which is |
---|
| 40 | PYOPENCL_CTX equivalent but not conflicting with other pyopnecl programs. |
---|
[92da231] | 41 | |
---|
| 42 | Some graphics cards have multiple devices on the same card. You cannot |
---|
| 43 | yet use both of them concurrently to evaluate models, but you can run |
---|
| 44 | the program twice using a different device for each session. |
---|
| 45 | |
---|
| 46 | OpenCL kernels are compiled when needed by the device driver. Some |
---|
| 47 | drivers produce compiler output even when there is no error. You |
---|
| 48 | can see the output by setting PYOPENCL_COMPILER_OUTPUT=1. It should be |
---|
| 49 | harmless, albeit annoying. |
---|
[14de349] | 50 | """ |
---|
[ba32cdd] | 51 | from __future__ import print_function |
---|
[a5b8477] | 52 | |
---|
[250fa25] | 53 | import os |
---|
| 54 | import warnings |
---|
[821a9c6] | 55 | import logging |
---|
[6e5b2a7] | 56 | import time |
---|
[250fa25] | 57 | |
---|
[7ae2b7f] | 58 | import numpy as np # type: ignore |
---|
[b3f6bc3] | 59 | |
---|
[250fa25] | 60 | try: |
---|
[6dba2f0] | 61 | if os.environ.get("SAS_OPENCL", "").lower() == "none": |
---|
| 62 | HAVE_OPENCL = False |
---|
| 63 | else: |
---|
[e59f60a] | 64 | import pyopencl as cl # type: ignore |
---|
| 65 | from pyopencl import mem_flags as mf |
---|
| 66 | from pyopencl.characterize import get_fast_inaccurate_build_options |
---|
[6dba2f0] | 67 | # Ask OpenCL for the default context so that we know that one exists |
---|
| 68 | cl.create_some_context(interactive=False) |
---|
| 69 | HAVE_OPENCL = True |
---|
[9404dd3] | 70 | except Exception as exc: |
---|
[40a87fa] | 71 | warnings.warn("OpenCL startup failed with ***" |
---|
| 72 | + str(exc) + "***; using C compiler instead") |
---|
[6dba2f0] | 73 | HAVE_OPENCL = False |
---|
[14de349] | 74 | |
---|
[cb6ecf4] | 75 | from . import generate |
---|
[f619de7] | 76 | from .kernel import KernelModel, Kernel |
---|
[14de349] | 77 | |
---|
[2d81cfe] | 78 | # pylint: disable=unused-import |
---|
[a5b8477] | 79 | try: |
---|
| 80 | from typing import Tuple, Callable, Any |
---|
| 81 | from .modelinfo import ModelInfo |
---|
| 82 | from .details import CallDetails |
---|
| 83 | except ImportError: |
---|
| 84 | pass |
---|
[2d81cfe] | 85 | # pylint: enable=unused-import |
---|
[a5b8477] | 86 | |
---|
[20317b3] | 87 | # CRUFT: pyopencl < 2017.1 (as of June 2016 needs quotes around include path) |
---|
| 88 | def quote_path(v): |
---|
| 89 | """ |
---|
| 90 | Quote the path if it is not already quoted. |
---|
| 91 | |
---|
| 92 | If v starts with '-', then assume that it is a -I option or similar |
---|
| 93 | and do not quote it. This is fragile: -Ipath with space needs to |
---|
| 94 | be quoted. |
---|
| 95 | """ |
---|
| 96 | return '"'+v+'"' if v and ' ' in v and not v[0] in "\"'-" else v |
---|
| 97 | |
---|
| 98 | def fix_pyopencl_include(): |
---|
[40a87fa] | 99 | """ |
---|
| 100 | Monkey patch pyopencl to allow spaces in include file path. |
---|
| 101 | """ |
---|
[20317b3] | 102 | import pyopencl as cl |
---|
| 103 | if hasattr(cl, '_DEFAULT_INCLUDE_OPTIONS'): |
---|
| 104 | cl._DEFAULT_INCLUDE_OPTIONS = [quote_path(v) for v in cl._DEFAULT_INCLUDE_OPTIONS] |
---|
| 105 | |
---|
[6dba2f0] | 106 | if HAVE_OPENCL: |
---|
| 107 | fix_pyopencl_include() |
---|
[20317b3] | 108 | |
---|
[ce27e21] | 109 | # The max loops number is limited by the amount of local memory available |
---|
| 110 | # on the device. You don't want to make this value too big because it will |
---|
| 111 | # waste resources, nor too small because it may interfere with users trying |
---|
| 112 | # to do their polydispersity calculations. A value of 1024 should be much |
---|
| 113 | # larger than necessary given that cost grows as npts^k where k is the number |
---|
| 114 | # of polydisperse parameters. |
---|
[5d4777d] | 115 | MAX_LOOPS = 2048 |
---|
| 116 | |
---|
[ce27e21] | 117 | |
---|
[5464d68] | 118 | # Pragmas for enable OpenCL features. Be sure to protect them so that they |
---|
| 119 | # still compile even if OpenCL is not present. |
---|
| 120 | _F16_PRAGMA = """\ |
---|
| 121 | #if defined(__OPENCL_VERSION__) // && !defined(cl_khr_fp16) |
---|
| 122 | # pragma OPENCL EXTENSION cl_khr_fp16: enable |
---|
| 123 | #endif |
---|
| 124 | """ |
---|
| 125 | |
---|
| 126 | _F64_PRAGMA = """\ |
---|
| 127 | #if defined(__OPENCL_VERSION__) // && !defined(cl_khr_fp64) |
---|
| 128 | # pragma OPENCL EXTENSION cl_khr_fp64: enable |
---|
| 129 | #endif |
---|
| 130 | """ |
---|
| 131 | |
---|
| 132 | |
---|
[14de349] | 133 | ENV = None |
---|
| 134 | def environment(): |
---|
[dd7fc12] | 135 | # type: () -> "GpuEnvironment" |
---|
[14de349] | 136 | """ |
---|
| 137 | Returns a singleton :class:`GpuEnvironment`. |
---|
| 138 | |
---|
| 139 | This provides an OpenCL context and one queue per device. |
---|
| 140 | """ |
---|
| 141 | global ENV |
---|
| 142 | if ENV is None: |
---|
| 143 | ENV = GpuEnvironment() |
---|
| 144 | return ENV |
---|
| 145 | |
---|
[5d316e9] | 146 | def has_type(device, dtype): |
---|
[dd7fc12] | 147 | # type: (cl.Device, np.dtype) -> bool |
---|
[14de349] | 148 | """ |
---|
[5d316e9] | 149 | Return true if device supports the requested precision. |
---|
[14de349] | 150 | """ |
---|
[5d316e9] | 151 | if dtype == generate.F32: |
---|
| 152 | return True |
---|
| 153 | elif dtype == generate.F64: |
---|
| 154 | return "cl_khr_fp64" in device.extensions |
---|
| 155 | elif dtype == generate.F16: |
---|
| 156 | return "cl_khr_fp16" in device.extensions |
---|
| 157 | else: |
---|
| 158 | return False |
---|
[14de349] | 159 | |
---|
[f5b9a6b] | 160 | def get_warp(kernel, queue): |
---|
[dd7fc12] | 161 | # type: (cl.Kernel, cl.CommandQueue) -> int |
---|
[f5b9a6b] | 162 | """ |
---|
| 163 | Return the size of an execution batch for *kernel* running on *queue*. |
---|
| 164 | """ |
---|
[750ffa5] | 165 | return kernel.get_work_group_info( |
---|
[63b32bb] | 166 | cl.kernel_work_group_info.PREFERRED_WORK_GROUP_SIZE_MULTIPLE, |
---|
| 167 | queue.device) |
---|
[14de349] | 168 | |
---|
[f5b9a6b] | 169 | def _stretch_input(vector, dtype, extra=1e-3, boundary=32): |
---|
[dd7fc12] | 170 | # type: (np.ndarray, np.dtype, float, int) -> np.ndarray |
---|
[14de349] | 171 | """ |
---|
| 172 | Stretch an input vector to the correct boundary. |
---|
| 173 | |
---|
| 174 | Performance on the kernels can drop by a factor of two or more if the |
---|
| 175 | number of values to compute does not fall on a nice power of two |
---|
[f5b9a6b] | 176 | boundary. The trailing additional vector elements are given a |
---|
| 177 | value of *extra*, and so f(*extra*) will be computed for each of |
---|
| 178 | them. The returned array will thus be a subset of the computed array. |
---|
| 179 | |
---|
| 180 | *boundary* should be a power of 2 which is at least 32 for good |
---|
| 181 | performance on current platforms (as of Jan 2015). It should |
---|
| 182 | probably be the max of get_warp(kernel,queue) and |
---|
| 183 | device.min_data_type_align_size//4. |
---|
| 184 | """ |
---|
[c85db69] | 185 | remainder = vector.size % boundary |
---|
[f5b9a6b] | 186 | if remainder != 0: |
---|
| 187 | size = vector.size + (boundary - remainder) |
---|
[c85db69] | 188 | vector = np.hstack((vector, [extra] * (size - vector.size))) |
---|
[14de349] | 189 | return np.ascontiguousarray(vector, dtype=dtype) |
---|
| 190 | |
---|
| 191 | |
---|
[5d316e9] | 192 | def compile_model(context, source, dtype, fast=False): |
---|
[dd7fc12] | 193 | # type: (cl.Context, str, np.dtype, bool) -> cl.Program |
---|
[14de349] | 194 | """ |
---|
| 195 | Build a model to run on the gpu. |
---|
| 196 | |
---|
| 197 | Returns the compiled program and its type. The returned type will |
---|
| 198 | be float32 even if the desired type is float64 if any of the |
---|
| 199 | devices in the context do not support the cl_khr_fp64 extension. |
---|
| 200 | """ |
---|
| 201 | dtype = np.dtype(dtype) |
---|
[5d316e9] | 202 | if not all(has_type(d, dtype) for d in context.devices): |
---|
| 203 | raise RuntimeError("%s not supported for devices"%dtype) |
---|
[14de349] | 204 | |
---|
[5464d68] | 205 | source_list = [generate.convert_type(source, dtype)] |
---|
| 206 | |
---|
| 207 | if dtype == generate.F16: |
---|
| 208 | source_list.insert(0, _F16_PRAGMA) |
---|
| 209 | elif dtype == generate.F64: |
---|
| 210 | source_list.insert(0, _F64_PRAGMA) |
---|
| 211 | |
---|
[14de349] | 212 | # Note: USE_SINCOS makes the intel cpu slower under opencl |
---|
| 213 | if context.devices[0].type == cl.device_type.GPU: |
---|
[5464d68] | 214 | source_list.insert(0, "#define USE_SINCOS\n") |
---|
[5d316e9] | 215 | options = (get_fast_inaccurate_build_options(context.devices[0]) |
---|
| 216 | if fast else []) |
---|
[ba32cdd] | 217 | source = "\n".join(source_list) |
---|
[5d316e9] | 218 | program = cl.Program(context, source).build(options=options) |
---|
[821a9c6] | 219 | #print("done with "+program) |
---|
[ce27e21] | 220 | return program |
---|
[14de349] | 221 | |
---|
| 222 | |
---|
| 223 | # for now, this returns one device in the context |
---|
| 224 | # TODO: create a context that contains all devices on all platforms |
---|
| 225 | class GpuEnvironment(object): |
---|
| 226 | """ |
---|
| 227 | GPU context, with possibly many devices, and one queue per device. |
---|
| 228 | """ |
---|
| 229 | def __init__(self): |
---|
[dd7fc12] | 230 | # type: () -> None |
---|
[250fa25] | 231 | # find gpu context |
---|
| 232 | #self.context = cl.create_some_context() |
---|
| 233 | |
---|
| 234 | self.context = None |
---|
[880a2ed] | 235 | if 'SAS_OPENCL' in os.environ: |
---|
| 236 | #Setting PYOPENCL_CTX as a SAS_OPENCL to create cl context |
---|
| 237 | os.environ["PYOPENCL_CTX"] = os.environ["SAS_OPENCL"] |
---|
[a557a99] | 238 | if 'PYOPENCL_CTX' in os.environ: |
---|
[250fa25] | 239 | self._create_some_context() |
---|
| 240 | |
---|
| 241 | if not self.context: |
---|
[3c56da87] | 242 | self.context = _get_default_context() |
---|
[250fa25] | 243 | |
---|
[f5b9a6b] | 244 | # Byte boundary for data alignment |
---|
| 245 | #self.data_boundary = max(d.min_data_type_align_size |
---|
| 246 | # for d in self.context.devices) |
---|
[d18582e] | 247 | self.queues = [cl.CommandQueue(context, context.devices[0]) |
---|
| 248 | for context in self.context] |
---|
[ce27e21] | 249 | self.compiled = {} |
---|
| 250 | |
---|
[5d316e9] | 251 | def has_type(self, dtype): |
---|
[dd7fc12] | 252 | # type: (np.dtype) -> bool |
---|
[eafc9fa] | 253 | """ |
---|
| 254 | Return True if all devices support a given type. |
---|
| 255 | """ |
---|
[d18582e] | 256 | return any(has_type(d, dtype) |
---|
| 257 | for context in self.context |
---|
| 258 | for d in context.devices) |
---|
| 259 | |
---|
| 260 | def get_queue(self, dtype): |
---|
[dd7fc12] | 261 | # type: (np.dtype) -> cl.CommandQueue |
---|
[d18582e] | 262 | """ |
---|
| 263 | Return a command queue for the kernels of type dtype. |
---|
| 264 | """ |
---|
| 265 | for context, queue in zip(self.context, self.queues): |
---|
| 266 | if all(has_type(d, dtype) for d in context.devices): |
---|
| 267 | return queue |
---|
| 268 | |
---|
| 269 | def get_context(self, dtype): |
---|
[dd7fc12] | 270 | # type: (np.dtype) -> cl.Context |
---|
[d18582e] | 271 | """ |
---|
| 272 | Return a OpenCL context for the kernels of type dtype. |
---|
| 273 | """ |
---|
[20317b3] | 274 | for context in self.context: |
---|
[d18582e] | 275 | if all(has_type(d, dtype) for d in context.devices): |
---|
| 276 | return context |
---|
[5d316e9] | 277 | |
---|
[250fa25] | 278 | def _create_some_context(self): |
---|
[dd7fc12] | 279 | # type: () -> cl.Context |
---|
[eafc9fa] | 280 | """ |
---|
| 281 | Protected call to cl.create_some_context without interactivity. Use |
---|
[880a2ed] | 282 | this if SAS_OPENCL is set in the environment. Sets the *context* |
---|
[eafc9fa] | 283 | attribute. |
---|
| 284 | """ |
---|
[250fa25] | 285 | try: |
---|
[d18582e] | 286 | self.context = [cl.create_some_context(interactive=False)] |
---|
[9404dd3] | 287 | except Exception as exc: |
---|
[250fa25] | 288 | warnings.warn(str(exc)) |
---|
| 289 | warnings.warn("pyopencl.create_some_context() failed") |
---|
[880a2ed] | 290 | warnings.warn("the environment variable 'SAS_OPENCL' might not be set correctly") |
---|
[250fa25] | 291 | |
---|
[300a2f7] | 292 | def compile_program(self, name, source, dtype, fast, timestamp): |
---|
| 293 | # type: (str, str, np.dtype, bool, float) -> cl.Program |
---|
[eafc9fa] | 294 | """ |
---|
| 295 | Compile the program for the device in the given context. |
---|
| 296 | """ |
---|
[300a2f7] | 297 | # Note: PyOpenCL caches based on md5 hash of source, options and device |
---|
| 298 | # so we don't really need to cache things for ourselves. I'll do so |
---|
| 299 | # anyway just to save some data munging time. |
---|
[7fcdc9f] | 300 | tag = generate.tag_source(source) |
---|
| 301 | key = "%s-%s-%s%s"%(name, dtype, tag, ("-fast" if fast else "")) |
---|
[300a2f7] | 302 | # Check timestamp on program |
---|
| 303 | program, program_timestamp = self.compiled.get(key, (None, np.inf)) |
---|
| 304 | if program_timestamp < timestamp: |
---|
| 305 | del self.compiled[key] |
---|
[cde11f0f] | 306 | if key not in self.compiled: |
---|
[821a9c6] | 307 | context = self.get_context(dtype) |
---|
[20317b3] | 308 | logging.info("building %s for OpenCL %s", key, |
---|
| 309 | context.devices[0].name.strip()) |
---|
[fec69dd] | 310 | program = compile_model(self.get_context(dtype), |
---|
| 311 | str(source), dtype, fast) |
---|
[300a2f7] | 312 | self.compiled[key] = (program, timestamp) |
---|
| 313 | return program |
---|
[14de349] | 314 | |
---|
[3c56da87] | 315 | def _get_default_context(): |
---|
[20317b3] | 316 | # type: () -> List[cl.Context] |
---|
[eafc9fa] | 317 | """ |
---|
[d18582e] | 318 | Get an OpenCL context, preferring GPU over CPU, and preferring Intel |
---|
| 319 | drivers over AMD drivers. |
---|
[eafc9fa] | 320 | """ |
---|
[d18582e] | 321 | # Note: on mobile devices there is automatic clock scaling if either the |
---|
| 322 | # CPU or the GPU is underutilized; probably doesn't affect us, but we if |
---|
| 323 | # it did, it would mean that putting a busy loop on the CPU while the GPU |
---|
| 324 | # is running may increase throughput. |
---|
| 325 | # |
---|
| 326 | # Macbook pro, base install: |
---|
| 327 | # {'Apple': [Intel CPU, NVIDIA GPU]} |
---|
| 328 | # Macbook pro, base install: |
---|
| 329 | # {'Apple': [Intel CPU, Intel GPU]} |
---|
| 330 | # 2 x nvidia 295 with Intel and NVIDIA opencl drivers installed |
---|
| 331 | # {'Intel': [CPU], 'NVIDIA': [GPU, GPU, GPU, GPU]} |
---|
| 332 | gpu, cpu = None, None |
---|
[3c56da87] | 333 | for platform in cl.get_platforms(): |
---|
[e6a5556] | 334 | # AMD provides a much weaker CPU driver than Intel/Apple, so avoid it. |
---|
[20317b3] | 335 | # If someone has bothered to install the AMD/NVIDIA drivers, prefer |
---|
| 336 | # them over the integrated graphics driver that may have been supplied |
---|
| 337 | # with the CPU chipset. |
---|
| 338 | preferred_cpu = (platform.vendor.startswith('Intel') |
---|
| 339 | or platform.vendor.startswith('Apple')) |
---|
| 340 | preferred_gpu = (platform.vendor.startswith('Advanced') |
---|
| 341 | or platform.vendor.startswith('NVIDIA')) |
---|
[3c56da87] | 342 | for device in platform.get_devices(): |
---|
| 343 | if device.type == cl.device_type.GPU: |
---|
[20317b3] | 344 | # If the existing type is not GPU then it will be CUSTOM |
---|
| 345 | # or ACCELERATOR so don't override it. |
---|
[e6a5556] | 346 | if gpu is None or (preferred_gpu and gpu.type == cl.device_type.GPU): |
---|
| 347 | gpu = device |
---|
| 348 | elif device.type == cl.device_type.CPU: |
---|
| 349 | if cpu is None or preferred_cpu: |
---|
| 350 | cpu = device |
---|
[d18582e] | 351 | else: |
---|
[e6a5556] | 352 | # System has cl.device_type.ACCELERATOR or cl.device_type.CUSTOM |
---|
| 353 | # Intel Phi for example registers as an accelerator |
---|
[20317b3] | 354 | # Since the user installed a custom device on their system |
---|
| 355 | # and went through the pain of sorting out OpenCL drivers for |
---|
| 356 | # it, lets assume they really do want to use it as their |
---|
| 357 | # primary compute device. |
---|
[e6a5556] | 358 | gpu = device |
---|
[199d40d] | 359 | |
---|
[20317b3] | 360 | # order the devices by gpu then by cpu; when searching for an available |
---|
| 361 | # device by data type they will be checked in this order, which means |
---|
| 362 | # that if the gpu supports double then the cpu will never be used (though |
---|
| 363 | # we may make it possible to explicitly request the cpu at some point). |
---|
[e6a5556] | 364 | devices = [] |
---|
| 365 | if gpu is not None: |
---|
| 366 | devices.append(gpu) |
---|
| 367 | if cpu is not None: |
---|
| 368 | devices.append(cpu) |
---|
| 369 | return [cl.Context([d]) for d in devices] |
---|
[3c56da87] | 370 | |
---|
[250fa25] | 371 | |
---|
[f619de7] | 372 | class GpuModel(KernelModel): |
---|
[14de349] | 373 | """ |
---|
| 374 | GPU wrapper for a single model. |
---|
| 375 | |
---|
[17bbadd] | 376 | *source* and *model_info* are the model source and interface as returned |
---|
| 377 | from :func:`generate.make_source` and :func:`generate.make_model_info`. |
---|
[14de349] | 378 | |
---|
| 379 | *dtype* is the desired model precision. Any numpy dtype for single |
---|
| 380 | or double precision floats will do, such as 'f', 'float32' or 'single' |
---|
| 381 | for single and 'd', 'float64' or 'double' for double. Double precision |
---|
| 382 | is an optional extension which may not be available on all devices. |
---|
[cde11f0f] | 383 | Half precision ('float16','half') may be available on some devices. |
---|
| 384 | Fast precision ('fast') is a loose version of single precision, indicating |
---|
| 385 | that the compiler is allowed to take shortcuts. |
---|
[14de349] | 386 | """ |
---|
[dd7fc12] | 387 | def __init__(self, source, model_info, dtype=generate.F32, fast=False): |
---|
[a4280bd] | 388 | # type: (Dict[str,str], ModelInfo, np.dtype, bool) -> None |
---|
[17bbadd] | 389 | self.info = model_info |
---|
[ce27e21] | 390 | self.source = source |
---|
[dd7fc12] | 391 | self.dtype = dtype |
---|
| 392 | self.fast = fast |
---|
[ce27e21] | 393 | self.program = None # delay program creation |
---|
[20317b3] | 394 | self._kernels = None |
---|
[14de349] | 395 | |
---|
[ce27e21] | 396 | def __getstate__(self): |
---|
[dd7fc12] | 397 | # type: () -> Tuple[ModelInfo, str, np.dtype, bool] |
---|
[eafc9fa] | 398 | return self.info, self.source, self.dtype, self.fast |
---|
[14de349] | 399 | |
---|
[ce27e21] | 400 | def __setstate__(self, state): |
---|
[dd7fc12] | 401 | # type: (Tuple[ModelInfo, str, np.dtype, bool]) -> None |
---|
[eafc9fa] | 402 | self.info, self.source, self.dtype, self.fast = state |
---|
| 403 | self.program = None |
---|
[ce27e21] | 404 | |
---|
[9eb3632] | 405 | def make_kernel(self, q_vectors): |
---|
[dd7fc12] | 406 | # type: (List[np.ndarray]) -> "GpuKernel" |
---|
[ce27e21] | 407 | if self.program is None: |
---|
[a4280bd] | 408 | compile_program = environment().compile_program |
---|
[0dc34c3] | 409 | timestamp = generate.ocl_timestamp(self.info) |
---|
[a4280bd] | 410 | self.program = compile_program( |
---|
| 411 | self.info.name, |
---|
| 412 | self.source['opencl'], |
---|
| 413 | self.dtype, |
---|
[300a2f7] | 414 | self.fast, |
---|
| 415 | timestamp) |
---|
[a4280bd] | 416 | variants = ['Iq', 'Iqxy', 'Imagnetic'] |
---|
| 417 | names = [generate.kernel_name(self.info, k) for k in variants] |
---|
| 418 | kernels = [getattr(self.program, k) for k in names] |
---|
[20317b3] | 419 | self._kernels = dict((k, v) for k, v in zip(variants, kernels)) |
---|
[eafc9fa] | 420 | is_2d = len(q_vectors) == 2 |
---|
[a4280bd] | 421 | if is_2d: |
---|
| 422 | kernel = [self._kernels['Iqxy'], self._kernels['Imagnetic']] |
---|
| 423 | else: |
---|
| 424 | kernel = [self._kernels['Iq']]*2 |
---|
[f2f67a6] | 425 | return GpuKernel(kernel, self.dtype, self.info, q_vectors) |
---|
[ce27e21] | 426 | |
---|
| 427 | def release(self): |
---|
[dd7fc12] | 428 | # type: () -> None |
---|
[eafc9fa] | 429 | """ |
---|
| 430 | Free the resources associated with the model. |
---|
| 431 | """ |
---|
[ce27e21] | 432 | if self.program is not None: |
---|
| 433 | self.program = None |
---|
[14de349] | 434 | |
---|
[eafc9fa] | 435 | def __del__(self): |
---|
[dd7fc12] | 436 | # type: () -> None |
---|
[eafc9fa] | 437 | self.release() |
---|
[14de349] | 438 | |
---|
| 439 | # TODO: check that we don't need a destructor for buffers which go out of scope |
---|
| 440 | class GpuInput(object): |
---|
| 441 | """ |
---|
| 442 | Make q data available to the gpu. |
---|
| 443 | |
---|
| 444 | *q_vectors* is a list of q vectors, which will be *[q]* for 1-D data, |
---|
| 445 | and *[qx, qy]* for 2-D data. Internally, the vectors will be reallocated |
---|
| 446 | to get the best performance on OpenCL, which may involve shifting and |
---|
| 447 | stretching the array to better match the memory architecture. Additional |
---|
| 448 | points will be evaluated with *q=1e-3*. |
---|
| 449 | |
---|
| 450 | *dtype* is the data type for the q vectors. The data type should be |
---|
| 451 | set to match that of the kernel, which is an attribute of |
---|
| 452 | :class:`GpuProgram`. Note that not all kernels support double |
---|
| 453 | precision, so even if the program was created for double precision, |
---|
| 454 | the *GpuProgram.dtype* may be single precision. |
---|
| 455 | |
---|
| 456 | Call :meth:`release` when complete. Even if not called directly, the |
---|
| 457 | buffer will be released when the data object is freed. |
---|
| 458 | """ |
---|
[cb6ecf4] | 459 | def __init__(self, q_vectors, dtype=generate.F32): |
---|
[dd7fc12] | 460 | # type: (List[np.ndarray], np.dtype) -> None |
---|
[17bbadd] | 461 | # TODO: do we ever need double precision q? |
---|
[14de349] | 462 | env = environment() |
---|
| 463 | self.nq = q_vectors[0].size |
---|
| 464 | self.dtype = np.dtype(dtype) |
---|
[eafc9fa] | 465 | self.is_2d = (len(q_vectors) == 2) |
---|
[f5b9a6b] | 466 | # TODO: stretch input based on get_warp() |
---|
| 467 | # not doing it now since warp depends on kernel, which is not known |
---|
| 468 | # at this point, so instead using 32, which is good on the set of |
---|
| 469 | # architectures tested so far. |
---|
[c072f83] | 470 | if self.is_2d: |
---|
[b8ddf2e] | 471 | # Note: 16 rather than 15 because result is 1 longer than input. |
---|
| 472 | width = ((self.nq+16)//16)*16 |
---|
[c072f83] | 473 | self.q = np.empty((width, 2), dtype=dtype) |
---|
| 474 | self.q[:self.nq, 0] = q_vectors[0] |
---|
| 475 | self.q[:self.nq, 1] = q_vectors[1] |
---|
| 476 | else: |
---|
[b8ddf2e] | 477 | # Note: 32 rather than 31 because result is 1 longer than input. |
---|
| 478 | width = ((self.nq+32)//32)*32 |
---|
[c072f83] | 479 | self.q = np.empty(width, dtype=dtype) |
---|
| 480 | self.q[:self.nq] = q_vectors[0] |
---|
| 481 | self.global_size = [self.q.shape[0]] |
---|
[d18582e] | 482 | context = env.get_context(self.dtype) |
---|
[c094758] | 483 | #print("creating inputs of size", self.global_size) |
---|
[c072f83] | 484 | self.q_b = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, |
---|
| 485 | hostbuf=self.q) |
---|
[14de349] | 486 | |
---|
| 487 | def release(self): |
---|
[dd7fc12] | 488 | # type: () -> None |
---|
[eafc9fa] | 489 | """ |
---|
| 490 | Free the memory. |
---|
| 491 | """ |
---|
[f2f67a6] | 492 | if self.q_b is not None: |
---|
| 493 | self.q_b.release() |
---|
| 494 | self.q_b = None |
---|
[14de349] | 495 | |
---|
[eafc9fa] | 496 | def __del__(self): |
---|
[dd7fc12] | 497 | # type: () -> None |
---|
[eafc9fa] | 498 | self.release() |
---|
| 499 | |
---|
[f619de7] | 500 | class GpuKernel(Kernel): |
---|
[ff7119b] | 501 | """ |
---|
| 502 | Callable SAS kernel. |
---|
| 503 | |
---|
[eafc9fa] | 504 | *kernel* is the GpuKernel object to call |
---|
[ff7119b] | 505 | |
---|
[17bbadd] | 506 | *model_info* is the module information |
---|
[ff7119b] | 507 | |
---|
[eafc9fa] | 508 | *q_vectors* is the q vectors at which the kernel should be evaluated |
---|
| 509 | |
---|
| 510 | *dtype* is the kernel precision |
---|
[ff7119b] | 511 | |
---|
| 512 | The resulting call method takes the *pars*, a list of values for |
---|
| 513 | the fixed parameters to the kernel, and *pd_pars*, a list of (value,weight) |
---|
| 514 | vectors for the polydisperse parameters. *cutoff* determines the |
---|
| 515 | integration limits: any points with combined weight less than *cutoff* |
---|
| 516 | will not be calculated. |
---|
| 517 | |
---|
| 518 | Call :meth:`release` when done with the kernel instance. |
---|
| 519 | """ |
---|
[f2f67a6] | 520 | def __init__(self, kernel, dtype, model_info, q_vectors): |
---|
| 521 | # type: (cl.Kernel, np.dtype, ModelInfo, List[np.ndarray]) -> None |
---|
| 522 | q_input = GpuInput(q_vectors, dtype) |
---|
[14de349] | 523 | self.kernel = kernel |
---|
[17bbadd] | 524 | self.info = model_info |
---|
[f2f67a6] | 525 | self.dtype = dtype |
---|
[a5b8477] | 526 | self.dim = '2d' if q_input.is_2d else '1d' |
---|
[c072f83] | 527 | # plus three for the normalization values |
---|
[b8ddf2e] | 528 | self.result = np.empty(q_input.nq+1, dtype) |
---|
[14de349] | 529 | |
---|
| 530 | # Inputs and outputs for each kernel call |
---|
[ce27e21] | 531 | # Note: res may be shorter than res_b if global_size != nq |
---|
| 532 | env = environment() |
---|
[f2f67a6] | 533 | self.queue = env.get_queue(dtype) |
---|
[c072f83] | 534 | |
---|
| 535 | self.result_b = cl.Buffer(self.queue.context, mf.READ_WRITE, |
---|
[b8ddf2e] | 536 | q_input.global_size[0] * dtype.itemsize) |
---|
[c072f83] | 537 | self.q_input = q_input # allocated by GpuInput above |
---|
[14de349] | 538 | |
---|
[20317b3] | 539 | self._need_release = [self.result_b, self.q_input] |
---|
[f2f67a6] | 540 | self.real = (np.float32 if dtype == generate.F32 |
---|
| 541 | else np.float64 if dtype == generate.F64 |
---|
| 542 | else np.float16 if dtype == generate.F16 |
---|
[8d62008] | 543 | else np.float32) # will never get here, so use np.float32 |
---|
[d18582e] | 544 | |
---|
[32e3c9b] | 545 | def __call__(self, call_details, values, cutoff, magnetic): |
---|
| 546 | # type: (CallDetails, np.ndarray, np.ndarray, float, bool) -> np.ndarray |
---|
[48fbd50] | 547 | context = self.queue.context |
---|
[8d62008] | 548 | # Arrange data transfer to card |
---|
[48fbd50] | 549 | details_b = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, |
---|
[8d62008] | 550 | hostbuf=call_details.buffer) |
---|
[48fbd50] | 551 | values_b = cl.Buffer(context, mf.READ_ONLY | mf.COPY_HOST_PTR, |
---|
| 552 | hostbuf=values) |
---|
| 553 | |
---|
[9eb3632] | 554 | kernel = self.kernel[1 if magnetic else 0] |
---|
| 555 | args = [ |
---|
| 556 | np.uint32(self.q_input.nq), None, None, |
---|
| 557 | details_b, values_b, self.q_input.q_b, self.result_b, |
---|
| 558 | self.real(cutoff), |
---|
| 559 | ] |
---|
| 560 | #print("Calling OpenCL") |
---|
[bde38b5] | 561 | #call_details.show(values) |
---|
[ae2b6b5] | 562 | # Call kernel and retrieve results |
---|
[6e5b2a7] | 563 | wait_for = None |
---|
| 564 | last_nap = time.clock() |
---|
| 565 | step = 1000000//self.q_input.nq + 1 |
---|
[bde38b5] | 566 | for start in range(0, call_details.num_eval, step): |
---|
| 567 | stop = min(start + step, call_details.num_eval) |
---|
[9eb3632] | 568 | #print("queuing",start,stop) |
---|
| 569 | args[1:3] = [np.int32(start), np.int32(stop)] |
---|
[6e5b2a7] | 570 | wait_for = [kernel(self.queue, self.q_input.global_size, None, |
---|
| 571 | *args, wait_for=wait_for)] |
---|
| 572 | if stop < call_details.num_eval: |
---|
| 573 | # Allow other processes to run |
---|
| 574 | wait_for[0].wait() |
---|
| 575 | current_time = time.clock() |
---|
| 576 | if current_time - last_nap > 0.5: |
---|
| 577 | time.sleep(0.05) |
---|
| 578 | last_nap = current_time |
---|
[c072f83] | 579 | cl.enqueue_copy(self.queue, self.result, self.result_b) |
---|
[bde38b5] | 580 | #print("result", self.result) |
---|
[ae2b6b5] | 581 | |
---|
| 582 | # Free buffers |
---|
[a738209] | 583 | for v in (details_b, values_b): |
---|
[c1114bf] | 584 | if v is not None: |
---|
| 585 | v.release() |
---|
[14de349] | 586 | |
---|
[14a15a3] | 587 | pd_norm = self.result[self.q_input.nq] |
---|
[c1114bf] | 588 | scale = values[0]/(pd_norm if pd_norm != 0.0 else 1.0) |
---|
[9eb3632] | 589 | background = values[1] |
---|
[14a15a3] | 590 | #print("scale",scale,values[0],self.result[self.q_input.nq],background) |
---|
[9eb3632] | 591 | return scale*self.result[:self.q_input.nq] + background |
---|
| 592 | # return self.result[:self.q_input.nq] |
---|
[14de349] | 593 | |
---|
| 594 | def release(self): |
---|
[dd7fc12] | 595 | # type: () -> None |
---|
[eafc9fa] | 596 | """ |
---|
| 597 | Release resources associated with the kernel. |
---|
| 598 | """ |
---|
[d18582e] | 599 | for v in self._need_release: |
---|
| 600 | v.release() |
---|
| 601 | self._need_release = [] |
---|
[14de349] | 602 | |
---|
| 603 | def __del__(self): |
---|
[dd7fc12] | 604 | # type: () -> None |
---|
[14de349] | 605 | self.release() |
---|