Multidimensional arraysΒΆ
The functionality in this module provides something of a workalike for
numpy
arrays, but with all operations executed on the CL compute device.
Data TypesΒΆ
PyOpenCL provides some amount of integration between the numpy
type system, as represented by numpy.dtype
, and the types
available in OpenCL. All the simple scalar types map straightforwardly
to their CL counterparts.
Vector TypesΒΆ

class
pyopencl.array.
vec
ΒΆ All of OpenCLβs supported vector types, such as float3 and long4 are available as
numpy
data types within this class. Thesenumpy.dtype
instances have field names of x, y, z, and w just like their OpenCL counterparts. They will work both for parameter passing to kernels as well as for passing data back and forth between kernels and Python code. For each type, a make_type function is also provided (e.g. make_float3(x,y,z)).If you want to construct a preinitialized vector type you have three new functions to choose from:
zeros_type()
ones_type()
filled_type(fill_value)
New in version 2014.1.
Changed in version 2014.1: The make_type functions have a default value (0) for each component. Relying on the default values has been deprecated. Either specify all components or use one of th new flavors mentioned above for constructing a vector.
Custom data typesΒΆ
If you would like to use your own (struct/union/whatever) data types in array
operations where you supply operation source code, define those types in the
preamble passed to pyopencl.elementwise.ElementwiseKernel
,
pyopencl.reduction.ReductionKernel
(or similar), and let PyOpenCL know
about them using this function:

pyopencl.tools.
get_or_register_dtype
(c_names, dtype=None)ΒΆ Get or register a
numpy.dtype
associated with the C type names in the string list c_names. If dtype is None, no registration is performed, and thenumpy.dtype
must already have been registered. If so, it is returned. If not,TypeNameNotKnown
is raised.If dtype is not None, registration is attempted. If the c_names are already known and registered to identical
numpy.dtype
objects, then the previously dtype object of the previously registered type is returned. If the c_names are not yet known, the type is registered. If one of the c_names is known but registered to a different type, an error is raised. In this latter case, the type may end up partially registered and any further behavior is undefined.New in version 2012.2.

exception
pyopencl.tools.
TypeNameNotKnown
ΒΆ New in version 2013.1.

pyopencl.tools.
register_dtype
(dtype, name)ΒΆ Changed in version 2013.1: This function has been deprecated. It is recommended that you develop against the new interface,
get_or_register_dtype()
.

pyopencl.tools.
dtype_to_ctype
(dtype)ΒΆ Returns a C name registered for dtype.
This function helps with producing C/OpenCL declarations for structured
numpy.dtype
instances:

pyopencl.tools.
match_dtype_to_c_struct
(device, name, dtype, context=None)ΒΆ Return a tuple (dtype, c_decl) such that the C struct declaration in c_decl and the structure
numpy.dtype
instance dtype have the same memory layout.Note that dtype may be modified from the value that was passed in, for example to insert padding.
(As a remark on implementation, this routine runs a small kernel on the given device to ensure that
numpy
and C offsets and sizes match.)This example explains the use of this function:
>>> import numpy as np >>> import pyopencl as cl >>> import pyopencl.tools >>> ctx = cl.create_some_context() >>> dtype = np.dtype([("id", np.uint32), ("value", np.float32)]) >>> dtype, c_decl = pyopencl.tools.match_dtype_to_c_struct( ... ctx.devices[0], 'id_val', dtype) >>> print c_decl typedef struct { unsigned id; float value; } id_val; >>> print dtype [('id', '<u4'), ('value', '<f4')] >>> cl.tools.get_or_register_dtype('id_val', dtype)
As this example shows, it is important to call
get_or_register_dtype()
on the modified dtype returned by this function, not the original one.
A more complete example of how to use custom structured types can be
found in examples/demostructreduce.py
in the PyOpenCL
distribution.
Complex NumbersΒΆ
PyOpenCLβs Array
type supports complex numbers out of the box, by
simply using the corresponding numpy
types.
If you would like to use this support in your own kernels, hereβs how to proceed: Since OpenCL 1.2 (and earlier) do not specify native complex number support, PyOpenCL works around that deficiency. By saying:
#include <pyopenclcomplex.h>
in your kernel, you get complex types cfloat_t and cdouble_t, along with functions defined on them such as cfloat_mul(a, b) or cdouble_log(z). Elementwise kernels automatically include the header if your kernel has complex input or output. See the source file for a precise list of whatβs available.
If you need double precision support, please:
#define PYOPENCL_DEFINE_CDOUBLE
before including the header, as DP support apparently cannot be reliably autodetected.
Under the hood, the complex types are struct types as defined in the header. Ideally, you should only access the structs through the provided functions, never directly.
New in version 2012.1.
Changed in version 2015.2: [INCOMPATIBLE] Changed PyOpenCLβs complex numbers from float2
and
double2
OpenCL vector types to custom struct
. This was changed
because it very easily introduced bugs where
complex*complex
real+complex
look like they may do the right thing, but silently do the wrong thing.
The Array
ClassΒΆ

