In last week's "<a href="http://sandbox.arrayfire.com/tag/learning-arrayfire-from-scratch/">Learning ArrayFire from scratch</a>" post we discussed how to interface ArrayFire and CUDA to improve your productivity. This week we demonstrate how to mix ArrayFire and OpenCL in your application.

<!--more-->

Much like with CUDA, ArrayFire controls almost all aspects of its execution on OpenCL platforms. ArrayFire manages its own context, queue, memory, and creates custom IDs for devices. As such, most of the interoperability functions focus on reducing potential synchronization conflicts between ArrayFire and OpenCL.

<strong>NOTE</strong>: This blog post was written against ArrayFire 3.3.x. We intend to implement additional convenience functions in ArrayFire 3.4 that should simplify this process further. Be sure to <a href="http://arrayfire.org/docs/interop_cuda.htm">check the documentation</a> for any updates in future releases.
<h4>Basics</h4>
It is fairly straightforward to interface ArrayFire with your own custom OpenCL code. ArrayFire provides several functions to ease this process including:
<table class="doxtable">
<tbody>
<tr>
<th>Function</th>
<th>Purpose</th>
</tr>
<tr>
<td><pre>af::array(...)</pre></td>
<td>Construct an ArrayFire array from cl_mem references or cl::Buffer objects</td>
</tr>
<tr>
<td>af::array.device()</td>
<td>Obtain a pointer to the cl_mem reference (implies lock())</td>
</tr>
<tr>
<td>af::array.lock()</td>
<td>Removes ArrayFire's control of a cl_mem buffer</td>
</tr>
<tr>
<td>af::array.unlock()</td>
<td>Restore's ArrayFire's control over a cl_mem buffer</td>
</tr>
<tr>
<td>afcl::getPlatform()</td>
<td>Get ArrayFire's current cl_platform</td>
</tr>
<tr>
<td>af::getDevice()</td>
<td>Get the current ArrayFire Device ID</td>
</tr>
<tr>
<td>afcl::getDeviceId()</td>
<td>Get ArrayFire's current cl_device_id</td>
</tr>
<tr>
<td>af::setDevice()</td>
<td>Set ArrayFire's device from an ArrayFire device ID</td>
</tr>
<tr>
<td>afcl::setDeviceId()</td>
<td>Set ArrayFire's device from a cl_device_id</td>
</tr>
<tr>
<td>afcl::setDevice()</td>
<td>Set ArrayFire's device from a cl_device_id and cl_context</td>
</tr>
<tr>
<td>afcl::getContext()</td>
<td>Get ArrayFire's current cl_context</td>
</tr>
<tr>
<td>afcl::getQueue()</td>
<td>Get ArrayFire's current cl_command_queue</td>
</tr>
<tr>
<td>afcl::getDeviceType()</td>
<td>Get the current afcl_device_type</td>
</tr>
</tbody>
</table>
Additionally, the OpenCL backend permits the programmer to add and remove custom devices from the ArrayFire device manager. These permit you to attach ArrayFire directly to the OpenCL queue used by other portions of your application.
<table class="doxtable">
<tbody>
<tr>
<th>Function</th>
<th>Purpose</th>
</tr>
<tr>
<td>afcl::addDevice()</td>
<td>Add a new device to ArrayFire's device manager</td>
</tr>
<tr>
<td>afcl::deleteDevice()</td>
<td>Remove a device from ArrayFire's device manager</td>
</tr>
</tbody>
</table>
Below we provide two worked examples on how ArrayFire can be integrated into new and existing projects.
<h4>Adding custom OpenCL kernels to an existing ArrayFire application</h4>
By default, ArrayFire manages its own context, queue, memory, and creates custom IDs for devices. Thus there is some bookkeeping that needs to be done to integrate your custom OpenCL kernel.

If your kernels can share operate in the same queue as ArrayFire, you should:
<ol type="1">
 	<li>Add an include for <code>af/opencl.h</code> to your project</li>
 	<li>Obtain the OpenCL context, device, and queue used by ArrayFire</li>
 	<li>Obtain cl_mem references to af::array objects</li>
 	<li>Load, build, and use your kernels</li>
 	<li>Return control of af::array memory to ArrayFire</li>
