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