1 \chapterauthor{Raphaël Couturier}{Femto-ST Institute, University of Franche-Comte, France}
3 \chapter{Introduction to CUDA}
9 In this chapter we give some simple examples of CUDA programming. The goal is
10 not to provide an exhaustive presentation of all the functionalities of CUDA but
11 rather to give some basic elements. Of course, readers who do not know CUDA are
12 invited to read other books that are specialized on CUDA programming (for
13 example, \cite{ch2:Sanders:2010:CEI}).
16 \section{First example}
19 This first example is intented to show how to build a very simple program with
20 CUDA. Its goal is to perform the sum of two arrays and put the result into a
21 third array. A CUDA program consists in a C code which calls CUDA kernels that
22 are executed on a GPU. This code is in Listing~\ref{ch2:lst:ex1}.
25 As GPUs have their own memory, the first step consists of allocating memory on
26 the GPU. A call to \texttt{cudaMalloc}\index{CUDA functions!cudaMalloc}
27 allocates memory on the GPU. The second parameter represents the size of the
28 allocated variables, this size is expressed in bits.
30 \lstinputlisting[label=ch2:lst:ex1,caption=simple example]{Chapters/chapter2/ex1.cu}
33 In this example, we want to compare the execution time of the additions of two
34 arrays in CPU and GPU. So for both these operations, a timer is created to
35 measure the time. CUDA proposes to manipulate timers quite easily. The first
36 step is to create the timer\index{CUDA functions!timer}, then to start it, and at
37 the end to stop it. For each of these operations a dedicated function is used.
39 In order to compute the same sum with a GPU, the first step consists of
40 transferring the data from the CPU (considered as the host with CUDA) to the GPU
41 (considered as the device with CUDA). A call to \texttt{cudaMemcpy} copies the content of an array allocated in the host to the device when the fourth
43 to \texttt{cudaMemcpyHostToDevice}\index{CUDA functions!cudaMemcpy}. The first
44 parameter of the function is the destination array, the second is the
45 source array, and the third is the number of elements to copy (expressed in
48 Now the GPU contains the data needed to perform the addition. In sequential
49 programming, such addition is achieved with a loop on all the elements.
50 With a GPU, it is possible to perform the addition of all the elements of the
51 two arrays in parallel (if the number of blocks and threads per blocks is
52 sufficient). In Listing~\ref{ch2:lst:ex1} at the beginning, a simple kernel,
53 called \texttt{addition} is defined to compute in parallel the summation of the
54 two arrays. With CUDA, a kernel starts with the
55 keyword \texttt{\_\_global\_\_} \index{CUDA keywords!\_\_shared\_\_} which
56 indicates that this kernel can be called from the C code. The first instruction
57 in this kernel is used to compute the variable \texttt{tid} which represents the
58 thread index. This thread index\index{CUDA keywords!thread index} is computed according to
59 the values of the block index
60 (called \texttt{blockIdx} \index{CUDA keywords!blockIdx} in CUDA) and of the
61 thread index (called \texttt{threadIdx}\index{CUDA keywords!threadIdx} in
62 CUDA). Blocks of threads and thread indexes can be decomposed into 1 dimension,
63 2 dimensions, or 3 dimensions. According to the dimension of manipulated data,
64 the dimension of blocks of threads must be chosen carefully. In our example, only one dimension is
65 used. Then using the notation \texttt{.x}, we can access the first dimension
66 (\texttt{.y} and \texttt{.z}, respectively allow access to the second and
67 third dimension). The variable \texttt{blockDim}\index{CUDA keywords!blockDim}
68 gives the size of each block.
74 \section{Second example: using CUBLAS \index{CUBLAS}}
77 The Basic Linear Algebra Subprograms (BLAS) allows programmers to use efficient
78 routines for basic linear operations. Those routines are heavily used in many
79 scientific applications and are optimized for vector operations, matrix-vector
80 operations, and matrix-matrix
81 operations~\cite{ch2:journals/ijhpca/Dongarra02}. Some of those operations seem
82 to be easy to implement with CUDA. Nevertheless, as soon as a reduction is
83 needed, implementing an efficient reduction routine with CUDA is far from being
84 simple. Roughly speaking, a reduction operation\index{reduction operation} is an
85 operation which combines all the elements of an array and extracts a number
86 computed from all the elements. For example, a sum, a maximum, or a dot product
87 are reduction operations.
89 In this second example, we have two vectors $A$ and $B$. First
90 of all, we want to compute the sum of both vectors and store the result in a vector $C$. Then we want
91 to compute the scalar product between $1/C$ and $1/A$. This is just an example
92 which has no direct interest except to show how to program it with CUDA.
94 Listing~\ref{ch2:lst:ex2} shows this example with CUDA. The first kernel for the
95 addition of two arrays is exactly the same as the one described in the
98 The kernel to compute the inverse of the elements of an array is very
99 simple. For each thread index, the inverse of the array replaces the initial
102 In the main function, the beginning is very similar to the one in the previous
103 example. First, the user is asked to define the number of elements. Then a
104 call to \texttt{cublasCreate} initializes the CUBLAS library. It
105 creates a handle. Then all the arrays are allocated in the host and the device,
106 as in the previous example. Both arrays $A$ and $B$ are initialized. The CPU
107 computation is performed and the time for this is measured. In
108 order to compute the same result for the GPU, first of all, data from the CPU
109 need to be copied into the memory of the GPU. For that, it is possible to use
110 CUBLAS function \texttt{cublasSetVector}. This function has several
111 arguments. More precisely, the first argument represents the number of elements
112 to transfer, the second arguments is the size of each element, the third element
113 represents the source of the array to transfer (in the GPU), the fourth is an
114 offset between each element of the source (usually this value is set to 1), the
115 fifth is the destination (in the GPU), and the last is an offset between each
116 element of the destination. Then we call the kernel \texttt{addition} which
117 computes the sum of all elements of arrays $A$ and $B$. The \texttt{inverse}
118 kernel is called twice, once to inverse elements of array $C$ and once for
119 $A$. Finally, we call the function \texttt{cublasDdot} which computes the dot
120 product of two vectors. To use this routine, we must specify the handle
121 initialized by CUDA, the number of elements to consider, then each vector is
122 followed by the offset between every element. After the GPU computation, it is
123 possible to check that both computations produce the same result.
125 \lstinputlisting[label=ch2:lst:ex2,caption=simple example with CUBLAS]{Chapters/chapter2/ex2.cu}
127 \section{Third example: matrix-matrix multiplication}
132 Matrix-matrix multiplication is an operation which is quite easy to parallelize
133 with a GPU. If we consider that a matrix is represented using a two-dimensional
134 array, $A[i][j]$ represents the element of the $i$ row and of the $j$
135 column. In many cases, it is easier to manipulate a one-dimentional (1D) array rather than a 2D
136 array. With CUDA, even if it is possible to manipulate 2D arrays, in the
137 following we present an example based on a 1D array. For the sake of simplicity,
138 we consider we have a square matrix of size \texttt{size}. So with a 1D
139 array, \texttt{A[i*size+j]} allows us to have access to the element of the
140 $i$ row and of the $j$ column.
142 With sequential programming, the matrix-matrix multiplication is performed using
143 three loops. We assume that $A$, $B$ represent two square matrices and the
144 result of the multiplication of $A \times B$ is $C$. The
145 element \texttt{C[i*size+j]} is computed as follows:
147 C[size*i+j]=\sum_{k=0}^{size-1} A[size*i+k]*B[size*k+j];
150 In Listing~\ref{ch2:lst:ex3}, the CPU computation is performed using 3 loops,
151 one for $i$, one for $j$, and one for $k$. In order to perform the same
152 computation on a GPU, a naive solution consists of considering that the matrix
153 $C$ is split into 2-dimensional blocks. The size of each block must be chosen
154 such that the number of threads per block is less than $1,024$.
157 In Listing~\ref{ch2:lst:ex3}, we consider that a block contains 16 threads in
158 each dimension, the variable \texttt{width} is used for that. The
159 variable \texttt{nbTh} represents the number of threads per block. So,
160 to compute the matrix-matrix product on a GPU, each block of threads is assigned
161 to compute the result of the product of the elements of that block. The main
162 part of the code is quite similar to the previous code. Arrays are allocated in
163 the CPU and the GPU. Matrices $A$ and $B$ are randomly initialized. Then
164 arrays are transferred to the GPU memory with call to \texttt{cudaMemcpy}.
165 So the first step for each thread of a block is to compute the corresponding row
166 and column. With a 2-dimensional decomposition, \texttt{int i=
167 blockIdx.y*blockDim.y+ threadIdx.y;} allows us to compute the corresponding line
168 and \texttt{int j= blockIdx.x*blockDim.x+ threadIdx.x;} the corresponding
169 column. Then each thread has to compute the sum of the product of the row of
170 $A$ by the column of $B$. In order to use a register, the
171 kernel \texttt{matmul} uses a variable called \texttt{sum} to compute the
172 sum. Then the result is set into the matrix at the right place. The computation
173 of CPU matrix-matrix multiplication is performed as described previously. A
174 timer measures the time. In order to use 2-dimensional blocks, \texttt{dim3
175 dimGrid(size/width,size/width);} allows us to create \texttt{size/width} blocks
176 in each dimension. Likewise, \texttt{dim3 dimBlock(width,width);} is used to
177 create \texttt{width} thread in each dimension. After that, the kernel for the
178 matrix multiplication is called. At the end of the listing, the matrix $C$
179 computed by the GPU is transferred back into the CPU and we check that both matrices
180 C computed by the CPU and the GPU are identical with a precision of $10^{-4}$.
183 With $1,024 \times 1,024$ matrices, on a C2070M Tesla card, this code takes
184 $37.68$ms to perform the multiplication. With an Intel Xeon E31245 at $3.30$GHz, it
185 takes $2465$ms without any parallelization (using only one core). Consequently
186 the speed up between the CPU and GPU version is about $65$ which is very good
187 considering the difficulty of parallelizing this code.
189 \lstinputlisting[label=ch2:lst:ex3,caption=simple matrix-matrix multiplication with cuda]{Chapters/chapter2/ex3.cu}
192 In this chapter, three simple CUDA examples have been presented. As we cannot
193 present all the possibilities of the CUDA programming, interested readers are
194 invited to consult CUDA programming introduction books if some issues regarding
195 the CUDA programming are not clear.
197 \putbib[Chapters/chapter2/biblio]