ArrayFire: Interoperability with CUDA (original) (raw)
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.
ArrayFire manages its own memory, runs within 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.
Basics
It is fairly straightforward to interface ArrayFire with your own custom CUDA code. ArrayFire provides several functions to ease this process including:
| Function | Purpose |
|---|---|
| af::array(...) | Construct an ArrayFire Array from device memory |
| af::array.device() | Obtain a pointer to the device memory (implies lock()) |
| af::array.lock() | Removes ArrayFire's control of a device memory pointer |
| af::array.unlock() | Restores ArrayFire's control over a device memory pointer |
| af::getDevice() | Gets the current ArrayFire device ID |
| af::setDevice() | Switches ArrayFire to the specified device |
| afcu::getNativeId() | Converts an ArrayFire device ID to a CUDA device ID |
| afcu::setNativeId() | Switches ArrayFire to the specified CUDA device ID |
| afcu::getStream() | Get the current CUDA stream used by ArrayFire |
Below we provide two worked examples on how ArrayFire can be integrated into new and existing projects.
Adding custom CUDA kernels to an existing ArrayFire application
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:
- Include the 'af/afcuda.h' header in your source code
- Use ArrayFire as normal
- Ensure any JIT kernels have executed using
[af::eval()](group%5F%5Fdata%5F%5Fmat.htm#gaabf89285b7036427efe452491025567d "Evaluate an expression (nonblocking).") - Obtain device pointers from ArrayFire array objects using
array::device() - Determine ArrayFire's CUDA stream
- Set arguments and run your kernel in ArrayFire's stream
- Return control of af::array memory to ArrayFire
- Compile with
nvcc, linking with theafcudalibrary.
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:
int main() {
size_t num = 10;
float *d_x = x.device<float>();
increment<<<1, num, 0, af_cuda_stream>>>(d_x);
return 0;
}
A multi dimensional data container.
T * device() const
Get the device pointer from the array and lock the buffer in memory manager.
void eval() const
Evaluate any JIT expressions to generate data for the array.
void unlock() const
Unlocks the device buffer in the memory manager.
static cudaStream_t getStream(int id)
Get the stream for the CUDA device with id in ArrayFire context.
array constant(T val, const dim4 &dims, const dtype ty=(af_dtype) dtype_traits< T >::ctype)
C++ Interface to generate an array with elements set to a specified value.
AFAPI int getDevice()
Gets the current device ID.
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 cudaDeviceSynchronize() (or similar) commands prior to returning control of the memory to ArrayFire:
- Include the 'af/afcuda.h' header in your source code
- Use ArrayFire as normal
- Ensure any JIT kernels have executed using
[af::eval()](group%5F%5Fdata%5F%5Fmat.htm#gaabf89285b7036427efe452491025567d "Evaluate an expression (nonblocking).") - Instruct ArrayFire to finish operations using af::sync()
- Obtain device pointers from ArrayFire array objects using
- Determine ArrayFire's CUDA stream
- Set arguments and run your kernel in your custom stream
- Ensure CUDA operations have finished using
cudaDeviceSyncronize()or similar commands. - Return control of af::array memory to ArrayFire
- Compile with
nvcc, linking with theafcudalibrary.
Adding ArrayFire to an existing CUDA application
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:
- ArrayFire assumes control of all memory provided to it.
- ArrayFire does not (in general) support in-place memory transactions.
We will discuss the implications of these items below. To add ArrayFire to existing code you need to:
- Include
[arrayfire.h](arrayfire%5F8h.htm)and[af/cuda.h](cuda%5F8h.htm)in your source file - Finish any pending CUDA operations (e.g. use cudaDeviceSynchronize() or similar stream functions)
- Create ArrayFire arrays from existing CUDA pointers
- Perform operations on ArrayFire arrays
- Instruct ArrayFire to finish operations using af::eval() and af::sync()
- Obtain pointers to important memory
- Continue your CUDA application.
- Free non-managed memory
- Compile and link with the appropriate paths and the
-lafcudaflags.
To create the af::array objects, you should use one of the following constructors with src=afDevice:
NOTE: 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 array::unlock() 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:
using namespace std;
int main() {
const int elements = 100;
size_t size = elements * sizeof(float);
float *cuda_A;
cudaMalloc((void**) &cuda_A, size);
cudaDeviceSynchronize();
d_A = d_A * 2;
float * outputValue = d_A.device<float>();
cudaFree(outputValue);
return 0;
}
@ afDevice
Device pointer.
array & eval(array &a)
Evaluate an expression (nonblocking).
AFAPI void sync(const int device=-1)
Blocks until the device is finished processing.
Using multiple devices
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:
| Function | ID Type | Purpose |
|---|---|---|
| cudaGetDevice() | CUDA | Gets the current CUDA device ID |
| cudaSetDevice() | CUDA | Sets the current CUDA device |
| af::getDevice() | AF | Gets the current ArrayFire device ID |
| af::setDevice() | AF | Sets the current ArrayFire device |
| afcu::getNativeId() | AF -> CUDA | Convert an ArrayFire device ID to a CUDA device ID |
| afcu::setNativeId() | CUDA -> AF | Set the current ArrayFire device from a CUDA ID |