CUDA is NVIDIA’s platform for parallel programming on Graphics Processing Units (GPUs). It exposes the massive parallelism of the GPU to scientific computing, with the goal of delivering high performance for scientific applications.
CUDA C/C++ and CUDA Fortran are based on the industry-standard C/C++ and Fortran languages, with:
a small set of extensions to enable heterogeneous programming
straightforward APIs to manage devices, memory, etc.
In this lecture, we will:
start from “Hello World!”
write and launch CUDA C/C++ kernels
manage GPU memory
manage communication and synchronization
Graphics Processing Units (GPU)¶
GPU model¶

A CPU core runs 1 thread at a time, with fast access to its main memory. A GPU runs about 32 threads per core, with very fast access to its own memory. But data has to be copied from the CPU main memory to the GPU memory and back, which is slow.
GPU programming¶
CUDA: NVIDIA GPUs are usually programmed using the vendor proprietary language CUDA. It is interfaced with C and C++ to create GPU kernels.
Warning: CUDA requires a complete rewrite of the computing intensive sections of the code, and lacks portability. Extracting maximum performance is difficult.
OpenACC: similar to OpenMP, it uses directives to load data on and retrieve data from the GPU, and to translate C and Fortran code into GPU kernels.
Better portability, but it usually also requires a rewrite of the routines.
Available in the NVIDIA HPC SDK (formerly the PGI compiler suite) and in GCC.
OpenMP: since version 4.5, OpenMP allows offloading of parallel sections to the GPU using the
targetdirective.Implemented in the GNU, Intel, LLVM, and NVIDIA compilers.
New generation of compilers and frameworks: the goal is to hide the dirty details from the programmer. Legion is an example of a compiler and runtime system. Kokkos is an example of a framework.
Heterogeneous computing¶
Terminology¶
Host: the CPU and its memory (host memory).
Device: the GPU and its memory (device memory).

A CUDA program mixes serial code, which runs on the host, and parallel code, which runs on the device. The parallel functions executed on the device are called kernels. Here is a complete example, which we will build up step by step in this lecture:
#include <stdio.h>
#include <stdlib.h>
#define N 100000
#define BLOCKSIZE 256
// kernel: each thread adds one element, using blocks and threads
__global__ void add(int *a, int *b, int *c, int n) {
int index = threadIdx.x + blockIdx.x * blockDim.x;
if (index < n)
c[index] = a[index] + b[index];
}
void random_ints(int *x, int size) {
int i;
for (i = 0; i < size; i++) x[i] = rand() % 10;
}
int main(void) {
int *a, *b, *c; // host copies of a, b, c
int *a_d, *b_d, *c_d; // device copies of a, b, c
int size = N * sizeof(int);
int i, errors = 0;
// Alloc space for device copies of a, b, c
cudaMalloc((void **)&a_d, size);
cudaMalloc((void **)&b_d, size);
cudaMalloc((void **)&c_d, size);
// Alloc space for host copies of a, b, c and setup input values
a = (int *)malloc(size); random_ints(a, N);
b = (int *)malloc(size); random_ints(b, N);
c = (int *)malloc(size);
// Copy inputs to device
cudaMemcpy(a_d, a, size, cudaMemcpyHostToDevice);
cudaMemcpy(b_d, b, size, cudaMemcpyHostToDevice);
// Launch add() kernel on GPU (parallel code), rounding the number of
// blocks up so that all N elements are covered
add<<<(N + BLOCKSIZE - 1) / BLOCKSIZE, BLOCKSIZE>>>(a_d, b_d, c_d, N);
// Copy result back to host
cudaMemcpy(c, c_d, size, cudaMemcpyDeviceToHost);
// Check the result on the host
for (i = 0; i < N; i++)
if (c[i] != a[i] + b[i]) errors++;
printf("%d errors\n", errors);
// Check for errors (from the API calls or from the kernel)
printf("%s\n", cudaGetErrorString(cudaGetLastError()));
// Cleanup
free(a); free(b); free(c);
cudaFree(a_d); cudaFree(b_d); cudaFree(c_d);
return 0;
}
Simple processing flow¶