class
pyopencl.array.
Array
(cq, shape, dtype, order='C', allocator=None, data=None, offset=0, strides=None, events=None, _flags=None)ΒΆ A
numpy.ndarray
workalike that stores its data and performs its computations on the compute device. shape and dtype work exactly as innumpy
. Arithmetic methods inArray
support the broadcasting of scalars. (e.g. array+5)cq must be a
CommandQueue
or aContext
.If it is a queue, cq specifies the queue in which the array carries out its computations by default. If a default queue (and thereby overloaded operators and many other niceties) are not desired, pass a
Context
.allocator may be None or a callable that, upon being called with an argument of the number of bytes to be allocated, returns an
pyopencl.Buffer
object. (Apyopencl.tools.MemoryPool
instance is one useful example of an object to pass here.)Changed in version 2011.1: Renamed context to cqa, made it generalpurpose.
All arguments beyond order should be considered keywordonly.
Changed in version 2015.2: Renamed context to cq, disallowed passing allocators through it.

data
ΒΆ The
pyopencl.MemoryObject
instance created for the memory that backs thisArray
.Changed in version 2013.1: If a nonzero
offset
has been specified for this array, this will fail withArrayHasOffsetError
.

base_data
ΒΆ The
pyopencl.MemoryObject
instance created for the memory that backs thisArray
. Unlikedata
, the base address of base_data is allowed to be different from the beginning of the array. The actual beginning is the base address of base_data plusoffset
bytes.Unlike
data
, retrievingbase_data
always succeeds.New in version 2013.1.

shape
ΒΆ The tuple of lengths of each dimension in the array.

dtype
ΒΆ The
numpy.dtype
of the items in the GPU array.

size
ΒΆ The number of meaningful entries in the array. Can also be computed by multiplying up the numbers in
shape
.

strides
ΒΆ Tuple of bytes to step in each dimension when traversing an array.

flags
ΒΆ Return an object with attributes c_contiguous, f_contiguous and forc, which may be used to query contiguity properties in analogy to
numpy.ndarray.flags
.
Methods

with_queue
(queue)ΒΆ Return a copy of self with the default queue set to queue.
None is allowed as a value for queue.
New in version 2013.1.

__len__
()ΒΆ Returns the size of the leading dimension of self.

reshape
(*shape, **kwargs)ΒΆ Returns an array containing the same data with a new shape.

ravel
()ΒΆ Returns flattened array containing the same data.

view
(dtype=None)ΒΆ Returns view of array with the same data. If dtype is different from current dtype, the actual bytes of memory will be reinterpreted.

squeeze
()ΒΆ Returns a view of the array with dimensions of length 1 removed.
New in version 2015.2.

transpose
(axes=None)ΒΆ Permute the dimensions of an array.
 Parameters
axes β list of ints, optional. By default, reverse the dimensions, otherwise permute the axes according to the values given.
 Returns
Array
A view of the array with its axes permuted.
New in version 2015.2.