</ol>
Note, ArrayFire uses an in-order queue, thus when ArrayFire and your kernels are operating in the same queue, there is no need to perform any synchronization operations.

This process is best illustrated with a fully worked example:
<div class="fragment">
<div class="line">
<pre class="lang:default decode:true ">#include &lt;arrayfire.h&gt;
// 1. Add the af/opencl.h include to your project
#include &lt;af/opencl.h&gt;
 
int main() {
size_t length = 10;
 
// Create ArrayFire array objects:
af::array A = af::randu(length, f32);
af::array B = af::constant(0, length, f32);
 
// ... additional ArrayFire operations here
 
// 2. Obtain the device, context, and queue used by ArrayFire
static cl_context af_context = afcl::getContext();
static cl_device_id af_device_id = afcl::getDeviceId();
static cl_command_queue af_queue = afcl::getQueue();
 
// 3. Obtain cl_mem references to af::array objects
cl_mem * d_A = A.device&lt;cl_mem&gt;();
cl_mem * d_B = B.device&lt;cl_mem&gt;();
 
// 4. Load, build, and use your kernels.
// For the sake of readability, we have omitted error checking.
int status = CL_SUCCESS;
 
// A simple copy kernel, uses C++11 syntax for multi-line strings.
const char * kernel_name = "copy_kernel";
const char * source = R"(
void __kernel
copy_kernel(__global float * gA, __global float * gB)
{
int id = get_global_id(0);
gB[id] = gA[id];
}
)";
 
// Create the program, build the executable, and extract the entry point
// for the kernel.
cl_program program = clCreateProgramWithSource(af_context, 1, &amp;source, NULL, &amp;status);
status = clBuildProgram(program, 1, &amp;af_device_id, NULL, NULL, NULL);
cl_kernel kernel = clCreateKernel(program, kernel_name, &amp;status);
 
// Set arguments and launch your kernels
clSetKernelArg(kernel, 0, sizeof(cl_mem), d_A);
clSetKernelArg(kernel, 1, sizeof(cl_mem), d_B);
clEnqueueNDRangeKernel(af_queue, kernel, 1, NULL, &amp;length, NULL, 0, NULL, NULL);
 
// 5. Return control of af::array memory to ArrayFire
A.unlock();
B.unlock();
 
// ... resume ArrayFire operations
 
// Because the device pointers, d_x and d_y, were returned to ArrayFire's
// control by the unlock function, there is no need to free them using
// clReleaseMemObject()
 
return 0;
}</pre>
</div>
</div>
If your kernels needs to operate in their own OpenCL queue, the process is essentially identical, except you need to instruct ArrayFire to complete its computations using the af::sync() function prior to launching your own kernel and ensure your kernels are complete using <code>clFinish</code> (or similar) commands prior to returning control of the memory to ArrayFire:
<ol type="1">
 	<li>Add an include for <code>af/opencl.h</code> to your project</li>
 	<li>Obtain the OpenCL context, device, and queue used by ArrayFire</li>
 	<li>Obtain cl_mem references to af::array objects</li>
 	<li>Instruct ArrayFire to finish operations using af::sync()</li>
 	<li>Load, build, and use your kernels</li>
 	<li>Instruct OpenCL to finish operations using clFinish() or similar commands.</li>
</ol>
<ol type="1">
 	<li>Return control of af::array memory to ArrayFire</li>
</ol>
<h4>Adding ArrayFire to an existing OpenCL application</h4>
Adding ArrayFire to an existing OpenCL application is slightly more involved and can be somewhat tricky due to several optimizations we implement. The most important are as follows:
<ul>
 	<li>ArrayFire assumes control of all memory provided to it.</li>
 	<li>ArrayFire does not (in general) support in-place memory transactions.</li>
</ul>
We will discuss the implications of these items below. To add ArrayFire to existing code you need to:
<ol type="1">
 	<li>Add includes</li>
 	<li>Instruct OpenCL to complete its operations using clFinish (or similar)</li>
 	<li>Instruct ArrayFire to use the user-created OpenCL Context</li>
 	<li>Create ArrayFire arrays from OpenCL memory objects</li>
 	<li>Perform ArrayFire operations on the Arrays</li>
 	<li>Instruct ArrayFire to finish operations using af::sync()</li>
 	<li>Obtain cl_mem references for important memory</li>
 	<li>Continue your OpenCL application</li>
