CUDA Performance Optimization
Chapter 7 — measure first, then fix what the measurement shows
What you will learn
- A repeatable method: measure, find the limiting resource, fix, measure again
- Memory-bound vs compute-bound kernels, and how to tell which you have
- Coalescing and shared-memory bank conflicts, through a matrix transpose in four steps
- Data layout: array of structures vs structure of arrays
- Profiling with Nsight Systems and Nsight Compute, and a checklist of common fixes
Optimization without measurement is guessing. Most GPU kernels are limited by one resource at a time, usually memory bandwidth, sometimes arithmetic throughput, sometimes latency. Each fix only helps if it targets the resource that is actually limiting. This chapter is about finding that resource.
The method
- Get it correct first, with a CPU reference or known answer to check against. A fast wrong kernel is worthless, and optimizations often introduce bugs.
- Measure with events after a warm-up (Chapter 4), or with a profiler.
- Compare with the hardware limit. Convert time to GB/s or FLOP/s and compare with what the GPU can do.
- Find the limiter with the profiler, change one thing, and measure again.
- Stop when you are close to the limit, or when the kernel no longer matters for total run time.
Also look at the whole program before tuning a kernel. If the run takes 100 ms and the kernel 2 ms of it, the copies or the CPU code are the problem. nsys shows this at a glance.
Memory-bound or compute-bound?
Arithmetic intensity is the number of floating-point operations a kernel performs per byte it moves to or from device memory. Compare it with the GPU's ratio of compute to bandwidth:
| GPU | FP32 peak | Memory bandwidth | Balance point |
|---|---|---|---|
| Tesla T4 | ~8 TFLOP/s | 320 GB/s | ~25 FLOP/byte |
| RTX 3070 Laptop | ~16 TFLOP/s | 448 GB/s | ~36 FLOP/byte |
| A100 40 GB | 19.5 TFLOP/s | 1,555 GB/s | ~13 FLOP/byte |
A kernel below the balance point is memory-bound: its speed is set by bandwidth, and the metric to watch is GB/s. Vector addition does 1 FLOP per 12 bytes (0.08 FLOP/byte), so it is deeply memory-bound, like most element-wise kernels, reductions and transposes. A kernel above the balance point is compute-bound, and FLOP/s is the metric. Large matrix multiplication can get there, but only with data reuse in shared memory and registers, which is the subject of Chapter 8. This simple model is called the roofline.
Coalescing
Device memory is read in 32-byte sectors. When the 32 threads of a warp read 32 consecutive floats, that is 128 bytes in 4 sectors, all of it useful. When they read with a stride of 32 floats, each thread touches a different sector: 32 sectors for the same 128 useful bytes, and most of the bandwidth is wasted. The rule: consecutive threads (threadIdx.x) should access consecutive addresses.
Worked example: matrix transpose
A transpose is the standard coalescing exercise, because the two sides want different orders. Read the input row by row and you write the output column by column, or the other way around. Every version below moves exactly the same bytes, so the GB/s numbers are directly comparable. A plain copy of the matrix is the upper bound.
- Naive: coalesced reads, but writes with a stride of a whole row.
- Shared tile: a block loads a 32×32 tile with coalesced reads into shared memory, then writes the transposed tile with coalesced writes. The reordering happens in fast shared memory.
- Padded tile: the same, with the tile declared as
[32][33].
Bank conflicts
Shared memory is divided into 32 banks; consecutive 4-byte words go to consecutive banks. A warp can access 32 different banks in one step. If several threads hit different addresses in the same bank, those accesses are serialized. In a [32][32] float tile, every element of a column lies in the same bank, because each row is exactly 32 words long. Reading a column, as the transposed write does, is a 32-way bank conflict. Padding each row to 33 words shifts each row by one bank, so a column touches all 32 banks.
#include <cstdio> #include <cstdlib> #define CUDA_CHECK(call) \ do { \ cudaError_t err_ = (call); \ if (err_ != cudaSuccess) { \ fprintf(stderr, "CUDA error %s at %s:%d\n", \ cudaGetErrorString(err_), __FILE__, __LINE__); \ exit(1); \ } \ } while (0) #define TILE 32 #define ROWS 8 // a 32x8 block handles a 32x32 tile: each thread does 4 elements // Reference: a plain copy with the same access pattern as the tiled kernels. The upper bound. __global__ void copy(const float *in, float *out, int n) { int x = blockIdx.x * TILE + threadIdx.x, y = blockIdx.y * TILE + threadIdx.y; for (int j = 0; j < TILE; j += ROWS) out[(y + j) * n + x] = in[(y + j) * n + x]; } // 1. Naive: reads are coalesced, writes have a stride of n floats. __global__ void transposeNaive(const float *in, float *out, int n) { int x = blockIdx.x * TILE + threadIdx.x, y = blockIdx.y * TILE + threadIdx.y; for (int j = 0; j < TILE; j += ROWS) out[x * n + (y + j)] = in[(y + j) * n + x]; } // 2. and 3. Through a shared tile. PAD = 0 has bank conflicts, PAD = 1 avoids them. template <int PAD> __global__ void transposeTiled(const float *in, float *out, int n) { __shared__ float tile[TILE][TILE + PAD]; int x = blockIdx.x * TILE + threadIdx.x, y = blockIdx.y * TILE + threadIdx.y; for (int j = 0; j < TILE; j += ROWS) tile[threadIdx.y + j][threadIdx.x] = in[(y + j) * n + x]; // coalesced read __syncthreads(); x = blockIdx.y * TILE + threadIdx.x; // swap block coordinates y = blockIdx.x * TILE + threadIdx.y; for (int j = 0; j < TILE; j += ROWS) out[(y + j) * n + x] = tile[threadIdx.x][threadIdx.y + j]; // coalesced write, column read from the tile } int main() { const int n = 4096; // n x n floats, n a multiple of TILE const size_t bytes = (size_t)n * n * sizeof(float); float *h = (float *)malloc(bytes), *out = (float *)malloc(bytes); for (size_t i = 0; i < (size_t)n * n; i++) h[i] = (float)i; float *d_in, *d_out; CUDA_CHECK(cudaMalloc(&d_in, bytes)); CUDA_CHECK(cudaMalloc(&d_out, bytes)); CUDA_CHECK(cudaMemcpy(d_in, h, bytes, cudaMemcpyHostToDevice)); dim3 block(TILE, ROWS), grid(n / TILE, n / TILE); const char *names[] = {"copy (bound)", "naive", "shared tile", "padded tile"}; cudaEvent_t a, b; CUDA_CHECK(cudaEventCreate(&a)); CUDA_CHECK(cudaEventCreate(&b)); bool ok = true; for (int v = 0; v < 4; v++) { auto run = [&]() { if (v == 0) copy<<<grid, block>>>(d_in, d_out, n); if (v == 1) transposeNaive<<<grid, block>>>(d_in, d_out, n); if (v == 2) transposeTiled<0><<<grid, block>>>(d_in, d_out, n); if (v == 3) transposeTiled<1><<<grid, block>>>(d_in, d_out, n); }; CUDA_CHECK(cudaMemset(d_out, 0, bytes)); run(); // warm-up, also the run we check CUDA_CHECK(cudaGetLastError()); CUDA_CHECK(cudaMemcpy(out, d_out, bytes, cudaMemcpyDeviceToHost)); long long errors = 0; for (int r = 0; r < n; r++) for (int c = 0; c < n; c++) { float expect = v == 0 ? h[(size_t)r * n + c] : h[(size_t)c * n + r]; if (out[(size_t)r * n + c] != expect) errors++; } const int reps = 20; CUDA_CHECK(cudaEventRecord(a)); for (int r = 0; r < reps; r++) run(); CUDA_CHECK(cudaEventRecord(b)); CUDA_CHECK(cudaEventSynchronize(b)); float ms; CUDA_CHECK(cudaEventElapsedTime(&ms, a, b)); ms /= reps; printf("%-13s %6.3f ms %6.1f GB/s errors: %lld\n", names[v], ms, 2.0 * bytes / ms / 1e6, errors); ok = ok && errors == 0; } printf(ok ? "PASS\n" : "FAIL\n"); CUDA_CHECK(cudaFree(d_in)); CUDA_CHECK(cudaFree(d_out)); free(h); free(out); return 0; }
On a laptop RTX 3070: copy 412 GB/s, naive 116 GB/s, shared tile 364 GB/s, padded tile 354 GB/s. The naive version wastes most of its bandwidth on scattered writes, and the shared tile recovers almost all of it. Padding made no measurable difference here: the kernel is limited by device memory, and the extra shared-memory cycles from the conflicts are hidden behind it. Nsight Compute still reports the conflicts, and in kernels that spend more time in shared memory, such as Chapter 8's matrix multiply, they do cost time. Measure before assuming a fix helps. The main lesson: shared memory is often useful not for reuse, but to reorder data so that global accesses can be coalesced.
Data layout: AoS vs SoA
An array of structures (AoS) stores each object's fields together: struct P { float x, y, z, vx, vy, vz, mass, charge; } p[n];. If a kernel only updates x from vx, consecutive threads read addresses 32 bytes apart, and most of each sector it loads is fields it doesn't need. A structure of arrays (SoA) keeps each field in its own array, so x[i] for consecutive i is contiguous.
#include <cstdio> #include <cstdlib> #include <cmath> #define CUDA_CHECK(call) \ do { \ cudaError_t err_ = (call); \ if (err_ != cudaSuccess) { \ fprintf(stderr, "CUDA error %s at %s:%d\n", \ cudaGetErrorString(err_), __FILE__, __LINE__); \ exit(1); \ } \ } while (0) struct Particle { float x, y, z, vx, vy, vz, mass, charge; }; // 32 bytes struct Particles { // the same data, one array per field float *x, *y, *z, *vx, *vy, *vz, *mass, *charge; }; // Both kernels do the same work: move x by vx * dt. __global__ void stepAoS(Particle *p, int n, float dt) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) p[i].x += p[i].vx * dt; } __global__ void stepSoA(Particles p, int n, float dt) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) p.x[i] += p.vx[i] * dt; } int main() { const int n = 1 << 23, threads = 256, blocks = (n + threads - 1) / threads, reps = 20; const float dt = 0.01f; Particle *h = (Particle *)malloc(n * sizeof(Particle)); for (int i = 0; i < n; i++) h[i] = {i * 0.001f, 0, 0, (i % 100) * 0.1f, 0, 0, 1, 0}; Particle *d_aos; CUDA_CHECK(cudaMalloc(&d_aos, n * sizeof(Particle))); CUDA_CHECK(cudaMemcpy(d_aos, h, n * sizeof(Particle), cudaMemcpyHostToDevice)); Particles d_soa; float **fields[] = {&d_soa.x, &d_soa.y, &d_soa.z, &d_soa.vx, &d_soa.vy, &d_soa.vz, &d_soa.mass, &d_soa.charge}; float *tmp = (float *)malloc(n * sizeof(float)); for (int f = 0; f < 8; f++) { CUDA_CHECK(cudaMalloc(fields[f], n * sizeof(float))); for (int i = 0; i < n; i++) tmp[i] = ((float *)&h[i])[f]; // field f of particle i CUDA_CHECK(cudaMemcpy(*fields[f], tmp, n * sizeof(float), cudaMemcpyHostToDevice)); } cudaEvent_t a, b; CUDA_CHECK(cudaEventCreate(&a)); CUDA_CHECK(cudaEventCreate(&b)); float ms[2]; for (int v = 0; v < 2; v++) { if (v == 0) stepAoS<<<blocks, threads>>>(d_aos, n, 0.0f); else stepSoA<<<blocks, threads>>>(d_soa, n, 0.0f); // warm-up, dt = 0 CUDA_CHECK(cudaEventRecord(a)); for (int r = 0; r < reps; r++) { if (v == 0) stepAoS<<<blocks, threads>>>(d_aos, n, dt); else stepSoA<<<blocks, threads>>>(d_soa, n, dt); } CUDA_CHECK(cudaEventRecord(b)); CUDA_CHECK(cudaEventSynchronize(b)); CUDA_CHECK(cudaEventElapsedTime(&ms[v], a, b)); ms[v] /= reps; } // Check: both layouts must give the same x, and match the CPU. Particle *back = (Particle *)malloc(n * sizeof(Particle)); CUDA_CHECK(cudaMemcpy(back, d_aos, n * sizeof(Particle), cudaMemcpyDeviceToHost)); CUDA_CHECK(cudaMemcpy(tmp, d_soa.x, n * sizeof(float), cudaMemcpyDeviceToHost)); int errors = 0; for (int i = 0; i < n; i += 101) { float x = h[i].x; for (int r = 0; r < reps; r++) x += h[i].vx * dt; if (fabsf(back[i].x - x) > 1e-3f || fabsf(tmp[i] - x) > 1e-3f) errors++; } double useful = 3.0 * n * sizeof(float); // read x, read vx, write x printf("AoS %6.3f ms useful bandwidth %6.1f GB/s\n", ms[0], useful / ms[0] / 1e6); printf("SoA %6.3f ms useful bandwidth %6.1f GB/s\n", ms[1], useful / ms[1] / 1e6); printf("errors: %d\n%s\n", errors, errors == 0 ? "PASS" : "FAIL"); CUDA_CHECK(cudaFree(d_aos)); for (int f = 0; f < 8; f++) CUDA_CHECK(cudaFree(*fields[f])); free(h); free(tmp); free(back); return 0; }
"Useful bandwidth" counts only the bytes the computation needs. The SoA version gets close to the GPU's bandwidth; the AoS version loads whole 32-byte particles to use 8 bytes of each, and its useful bandwidth is several times lower (75 vs 418 GB/s on an RTX 3070). If a kernel uses all fields of each object, AoS is fine; the problem is reading data you don't use.
Other fixes worth knowing
constand__restrict__. Marking pointers asconst float *__restrict__ inpromises the compiler that they don't alias. It can then keep values in registers and use the read-only data path. It's free when the promise is true, and a source of wrong results when it isn't.- Vectorized access. Loading
float4instead offloatmoves 16 bytes per instruction and cuts the instruction count. It needs 16-byte aligned addresses. - Precision. Consumer GPUs run FP64 at 1/32 to 1/64 of the FP32 rate. A literal
1.0instead of1.0f, orsininstead ofsinf, silently promotes the whole expression to double.--use_fast_mathand intrinsics such as__expftrade accuracy for speed. - Thread coarsening. Giving each thread several elements amortizes index math and setup, as the grid-stride reduction in Chapter 5 showed.
- Fewer, bigger transfers. PCIe is an order of magnitude slower than device memory. Keep data on the GPU between kernels, and batch small copies.
Profiling
Two NVIDIA tools cover almost everything. Both come with the CUDA Toolkit. The older nvprof and Visual Profiler don't support GPUs of compute capability 8.0 and newer, so use these instead:
# Build with line info so results map to source lines (no runtime cost) nvcc -O3 -lineinfo transpose.cu -o transpose # Nsight Systems: timeline of the whole program (copies, kernels, CPU, gaps) nsys profile --stats=true ./transpose # Nsight Compute: detailed metrics per kernel ncu ./transpose # default sections for every kernel ncu --set full -k transposeNaive -o naive ./transpose # everything, one kernel, saved to naive.ncu-rep ncu-ui naive.ncu-rep # open the report in the GUI
In Nsight Compute, start with GPU Speed Of Light: it shows memory and compute throughput as a percentage of peak and says which one limits the kernel. The Memory Workload Analysis section shows sectors per request (more than 4 per warp request for 4-byte loads means uncoalesced access) and shared-memory bank conflicts. Warp State Statistics explains what warps are waiting for. Run the naive and padded transpose through ncu and compare those sections.
A checklist
Most kernel optimizations are one of these, roughly in order of how often they matter:
| Fix | Helps when | Covered in |
|---|---|---|
| Coalesce global accesses | memory-bound, profiler shows many sectors per request | this chapter |
| Keep data on the GPU, overlap copies | the timeline is dominated by copies | Chapters 3, 6 |
| Enough parallelism and occupancy | few blocks, or warps mostly waiting on memory | Chapter 4 |
| Tiling in shared memory | the same data is read many times | Chapter 3, Chapter 8 |
| Privatization | atomics contend on few addresses | Chapter 5 |
| Thread coarsening and register tiling | overhead per element, or compute-bound with reuse | Chapters 5, 8 |
| Avoid divergence, bank conflicts | the profiler reports them on a hot path | Chapter 4, this chapter |
| Use a better algorithm or a library | always worth checking first | cuBLAS, cuFFT, CUB, Thrust |
Summary
- Correct first, then measure, compare with the hardware limit, and fix what limits you.
- Arithmetic intensity tells you whether to watch GB/s (memory-bound) or FLOP/s (compute-bound).
- Consecutive threads should access consecutive addresses. Shared memory can reorder data to make that possible.
- Pad 2D shared tiles to avoid bank conflicts on column access.
- Lay out data so kernels read only the fields they use (SoA).
- Use
nsysfor the timeline andncufor kernel metrics.nvprofdoesn't support current GPUs.
Exercises
1. Arithmetic intensity. A kernel computes y[i] = a * x[i] * x[i] + b * x[i] + c for float arrays. Count FLOPs and bytes per element. Is it memory-bound on a T4?
Solution
About 4–5 FLOPs (3 multiplies and 2 adds, or 2 fused multiply-adds) per 8 bytes (read x, write y): roughly 0.6 FLOP/byte. That is far below the T4's ~25 FLOP/byte, so the kernel is memory-bound and should be judged by GB/s.
2. Where does the naive transpose lose? Run transpose.cu under ncu --section MemoryWorkloadAnalysis_Tables. Compare sectors per request for loads and stores between the naive and padded kernels.
Solution
The naive kernel's loads have 4 sectors per request (coalesced), but its stores have about 32: every thread of the warp writes to a different row. In the padded kernel both loads and stores are near 4, and the shared-memory section shows no bank conflicts. The unpadded tile kernel shows coalesced global access but many shared-memory conflicts.
3. Partial use. Change stepAoS to update all three positions from all three velocities. How does the gap between AoS and SoA change?
Solution
The gap shrinks. The kernel now uses 6 of the 8 fields of each particle, so most of the bytes AoS loads are useful. Layout matters most when kernels use few fields of large objects.
Check your understanding
A kernel reaches 85% of peak memory bandwidth. You make its arithmetic twice as fast. What happens?
Almost nothing. The kernel is limited by memory bandwidth, not arithmetic. Only reducing the bytes moved, or reusing data, can make it much faster.
Why does a [32][33] tile avoid bank conflicts when [32][32] has them?
Element (r, c) is in bank (r · width + c) mod 32. With width 32, every element of column c is in bank c. With width 33, element (r, c) is in bank (r + c) mod 32, so a column spans all 32 banks.
Further reading & credits
- An efficient matrix transpose in CUDA C/C++ (NVIDIA blog)
- Nsight Compute profiling guide
- Nsight Systems user guide
- GPU MODE lecture 8: CUDA performance checklist (Apache-2.0)
- OLCF CUDA Training Series, parts 4 and 8: memory and profiling
- NVIDIA CUDA C++ Programming Guide — the reference for every API and rule used here
- NVIDIA CUDA C++ Best Practices Guide
The chapter order and topic coverage of this course draw on the OLCF / NERSC CUDA Training Series, the NVIDIA Accelerated Computing Hub CUDA C++ tutorial, the GPU MODE lectures (Apache-2.0) and Simon Boehm's CUDA matrix multiplication worklog (code MIT). The text and example programs on this page are original and were tested on NVIDIA Turing and Ampere GPUs.
Next: putting all of this together on the most important kernel in computing. Continue to Case Study: Matrix Multiplication.
Practice These Concepts
Reinforce what you just learned with hands-on GPU coding challenges.
Write a kernel that sums all elements of an array using parallel reduction. The array size is 1024 elements. Use shared memory for efficiency.
Implement a simple 2D box blur filter for a 64x64 grayscale image. Each output pixel should be the average of itself and its 8 neighbors (3x3 kernel). Handle edge pixels by only averaging valid neighbors.
Sign in to track your progress across challenges.