T
ΒΆ

set
(ary, queue=None, async_=None, **kwargs)ΒΆ Transfer the contents the
numpy.ndarray
object ary onto the device.ary must have the same dtype and size (not necessarily shape) as self.
async_ is a Boolean indicating whether the function is allowed to return before the transfer completes. To avoid synchronization bugs, this defaults to False.
Changed in version 2017.2.1: Python 3.7 makes
async
a reserved keyword. On older Pythons, we will continue to accept async as a parameter, however this should be considered deprecated. async_ is the new, official spelling.

get
(queue=None, ary=None, async_=None, **kwargs)ΒΆ Transfer the contents of self into ary or a newly allocated
numpy.ndarray
. If ary is given, it must have the same shape and dtype.Changed in version 2019.1.2: Calling with async_=True was deprecated and replaced by
get_async()
. The event returned bypyopencl.enqueue_copy()
is now stored intoevents
to ensure data is not modified before the copy is complete.Changed in version 2015.2: ary with different shape was deprecated.
Changed in version 2017.2.1: Python 3.7 makes
async
a reserved keyword. On older Pythons, we will continue to accept async as a parameter, however this should be considered deprecated. async_ is the new, official spelling.

get_async
(queue=None, ary=None, **kwargs)ΒΆ Asynchronous version of
get()
which returns a tuple(ary, event)
containing the host array ary and thepyopencl.NannyEvent
event returned bypyopencl.enqueue_copy()
.New in version 2019.1.2.

copy
(queue=<class 'pyopencl.array._copy_queue'>)ΒΆ  Parameters
queue β The
CommandQueue
for the returned array.
Changed in version 2017.1.2: Updates the queue of the returned array.
New in version 2013.1.

__str__
()ΒΆ Return str(self).

__repr__
()ΒΆ Return repr(self).

mul_add
(selffac, other, otherfac, queue=None)ΒΆ Return selffac * self + otherfac*other.

__add__
(other)ΒΆ Add an array with an array or an array with a scalar.

__sub__
(other)ΒΆ Substract an array from an array or a scalar from an array.

__iadd__
(other)ΒΆ

__isub__
(other)ΒΆ

__neg__
()ΒΆ

__mul__
(other)ΒΆ

__div__
(other)ΒΆ Divides an array by an array or a scalar, i.e.
self / other
.

__rdiv__
(other)ΒΆ Divides an array by a scalar or an array, i.e.
other / self
.

__and__
(other)ΒΆ

__xor__
(other)ΒΆ

__or__
(other)ΒΆ

__iand__
(other)ΒΆ

__ixor__
(other)ΒΆ

__ior__
(other)ΒΆ

__abs__
()ΒΆ Return a Array of the absolute values of the elements of self.

__invert__
()ΒΆ

fill
(value, queue=None, wait_for=None)ΒΆ Fill the array with scalar.
 Returns
self.

astype
(dtype, queue=None)ΒΆ Return a copy of self, cast to dtype.

real
ΒΆ New in version 2012.1.

imag
ΒΆ New in version 2012.1.

conj
()ΒΆ New in version 2012.1.

conjugate
()ΒΆ New in version 2012.1.

__getitem__
(index)ΒΆ New in version 2013.1.

__setitem__
(subscript, value)ΒΆ Set the slice of self identified subscript to value.
value is allowed to be:
A
Array
of the sameshape
and (for now)strides
, but with potentially differentdtype
.A
numpy.ndarray
of the sameshape
and (for now)strides
, but with potentially differentdtype
.A scalar.
Nonscalar broadcasting is not currently supported.
New in version 2013.1.

setitem
(subscript, value, queue=None, wait_for=None)ΒΆ Like
__setitem__()
, but with the ability to specify a queue and wait_for.New in version 2013.1.
Changed in version 2013.2: Added wait_for.

