CUDA Libraries
Parallel Algorithms
David Mayerich
Scalable Tissue Imaging and Modeling (STIM) Laboratory
Department of Electrical and Computer Engineering
Cullen College of Engineering
University of Houston
David Mayerich
STIM Laboratory, University of Houston

CUDA Libraries
cuFFT - fast Fourier transforms
cuBLAS - basic linear algorithm subroutines
not discussed (but useful): cuSPARSE, cuRAND, cuSOLVER
David Mayerich
STIM Laboratory, University of Houston
cuFFT - Fast Fourier Transform
David Mayerich
STIM Laboratory, University of Houston
#include <cufft.h>
const int n;
cufftComplex* x = new cufftComplex[n]; // allocate space to store the signal array
// fill the array
cufftComplex* gpu_x; // allocate an on-device array
cudaMalloc(&gpu_x, sizeof(cufftComplex) * n); // allocate an array on the GPU
// copy data from the host to the device
cudaMemcpy(gpu_x, x, sizeof(cufftComplex) * n, cudaMemcpyHostToDevice);
cufftHandle plan; // create a "plan" (cuFFT instance)
cufftPlan1d(&plan, n, CUFFT_C2C, 1);
cufftExecC2C(plan, gpu_x, gpu_x, CUFFT_FORWARD); // perform the in-place transformBLAS - Basic Linear Algebra Subprograms
-
Specification for low-level linear algebra routines
-
Implementations: OpenBLAS, Intel MKL, ...
-
Uses: MATLAB, NumPy, GNU Octave, ...
-
netlib Reference Implementation (FORTRAN): https://www.netlib.org/blas
-
- Functions are specified with a prefix and function name
- (s) single (32-bit) precision
- (d) double (64-bit) precision
- (c) single complex (total = 64 bits)
- (z) double complex (total = 128 bits)
- common function names:
*axpy,*gemv,*gemm, ... sazpy()- add two single-precision (32-bit) vectorszgemm()- multiply complex double-precision matrices
David Mayerich
STIM Laboratory, University of Houston
BLAS Subroutine Levels
-
Level 1 - vector/vector operations
-
"a x plus y" (axpy): \(\mathbf{y} \leftarrow \alpha \mathbf{x} + \mathbf{y}\)
-
dot product (dot): \(d\leftarrow \mathbf{x}^T\mathbf{y}\)
-
"absolute value sum" (asum): \(a \leftarrow || \text{Re} \{\mathbf{x}\}||_1 + ||\text{Im}\{\mathbf{x}\}||_1\)
-
-
Level 2 - matrix/vector operations
-
"generalized matrix-vector multiplication" (gemv): \(\mathbf{y}\leftarrow \alpha \mathbf{A}\mathbf{x} +\beta \mathbf{y}\)
-
"triangular packed solver" (tpsv): \(\mathbf{x}\leftarrow \mathbf{A}^{-1}\mathbf{x}\)
-
-
Level 3 - matrix/matrix operations
-
"general matrix multiplication" (gemm): \(\mathbf{C} \leftarrow \alpha \mathbf{A}\mathbf{B} + \beta \mathbf{C}\)
-
David Mayerich
STIM Laboratory, University of Houston
cuBLAS: \(\mathbf{y}\leftarrow \alpha \mathbf{A}\mathbf{x} +\beta \mathbf{y}\)
David Mayerich
STIM Laboratory, University of Houston
#include <cublas_v2.h>
const int m = 4096; const int n = 4096;
float* A = new float[m * n];
float* x = new float[n];
float* y = new float[m];
const float alpha = 1.0f, beta = 0.0f;
// fill arrays
float *gpu_A, *gpu_x, *gpu_y;
cudaMalloc(&gpu_A, sizeof(float) * m * n);
cudaMemcpy(gpu_A, A, sizeof(float) * m * n, cudaMemcpyHostToDevice);
cudaMalloc(&gpu_x, sizeof(float) * n);
cudaMemcpy(gpu_x, x, sizeof(float) * n, cudaMemcpyHostToDevice);
cudaMalloc(&gpu_y, sizeof(float) * m);
cudaMemcpy(gpu_y, y, sizeof(float) * m, cudaMemcpyHostToDevice);cuBLAS: \(\mathbf{y}\leftarrow \alpha \mathbf{A}\mathbf{x} +\beta \mathbf{y}\)
David Mayerich
STIM Laboratory, University of Houston
cublasHandle_t handle; // create a device handle (cuBLAS instance)
cublasCreate(&handle));
//execute gemv
cublasSgemv(handle, // cuBLAS handle
CUBLAS_OP_N, // flag indicates no transpose
m, n, // size of the matrix
&alpha, // alpha scalar
gpu_A, m, // matrix pointer (and leading dim size)
gpu_x, 1, // x vector array (and leading dim size)
&beta, // beta scalar
gpu_y, 1); // y vector array (and leading dim size)
// copy the results to host memory
cudaMemcpy(y, gpu_y, sizeof(float) * m, cudaMemcpyDeviceToHost);
// destroy everything
cublasDestroy(handle);
cudaFree(gpu_A); cudaFree(gpu_x); cudaFree(gpu_y);CUDA Thrust
David Mayerich
STIM Laboratory, University of Houston
Templates
-
Templates provide a method for writing C++ code independent of data type
-
Data type is specified when a variable is declared
-
must be known at compile time
-
different versions of a template variable are created for each data type
-
-
Specify a template parameter using:
template <typename T>
or
template <class T> -
Writing code for generic types is known as generic programming
David Mayerich
STIM Laboratory, University of Houston
Template Functions
-
A template function can be defined
David Mayerich
STIM Laboratory, University of Houston
-
A template function can be defined
-
Or the compiler can infer the data type based on parameters
template <typename T>
T max(T v0, T v1) {
if(v0 >= v1) return v0;
return v1;
}float v = max<float>(v0, v1);float v0 = 1.0f;
float v1 = 2.0f;
float v = max(v0, v1);Common Template Problems
-
You will generally get a compiler error if the template is inferred and ambiguous:
David Mayerich
STIM Laboratory, University of Houston
-
Template declarations and definitions have to be in the same file
-
you can't have a separate *.h file to store function declarations
-
since the data type is unknown when the function is written, pre-compiled libraries can't be made
-
-
Operators used in template functions must be defined for the data type being used:
float v0 = 1.0f;
double v1 = 2.0;
float v = max(v0, v1);std::string s0 = "Hello ";
std::string s1 = "world!";
std::string s = max(s0, s1);Example - Complex Numbers
-
A complex number is defined as:
David Mayerich
STIM Laboratory, University of Houston
-
An application may require various precisions for \(a\) and \(b\)
-
you can write multiple versions of a data structure to store complex values
-
OR you can implement complex numbers as a template class:
-
struct complex {
float a;
float b;
}struct complexDouble {
double a;
double b;
}template <typename T>
struct complex {
T a;
T b;
}Example - Complex Numbers
David Mayerich
STIM Laboratory, University of Houston
template <typename T>
class complex {
T a;
T b;
public:
// constructor
complex(T real, T imag) {
a = real; b = imag;
}
// implement addition
complex<T> operator+(complex<T> rhs) {
return complex( a + rhs.a,
b + rhs.b);
}
}T operator-(...) {...} // implement sub
T operator*(complex<T> rhs) {
return complex(a * rhs.a - b * rhs.b,
a * rhs.b + b * rhs.a);
}
T operator/(...) {...} // implement div
} // end complex classC++ Standard Template Library
-
Standard Template Library (STL)
-
series of template-based algorithms and containers
-
developed primarily by Alexander Stepanov and Meng Lee
-
implementations are often distributed with compilers
-
David Mayerich
STIM Laboratory, University of Houston
-
C++ Standard Library
-
based on conventions in STL (several shared features)
-
syntax and semantics are standardized
-
there are some performance standards
-
implementation is up to the compiler developer (Microsoft, Intel, etc.)
-


