ArrayFire: Getting Started (original) (raw)

Introduction

ArrayFire is a high performance software library for parallel computing with an easy-to-use API. ArrayFire abstracts away much of the details of programming parallel architectures by providing a high-level container object, the array, that represents data stored on a CPU, GPU, FPGA, or other type of accelerator. This abstraction permits developers to write massively parallel applications in a high-level language where they need not be concerned about low-level optimizations that are frequently required to achieve high throughput on most parallel architectures.

Supported data types

ArrayFire provides one generic container object, the array on which functions and mathematical operations are performed. The array can represent one of many different basic data types:

Most of these data types are supported on all modern GPUs; however, some older devices may lack support for double precision arrays. In this case, a runtime error will be generated when the array is constructed.

If not specified otherwise, arrays are created as single precision floating point numbers (f32).

Creating and populating an ArrayFire array

ArrayFire arrays represent memory stored on the device. As such, creation and population of an array will consume memory on the device which cannot freed until the array object goes out of scope. As device memory allocation can be expensive, ArrayFire also includes a memory manager which will re-use device memory whenever possible.

Arrays can be created using one of the array constructors. Below we show how to create 1D, 2D, and 3D arrays with uninitialized values:

array undefined_1D(100);

array undefined_2D(10, 100);

array undefined_3D(10, 10, 10);

However, uninitialized memory is likely not useful in your application. ArrayFire provides several convenient functions for creating arrays that contain pre-populated values including constants, uniform random numbers, uniform normally distributed numbers, and the identity matrix:

array zeros = constant(0, 3);

array rand1 = randu(1, 4);

array rand2 = randn(2, 2);

array iden = identity(3, 3);

array randcplx = randu(2, 1, c32);

@ c32

32-bit complex floating point values

A complete list of ArrayFire functions that automatically generate data on the device may be found on the functions to create arrays page. As stated above, the default data type for arrays is f32 (a 32-bit floating point number) unless specified otherwise.

ArrayFire arrays may also be populated from data found on the host. For example:

float hA[] = {0, 1, 2, 3, 4, 5};

array A(2, 3, hA);

array dB(3, 1, (cfloat *)hA);

ArrayFire also supports array initialization from memory already on the GPU. For example, with CUDA one can populate an array directly using a call to cudaMemcpy:

float host_ptr[] = {0, 1, 2, 3, 4, 5};

array a(2, 3, host_ptr);

float *device_ptr;

cudaMalloc((void **)&device_ptr, 6 * sizeof(float));

cudaMemcpy(device_ptr, host_ptr, 6 * sizeof(float), cudaMemcpyHostToDevice);

array b(2, 3, device_ptr, afDevice);

@ afDevice

Device pointer.

Similar functionality exists for OpenCL too. If you wish to intermingle ArrayFire with CUDA or OpenCL code, we suggest you consult the CUDA interoperability or OpenCL interoperability pages for detailed instructions.

ArrayFire array contents, dimensions, and properties

ArrayFire provides several functions to determine various aspects of arrays. This includes functions to print the contents, query the dimensions, and determine various other aspects of arrays.

The af_print function can be used to print arrays that have already been generated or any expression involving arrays:

array a = randu(2, 2);

array b = constant(1, 2, 1);

The dimensions of an array may be determined using either a dim4 object or by accessing the dimensions directly using the dims() and numdims() functions:

array a = randu(4, 5, 2);

printf("numdims(a) %d\n", a.numdims());

printf("dims = [%lld %lld]\n", a.dims(0), a.dims(1));

dim4 dims = a.dims();

printf("dims = [%lld %lld]\n", dims[0], dims[1]);

In addition to dimensions, arrays also carry several properties including methods to determine the underlying type and size (in bytes). You can even determine whether the array is empty, real/complex, a row/column, or a scalar or a vector:

printf("underlying type: %d\n", a.type());

printf("is complex? %d is real? %d\n", a.iscomplex(), a.isreal());

printf("is vector? %d column? %d row? %d\n", a.isvector(), a.iscolumn(),

a.isrow());

printf("empty? %d total elements: %lld bytes: %zu\n", a.isempty(),

a.elements(), a.bytes());

For further information on these capabilities, we suggest you consult the full documentation on the array.

Writing mathematical expressions in ArrayFire

ArrayFire features an intelligent Just-In-Time (JIT) compilation engine that converts expressions using arrays into the smallest number of CUDA/OpenCL kernels. For most operations on arrays, ArrayFire functions like a vector library. That means that an element-wise operation, like c[i] = a[i] + b[i] in C, would be written more concisely without indexing, like c = a + b. When there are multiple expressions involving arrays, ArrayFire's JIT engine will merge them together. This "kernel fusion" technology not only decreases the number of kernel calls, but, more importantly, avoids extraneous global memory operations. Our JIT functionality extends across C/C++ function boundaries and only ends when a non-JIT function is encountered or a synchronization operation is explicitly called by the code.