map_to_host
(queue=None, flags=None, is_blocking=True, wait_for=None)ΒΆ If is_blocking, return a
numpy.ndarray
corresponding to the same memory as self.If is_blocking is not true, return a tuple
(ary, evt)
, where ary is the abovementioned array.The host array is obtained using
pyopencl.enqueue_map_buffer()
. See there for further details. Parameters
flags β A combination of
pyopencl.map_flags
. Defaults to readwrite.
New in version 2013.2.
Comparisons, conditionals, any, all
New in version 2013.2.
Boolean arrays are stored as
numpy.int8
becausebool
has an unspecified size in the OpenCL spec.
__nonzero__
()ΒΆ Only works for device scalars. (i.e. βarraysβ with
shape == ()
.)

any
(queue=None, wait_for=None)ΒΆ

all
(queue=None, wait_for=None)ΒΆ

__eq__
(other)ΒΆ Return self==value.

__ne__
(other)ΒΆ Return self!=value.

__lt__
(other)ΒΆ Return self<value.

__le__
(other)ΒΆ Return self<=value.

__gt__
(other)ΒΆ Return self>value.

__ge__
(other)ΒΆ Return self>=value.
Event management
If an array is used from within an outoforder queue, it needs to take care of its own operation ordering. The facilities in this section make this possible.
New in version 2014.1.1.

events
ΒΆ A list of
pyopencl.Event
instances that the current content of this array depends on. User code may read, but should never modify this list directly. To update this list, instead use the following methods.


exception
pyopencl.array.
ArrayHasOffsetError
(val='The operation you are attempting does not yet support arrays that start at an offset from the beginning of their buffer.')ΒΆ New in version 2013.1.
Constructing Array
InstancesΒΆ

pyopencl.array.
to_device
(queue, ary, allocator=None, async_=None, array_queue=<class 'pyopencl.array._same_as_transfer'>, **kwargs)ΒΆ Return a
Array
that is an exact copy of thenumpy.ndarray
instance ary. Parameters
array_queue β The
CommandQueue
which will be stored in the resulting array. Useful to make sure there is no implicit queue associated with the array by passing None.
See
Array
for the meaning of allocator.Changed in version 2015.2: array_queue argument was added.
Changed in version 2017.2.1: Python 3.7 makes
async
a reserved keyword. On older Pythons, we will continue to accept async as a parameter, however this should be considered deprecated. async_ is the new, official spelling.

pyopencl.array.
empty
(queue, shape, dtype, order='C', allocator=None, data=None)ΒΆ A synonym for the
Array
constructor.

pyopencl.array.
zeros
(queue, shape, dtype, order='C', allocator=None)ΒΆ Same as
empty()
, but theArray
is zeroinitialized before being returned.Changed in version 2011.1: context argument was deprecated.

pyopencl.array.
empty_like
(ary, queue=<class 'pyopencl.array._copy_queue'>, allocator=None)ΒΆ Make a new, uninitialized
Array
having the same properties as other_ary.

pyopencl.array.
zeros_like
(ary)ΒΆ Make a new, zeroinitialized
Array
having the same properties as other_ary.

pyopencl.array.
arange
(queue, [start, ]stop, [step, ]**kwargs)ΒΆ Create a
Array
filled with numbers spaced step apart, starting from start and ending at stop. If not given, start defaults to 0, step defaults to 1.For floating point arguments, the length of the result is ceil((stop  start)/step). This rule may result in the last element of the result being greater than stop.
dtype is a required keyword argument.
Changed in version 2011.1: context argument was deprecated.
Changed in version 2011.2: allocator keyword argument was added.

pyopencl.array.
take
(a, indices, out=None, queue=None, wait_for=None)ΒΆ Return the
Array
[a[indices[0]], ..., a[indices[n]]]
. For the moment, a must be a type that can be bound to a texture.

pyopencl.array.
concatenate
(arrays, axis=0, queue=None, allocator=None)ΒΆ New in version 2013.1.
Manipulating Array
instancesΒΆ

pyopencl.array.
transpose
(a, axes=None)ΒΆ Permute the dimensions of an array.