The CPU and the GPU are connected through the PCI bus. A typical GPU computation proceeds in three steps:
Copy input data from CPU memory to GPU memory.
Load the GPU program and execute it, caching data on chip for performance.
Copy results from GPU memory back to CPU memory.
Transfers over the PCI bus are slow compared to the GPU memory bandwidth, so a good GPU code minimizes the data movement between host and device.
Compiling and running CUDA code¶
What you need¶
To compile and run the examples of this lecture, you need:
an NVIDIA GPU with its driver. CUDA does not run on other GPUs, such as the Apple GPUs of recent Macs, or AMD and Intel GPUs. If your laptop has no NVIDIA GPU, use a cluster.
the CUDA compiler
nvcc. It is provided by the CUDA Toolkit and by the NVIDIA HPC SDK.
All the complete programs of this lecture are in the codes/ directory.
Using the adroit cluster¶
At Princeton, students can use the GPUs of the adroit cluster. First log in
and load the NVIDIA HPC SDK, which provides nvcc:
$ ssh <YourNetID>@adroit.princeton.edu
$ module load nvhpc/24.11
$ nvcc --versionYou can compile on the login node, but the login node has no GPU: the programs must run on a GPU compute node. Like most clusters, adroit uses the Slurm job scheduler. For short tests, ask for an interactive session on a node with one GPU:
[user@adroit5 ~]$ salloc -N 1 -n 1 --gres=gpu:1 -t 00:10:00
salloc: Granted job allocation 3455102
salloc: Waiting for resource configuration
salloc: Nodes adroit-h11g2 are ready for job
[user@adroit-h11g2 ~]$ nvidia-smi
Wed Nov 4 23:29:05 2026
+-----------------------------------------------------------------------------------------+
| NVIDIA-SMI 610.57.04 KMD Version: 610.57.04 CUDA UMD Version: 13.3 |
+-----------------------------------------+------------------------+----------------------+
| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |
| | | MIG M. |
|=========================================+========================+======================|
| 0 NVIDIA A100-PCIE-40GB On | 00000000:17:00.0 Off | On |
| N/A 30C P0 32W / 250W | 203MiB / 40960MiB | N/A Default |
| | | Enabled |
+-----------------------------------------+------------------------+----------------------+
+-----------------------------------------------------------------------------------------+
| MIG devices: |
+------------------+----------------------------------+-----------+-----------------------+
| GPU GI CI MIG | Shared Memory-Usage | Vol| Shared |
| ID ID Dev | Shared BAR1-Usage | SM Unc| CE ENC DEC OFA JPG |
| | | ECC| |
|==================+==================================+===========+=======================|
| 0 1 0 0 | 102MiB / 20096MiB | 42 0 | 3 0 2 0 0 |
| | 0MiB / 12199MiB | | |
+------------------+----------------------------------+-----------+-----------------------+
+-----------------------------------------------------------------------------------------+
| Processes: |
| GPU GI CI PID Type Process name GPU Memory |
| ID ID Usage |
|=========================================================================================|
| No running processes found |
+-----------------------------------------------------------------------------------------+
[user@adroit-h11g2 ~]$ exitThe options request 1 node (-N 1), 1 task (-n 1), 1 GPU (--gres=gpu:1)
for 10 minutes (-t 00:10:00). Note that the prompt changes from the login node
adroit5 to the compute node adroit-h11g2: you are now on a machine with a
GPU, where you can run your programs. Always exit the session when you are
done, to release the GPU for other users.
nvidia-smi describes the GPU you have access to. Here, it is an NVIDIA A100
(PCIe version with 40 GB of memory), of compute capability 8.0, so we compile
with -arch=sm_80. Note the MIG M. field, which is Enabled: on adroit, the
A100 GPUs are split into several smaller GPUs using Multi-Instance GPU
(MIG), so that several users can share the same A100. The MIG devices table
shows the slice you were given: 42 SMs (out of 108 for the full A100) and about
20 GB of memory. For your program, this slice behaves like a smaller,
independent GPU.
For longer runs, write a batch script, for example job.slurm:
#!/bin/bash
#SBATCH --job-name=cuda
#SBATCH --nodes=1
#SBATCH --ntasks=1
#SBATCH --gres=gpu:1
#SBATCH --time=00:05:00
module purge
module load nvhpc/24.11
./helloand submit it with:
$ sbatch job.slurmThe output of the program is written to the file slurm-<jobid>.out.
Compiling with nvcc¶
All the examples of this lecture are compiled with the same command:
$ nvcc -O3 -arch=sm_80 hello.cu -o helloCUDA source files have the extension
.cu.nvccuses it to recognize CUDA code: with a.cextension, the file is passed to the host compiler, which does not understand the CUDA extensions such as__global__.-o hellonames the executable, as forgcc. Without it, the executable is calleda.out.-O3turns on optimizations, as forgcc.-arch=sm_XXtellsnvccwhich GPU to compile for. Each GPU generation has a compute capability: for example 7.0 for the V100, 8.0 for the A100 and 9.0 for the H100, which correspond to-arch=sm_70,-arch=sm_80and-arch=sm_90. You can query the compute capability of your GPU on a compute node with:$ nvidia-smi --query-gpu=name,compute_cap --format=csvIf you compile on the GPU compute node itself,
-arch=nativeselects the GPU of that node automatically.
The host code is standard C, so nvcc does not need any #include to recognize
CUDA functions such as cudaMalloc(): the CUDA runtime header is included
automatically.
Hello World!¶
Host code only¶
#include <stdio.h>
int main(void) {
printf("Hello World!\n");
return 0;
}$ nvcc hello_host.cu -o hello_host
$ ./hello_host
Hello World!This is standard C that runs on the host. The NVIDIA compiler nvcc can also be
used to compile programs with no device code.
Hello World! with device code¶
#include <stdio.h>
// kernel: runs on the device, called from the host
__global__ void mykernel(void) {
printf("Hello World from the GPU!\n");
}
int main(void) {
// Launch mykernel() on the GPU with 1 block of 1 thread
mykernel<<<1, 1>>>();
// Kernel launches are asynchronous: wait for the GPU to finish
cudaDeviceSynchronize();
printf("Hello World from the CPU!\n");
// Check for errors (from the API calls or from the kernel)
printf("%s\n", cudaGetErrorString(cudaGetLastError()));
return 0;
}
There are three new syntactic elements here. First, the __global__ keyword
indicates a function, called a kernel, that:
runs on the device
is called from the host
nvcc separates the source code into host and device components:
device functions (e.g.
mykernel()) are processed by the NVIDIA compilerhost functions (e.g.
main()) are processed by the standard host compiler, for examplegcc
Second, the call mykernel<<<1,1>>>():
Triple angle brackets mark a call from host code to device code. This is also called a kernel launch.
The arguments inside the brackets correspond to
<<<blocks, threads_per_block>>>. We will return to this terminology later.
Third, cudaDeviceSynchronize() makes the host wait for the kernel to finish.
Kernel launches are asynchronous: control returns to the host immediately.
Without this call, the program could exit before the GPU prints its message.
That’s all that is required to execute a function on the GPU! On a GPU node of adroit:
$ nvcc -O3 -arch=sm_80 hello.cu -o hello
$ ./hello
Hello World from the GPU!
Hello World from the CPU!
no errorSo far, mykernel() only prints a message. Let’s write a parallel code.
Parallel programming in CUDA¶
GPU computing is about massive parallelism. We will start by adding two integers and build up to adding two vectors .
Addition on the device¶
A simple kernel to add two integers:
__global__ void add(int *a, int *b, int *c) {
*c = *a + *b;
}As before, __global__ is a CUDA keyword meaning that:
add()will be executed on the deviceadd()will be called from the host
Note that we use pointers for the variables. Because add() runs on the device,
a, b and c must point to device memory. In other words, we need to
allocate memory on the GPU.
Memory management¶
Host and device memory are separate entities:
Device pointers point to GPU memory. They may be passed to and from host code, but may not be dereferenced in host code.
Host pointers point to CPU memory. They may be passed to and from device code, but may not be dereferenced in device code.
CUDA provides a simple API for handling device memory: cudaMalloc(),
cudaFree() and cudaMemcpy(). They are similar to their C equivalents
malloc(), free() and memcpy().
Addition on the device: the complete program¶
A CUDA source file contains both the device code and the host code. Here is the
complete program, in codes/add.cu: the #include lines, then the add()
kernel defined above, then the main() function that runs on the host and
launches the kernel:
#include <stdio.h>
// kernel: add two integers
__global__ void add(int *a, int *b, int *c) {
*c = *a + *b;
}
int main(void) {
int a, b, c; // host copies of a, b, c
int *a_d, *b_d, *c_d; // device copies of a, b, c
int size = sizeof(int);
// Allocate space for device copies of a, b, c
cudaMalloc((void **)&a_d, size);
cudaMalloc((void **)&b_d, size);
cudaMalloc((void **)&c_d, size);
// Setup input values
a = 2;
b = 7;
// Copy inputs to device
cudaMemcpy(a_d, &a, size, cudaMemcpyHostToDevice);
cudaMemcpy(b_d, &b, size, cudaMemcpyHostToDevice);
// Launch add() kernel on GPU
add<<<1, 1>>>(a_d, b_d, c_d);
// Copy result back to host
cudaMemcpy(&c, c_d, size, cudaMemcpyDeviceToHost);
// Print the result
printf("c = %d\n", c);
// Check for errors (from the API calls or from the kernel)
printf("%s\n", cudaGetErrorString(cudaGetLastError()));
// Cleanup
cudaFree(a_d); cudaFree(b_d); cudaFree(c_d);
return 0;
}
We use the suffix _d to identify pointers to device memory. This naming
convention is not required by CUDA, but it helps avoid dereferencing a device
pointer in host code by mistake.
$ nvcc -O3 -arch=sm_80 add.cu -o add
$ ./add
c = 9
no errorMoving to parallel¶
So how do we run code in parallel on the device? Instead of executing add()
once with add<<<1, 1>>>, we launch many copies of it at the same time, one per
element of the vectors.
Grids, blocks and threads¶
A kernel is launched as a grid of blocks of threads:
each parallel invocation of
add()is a thread;threads are grouped into blocks, all of the same size;
the set of blocks is the grid.
The two numbers between <<< >>> are the number of blocks in the grid and the
number of threads per block:
add<<<blocks, threads_per_block>>>(a_d, b_d, c_d);
Inside the kernel, each thread finds out where it is with the following built-in variables:
| Variable | Meaning |
|---|---|
threadIdx.x | Thread index inside the block |
blockIdx.x | Block index |
blockDim.x | Number of threads per block |
gridDim.x | Number of blocks in the grid |
Indexing arrays¶
To add two vectors, we give each thread one element of the arrays. Each thread must therefore compute a unique global index from its block and thread indices. Consider an array with one element per thread, with 8 threads per block:

With 8 threads per block, a unique index for each thread is given by:
int index = threadIdx.x + blockIdx.x * 8;Which thread will operate on the red element below?

int index = threadIdx.x + blockIdx.x * BLOCKSIZE;
// = 5 + 2 * 8;
// = 21;Vector addition with blocks and threads¶
Instead of hard-coding the block size, we use the built-in variable blockDim.x
for the number of threads per block:
int index = threadIdx.x + blockIdx.x * blockDim.x;The combined version of add() uses parallel threads and parallel blocks:
__global__ void add(int *a, int *b, int *c) {
int index = threadIdx.x + blockIdx.x * blockDim.x;
c[index] = a[index] + b[index];
}What changes need to be made in main()?
#define N (2048 * 2048)
#define BLOCKSIZE 512
int main(void) {
int *a, *b, *c; // host copies of a, b, c
int *a_d, *b_d, *c_d; // device copies of a, b, c
int size = N * sizeof(int);
// Alloc space for device copies of a, b, c
cudaMalloc((void **)&a_d, size);
cudaMalloc((void **)&b_d, size);
cudaMalloc((void **)&c_d, size);
// Alloc space for host copies of a, b, c and setup input values
a = (int *)malloc(size); random_ints(a, N);
b = (int *)malloc(size); random_ints(b, N);
c = (int *)malloc(size);
// Copy inputs to device
cudaMemcpy(a_d, a, size, cudaMemcpyHostToDevice);
cudaMemcpy(b_d, b, size, cudaMemcpyHostToDevice);
// Launch add() kernel on GPU
add<<<N / BLOCKSIZE, BLOCKSIZE>>>(a_d, b_d, c_d);
// Copy result back to host
cudaMemcpy(c, c_d, size, cudaMemcpyDeviceToHost);
// Cleanup
free(a); free(b); free(c);
cudaFree(a_d); cudaFree(b_d); cudaFree(c_d);
return 0;
}As in the previous programs, the add() kernel above must be defined in the
same file, before main().
Handling arbitrary vector sizes¶
Typical problems are not friendly multiples of blockDim.x. We need to avoid
accessing beyond the end of the arrays:
__global__ void add(int *a, int *b, int *c, int n) {
int index = threadIdx.x + blockIdx.x * blockDim.x;
if (index < n)
c[index] = a[index] + b[index];
}and update the kernel launch to round the number of blocks up:
add<<<(N + BLOCKSIZE - 1) / BLOCKSIZE, BLOCKSIZE>>>(a_d, b_d, c_d, N);This is the complete example shown at the beginning of the lecture, which is in
codes/vector_add.cu:
$ nvcc -O3 -arch=sm_80 vector_add.cu -o vector_add
$ ./vector_add
0 errors
no errorRecapitulation¶
Difference between host and device:
Host: CPU
Device: GPU
Using
__global__to declare a function as device code:executes on the device
is called from the host
Passing parameters from host code to a device function.
Basic device memory management:
cudaMalloc()cudaMemcpy()cudaFree()
Launching parallel kernels:
launch a grid of blocks of threads with
add<<<blocks, threads_per_block>>>(...);compute a global index with
threadIdx.x + blockIdx.x * blockDim.xguard against out-of-bounds accesses with
if (index < n)
Why bother with threads and blocks?¶
Using both threads and blocks seems unnecessarily complicated: they add a level of complexity. What do we gain?
Unlike parallel blocks, threads have mechanisms to:
communicate
synchronize
To understand why, we need to look at the hardware.
GPU architecture¶
Pascal P100¶
As an example, we consider the NVIDIA Pascal P100, a GPU designed for High Performance Computing. The chip is organized into many Streaming Multiprocessors (SMs), connected to a shared L2 cache and to the high-bandwidth device memory:

Streaming Multiprocessor (SM)¶

Each SM contains many cores, organized in groups of 32 called warps. The software hierarchy maps onto this hardware hierarchy:
an SM is made of warps, each warp of 32 cores
a block is made of warps, each warp of 32 threads
Terminology¶
| Concept | Description |
|---|---|
| Thread | Each thread is executed by one core. |
| Warp | A warp consists of 32 cores that share the register memory and operate simultaneously by construction. |
| Block | Each block is assigned to one SM and consists of warps. The threads of a block share the SM’s 64 KB on-chip memory. |
| Grid | The kernel is executed over a grid of blocks. |
This explains why threads within a block can communicate and synchronize: they run on the same SM and share its fast on-chip memory. Blocks, on the other hand, may run on different SMs, in any order.
Recapitulation¶
What have we learned?
Write and launch CUDA kernels:
__global__,<<<blocks, threads_per_block>>>threadIdx.x,blockIdx.x,blockDim.x
Manage GPU memory:
cudaMalloc(),cudaMemcpy(),cudaFree()
Extra topics¶
Coordinating host and device¶
Kernel launches are asynchronous: control returns to the host immediately. The host needs to synchronize before consuming the results.
| Function | Behavior |
|---|---|
cudaMemcpy() | Blocks the host until the copy is complete. The copy begins when all preceding kernel calls have completed. |
cudaMemcpyAsync() | Asynchronous, does not block the host. |
cudaDeviceSynchronize() | Blocks the host until all preceding kernel calls have completed. |
Reporting errors¶
All CUDA API calls return an error code (cudaError_t). This error can come
from:
the API call itself, or
an earlier asynchronous operation (e.g. a kernel).
Get the error code for the last error:
cudaError_t cudaGetLastError(void);Get a string to describe the error:
char *cudaGetErrorString(cudaError_t);For example:
printf("%s\n", cudaGetErrorString(cudaGetLastError()));3D indexing¶
A kernel is launched as a grid of blocks of threads, and blockIdx and
threadIdx are in fact 3D. So far, we showed only one dimension (x).

