VexCL
C++ vector expression template library for OpenCL/CUDA

VexCL is a vector expression template library for OpenCL/CUDA. It has been created for ease of GPGPU development with C++. VexCL strives to reduce amount of boilerplate code needed to develop GPGPU applications. The library provides convenient and intuitive notation for vector arithmetic, reduction, sparse matrixvector products, etc. Multidevice and even multiplatform computations are supported. The source code of the library is distributed under very permissive MIT license.
The code is available at https://github.com/ddemidov/vexcl.
Doxygengenerated documentation: http://ddemidov.github.io/vexcl.
Slides from VexCLrelated talks:
The paper Programming CUDA and OpenCL: A Case Study Using Modern C++ Libraries compares both convenience and performance of several GPGPU libraries, including VexCL.
VexCL provides two backends: OpenCL and CUDA. In order to choose either of those, user has to define VEXCL_BACKEND_OPENCL
or VEXCL_BACKEND_CUDA
macros. In case neither of those are defined, OpenCL backend is chosen by default. One also has to link to either libOpenCL.so (OpenCL.dll) or libcuda.so (cuda.dll).
For the CUDA backend to work, CUDA Toolkit has to be installed, NVIDIA CUDA compiler driver nvcc
has to be in executable PATH and usable at runtime.
VexCL transparently works with multiple compute devices that are present in the system. A VexCL context is initialized with a device filter, which is just a functor that takes a reference to vex::device
and returns a bool
. Several standard filters are provided, but one can easily add a custom functor. Filters may be combined with logical operators. All compute devices that satisfy the provided filter are added to the created context. In the example below all GPU devices that support double precision arithmetic are selected:
One of the most convenient filters is vex::Filter::Env
which selects compute devices based on environment variables. It allows to switch compute device without need to recompile the program.
The vex::vector<T>
class constructor accepts a const reference to std::vector<vex::command_queue>
. A vex::Context
instance may be conveniently converted to this type, but it is also possible to initialize the command queues elsewhere (e.g. with the OpenCL backend vex::command_queue
is typedefed to cl::CommandQueue
), thus completely eliminating the need to create a vex::Context
. Each command queue in the list should uniquely identify a single compute device.
The contents of the created vector will be partitioned across all devices that were present in the queue list. The size of each partition will be proportional to the device bandwidth, which is measured the first time the device is used. All vectors of the same size are guaranteed to be partitioned consistently, which minimizes interdevice communication.
In the example below, three device vectors of the same size are allocated. Vector A
is copied from host vector a
, and the other vectors are created uninitialized:
Assuming that the current system has an NVIDIA and an AMD GPUs along with an Intel CPU installed, possible partitioning may look as in the following figure:
The function vex::copy()
allows one to copy data between host and device memory spaces. There are two forms of the function – a simple one and an STLlike one:
The STLlike variant can copy subranges of the vectors, or copy data from/to raw host pointers.
Vectors also overload the array subscript operator, operator[]
, so that users may directly read or write individual vector elements. This operation is highly ineffective and should be used with caution. Iterators allow for element access as well, so that STL algorithms may in principle be used with device vectors. This would be very slow but may be used as a temporary building block.
Another option for hostdevice data transfer is mapping device memory buffer to a host array. The mapped array then may be transparently read or written. The method vector::map(unsigned d)
maps the dth partition of the vector and returns the mapped array:
VexCL allows the use of convenient and intuitive notation for vector operations. In order to be used in the same expression, all vectors have to be compatible:
If these conditions are satisfied, then vectors may be combined with rich set of available expressions. Vector expressions are processed in parallel across all devices they were allocated on. One should keep in mind that in case several command queues are used, then the queues of the vector that is being assigned to will be employed. Each vector expression results in the launch of a single compute kernel. The kernel is automatically generated and launched the first time the expression is encountered in the program. If the VEXCL_SHOW_KERNELS
macro is defined, then the sources of all generated kernels will be dumped to the standard output. For example, the expression:
will lead to the launch of the following compute kernel:
Here and in the rest of examples X
, Y
, and Z
are compatible instances of vex::vector<double>
; it is also assumed that OpenCL backend is selected.
VexCL is able to cache the compiled kernels offline. The compiled binaries are stored in $HOME/.vexcl
on Linux and MacOSX, and in APPDATA%\vexcl
on Windows systems. In order to enable this functionality for OpenCL backend, the user has to define the VEXCL_CACHE_KERNELS
macro. NVIDIA OpenCL implementation does the caching already, but on AMD or Intel platforms this may lead to dramatic decrease of program initialization time (e.g. VexCL tests take around 20 seconds to complete without kernel caches, and 2 seconds when caches are available). In case of the CUDA backend the offline caching is always enabled.
VexCL expressions may combine device vectors and scalars with arithmetic, logic, or bitwise operators as well as with builtin OpenCL functions. If some builtin operator or function is unavailable, it should be considered a bug. Please do not hesitate to open an issue in this case.
As you have seen above, 2
in the expression 2 * Y  sin(Z)
is passed to the generated compute kernel as an int
parameter (prm_2
). Sometimes this is desired behaviour, because the same kernel will be reused for the expressions 42 * Z  sin(Y)
or a * Y  sin(Y)
(where a
is an integer variable). But this may lead to a slight overhead if an expression involves true constant that will always have same value. The macro VEX_CONSTANT
allows one to define such constants for use in vector expressions. Compare the generated kernel for the following example with the kernel above:
VexCL provides some predefined constants in the vex::constants
namespace that correspond to boost::math::constants (e.g. vex::constants::pi()
).
The function vex::element_index(size_t offset = 0)
allows one to use the index of each vector element inside vector expressions. The numbering is continuous across the compute devices and starts with an optional offset
.
Users may define custom functions for use in vector expressions. One has to define the function signature and the function body. The body may contain any number of lines of valid OpenCL or CUDA code, depending on the selected backend. The most convenient way to define a function is via the VEX_FUNCTION
macro:
The first macro parameter here defines the function return type, the second parameter is the function name, the third parameter defines function arguments in form of a preprocessor sequence. Each element of the sequence is a tuple of argument type and name. The rest of the macro is the function body (compare this with how functions are defined in C/C++). The resulting squared_radius
function object is stateless; only its type is used for kernel generation. Hence, it is safe to define commonly used functions at the global scope.
Note that any valid vector expression may be passed as a function parameter, including nested function calls:
Another version of the macro takes the function body directly as a string:
In case the function that is being defined calls other custom function inside its body, one can use the version of the VEX_FUNCTION
macro that takes sequence of parent function names as the fourth parameter:
Similarly to VEX_FUNCTION_S
, there is a version called VEX_FUNCTION_DS
(or VEX_FUNCTION_SD
) that takes the function body as a string parameter.
Custom functions may be used not only for convenience, but also for performance reasons. The example with squared_radius
could in principle be rewritten as:
The drawback of the latter variant is that X
and Y
will be passed to the kernel and read twice (see next section for an explanation).
Note that prior to release 1.2 of VexCL the VEX_FUNCTION
macro had different interface. That version is considered deprecated but is still available as VEX_FUNCTION_V1
.
The last example of the previous section is ineffective because the compiler cannot tell if any two terminals in an expression tree are actually referring to the same data. But programmers often have this information. VexCL allows one to pass this knowledge to compiler by tagging terminals with unique tags. By doing this, the programmer guarantees that any two terminals with matching tags are referencing same data.
Below is a more effective variant of the above example:
Here, the generated kernel will have one parameter for each of the vectors X
and Y
.
Some expressions may have several occurences of the same subexpression. Unfortunately, VexCL is not able to determine these cases without the programmer's help. For example, let's look at the following expression:
Here, log(X)
would be computed twice. One could tag vector X
as in:
and hope that the backend compiler is smart enough to reuse result of log(x)
(e.g. NVIDIA's compiler is smart enough to do this). But it is also possible to explicitly ask VexCL to store result of a subexpression in a local variable and reuse it. The vex::make_temp()
function template serves this purpose:
Any valid vector or multivector expression (but not additive expressions, such as sparse matrixvector products) may be wrapped into a make_temp()
call.
VexCL provides a counterbased random number generators from Random123 suite, in which Nth random number is obtained by applying a stateless mixing function to N instead of the conventional approach of using N iterations of a stateful transformation. This technique is easily parallelizable and is well suited for use in GPGPU applications.
For integral types, the generated values span the complete range; for floating point types, the generated values lie in the interval [0,1].
In order to use a random number sequence in a vector expression, the user has to declare an instance of either vex::Random
or vex::RandomNormal
class template as in the following example:
Note that vex::element_index()
here provides the random number generator with a sequence position N.
vex::permutation()
allows the use of a permuted vector in a vector expression. The function accepts a vector expression that returns integral values (indices). The following example reverses X
and assigns it to Y
:
The drawback of the above approach is that you have to store and access an index vector. Sometimes this is a necessary evil, but in this simple example we can do better. In the following snippet a lightweight expression is used to construct the same permutation:
Note that any valid vector expression may be used as an index, including userdefined functions.
Permutation operations are only supported in singledevice contexts.
An instance of the vex::slicer<NDIM>
class allows one to conveniently access subblocks of multidimensional arrays that are stored in vex::vector
in rowmajor order. The constructor of the class accepts the dimensions of the array to be sliced. The following example extracts every other element from interval [100, 200)
of a onedimensional vector X:
And the example below shows how to work with a twodimensional matrix:
Slicing is only supported in singledevice contexts.
vex::reduce()
function allows one to reduce a multidimensional expression along one or more dimensions. The result is again a vector expression. The supported reduction operations are SUM
, MIN
, and MAX
. The function takes three arguments: the shape of the expression to reduce (with the slowest changing dimension in the front), the expression to reduce, and the dimension(s) to reduce along. The latter are specified as indices into the shape array.
In the following example we find maximum absolute value of each row in a twodimensional matrix and assign the result to a vector:
Expression reduction is only supported in singledevice contexts.
vex::reshape(expr, dst_dims, src_dims)
function is a powerful primitive that allows one to conveniently manipulate multidimensional data. It takes three arguments – an arbitrary vector expression expr
to reshape, the dimensions dst_dims
of the final result (with the slowest changing dimension in the front), and the dimensions src_dims
of the expression, which are specified as indices into dst_dims
. The function returns a vector expression that could be assigned to a vector or participate in a larger expression. The dimensions may be conveniently specified with help of vex::extents
object.
Here is an example of transposing a twodimensional matrix of size NxM:
If the source expression lacks some of the destination dimensions, then those will be introduced by replicating the available data. For example, to make a twodimensional matrix from a onedimensional vector by copying the vector to each row of the matrix, one could do the following:
Here is a more realistic example of a dense matrixmatrix multiplication. Elements of a matrix product C = A * B
are defined as C[i][j] = sum_k(A[i][k] * B[k][j])
. Let's assume that matrix A
has shape [N][L]
, and matrix B
is shaped as [L][M]
. Then matrix C
has dimensions [N][M]
. In order to implement the multiplication we extend matrices A
and B
to the shape of [N][L][M]
, multiply the resulting expressions, and reduce the product along the middle dimension L
:
This of course would not be as efficient as a carefully crafted custom implementation or a call to a vendor BLAS function. Still, the fact that the result is a vector expression (and hence may be a part of a still larger expression) could be more important sometimes.
Reshaping is only supported in singledevice contexts.
VexCL provides an implementation of the MBA algorithm based on paper by Lee, Wolberg, and Shin ([S. Lee, G. Wolberg, and S. Y. Shin. Scattered data interpolation with multilevel BSplines. IEEE Transactions on Visualization and Computer Graphics, 3:228–244, 1997][bsplines]). This is a fast algorithm for scattered Ndimensional data interpolation and approximation. Multilevel Bsplines are used to compute a C2continuously differentiable surface through a set of irregularly spaced points. The algorithm makes use of a coarsetofine hierarchy of control lattices to generate a sequence of bicubic Bspline functions whose sum approaches the desired interpolation function. Large performance gains are realized by using Bspline refinement to reduce the sum of these functions into one equivalent Bspline function. Highfidelity reconstruction is possible from a selected set of sparse and irregular samples.
The algorithm is first prepared on a CPU. After that, it may be used in vector expressions. Here is an example in 2D:
VexCL provides an implementation of the Fast Fourier Transform (FFT) that accepts arbitrary vector expressions as input, allows one to perform multidimensional transforms (of any number of dimensions), and supports arbitrary sized vectors:
The restriction of the FFT is that it currently only supports contexts with a single compute device.
An instance of vex::Reductor<T, OP>
allows one to reduce an arbitrary vector expression to a single value of type T. Supported reduction operations are SUM
, MIN
, and MAX
. Reductor objects receive a list of command queues at construction and should only be applied to vectors residing on the same compute devices.
In the following example an inner product of two vectors is computed:
And here is an easy way to compute an approximate value of π with MonteCarlo method:
One of the most common operations in linear algebra is matrixvector multiplication. An instance of vex::SpMat
class holds a representation of a sparse matrix. Its constructor accepts a sparse matrix in common CRS format. In the example below a vex::SpMat
is constructed from an Eigen sparse matrix:
Matrixvector products may be used in vector expressions. The only restriction is that the expressions have to be additive. This is due to the fact that the matrix representation may span several compute devices. Hence, a matrixvector product operation may require several kernel launches and interdevice communication.
This restriction may be lifted for singledevice contexts. In this case VexCL does not need to worry about interdevice communication. Hence, it is possible to inline matrixvector product into a normal vector expression with the help of vex::make_inline()
:
Stencil convolution is another common operation that may be used, for example, to represent a signal filter, or a (onedimensional) differential operator. VexCL implements two stencil kinds. The first one is a simple linear stencil that holds linear combination coefficients. The example below computes the moving average of a vector with a 5point window:
Users may also define custom stencil operators. This may be of use if, for example, the operator is nonlinear. The definition of a stencil operator looks very similar to a definition of a custom function. The only difference is that the stencil operator constructor accepts a vector of command queues. The following example implements the nonlinear operator y(i) = sin(x(i)  x(i  1)) + sin(x(i+1)  sin(x(i))
:
The current window is available inside the body of the operator through the X
array, which is indexed relative to the stencil center.
Stencil convolution operations, similar to the matrixvector products, are only allowed in additive expressions.
Unfortunately, describing two dimensional stencils (e.g. discretization of the Laplace operator) would not be effective, because the stencil width would be too large. One can solve this problem by using a raw_pointer(const vector<T>&)
with a subscript operator. For the sake of simplicity, the example below implements a 3point laplace operator for a onedimensional vector; but this could be easily extended onto a twodimensional case:
Similar approach could be used in order to implement an Nbody problem with a userdefined function:
Note that the use of raw_pointer()
is limited to singledevice contexts for obvious reasons.
VexCL provides several standalone parallel primitives that may not be used as part of a vector expression. These are inclusive_scan
, exclusive_scan
, sort
, sort_by_key
, reduce_by_key
. All of these functions take VexCL vectors as both input and output parameters.
Sorting and scan functions take an optional function object used for comparison and summing of elements. The functor should provide the same interface as, e.g. std::less
for sorting or std::plus
for summing; additionally, it should provide a VexCL function for deviceside operations.
Here is an example of such an object comparing integer elements in such a way that even elements precede odd ones:
Same functor could be created with help of VEX_DUAL_FUNCTOR
macro, which takes return type, sequence of arguments (similar to VEX_FUNCTION
), and the body of the functor:
Note that VexCL already provides vex::less<T>
, vex::less_equal<T>
, vex::greater<T>
, vex::greater_equal<T>
, and vex::plus<T>
.
The need to provide both hostside and deviceside parts of the functor comes from the fact that multidevice vectors are first sorted partially on each of the compute devices they are allocated on and then merged on the host.
Sorting algorithms may also take tuples of keys/values (in fact, any Boost.Fusion sequence will do). One will have to explicitly specify the comparison functor in this case. Both host and device variants of the comparison functor should take 2n
arguments, where n
is the number of keys. The first n
arguments correspond to the left set of keys, and the second n
arguments correspond to the right set of keys. Here is an example that sorts values by a tuple of two keys:
The class template vex::multivector<T,N>
allows one to store several equally sized device vectors and perform computations on all components synchronously. Each operation is delegated to the underlying vectors, but usually results in the launch of a single fused kernel. Expressions may include values of std::array<T,N>
type, where N is equal to the number of multivector components. Each component gets the corresponding element of std::array<>
when the expression is applied. Similarly, the array subscript operator or reduction of a multivector returns an std::array<T,N>
. In order to access kth component of a multivector, one can use the overloaded operator()
:
Some operations can not be expressed with simple multivector arithmetic. For example, an operation of two dimensional rotation mixes components in the right hand side expressions:
This may in principle be implemented as:
But this would result in two kernel launches. VexCL allows one to assign a tuple of expressions to a multivector, which will lead to the launch of a single fused kernel:
CUDA and OpenCL differ in their handling of compute kernels compilation. In NVIDIA's framework the compute kernels are compiled to PTX code together with the host program. In OpenCL the compute kernels are compiled at runtime from highlevel Clike sources, adding an overhead which is particularly noticeable for smaller sized problems. This distinction leads to higher initialization cost of OpenCL programs, but at the same time it allows one to generate better optimized kernels for the problem at hand. VexCL exploits this possibility with help of its kernel generator mechanism. Moreover, VexCL's CUDA backend uses the same technique to generate and compile CUDA kernels at runtime.
An instance of vex::symbolic<T>
dumps to an output stream any arithmetic operations it is being subjected to. For example, this code snippet:
results in the following output:
The symbolic type allows one to record a sequence of arithmetic operations made by a generic C++ algorithm. To illustrate the idea, consider the generic implementation of a 4th order RungeKutta ODE stepper:
This function takes a system function sys
, state variable x
, and advances x
by time step dt
. For example, to model the equation dx/dt = sin(x)
, one has to provide the following system function:
The following code snippet makes one hundred RK4 iterations for a single double
value on a CPU:
Let's now generate the kernel for a single RK4 step and apply the kernel to a vex::vector<double>
(by doing this we essentially simultaneously solve a large number of identical ODEs with different initial conditions).
This approach has some obvious restrictions. Namely, the C++ code has to be embarrassingly parallel and is not allowed to contain any branching or datadependent loops. Nevertheless, the kernel generation facility may save a substantial amount of both human and machine time when applicable.
VexCL also provides a userdefined function generator which takes a function signature and generic function object, and returns custom VexCL function ready to be used in vector expressions. Let's rewrite the above example using an autogenerated function for a RungeKutta stepper. First, we need to implement generic functor:
Now we can generate and apply the custom function:
Note that both runge_kutta_4()
and rk4_stepper
may be reused for hostside computations.
It is very easy to generate a VexCL function from a Boost.Phoenix lambda expression (since Boost.Phoenix lambdas are themselves generic functors):
As Kozma Prutkov repeatedly said, "One cannot embrace the unembraceable". So in order to be usable, VexCL has to support custom kernels. vex::vector::operator()(uint k)
returns a cl::Buffer
that holds vector data on the kth compute device. If the result depends on the neighboring points, one has to keep in mind that these points are possibly located on a different compute device. In this case the exchange of these halo points has to be addressed manually.
The following example builds and launches a custom kernel for each device in the context:
Since VexCL is built upon standard Khronos OpenCL C++ bindings, it is easily interoperable with other OpenCL libraries. In particular, VexCL provides some glue code for the ViennaCL, Boost.compute and CLOGS libraries.
VexCL makes heavy use of C++11 features, so your compiler has to be modern enough. The compilers that have been tested and supported:
VexCL uses standard OpenCL bindings for C++ from Khronos group. The cl.hpp file should be included with the OpenCL implementation on your system, but it is also provided with the library.
This work is a joint effort of Supercomputer Center of Russian Academy of Sciences (Kazan branch) and Kazan Federal University. It is partially supported by RFBR grants No 12070007 and 120100333a.