pyopencl.array.
reshape
(a, shape)ΒΆ Gives a new shape to an array without changing its data.
New in version 2015.2.
ConditionalsΒΆ

pyopencl.array.
if_positive
(criterion, then_, else_, out=None, queue=None)ΒΆ Return an array like then_, which, for the element at index i, contains then_[i] if criterion[i]>0, else else_[i].

pyopencl.array.
maximum
(a, b, out=None, queue=None)ΒΆ Return the elementwise maximum of a and b.

pyopencl.array.
minimum
(a, b, out=None, queue=None)ΒΆ Return the elementwise minimum of a and b.
ReductionsΒΆ

pyopencl.array.
sum
(a, dtype=None, queue=None, slice=None)ΒΆ New in version 2011.1.

pyopencl.array.
dot
(a, b, dtype=None, queue=None, slice=None)ΒΆ New in version 2011.1.

pyopencl.array.
vdot
(a, b, dtype=None, queue=None, slice=None)ΒΆ Like
numpy.vdot()
.New in version 2013.1.

pyopencl.array.
subset_dot
(subset, a, b, dtype=None, queue=None, slice=None)ΒΆ New in version 2011.1.

pyopencl.array.
max
(a, queue=None)ΒΆ New in version 2011.1.

pyopencl.array.
min
(a, queue=None)ΒΆ New in version 2011.1.

pyopencl.array.
subset_max
(subset, a, queue=None, slice=None)ΒΆ New in version 2011.1.

pyopencl.array.
subset_min
(subset, a, queue=None, slice=None)ΒΆ New in version 2011.1.
See also Sums and counts (βreduceβ).
Elementwise Functions on Array
InstancesΒΆ
The pyopencl.clmath
module contains exposes array versions of the C
functions available in the OpenCL standard. (See table 6.8 in the spec.)

pyopencl.clmath.
acos
(array, queue=None)ΒΆ

pyopencl.clmath.
acosh
(array, queue=None)ΒΆ

pyopencl.clmath.
acospi
(array, queue=None)ΒΆ

pyopencl.clmath.
asin
(array, queue=None)ΒΆ

pyopencl.clmath.
asinh
(array, queue=None)ΒΆ

pyopencl.clmath.
asinpi
(array, queue=None)ΒΆ

pyopencl.clmath.
atan
(array, queue=None)ΒΆ

pyopencl.clmath.
atan2
(y, x, queue=None)ΒΆ New in version 2013.1.

pyopencl.clmath.
atanh
(array, queue=None)ΒΆ

pyopencl.clmath.
atanpi
(array, queue=None)ΒΆ

pyopencl.clmath.
atan2pi
(y, x, queue=None)ΒΆ New in version 2013.1.

pyopencl.clmath.
cbrt
(array, queue=None)ΒΆ

pyopencl.clmath.
ceil
(array, queue=None)ΒΆ

pyopencl.clmath.
cos
(array, queue=None)ΒΆ

pyopencl.clmath.
cosh
(array, queue=None)ΒΆ

pyopencl.clmath.
cospi
(array, queue=None)ΒΆ

pyopencl.clmath.
erfc
(array, queue=None)ΒΆ

pyopencl.clmath.
erf
(array, queue=None)ΒΆ

pyopencl.clmath.
exp
(array, queue=None)ΒΆ

pyopencl.clmath.
exp2
(array, queue=None)ΒΆ

pyopencl.clmath.
exp10
(array, queue=None)ΒΆ

pyopencl.clmath.
expm1
(array, queue=None)ΒΆ

pyopencl.clmath.
fabs
(array, queue=None)ΒΆ

pyopencl.clmath.
floor
(array, queue=None)ΒΆ

pyopencl.clmath.
fmod
(arg, mod, queue=None)ΒΆ Return the floating point remainder of the division arg/mod, for each element in arg and mod.

pyopencl.clmath.
frexp
(arg, queue=None)ΒΆ Return a tuple (significands, exponents) such that arg == significand * 2**exponent.

pyopencl.clmath.
ilogb
(array, queue=None)ΒΆ