Microsoft STL
(based on Dinkum STL)
libstdc++
(GNU)

Thrust
(Nvidia)
C++ Standard Template Library
-
Implemented as a series of header files
-
Includes the original ISO C90 C header files
stdlib.h, math.h, time.h, complex.h, etc.
-
Template classes are in the std namespace
-
containers:
std::list,std::vector,std::queue,std::array(C++ 11), etc. -
input/output and strings
std::cin,std::cout,std::ifstream,std::ofstream,std::string, etc. -
numerical
std::complex,std::valarray,std::accumulate(), etc. -
algorithms
std::sort(),std::find(),std::shuffle(), etc. -
threads (C++ 11)
-
David Mayerich
STIM Laboratory, University of Houston
Example - Containers
C++ Containers
David Mayerich
STIM Laboratory, University of Houston
#include <vector>
/// set or load values
std::vector<float> x(100, 0.0f); // array of 100 values initialized to 0
float v0 = x[20];
float v1 = x[19];
x.push_back(v0 + v1);Nested Templates
#include <vector>
#include <complex>
// fill array
std::vector< complex<float> > X(100, 0.0f);
complex<float> c0 = X[20];
complex<float> c1 = X[21];Nvidia Thrust
David Mayerich
STIM Laboratory, University of Houston
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
size_t N = 10;
thrust::host_vector<float> H(N);
H[0] = 1;
H[1] = 1;
for(size_t n = 2; n < N; n++) // calculate the Fibonacci sequence
H[n] = H[n-1] + H[n-2];
thrust::device_vector<float> D = H; // upload data to the CUDA device
for(size_t n = 0; n < N; n++) // output results from the device
std::cout<<"D["<<n<<"] = "<<D[n]<<std::endl;Thrust Compatibility with C++ STD
Operator overloads support transforming std::vector objects to thrust::host_vector and thrust::device_vector
David Mayerich
STIM Laboratory, University of Houston
#include <vector>
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
size_t N = 10;
std::vector<float> V(N, 0.0f); // create an array of 0s
thrust::host_vector<float> H = V; // host vector with values in V
thrust::device_vector<float> D = V; // device vector with values in v
for(size_t n = 0; n < N; n++) // output device values
std::cout<<"D["<<n<<"] = "<<D[n]<<std::endl;Thrust Data Access
What can we infer about accessing elements in thrust::device_vector?
David Mayerich
STIM Laboratory, University of Houston
thrust::device_vector<float> D;
// fill device vector
for(size_t n = 0; n < N; n++)
std::cout<<"D["<<n<<"] = "<<D[n]<<std::endl;- Accessing individual elements on the device requires a
cudaMemcpy()call - Use these calls sparingly (ex. debugging)
Iterators
The begin() and end() methods return iterators to the beginning and end of a container
David Mayerich
STIM Laboratory, University of Houston
thrust::device_vector<float> D(12);
thrust::sequence(D.begin(), D.end());thrust::fill(D.begin() + 2, D.begin() + 10, 99.0f);0
12.3
1
1.22
2
3.64
3
2.28
4
3.11
5
5.20
6
22.1
7
4.57
8
3.11
9
5.20
A
22.1
B
4.57
0
12.3
1
1.22
2
99.0
3
99.0
4
99.0
5
99.0
6
99.0
7
99.0
8
99.0
9
99.0
A
99.0
B
4.57
Thrust Transformations
-
A transformation is an algorithm that operates on every element of a container
-
The transform functor defines the transformation
David Mayerich
STIM Laboratory, University of Houston
Calculate \(\mathbf{c} = \mathbf{a} \circ \mathbf{b}\) where \(\mathbf{a}\), \(\mathbf{b}\), and \(\mathbf{c} \in \mathbb{R}^n\)
#include <thrust/transform.h>
#include <thrust/functional.h>
std::vector<float> a(N);
std::vector<float> b(N);
// fill arrays
thrust::device_vector<float> gpu_a = a;
thrust::device_vector<float> gpu_b = b;
thrust::device_vector<float> gpu_c(N);
thrust::transform(gpu_a.begin(), gpu_a.end(),
gpu_b.begin(), gpu_c.begin(),
thrust::multiplies<float>());Thrust Transformations
Calculate \(\mathbf{y} = (\mathbf{x} + \mathbf{f})\circ (\mathbf{x} + \mathbf{f})\) where \(\mathbf{x},\mathbf{f}\in\mathbb{R}^n\), \(x_i = i\), and \(\mathbf{f}\) is a vector representing the Fibonacci sequence
David Mayerich
STIM Laboratory, University of Houston
template <typename T> thrust::host_vector<T> fib(N) {
thrust::host_vector<T> x(N); // declare an output host vector
f[0] = f[1] = 1; // initialize the first two values
for(size_t i = 2; i < N; i++) // calculate remaining values
x[i] = f[i-1] + f[i-2]; // calculate the Fib sequence
return x; // return the host vector
}First, define a function to calculate the Fibonacci sequence:
Thrust Transformations
Thrust implementation of \(\mathbf{y} = (\mathbf{x} + \mathbf{f})\circ (\mathbf{x} + \mathbf{f})\)
David Mayerich
STIM Laboratory, University of Houston
size_t N; // length of the array
// fill arrays
thrust::device_vector<float> f = fib<float>(N); // calculate the fib sequence
thrust::device_vector<float> x(N); // allocate space for x
thrust::sequence(x.begin(), x.end(), 1, 1); // calculate x = [1, N]
thrust::device_vector<float> tmp(N); // temp array to store sum
thrust::transform(f.begin(), f.end(), x.begin(), // calculate the sum
tmp.begin(), thrust::plus<float>());
thrust::device_vector<float> y(N); // allocate output
thrust::transform(tmp.begin(), tmp.end(), tmp.begin(), // calculate the product
y.begin(), thrust::multiplies<float>());Defining Functors: saxpy()
Calculate \(\mathbf{y} = \alpha \mathbf{x} + \mathbf{y}\)
David Mayerich
STIM Laboratory, University of Houston
void slow_saxpy(float alpha, thrust:device_vector<float>& x,
thrust::device_vector<float>& y) {
// create a temporary vector to store alpha
thrust::device_vector<float> a(x.size());
thrust::fill(a.begin(), a.end(), alpha); // fill it with alpha
thrust::transform(x.begin(), x.end(), a.begin(), // a = alpha * x
a.begin(), thrust::multiplies<float>());
thrust::transform(a.begin(), a.end(), y.begin(), // y = y + a
y.begin(), thrust::plus<float>());
}Defining Functors: saxpy()
Use slow_saxpy() to calculate \(\mathbf{y} = \alpha \mathbf{x} + \mathbf{y}\)
David Mayerich
STIM Laboratory, University of Houston
size_t N; // length of the vectors
thrust::host_vector<float> x; // host vector for storing x
float a; // scalar value alpha
// load X and a
thrust::device_vector<float gpu_x = x; // copy x to the GPU
// create an output vector an initialize it to zero
thrust::device_vector<float> y(N, 0.0f);
slow_saxpy(a, x, y); // perform the saxpy operationDefining Functors: saxpy()
Create a functor structure to perform the transform
David Mayerich
STIM Laboratory, University of Houston
template <typename T>
struct saxpy_functor {
const T a;
saxpy_functor(T alpha) : a(alpha) {}; // constructor assigns alpha
// create a function that will be applied to each element of a vector
__host__ __device__ // usable on either platform
T operator()(const T& x, const T& y) const {
return a * x + y;
}
}Defining Functors: saxpy()
Use the saxpy() functor (fast vs. slow)
David Mayerich
STIM Laboratory, University of Houston
void fast_saxpy(float alpha, thrust::device_vector<float>& x,
thrust::device_vector<float>& y) {
thrust::transform(x.begin(), x.end(), y.begin(),
y.begin(), saxpy_functor(alpha));
}
void slow_saxpy(float alpha, thrust:device_vector<float>& x,
thrust::device_vector<float>& y) {
// create a temporary vector to store alpha
thrust::device_vector<float> a(x.size());
thrust::fill(a.begin(), a.end(), alpha); // fill it with alpha
thrust::transform(x.begin(), x.end(), a.begin(), // a = alpha * x
a.begin(), thrust::multiplies<float>());
thrust::transform(a.begin(), a.end(), y.begin(), // y = y + a
y.begin(), thrust::plus<float>());
}Reductions
-
A parallel reduction produces a small output from a large input
-
Iterative divide-and-conquer: split into pairs and reduce
David Mayerich
STIM Laboratory, University of Houston
0
54.4
0
12.3
1
1.22
2
3.64
3
2.28
4
3.11
5
5.20
6
22.1
7
4.57
0
13.5
1
5.92
2
8.31
3
26.7
0
19.4
1
35.0
Multiplication Reduction
-
Reduction Thrust API call:
David Mayerich
STIM Laboratory, University of Houston
-
Calculate \(n!\) in parallel
template <typename T>
thrust::reduce(InputIterator first, InputIterator last, T init, BinaryFunc op);size_t n;
thrust::device_vector<size_t> x(n);
thrust::sequence(x.begin(), x.end(), 1, 1);
// perform the reduction transform using the thrust::multiplies functor
// - the initial value of the result is 1 (0 would return 0)
size_t nfac = thrust::reduce(x.begin(), x.end(), (size_t) 1,
thrust::multiplies<size_t>());Scanning
-
A scan applies the reduction operation to all values preceding an index:
David Mayerich
STIM Laboratory, University of Houston
#include <thrust/scan.h>
size_t N = 100;
thrust::host_vector<float> x(N);
thrust::host_vector<float> y(N);
thrust::sequence(x.begin(), x.end());
// x = {0, 1, 2, 3, 4, 5, 6, ...}
thrust::inclusive_scan(x.begin(), x.end(), y.begin(), thrust::plus<float>());
// y = {0, 1, 3, 6, 10, 15, 21, ...} (includes the value at n)
thrust::exclusive_scan(x.begin(), x.end(), y.begin(), thrust::plus<float>());
// y = {0, 0, 1, 3, 6, 10, 15, ...} (excludes the value at n)Sorting
-
Sort an array:
David Mayerich
STIM Laboratory, University of Houston
#include <thrust/sort.h>
size_t N = 100;
thrust::device_vector<int> x;
// fill x
thrust::sort(x.begin(), x.end());-
Sort the array \(x[i]\) using values in \(y[i]\)
thrust::host_vector<int> keys(n);
thrust::sequence(keys.begin(), keys.end(), (int)n, -1);
// keys = {6, 5, 4, 3, 2, 1}
thrust::host_vector<char> values(n);
thrust::sequence(values.begin(), values.end(), 'a', (char)1);
// values = {'a', 'b', 'c', 'd', 'e', 'f'}
thrust::sort_by_key(keys.begin(), keys.end(), values.begin());
// keys = {1, 2, 3, 4, 5}
// values = {'f', 'e', 'd', 'c', 'b', 'a'}E.3 CUDA Libraries
By STIM Laboratory
E.3 CUDA Libraries
- 217