The built-in variables are:
| Variable | Meaning |
|---|---|
threadIdx | Thread indices (x, y, z) |
blockIdx | Block indices (x, y, z) |
blockDim | Number of threads per block (x, y, z) |
gridDim | Number of blocks (x, y, z) |
Sharing data between threads¶
Terminology: within a block, threads share data via shared memory:
extremely fast on-chip memory, managed by the user
declared using
__shared__, allocated per blockdata is not visible to threads in other blocks
Thread synchronization¶
void __syncthreads();Synchronizes all threads within a block. It is used to prevent race condition hazards.
All threads must reach the barrier. In conditional code, the condition must be uniform across the block.
For example, the following kernel computes the sum of the elements handled by each block. Each thread first copies one element into shared memory, then the threads cooperate to reduce the shared array, with a barrier between each step:
#define BLOCKSIZE 512
__global__ void block_sum(int *in, int *out, int n) {
__shared__ int temp[BLOCKSIZE];
int index = threadIdx.x + blockIdx.x * blockDim.x;
// Copy one element per thread into shared memory
temp[threadIdx.x] = (index < n) ? in[index] : 0;
__syncthreads();
// Tree reduction within the block
for (int stride = blockDim.x / 2; stride > 0; stride /= 2) {
if (threadIdx.x < stride)
temp[threadIdx.x] += temp[threadIdx.x + stride];
__syncthreads();
}
// Thread 0 writes the partial sum of this block
if (threadIdx.x == 0)
out[blockIdx.x] = temp[0];
}Note that __syncthreads() is called outside the if statements, so that every
thread of the block reaches the barrier.
Device management¶
An application can query and select GPUs:
cudaGetDeviceCount(int *count);
cudaSetDevice(int device);
cudaGetDevice(int *device);
cudaGetDeviceProperties(cudaDeviceProp *prop, int device);Multiple host threads can share a device.
A single host thread can manage multiple devices, using
cudaSetDevice(i)to select the current device.
Examples¶
We now revisit the two examples of the OpenMP and MPI lectures, this time using
CUDA. They can be found in the codes/ directory. They were run on adroit, on
a node with an NVIDIA A100 GPU, a GPU designed for High Performance Computing,
with 108 SMs and 32 double precision cores per SM, that is 3456 double
precision cores in total. We request one GPU of this type with:
$ salloc --nodes=1 --ntasks=1 --time=00:15:00 --gres=gpu:1 --constraint=a100As explained above, on adroit this gives us a MIG slice of the A100, with 42 of its 108 SMs, that is 1344 double precision cores, and 20 GB of memory, half of the full GPU. The timings below were measured on such a slice: on a full A100, the example runs about 2.5 times faster.
Computing ¶
We compute using the integral
approximated with the midpoint rule using points. We launch a
fixed number of blocks, and each thread loops over the points index,
index + stride, index + 2*stride, ..., where stride is the total number of
threads. This is called a grid-stride loop. Each thread computes its own
partial sum. The threads of each block then combine their partial sums in
shared memory using the same tree reduction as in the block_sum example above.
Finally, thread 0 of each block adds the result of its block to the total using
atomicAdd(), which guarantees that two blocks cannot update the total at the
same time:
// Based on Tim Mattson's code for
// https://github.com/tgmattso/OpenMP_intro_tutorial
#include <stdio.h>
#include <sys/time.h>
#define NBLOCKS 1024
#define BLOCKSIZE 256
// parallel function: each thread computes a partial sum over many steps,
// then the threads of each block combine their partial sums
__global__ void compute_sum(long long num_steps, double step, double *sum) {
__shared__ double temp[BLOCKSIZE];
long long index = threadIdx.x + (long long)blockIdx.x * blockDim.x;
long long stride = (long long)blockDim.x * gridDim.x;
// Each thread handles the steps index, index+stride, index+2*stride, ...
double partial = 0;
for (long long i = index; i < num_steps; i += stride) {
double x = (i + 0.5) * step;
partial += 4.0 / (1.0 + x * x);
}
// Copy one partial sum per thread into shared memory
temp[threadIdx.x] = partial;
__syncthreads();
// Tree reduction within the block
for (int s = blockDim.x / 2; s > 0; s /= 2) {
if (threadIdx.x < s)
temp[threadIdx.x] += temp[threadIdx.x + s];
__syncthreads();
}
// Thread 0 adds the partial sum of this block to the total
if (threadIdx.x == 0)
atomicAdd(sum, temp[0]);
}
// wall-clock time in seconds
double wtime(void) {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + 1e-6 * tv.tv_usec;
}
int main(void) {
long long num_steps = 10000000000LL;
double step = 1.0 / num_steps;
double sum; // host copy of sum
double *sum_d; // device copy of sum
double t0, t1;
int k;
// Alloc space for device copy of sum
cudaMalloc((void **)&sum_d, sizeof(double));
printf("Starting with %d blocks of %d threads\n", NBLOCKS, BLOCKSIZE);
for (k = 0; k < 4; k++) {
// Set the device copy of sum to zero
cudaMemset(sum_d, 0, sizeof(double));
t0 = wtime();
// Launch compute_sum() kernel on GPU
compute_sum<<<NBLOCKS, BLOCKSIZE>>>(num_steps, step, sum_d);
// Kernel launches are asynchronous: wait for the GPU to finish
cudaDeviceSynchronize();
t1 = wtime();
// Copy result back to host
cudaMemcpy(&sum, sum_d, sizeof(double), cudaMemcpyDeviceToHost);
printf("pass %d time (ms): %f %.15f\n", k + 1, 1000 * (t1 - t0),
step * sum);
}
// Check for errors (from the API calls or from the kernels)
printf("%s\n", cudaGetErrorString(cudaGetLastError()));
// Cleanup
cudaFree(sum_d);
return 0;
}
Here the -arch option is essential: atomicAdd() for double precision numbers
requires a GPU of compute capability 6.0 or higher, and does not compile for
older targets. For the A100, we use -arch=sm_80:
$ nvcc -O3 -arch=sm_80 compute_pi_cuda.cu -o compute_pi_cuda
$ ./compute_pi_cuda
Starting with 1024 blocks of 256 threads
pass 1 time (ms): 72.767019 3.141592653589794
pass 2 time (ms): 72.654009 3.141592653589794
pass 3 time (ms): 72.764158 3.141592653589794
pass 4 time (ms): 72.829962 3.141592653589794
no errorAs for the CPU codes, we repeat the computation 4 times and report the time of the last pass:
| Version | Time (s) | Speedup |
|---|---|---|
| 1 CPU core | 12.86 | 1 |
| OpenMP (8 threads) | 1.82 | 7 |
| MPI (8 tasks) | 1.76 | 7 |
| CUDA (A100 slice) | 0.073 | 176 |
The CPU timings are those of the OpenMP and MPI lectures on the Apple M1 Max. This example is compute bound: it performs only computations on variables that stay in the registers. It therefore fully benefits from the thousands of cores of the GPU, which is about 24 times faster than the 8 CPU cores.
The power function¶
We now parallelize the loop computing the polynomial
for elements. Each thread computes one
element of y. The input array x is copied to the GPU only once, then the
kernel is launched 4 times, and the result y is copied back to the CPU at the
end. We also time the two copies:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#define N 100000000
#define BLOCKSIZE 256
// parallel function: each thread computes one element of y
__global__ void power(double *x, double *y, int n) {
int index = threadIdx.x + blockIdx.x * blockDim.x;
if (index < n) {
double xi = x[index];
y[index] = xi * (1 + xi * (1 + xi * (1 + xi * (1 + xi * (1 + xi * (1 + xi * (1 + xi)))))));
}
}
// wall-clock time in seconds
double wtime(void) {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + 1e-6 * tv.tv_usec;
}
int main(void) {
double *x, *y; // host copies of x, y
double *x_d, *y_d; // device copies of x, y
size_t size = (size_t)N * sizeof(double);
double t0, t1;
int i, k;
// Alloc space for device copies of x, y
cudaMalloc((void **)&x_d, size);
cudaMalloc((void **)&y_d, size);
// Alloc space for host copies of x, y and setup input values
x = (double *)malloc(size);
y = (double *)malloc(size);
for (i = 0; i < N; i++) x[i] = rand() / (double)RAND_MAX;
// Copy input to device (only once: transfers over the PCI bus are slow)
t0 = wtime();
cudaMemcpy(x_d, x, size, cudaMemcpyHostToDevice);
t1 = wtime();
printf("Starting with %d blocks of %d threads\n",
(N + BLOCKSIZE - 1) / BLOCKSIZE, BLOCKSIZE);
printf("copy x to device time (ms): %f\n", 1000 * (t1 - t0));
for (k = 0; k < 4; k++) {
t0 = wtime();
// Launch power() kernel on GPU
power<<<(N + BLOCKSIZE - 1) / BLOCKSIZE, BLOCKSIZE>>>(x_d, y_d, N);
// Kernel launches are asynchronous: wait for the GPU to finish
cudaDeviceSynchronize();
t1 = wtime();
// Copy one element of the result back to host for printing
cudaMemcpy(&y[k], &y_d[k], sizeof(double), cudaMemcpyDeviceToHost);
printf("pass %d time (ms): %f %f\n", k + 1, 1000 * (t1 - t0), y[k]);
}
// Check for errors (from the API calls or from the kernels)
printf("%s\n", cudaGetErrorString(cudaGetLastError()));
// Copy the full result back to host
t0 = wtime();
cudaMemcpy(y, y_d, size, cudaMemcpyDeviceToHost);
t1 = wtime();
printf("copy y to host time (ms): %f\n", 1000 * (t1 - t0));
// Cleanup
free(x); free(y);
cudaFree(x_d); cudaFree(y_d);
return 0;
}
$ nvcc -O3 -arch=sm_80 power_cuda.cu -o power_cuda
$ ./power_cuda
Starting with 390625 blocks of 256 threads
copy x to device time (ms): 70.031166
pass 1 time (ms): 2.600908 3.951842
pass 2 time (ms): 2.340078 0.650827
pass 3 time (ms): 2.340078 3.099792
pass 4 time (ms): 2.335072 3.307003
no error
copy y to host time (ms): 174.663782As for the CPU codes, the first pass is slower, and we report the time of the last pass:
| Version | Time (ms) | Speedup |
|---|---|---|
| 1 CPU core | 37.1 | 1 |
| OpenMP (8 threads) | 11.7 | 3.2 |
| MPI (8 tasks) | 11.9 | 3.1 |
| CUDA (A100 slice) | 2.34 | 16 |
This example is memory bandwidth bound. On the CPU, we saw that the speedup saturates when the cores reach the maximum memory bandwidth of about 200 GB/s. The GPU memory has a much higher bandwidth, about 1.5 TB/s for a full A100, and half of that, about 0.75 TB/s, for our MIG slice, which gets half of the memory. For each element, the kernel reads 8 bytes and writes 8 bytes, so the GPU moves bytes in 2.34 ms, which is about 0.7 TB/s, close to the maximum bandwidth of the slice. The speedup compared to the 8 CPU cores, about 5, is therefore close to the ratio of the memory bandwidths, and is much smaller than for the example.
But this is not the whole story. Copying x to the GPU and y back to the CPU
over the PCI bus takes about 245 ms, more than 100 times the time of the kernel
itself, and even 6.5 times more than the time of the serial CPU code! The GPU
only pays off if the data stays in the GPU memory long enough, so that many
kernels can be executed between the copies. This is why porting an application
to the GPU often means moving most of the code to the GPU, not only the most
expensive loops.