pyopencl.clmath.
ldexp
(significand, exponent, queue=None)ΒΆ Return a new array of floating point values composed from the entries of significand and exponent, paired together as result = significand * 2**exponent.

pyopencl.clmath.
lgamma
(array, queue=None)ΒΆ

pyopencl.clmath.
log
(array, queue=None)ΒΆ

pyopencl.clmath.
log2
(array, queue=None)ΒΆ

pyopencl.clmath.
log10
(array, queue=None)ΒΆ

pyopencl.clmath.
log1p
(array, queue=None)ΒΆ

pyopencl.clmath.
logb
(array, queue=None)ΒΆ

pyopencl.clmath.
modf
(arg, queue=None)ΒΆ Return a tuple (fracpart, intpart) of arrays containing the integer and fractional parts of arg.

pyopencl.clmath.
nan
(array, queue=None)ΒΆ

pyopencl.clmath.
rint
(array, queue=None)ΒΆ

pyopencl.clmath.
round
(array, queue=None)ΒΆ

pyopencl.clmath.
sin
(array, queue=None)ΒΆ

pyopencl.clmath.
sinh
(array, queue=None)ΒΆ

pyopencl.clmath.
sinpi
(array, queue=None)ΒΆ

pyopencl.clmath.
sqrt
(array, queue=None)ΒΆ

pyopencl.clmath.
tan
(array, queue=None)ΒΆ

pyopencl.clmath.
tanh
(array, queue=None)ΒΆ

pyopencl.clmath.
tanpi
(array, queue=None)ΒΆ

pyopencl.clmath.
tgamma
(array, queue=None)ΒΆ

pyopencl.clmath.
trunc
(array, queue=None)ΒΆ
Generating Arrays of Random NumbersΒΆ
PyOpenCL now includes and uses some of the Random123 random number generators by D.E. Shaw Research. In addition to being usable through the convenience functions above, they are available in any piece of code compiled through PyOpenCL by:
#include <pyopenclrandom123/philox.cl>
#include <pyopenclrandom123/threefry.cl>
See the Philox source and the Threefry source for some documentation if youβre planning on using Random123 directly.
Note
PyOpenCL previously had documented support for the RANLUXCL random number
generator by Ivar Ursin
Nikolaisen. This support is now deprecated because of the general slowness
of these generators and will be removed from PyOpenCL in the 2018.x series.
All users are encouraged to switch to one of the Random123 genrators,
PhiloxGenerator
or ThreefryGenerator
.

class
pyopencl.clrandom.
PhiloxGenerator
(context, key=None, counter=None, seed=None)ΒΆ New in version 2016.2.

fill_uniform
(ary, a=0, b=1, queue=None)ΒΆ

uniform
(*args, **kwargs)ΒΆ Make a new empty array, apply
fill_uniform()
to it.

fill_normal
(ary, mu=0, sigma=1, queue=None)ΒΆ Fill ary with normally distributed numbers with mean mu and standard deviation sigma.

normal
(*args, **kwargs)ΒΆ Make a new empty array, apply
fill_normal()
to it.


class
pyopencl.clrandom.
ThreefryGenerator
(context, key=None, counter=None, seed=None)ΒΆ New in version 2016.2.

fill_uniform
(ary, a=0, b=1, queue=None)ΒΆ

uniform
(*args, **kwargs)ΒΆ Make a new empty array, apply
fill_uniform()
to it.

fill_normal
(ary, mu=0, sigma=1, queue=None)ΒΆ Fill ary with normally distributed numbers with mean mu and standard deviation sigma.

normal
(*args, **kwargs)ΒΆ Make a new empty array, apply
fill_normal()
to it.


pyopencl.clrandom.
rand
(queue, shape, dtype, luxury=None, a=0, b=1)ΒΆ Return an array of shape filled with random values of dtype in the range [a,b).

pyopencl.clrandom.
fill_rand
(result, queue=None, luxury=None, a=0, b=1)ΒΆ Fill result with random values of dtype in the range [0,1).