OpenCL Runtime¶
Version Queries¶
-
pyopencl.VERSION¶ Gives the numeric version of PyOpenCL as a variable-length tuple of integers. Enables easy version checks such as VERSION >= (0, 93).
-
pyopencl.VERSION_STATUS¶ A text string such as “rc4” or “beta” qualifying the status of the release.
-
pyopencl.VERSION_TEXT¶ The full release name (such as “0.93rc4”) in string form.
-
pyopencl.get_cl_header_version()¶ Return a variable-length tuple of integers representing the version of the OpenCL header against which PyOpenCL was compiled.
New in version 0.92.
Error Reporting¶
-
class
pyopencl.Error¶ Base class for all PyOpenCL exceptions.
-
class
pyopencl.MemoryError¶
-
class
pyopencl.LogicError¶
-
class
pyopencl.RuntimeError¶
Constants¶
Platforms, Devices and Contexts¶
-
class
pyopencl.Platform¶ -
info¶ Lower case versions of the
platform_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
get_info(param)¶ See
platform_infofor values of param.
-
get_devices(device_type=device_type.ALL)¶ Return a list of devices matching device_type. See
device_typefor values of device_type.
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
-
-
class
pyopencl.Device¶ -
info¶ Lower case versions of the
device_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
get_info(param)¶ See
device_infofor values of param.
Two instances of this class may be compared using ==” and ”!=”.
-
-
class
pyopencl.Context(devices=None, properties=None, dev_type=None)¶ Create a new context. properties is a list of key-value tuples, where each key must be one of
context_properties. At most one of devices and dev_type may be not None, where devices is a list ofDeviceinstances, and dev_type is one of thedevice_typeconstants. If neither is specified, a context with a dev_type ofdevice_type.DEFAULTis created.Note
Calling the constructor with no arguments will fail for recent CL drivers that support the OpenCL ICD. If you want similar, just-give-me-a-context-already behavior, we recommend
create_some_context(). See, e.g. this explanation by AMD.Note
For
context_properties.CL_GL_CONTEXT_KHR,context_properties.CL_EGL_DISPLAY_KHR,context_properties.CL_GLX_DISPLAY_KHR,context_properties.CL_WGL_HDC_KHR, andcontext_properties.CL_CGL_SHAREGROUP_KHRcontext_properties.CL_CGL_SHAREGROUP_APPLEthe value in the key-value pair is a PyOpenGL context or display instance.Changed in version 0.91.2: Constructor arguments dev_type added.
-
info¶ Lower case versions of the
context_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
get_info(param)¶ See
context_infofor values of param.
-
create_sub_devices(properties)¶ properties is an array of one (or more) of the forms:
[ dpp.EQUALLY, 8] [ dpp.BY_COUNTS, 5, 7, 9, dpp.PARTITION_BY_COUNTS_LIST_END] [ dpp.BY_NAMES, 5, 7, 9, dpp.PARTITION_BY_NAMES_LIST_END] [ dpp.BY_AFFINITY_DOMAIN, dad.L1_CACHE]
where dpp represents
device_partition_propertyand dad representdevice_affinity_domain.PROPERTIES_LIST_END_EXT is added automatically.
Only available with CL 1.2.
New in version 2011.2.
-
create_sub_devices_ext(properties)¶ properties is an array of one (or more) of the forms:
[ dppe.EQUALLY, 8] [ dppe.BY_COUNTS, 5, 7, 9, dppe.PARTITION_BY_COUNTS_LIST_END] [ dppe.BY_NAMES, 5, 7, 9, dppe.PARTITION_BY_NAMES_LIST_END] [ dppe.BY_AFFINITY_DOMAIN, ad.L1_CACHE]
where dppe represents
device_partition_property_extand ad representaffinity_domain_ext.PROPERTIES_LIST_END_EXT is added automatically.
Only available with the cl_ext_device_fission extension.
New in version 2011.1.
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
-
-
pyopencl.create_some_context(interactive=True)¶ Create a
Context‘somehow’.If multiple choices for platform and/or device exist, interactive is True, and sys.stdin.isatty() is also True, then the user is queried about which device should be chosen. Otherwise, a device is chosen in an implementation-defined manner.
Command Queues and Events¶
-
class
pyopencl.CommandQueue(context, device=None, properties=None)¶ Create a new command queue. properties is a bit field consisting of
command_queue_propertiesvalues.if device is None, one of the devices in context is chosen in an implementation-defined manner.
A
CommandQueuemay be used as a context manager, like this:with cl.CommandQueue(self.cl_context) as queue: enqueue_stuff(queue, ...)
finish()is automatically called at the end of the context.New in version 2013.1: Context manager capability.
-
info¶ Lower case versions of the
command_queue_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
get_info(param)¶ See
command_queue_infofor values of param.
-
set_property(prop, enable)¶ See
command_queue_propertiesfor possible values of prop. enable is abool.Unavailable in OpenCL 1.1 and newer.
-
flush()¶
-
finish()¶
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
-
-
class
pyopencl.Event¶ -
info¶ Lower case versions of the
event_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
profile.info¶ Lower case versions of the
profiling_infoconstants may be used as attributes on the attribute profile of this class to directly query profiling info.For example, you may use evt.profile.end instead of evt.get_profiling_info(pyopencl.profiling_info.END).
-
get_info(param)¶ See
event_infofor values of param.
-
get_profiling_info(param)¶ See
profiling_infofor values of param. Seeprofilefor an easier way of obtaining the same information.
-
wait()¶
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
-
-
pyopencl.wait_for_events(events)¶
-
pyopencl.enqueue_barrier(queue, wait_for=None)¶ Enqueues a barrier operation. which ensures that all queued commands in command_queue have finished execution. This command is a synchronization point.
New in version 0.91.5.
Changed in version 2011.2: Takes wait_for and returns an
Event
-
pyopencl.enqueue_marker(queue, wait_for=None)¶ Returns an
Event.Changed in version 2011.2: Takes wait_for.
-
pyopencl.enqueue_wait_for_events(queue, events)¶ - Note: This function is deprecated as of PyOpenCL 2011.2.
- Use
enqueue_marker()instead.
-
class
pyopencl.UserEvent(context)¶ A subclass of
Event. Only available with OpenCL 1.1 and newer.New in version 0.92.
-
set_status(status)¶ See
command_execution_statusfor possible values of status.
-
-
class
pyopencl.NannyEvent¶ Transfers between host and device return events of this type. They hold a reference to the host-side buffer and wait for the transfer to complete when they are freed. Therefore, they can safely release the reference to the object they’re guarding upon destruction.
A subclass of
Event.New in version 2011.2.
-
get_ward()¶
-
wait()¶ In addition to performing the same wait as
Event.wait(), this method also releases the reference to the guarded object.
-
Memory¶
-
class
pyopencl.MemoryObject¶ -
info¶ Lower case versions of the
mem_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
hostbuf¶
-
get_info(param)¶ See
mem_infofor values of param.
-
release()¶
-
get_host_array(shape, dtype, order="C")¶ Return the memory object’s associated host memory area as a
numpy.ndarrayof the given shape, dtype and order.
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
-
-
pyopencl.enqueue_migrate_mem_objects(queue, mem_objects, flags=0, wait_for=None)¶ Parameters: flags – from mem_migration_flagsNew in version 2011.2.
Only available with CL 1.2.
-
pyopencl.enqueue_migrate_mem_object_ext(queue, mem_objects, flags=0, wait_for=None)¶ Parameters: flags – from migrate_mem_object_flags_extNew in version 2011.2.
Only available with the cl_ext_migrate_memobject extension.
Buffers¶
-
class
pyopencl.Buffer(context, flags, size=0, hostbuf=None)¶ Create a
Buffer. Seemem_flagsfor values of flags. If hostbuf is specified, size defaults to the size of the specified buffer if it is passed as zero.Bufferis a subclass ofMemoryObject.Note that actual memory allocation in OpenCL may be deferred. Buffers are attached to a
Contextand are only moved to a device once the buffer is used on that device. That is also the point when out-of-memory errors will occur. If you’d like to be sure that there’s enough memory for your allocation, either useenqueue_migrate_mem_objects()(if available) or simply perform a small transfer to the buffer. See alsopyopencl.tools.ImmediateAllocator.-
get_sub_region(origin, size, flags=0)¶ Only available in OpenCL 1.1 and newer.
-
__getitem__(slc)¶ slc is a
sliceobject indicating from which byte index range a sub-buffer is to be created. The flags argument ofget_sub_region()is set to the same flags with which self was created.
-
-
pyopencl.enqueue_fill_buffer(queue, mem, pattern, offset, size, wait_for=None)¶ Parameters: pattern – a buffer object (likely a numpy.ndarray)Returns a new
pyopencl.Event. wait_for may either be None or a list ofpyopencl.Eventinstances for whose completion this command waits before starting exeuction.Only available with CL 1.2.
New in version 2011.2.
Image Formats¶
-
class
pyopencl.ImageFormat([channel_order, channel_type])¶ Changed in version 0.91: Constructor arguments added.
-
channel_order¶ See
channel_orderfor possible values.
-
channel_data_type¶ See
channel_typefor possible values.
-
channel_count¶ New in version 0.91.5.
-
dtype_size¶ New in version 0.91.5.
-
itemsize¶ New in version 0.91.5.
-
-
pyopencl.get_supported_image_formats(context, flags, image_type)¶ See
mem_flagsfor possible values of flags andmem_object_typefor possible values of image_type.
Images¶
-
Image(context, flags, format, shape=None, pitches=None, hostbuf=None, is_array=False, buffer=None): See
mem_flagsfor values of flags. shape is a 2- or 3-tuple. format is an instance ofImageFormat. pitches is a 1-tuple for 2D images and a 2-tuple for 3D images, indicating the distance in bytes from one scan line to the next, and from one 2D image slice to the next.If hostbuf is given and shape is None, then hostbuf.shape is used as the shape parameter.
Imageis a subclass ofMemoryObject.Note
If you want to load images from
numpy.ndarrayinstances or read images back into them, be aware that OpenCL images expect the x dimension to vary fastest, whereas in the default (C) order ofnumpyarrays, the last index varies fastest. If your array is arranged in the wrong order in memory, there are two possible fixes for this:- Convert the array to Fortran (column-major) order using
numpy.asarray(). - Pass ary.T.copy() to the image creation function.
New in version 0.91.
Changed in version 2011.2: Added is_array and buffer, which are only available on CL 1.2 and newer.
-
pyopencl.info¶ Lower case versions of the
mem_infoandimage_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
pyopencl.get_image_info(param)¶ See
image_infofor values of param.
-
pyopencl.release()¶
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
- Convert the array to Fortran (column-major) order using
-
pyopencl.image_from_array(ctx, ary, num_channels=None, mode="r", norm_int=False)¶ Build a 2D or 3D
Imagefrom thenumpy.ndarrayary. If num_channels is greater than one, the last dimension of ary must be identical to num_channels. ary must be in C order. If num_channels is not given, it defaults to 1 for scalar types and the number of entries for Vector Types.The
ImageFormatis chosen as the first num_channels components of “RGBA”.Parameters: mode – “r” or “w” for read/write Note
When reading from the image object, the indices passed to read_imagef are in the reverse order from what they would be when accessing ary from Python.
If norm_int is True, then the integer values are normalized to a floating point scale of 0..1 when read.
New in version 2011.2.
-
pyopencl.enqueue_fill_image(queue, mem, color, origin, region, wait_for=None)¶ Parameters: color – a buffer object (likely a numpy.ndarray)Returns a new
pyopencl.Event. wait_for may either be None or a list ofpyopencl.Eventinstances for whose completion this command waits before starting exeuction.Only available with CL 1.2.
New in version 2011.2.
Transfers¶
Mapping Memory into Host Address Space¶
-
pyopencl.enqueue_map_buffer(queue, buf, flags, offset, shape, dtype, order="C", wait_for=None, is_blocking=True)¶ wait_for may either be None or a list of
pyopencl.Eventinstances for whose completion this command waits before starting exeuction. shape, dtype, and order have the same meaning as innumpy.empty(). Seemap_flagsfor possible values of flags.Returns: a tuple (array, event). array is a numpy.ndarrayrepresenting the host side of the map. Its .base member contains aMemoryMap.Changed in version 2011.1: is_blocking now defaults to True.
Changed in version 2013.1: order now defaults to “C”.
-
pyopencl.enqueue_map_image(queue, buf, flags, origin, region, shape, dtype, order="C", wait_for=None, is_blocking=True)¶ wait_for may either be None or a list of
pyopencl.Eventinstances for whose completion this command waits before starting exeuction. shape, dtype, and order have the same meaning as innumpy.empty(). Seemap_flagsfor possible values of flags.Returns: a tuple (array, event). array is a numpy.ndarrayrepresenting the host side of the map. Its .base member contains aMemoryMap.Changed in version 2011.1: is_blocking now defaults to True.
Changed in version 2013.1: order now defaults to “C”.
Samplers¶
-
class
pyopencl.Sampler(context, normalized_coords, addressing_mode, filter_mode)¶ normalized_coords is a
boolindicating whether to use coordinates between 0 and 1 (True) or the texture’s natural pixel size (False). Seeaddressing_modeandfilter_modefor possible argument values.-
info¶ Lower case versions of the
sampler_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
get_info(param)¶ See
sampler_infofor values of param.
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
-
Programs and Kernels¶
-
class
pyopencl.Program(context, src)¶ -
class
pyopencl.Program(context, devices, binaries) binaries must contain one binary for each entry in devices.
-
info¶ Lower case versions of the
program_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
get_info(param)¶ See
program_infofor values of param.
-
get_build_info(device, param)¶ See
program_build_infofor values of param.
-
build(options=[], devices=None)¶ options is a string of compiler flags. Returns self.
By default, built binaries are cached in an on-disk cache called
pyopencl-compiler-cache-vN-uidNAME-pyVERSIONin the directory returned bytempfile.gettempdir(). By setting the environment variablePYOPENCL_NO_CACHEto any non-empty value, this caching is suppressed. Any options found in the environment variablePYOPENCL_BUILD_OPTIONSwill be appened to options.Changed in version 2013.1: Added
PYOPENCL_NO_CACHE. AddedPYOPENCL_BUILD_OPTIONS.
-
compile(self, options=[], devices=None, headers=[])¶ Parameters: headers – a list of tuples (name, program). Only available with CL 1.2.
New in version 2011.2.
-
kernel_name¶ Kernelobjects can be produced from a built (seebuild()) program simply by attribute lookup.Note
The
program_infoattributes live in the same name space and take precedence overKernelnames.
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
-
-
pyopencl.create_program_with_built_in_kernels(context, devices, kernel_names)¶ Only available with CL 1.2.
New in version 2011.2.
-
pyopencl.link_program(context, programs, options=[], devices=None)¶ Only available with CL 1.2.
New in version 2011.2.
-
pyopencl.unload_platform_compiler(platform)¶ Only available with CL 1.2.
New in version 2011.2.
-
class
pyopencl.Kernel(program, name)¶ -
info¶ Lower case versions of the
kernel_infoconstants may be used as attributes on instances of this class to directly query info attributes.
-
get_info(param)¶ See
kernel_infofor values of param.
-
get_work_group_info(param, device)¶ See
kernel_work_group_infofor values of param.
-
get_arg_info(arg_index, param)¶ See
kernel_arg_infofor values of param.Only available in OpenCL 1.2 and newer.
-
set_arg(self, index, arg)¶ arg may be
None: This may be passed for __global memory references to pass a NULL pointer to the kernel.
Anything that satisfies the Python buffer interface, in particular
numpy.ndarray,str, ornumpy‘s sized scalars, such asnumpy.int32ornumpy.float64.Note
Note that Python’s own
intorfloatobjects will not work out of the box. SeeKernel.set_scalar_arg_dtypes()for a way to make them work. Alternatively, the standard library modulestructcan be used to convert Python’s native number types to binary data in astr.An instance of
MemoryObject. (e.g.Buffer,Image, etc.)An instance of
LocalMemory.An instance of
Sampler.
-
set_scalar_arg_dtypes(arg_dtypes)¶ Inform the wrapper about the sized types of scalar
Kernelarguments. For each argument, arg_dtypes contains an entry. For non-scalars, this must be None. For scalars, it must be an object acceptable to thenumpy.dtypeconstructor, indicating that the corresponding scalar argument is of that type.After invoking this function with the proper information, most suitable number types will automatically be cast to the right type for kernel invocation.
Note
The information set by this rountine is attached to a single kernel instance. A new kernel instance is created every time you use program.kernel attribute access. The following will therefore not work:
prg = cl.Program(...).build() prg.kernel.set_scalar_arg_dtypes(...) prg.kernel(queue, n_globals, None, args)
-
__call__(queue, global_size, local_size, *args, global_offset=None, wait_for=None, g_times_l=False)¶ Use
enqueue_nd_range_kernel()to enqueue a kernel execution, after usingset_args()to set each argument in turn. See the documentation forset_arg()to see what argument types are allowed. Returns a newpyopencl.Event. wait_for may either be None or a list ofpyopencl.Eventinstances for whose completion this command waits before starting exeuction.None may be passed for local_size.
If g_times_l is specified, the global size will be multiplied by the local size. (which makes the behavior more like Nvidia CUDA) In this case, global_size and local_size also do not have to have the same number of dimensions.
Note
__call__()is not thread-safe. It sets the arguments usingset_args()and then runsenqueue_nd_range_kernel(). Another thread could race it in doing the same things, with undefined outcome. This issue is inherited from the C-level OpenCL API. The recommended solution is to make a kernel (i.e. access prg.kernel_name, which corresponds to making a new kernel) for every thread that may enqueue calls to the kernel.A solution involving implicit locks was discussed and decided against on the mailing list in October 2012.
Changed in version 0.92: local_size was promoted to third positional argument from being a keyword argument. The old keyword argument usage will continue to be accepted with a warning throughout the 0.92 release cycle. This is a backward-compatible change (just barely!) because local_size as third positional argument can only be a
tupleor None.tupleinstances are never validKernelarguments, and None is valid as an argument, but its treatment in the wrapper had a bug (now fixed) that prevented it from working.Changed in version 2011.1: Added the g_times_l keyword arg.
-
capture_call(filename, queue, global_size, local_size, *args, global_offset=None, wait_for=None, g_times_l=False)¶ This method supports the exact same interface as
__call__(), but instead of invoking the kernel, it writes a self-contained PyOpenCL program to filename that reproduces this invocation. Data and kernel source code will be packaged up in filename‘s source code.This is mainly intended as a debugging aid. For example, it can be used to automate the task of creating a small, self-contained test case for an observed problem. It can also help separate a misbehaving kernel from a potentially large or time-consuming outer code.
To use, simply change:
evt = my_kernel(queue, gsize, lsize, arg1, arg2, ...)
to:
evt = my_kernel.capture_call("bug.py", queue, gsize, lsize, arg1, arg2, ...)
New in version 2013.1.
Instances of this class are hashable, and two instances of this class may be compared using “==” and ”!=”. (Hashability was added in version 2011.2.)
-
-
class
pyopencl.LocalMemory(size)¶ A helper class to pass __local memory arguments to kernels.
New in version 0.91.2.
-
size¶ The size of local buffer in bytes to be provided.
-
-
pyopencl.enqueue_nd_range_kernel(queue, kernel, global_work_size, local_work_size, global_work_offset=None, wait_for=None, g_times_l=False)¶ Returns a new
pyopencl.Event. wait_for may either be None or a list ofpyopencl.Eventinstances for whose completion this command waits before starting exeuction.If g_times_l is specified, the global size will be multiplied by the local size. (which makes the behavior more like Nvidia CUDA) In this case, global_size and local_size also do not have to have the same number of dimensions.
Changed in version 2011.1: Added the g_times_l keyword arg.
-
pyopencl.enqueue_task(queue, kernel, wait_for=None)¶ Returns a new
pyopencl.Event. wait_for may either be None or a list ofpyopencl.Eventinstances for whose completion this command waits before starting exeuction.
GL Interoperability¶
Functionality in this section is only available when PyOpenCL is compiled
with GL support. See have_gl().
New in version 0.91.
-
pyopencl.have_gl()¶ Return True if PyOpenCL was compiled with OpenGL interoperability, otherwise False.
-
pyopencl.get_gl_sharing_context_properties()¶ Return a
listofcontext_propertiesthat will allow a newly created context to share the currently active GL context.
Get share group handle for current CGL context.
Apple OS X only.
New in version 2011.1.
-
class
pyopencl.GLBuffer(context, flags, bufobj)¶ GLBufferis a subclass ofMemoryObject.-
gl_object¶
-
-
class
pyopencl.GLRenderBuffer(context, flags, bufobj)¶ GLRenderBufferis a subclass ofMemoryObject.-
gl_object¶
-
-
class
pyopencl.GLTexture(context, flags, texture_target, miplevel, texture, dims)¶ dims is either 2 or 3.
GLTextureis a subclass ofImage.-
gl_object¶
-
-
pyopencl.enqueue_acquire_gl_objects(queue, mem_objects, wait_for=None)¶ mem_objects is a list of
MemoryObjectinstances. Returns a newpyopencl.Event. wait_for may either be None or a list ofpyopencl.Eventinstances for whose completion this command waits before starting exeuction.
-
pyopencl.enqueue_release_gl_objects(queue, mem_objects, wait_for=None)¶ mem_objects is a list of
MemoryObjectinstances. Returns a newpyopencl.Event. wait_for may either be None or a list ofpyopencl.Eventinstances for whose completion this command waits before starting exeuction.
-
pyopencl.get_gl_context_info_khr(properties, param_name, platform=None)¶ Get information on which CL device corresponds to a given GL/EGL/WGL/CGL device.
See the
Contextconstructor for the meaning of properties andgl_context_infofor param_name.Changed in version 2011.2: Accepts the platform argument. Using platform equal to None is deprecated as of PyOpenCL 2011.2.