</ol>
To create the af::array objects, you should use one of the following constructors:
<div class="fragment">
<div class="line">
<pre class="lang:default decode:true ">// 1D - 3D af::array constructors
static af::array array (dim_t dim0, cl_mem buf, af::dtype type, bool retain=false)
static af::array array (dim_t dim0, dim_t dim1, cl_mem buf, af::dtype type, bool retain=false)
static af::array array (dim_t dim0, dim_t dim1, dim_t dim2, cl_mem buf, af::dtype type, bool retain=false)
static af::array array (dim_t dim0, dim_t dim1, dim_t dim2, dim_t dim3, cl_mem buf, af::dtype type, bool retain=false)
 
// af::array constructor using a dim4 object
static af::array array (af::dim4 idims, cl_mem buf, af::dtype type, bool retain=false)</pre>
</div>
</div>
<em>NOTE</em>: With all of these constructors, ArrayFire's memory manager automatically assumes responsibility for any memory provided to it. If you are creating an array from a <code>cl::Buffer</code>, you should specify <code>retain=true</code> to ensure your memory is not deallocated if your <code>cl::Buffer</code> were to go out of scope. We use this technique in the example below. If you do not wish for ArrayFire to manage your memory, you may call the <code>array::unlock()</code> function and manage the memory yourself; however, if you do so, please be cautious not to call <code>clReleaseMemObj</code> on a <code>cl_mem</code> when ArrayFire might be using it!

The eight steps above are best illustrated using a fully-worked example. Below we use the OpenCL 2.0 C++ API and omit error checking to keep the code readable.
<div class="fragment">
<div class="line">
<pre class="lang:default decode:true ">#include &lt;CL/cl2.hpp&gt;
 
// 1. Add arrayfire.h and af/opencl.h to your application
#include "arrayfire.h"
#include "af/opencl.h"
 
#include &lt;cstdio&gt;
#include &lt;vector&gt;
 
int main() {
 
// Set up the OpenCL context, device, and queues
cl::Context context(CL_DEVICE_TYPE_ALL);
vector&lt;cl::Device&gt; devices = context.getInfo&lt;CL_CONTEXT_DEVICES&gt;();
cl::Device device = devices[0];
cl::CommandQueue queue(context, device);
 
// Create a buffer of size 10 filled with ones, copy it to the device
int length = 10;
vector&lt;float&gt; h_A(length, 1);
cl::Buffer cl_A(context, CL_MEM_READ_WRITE, length * sizeof(float), h_A.data());
 
// 2. Instruct OpenCL to complete its operations using clFinish (or similar)
queue.finish();
 
// 3. Instruct ArrayFire to use the user-created context
// First, create a device from the current OpenCL device + context + queue
afcl::addDevice(device(), context(), queue());
// Next switch ArrayFire to the device using the device and context as
// identifiers:
afcl::setDevice(device(), context());
 
// 4. Create ArrayFire arrays from OpenCL memory objects
af::array af_A = afcl::array(length, cl_A(), f32, true);
 
// 5. Perform ArrayFire operations on the Arrays
af_A = af_A + af::randu(length);
 
// NOTE: ArrayFire does not perform the above transaction using in-place memory,
// thus the underlying OpenCL buffers containing the memory containing memory to
// probably have changed
 
// 6. Instruct ArrayFire to finish operations using af::sync
af::sync();
 
// 7. Obtain cl_mem references for important memory
cl_A = *af_A.device&lt;cl_mem&gt;();
 
// 8. Continue your OpenCL application
 
// ...
 
return 0;
}</pre>
</div>
</div>
<h4>Using multiple devices</h4>
If you are using ArrayFire and OpenCL with multiple devices be sure to use <code>afcl::addDevice</code> to add your custom context + device + queue to ArrayFire's device manager. This will let you switch ArrayFire devices using your current<code>cl_device_id</code> and <code>cl_context</code>.