Although ArrayFire is quite extensive, there remain many cases in which you may want to write custom kernels in CUDA or OpenCL. For example, you may wish to add ArrayFire to an existing code base to increase your productivity, or you may need to supplement ArrayFire's functionality with your own custom implementation of specific algorithms. Today's "<a href="http://sandbox.arrayfire.com/tag/learning-arrayfire-from-scratch/">Learning ArrayFire from scratch</a>", blog post discusses how you can interface ArrayFire and CUDA.

<!--more-->

When it comes to interoperability with CUDA, the most important thing to remember about ArrayFire is that it manages its own memory, runs  in  its own CUDA stream, and  creates custom IDs for devices. As such, most of the interoperability functions focus on reducing potential synchronization conflicts between ArrayFire and CUDA.

<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 CUDA code. ArrayFire provides several functions to ease this process including:
<table class="doxtable">
<tbody>
<tr>
<th>Function</th>
<th>Purpose</th>
</tr>
<tr>
<td>af::array(...)</td>
<td>Construct an ArrayFire Array from device memory</td>
</tr>
<tr>
<td>af::array.device()</td>
<td>Obtain a pointer to the device memory (implies lock()</td>
</tr>
<tr>
<td>af::array.lock()</td>
<td>Removes ArrayFire's control of a device memory pointer</td>
</tr>
<tr>
<td>af::array.unlock()</td>
<td>Restore's ArrayFire's control over a device memory pointer</td>
</tr>
<tr>
<td>af::getDevice()</td>
<td>Gets the current ArrayFire device ID</td>
</tr>
<tr>
<td>af::setDevice()</td>
<td>Switches ArrayFire to the specified device</td>
</tr>
<tr>
<td>afcu::getNativeId()</td>
<td>Converts an ArrayFire device ID to a CUDA device ID</td>
</tr>
<tr>
<td>afcu::setNativeId()</td>
<td>Switches ArrayFire to the specified CUDA device ID</td>
</tr>
<tr>
<td>afcu::getStream()</td>
<td>Get the current CUDA stream used by ArrayFire</td>
</tr>
</tbody>
</table>
Below we provide two worked examples on how ArrayFire can be integrated into new and existing projects.
<h4>Adding custom CUDA kernels to an existing ArrayFire application</h4>
By default, ArrayFire manages its own memory and operates in its own CUDA stream. Thus there is a slight amount of bookkeeping that needs to be done in order to integrate your custom CUDA kernel.

If your kernels can share the ArrayFire CUDA stream, you should:
<ol type="1">
 	<li>Include the 'af/afcuda.h' header in your source code</li>
 	<li>Use ArrayFire as normal</li>
 	<li>Ensure any JIT kernels have executed using `<code>af::eval()</code></li>
 	<li>Obtain device pointers from ArrayFire array objects using</li>
 	<li>Determine ArrayFire's CUDA stream</li>
 	<li>Set arguments and run your kernel in ArrayFire's stream</li>
 	<li>Return control of af::array memory to ArrayFire</li>
 	<li>Compile with <code>nvcc</code>, linking with the <code>afcuda</code> library.</li>
</ol>
Notice that since ArrayFire and your kernels are sharing the same CUDA stream, there is no need to perform any synchronization operations as operations within a stream are executed in order.

This process is best illustrated with a fully worked example:
<div class="fragment">
<div class="line">
<pre class="lang:default decode:true ">// 1. Add includes
#include &lt;arrayfire.h&gt;
#include &lt;af/cuda.h&gt;
 
int main() {
 
// 2. Use ArrayFire as normal
size_t num = 10;
af::array x = af::constant(0, num);
 
// ... many ArrayFire operaitons here
 
// 3. Ensure any JIT kernels have executed
x.eval();
af_print(x);
 
// Run a custom CUDA kernel in the ArrayFire CUDA stream
 
// 4. Obtain device pointers from ArrayFire array objects using
// the array::device() function:
float *d_x = x.device&lt;float&gt;();
 
// 5. Determine ArrayFire's CUDA stream
int af_id = af::getDevice();
int cuda_id = afcu::getNativeId(af_id);
cudaStream_t af_cuda_stream = afcu::getStream(cuda_id);
 
// 6. Set arguments and run your kernel in ArrayFire's stream
// Here launch with 10 blocks of 10 threads
increment&lt;&lt;&lt;1, num, 0, af_cuda_stream&gt;&gt;&gt;(d_x);
 
// 7. Return control of af::array memory to ArrayFire using
// the array::unlock() function:
x.unlock();
 
// ... resume ArrayFire operations
af_print(x);
 
// 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
// cudaFree()
 
return 0;
}</pre>
</div>
</div>
If your kernels needs to operate in their own CUDA stream, 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>cudaDeviceSynchronize()</code> (or similar) commands prior to returning control of the memory to ArrayFire:
<ol type="1">
 	<li>Include the 'af/afcuda.h' header in your source code</li>
 	<li>Use ArrayFire as normal</li>
 	<li>Ensure any JIT kernels have executed using `<code>af::eval()</code></li>
 	<li>Instruct ArrayFire to finish operations using af::sync()</li>
 	<li>Obtain device pointers from ArrayFire array objects using</li>
 	<li>Determine ArrayFire's CUDA stream</li>
 	<li>Set arguments and run your kernel in your custom stream</li>
 	<li>Ensure CUDA operations have finished using <code>cudaDeviceSyncronize()</code> or similar commands.</li>
 	<li>Return control of af::array memory to ArrayFire</li>
 	<li>Compile with <code>nvcc</code>, linking with the <code>afcuda</code> library.</li>
</ol>
<h4>Adding ArrayFire to an existing CUDA application</h4>
Adding ArrayFire to an existing CUDA 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>Include <code>arrayfire.h</code> and <code>af/cuda.h</code> in your source file</li>
 	<li>Finish any pending CUDA operations (e.g. use cudaDeviceSynchronize() or similar stream functions)</li>
 	<li>Create ArrayFire arrays from existing CUDA pointers</li>
 	<li>Perform operations on ArrayFire arrays</li>
 	<li>Instruct ArrayFire to finish operations using af::eval() and af::sync()</li>
 	<li>Obtain pointers to important memory</li>
 	<li>Continue your CUDA application.</li>
 	<li>Free non-managed memory</li>
 	<li>Compile and link with the appropriate paths and the <code>-lafcuda</code> flags.</li>
</ol>
To create the af::array objects, you should use one of the following constructors with <code>src=afDevice</code>:
<div class="fragment">
<div class="line">
<pre class="lang:default decode:true ">// 1D - 3D af::array constructors
af::array (dim_t dim0, const T *pointer, af::source src=afHost)
af::array (dim_t dim0, dim_t dim1, const T *pointer, af::source src=afHost)
af::array (dim_t dim0, dim_t dim1, dim_t dim2, const T *pointer, af::source src=afHost)
af::array (dim_t dim0, dim_t dim1, dim_t dim2, dim_t dim3, const T *pointer, af::source src=afHost)
 
// af::array constructor using a dim4 object
af::array (const dim4 &amp;dims, const T *pointer, af::source src=afHost)</pre>
</div>
</div>
<em>NOTE</em>: With all of these constructors, ArrayFire's memory manager automatically assumes responsibility for any memory provided to it. Thus ArrayFire could free or reuse the memory at any later time. If this behavior is not desired, you may call<code>array::unlock()</code> and manage the memory yourself. However, if you do so, please be cautious not to free memory when ArrayFire might be using it!

The seven steps above are best illustrated using a fully-worked example:
<div class="fragment">
<div class="line">
<pre class="lang:default decode:true ">// 1. Add includes
#include &lt;arrayfire.h&gt;
#include &lt;af/cuda.h&gt;
 
using namespace std;
 
int main() {
 
// Create and populate CUDA memory objects
const int elements = 100;
size_t size = elements * sizeof(float);
float *cuda_A;
cudaMalloc((void**) &amp;cuda_A, size);
 
// ... perform many CUDA operations here
 
// 2. Finish any pending CUDA operations
cudaDeviceSynchronize();
 
// 3. Create ArrayFire arrays from existing CUDA pointers.
// Be sure to specify that the memory type is afDevice.
af::array d_A(elements, cuda_A, afDevice);
 
// NOTE: ArrayFire now manages cuda_A
 
// 4. Perform operations on the ArrayFire Arrays.
d_A = d_A * 2;
 
// NOTE: ArrayFire does not perform the above transaction using
// in-place memory, thus the pointers containing memory to d_A have
// likely changed.
 
// 5. Instruct ArrayFire to finish pending operations using eval and sync.
af::eval(d_A);
af::sync();
 
// 6. Get pointers to important memory objects.
// Once device is called, ArrayFire will not manage the memory.
float * outputValue = d_A.device&lt;float&gt;();
 
// 7. continue CUDA application as normal
 
// 8. Free non-managed memory
// We removed outputValue from ArrayFire's control, we need to free it
cudaFree(outputValue);
 
return 0;
}</pre>
</div>
</div>
<h4>Using multiple devices</h4>
If you are using multiple devices with ArrayFire and CUDA kernels, there is one "gotcha" of which you should be aware. ArrayFire implements its own internal order of compute devices, thus a CUDA device ID may not be the same as an ArrayFire device ID. Thus when switching between devices it is important that you use our interoperability functions to get/set the correct device IDs. Below is a quick listing of the various functions needed to switch between devices along with some disambiguation as to the device identifiers used with each function:
<table class="doxtable">
<tbody>
<tr>
<th>Function</th>
<th>ID Type</th>
<th>Purpose</th>
</tr>
<tr>
<td>cudaGetDevice()</td>
<td>CUDA</td>
<td>Gets the current CUDA device ID</td>
</tr>
<tr>
<td>cudaSetDevice()</td>
<td>CUDA</td>
<td>Sets the current CUDA device</td>
</tr>
<tr>
<td>af::getDevice()</td>
<td>AF</td>
<td>Gets the current ArrayFire device ID</td>
</tr>
<tr>
<td>af::setDevice()</td>
<td>AF</td>
<td>Sets the current ArrayFire device</td>
</tr>
<tr>
<td>afcu::getNativeId()</td>
<td>AF -&gt; CUDA</td>
<td>Convert an ArrayFire device ID to a CUDA device ID</td>
</tr>
<tr>
<td>afcu::setNativeId()</td>
<td>CUDA -&gt; AF</td>
<td>Set the current ArrayFire device from a CUDA ID</td>
</tr>
</tbody>
</table>