ArrayFire provides hundreds of functions for element-wise operations. All of the standard operators (e.g. +,-,*,/) are supported as are most transcendental functions (sin, cos, log, sqrt, etc.). Here are a few examples:

array R = randu(3, 3);

af_print(constant(1, 3, 3) + complex(sin(R)));

array a = randn(5, c32);

array X = randn(3, 4);

af_print(sqrt(sum(pow(X, 2))));

af_print(sqrt(sum(pow(X, 2), 0)));

af_print(sqrt(sum(pow(X, 2), 1)));

To see the complete list of functions please consult the documentation on mathematical, linear algebra, signal processing, and statistics.

Mathematical constants

ArrayFire contains several platform-independent constants, like Pi, NaN, and Inf. If ArrayFire does not have a constant you need, you can create your own using the af::constant array constructor.

Constants can be used in all of ArrayFire's functions. Below we demonstrate their use in element selection and a mathematical expression:

array A = randu(5, 5);

A(where(A > .5)) = NaN;

array x = randu(10e6), y = randu(10e6);

double pi_est = 4 * sum(hypot(x, y) < 1) / 10e6;

printf("estimation error: %g\n", fabs(Pi - pi_est));

Please note that our constants may, at times, conflict with macro definitions in standard header files. When this occurs, please refer to our constants using the af:: namespace.

Indexing

Like all functions in ArrayFire, indexing is also executed in parallel on the OpenCL/CUDA devices. Because of this, indexing becomes part of a JIT operation and is accomplished using parentheses instead of square brackets (i.e. as A(0) instead of A[0]). To index [af::array](classaf%5F1%5F1array.htm "A multi dimensional data container.")s you may use one or a combination of the following functions:

Please see the indexing page for several examples of how to use these functions.

Getting access to ArrayFire array memory on the host and device

Memory in [af::array](classaf%5F1%5F1array.htm "A multi dimensional data container.")s may be accessed using the host() and device() functions. The host function copies the data from the device and makes it available in a C-style array on the host. As such, it is up to the developer to manage any memory returned by host. The device function returns a pointer/reference to device memory for interoperability with external CUDA/OpenCL kernels. As this memory belongs to ArrayFire, the programmer should not attempt to free/deallocate the pointer. For example, here is how we can interact with both OpenCL and CUDA:

array a = randu(3, f32);

float *host_a = a.host<float>();

printf("host_a[2] = %g\n", host_a[2]);

freeHost(host_a);

float *d_cuda = a.device<float>();

float value;

cudaMemcpy(&value, d_cuda + 2, sizeof(float), cudaMemcpyDeviceToHost);

printf("d_cuda[2] = %g\n", value);

a.unlock();

cl_mem d_opencl = (cl_mem)a.device<float>();

@ f32

32-bit floating point values

ArrayFire also provides several helper functions for creating [af::array](classaf%5F1%5F1array.htm "A multi dimensional data container.")s from OpenCL cl_mem references and cl::Buffer objects. See the [include/af/opencl.h](opencl%5F8h.htm) file for further information.

Lastly, if you want only the first value from an [af::array](classaf%5F1%5F1array.htm "A multi dimensional data container.") you can use get it using the scalar() function:

array a = randu(3);

float val = a.scalar<float>();

printf("scalar value: %g\n", val);

Bitwise operators

In addition to supporting standard mathematical functions, arrays that contain integer data types also support bitwise operators including and, or, and shift:

int h_A[] = {1, 1, 0, 0, 4, 0, 0, 2, 0};

int h_B[] = {1, 0, 1, 0, 1, 0, 1, 1, 1};

array A = array(3, 3, h_A), B = array(3, 3, h_B);

array A_and_B = A & B;

array A_or_B = A | B;

array A_xor_B = A ^ B;

Using the ArrayFire API in C and C++

The ArrayFire API is wrapped into a unified C/C++ header. To use the library simply include the [arrayfire.h](arrayfire%5F8h.htm) header file and start coding!

Sample using the C API

int main(void)

{

int n_dims = 1;

dim_t dims[] = {10000};

double result;

printf("sum: %g\n", result);

return 0;

}

AFAPI af_err af_randu(af_array *out, const unsigned ndims, const dim_t *const dims, const af_dtype type)

AFAPI af_err af_sum_all(double *real, double *imag, const af_array in)

C Interface to sum array elements over all dimensions.

Sample using the C++ API

int main(void)

{

double sum = af::sum(a);

printf("sum: %g\n", sum);

return 0;

}

A multi dimensional data container.

AFAPI array randu(const dim4 &dims, const dtype ty, randomEngine &r)

C++ Interface to create an array of random numbers uniformly distributed.

Now that you have a general introduction to ArrayFire, where do you go from here? In particular you might find these documents useful

Where to go for help?