CUDA Memory Management
Chapter 3 — Device memory, copies, and the GPU memory hierarchy
What you will learn
- The explicit allocate → copy → compute → copy back pattern, and what each step costs
- The memory spaces inside the GPU and when to use each
- Shared memory: loading data once per block and reusing it
- Constant, unified and pinned memory, and their trade-offs
Two separate memories
A discrete GPU has its own memory (VRAM), connected to the CPU over PCIe. A pointer from malloc points into host memory and cannot be dereferenced in a kernel. A pointer from cudaMalloc points into device memory and cannot be dereferenced on the CPU. Nothing in the pointer's type tells them apart, so a common convention is to prefix names with h_ and d_.
| Call | Does |
|---|---|
cudaMalloc(&d_p, bytes) | Allocate device memory. Contents are not initialized. |
cudaMemcpy(dst, src, bytes, kind) | Copy; kind is cudaMemcpyHostToDevice, DeviceToHost or DeviceToDevice. Waits for earlier GPU work in the same stream. |
cudaMemset(d_p, value, bytes) | Fill device memory byte by byte (handy for zeroing). |
cudaFree(d_p) | Release device memory. |
The program below does a vector addition the explicit way and times every phase. Run it and look at where the time goes. (CUDA events, used here for timing, are explained in Chapter 4.)
#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) __global__ void add(const float *a, const float *b, float *c, int n) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += blockDim.x * gridDim.x) c[i] = a[i] + b[i]; } int main() { const int n = 1 << 24; // 16M floats = 64 MB per array const size_t bytes = n * sizeof(float); float *h_a = (float *)malloc(bytes), *h_b = (float *)malloc(bytes), *h_c = (float *)malloc(bytes); for (int i = 0; i < n; i++) { h_a[i] = sinf(i); h_b[i] = cosf(i); } float *d_a, *d_b, *d_c; CUDA_CHECK(cudaMalloc(&d_a, bytes)); CUDA_CHECK(cudaMalloc(&d_b, bytes)); CUDA_CHECK(cudaMalloc(&d_c, bytes)); cudaEvent_t t0, t1, t2, t3; for (cudaEvent_t *e : {&t0, &t1, &t2, &t3}) CUDA_CHECK(cudaEventCreate(e)); // Warm-up: the first launch of a kernel also pays one-time setup (loading the // GPU code into the context). Never include it in a timing. add<<<1, 1>>>(d_a, d_b, d_c, 0); CUDA_CHECK(cudaDeviceSynchronize()); CUDA_CHECK(cudaEventRecord(t0)); CUDA_CHECK(cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaMemcpy(d_b, h_b, bytes, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaEventRecord(t1)); add<<<1024, 256>>>(d_a, d_b, d_c, n); CUDA_CHECK(cudaGetLastError()); CUDA_CHECK(cudaEventRecord(t2)); CUDA_CHECK(cudaMemcpy(h_c, d_c, bytes, cudaMemcpyDeviceToHost)); CUDA_CHECK(cudaEventRecord(t3)); CUDA_CHECK(cudaEventSynchronize(t3)); float in_ms, k_ms, out_ms; CUDA_CHECK(cudaEventElapsedTime(&in_ms, t0, t1)); CUDA_CHECK(cudaEventElapsedTime(&k_ms, t1, t2)); CUDA_CHECK(cudaEventElapsedTime(&out_ms, t2, t3)); printf("copy in : %7.2f ms (128 MB)\n", in_ms); printf("kernel : %7.2f ms (reads 128 MB, writes 64 MB on the GPU)\n", k_ms); printf("copy out: %7.2f ms (64 MB)\n", out_ms); int errors = 0; for (int i = 0; i < n; i++) if (fabsf(h_c[i] - (h_a[i] + h_b[i])) > 1e-6f) errors++; printf(errors == 0 ? "PASS\n" : "FAIL\n"); CUDA_CHECK(cudaFree(d_a)); CUDA_CHECK(cudaFree(d_b)); CUDA_CHECK(cudaFree(d_c)); free(h_a); free(h_b); free(h_c); return 0; }
On typical hardware the copies take many times longer than the kernel. The kernel moves its data at the GPU's memory bandwidth (hundreds of GB/s); the copies are limited by PCIe (around 10–25 GB/s in practice). That is the lesson behind "keep data on the GPU": a real application would copy a and b once and then run many kernels on them.
The memory hierarchy inside the GPU
Device memory is only one of several places data can live. The closer to the arithmetic units, the faster and smaller it is:
| Space | Declared as | Visible to | Typical size | Use it for |
|---|---|---|---|---|
| Registers | ordinary local variables | one thread | up to 255 per thread; 64K 32-bit registers per SM | everything hot |
| Local | (compiler decides) | one thread | lives in device memory | spilled registers, large per-thread arrays — avoid in hot loops |
| Shared | __shared__ | one block | 48 KB per block by default, more on request on recent GPUs | data reused by several threads of a block |
| Global | cudaMalloc, __device__ | all threads + host via copies | whole VRAM | inputs and outputs |
| Constant | __constant__ | all threads, read-only | 64 KB | small values every thread reads at the same time |
Exact latencies depend on the GPU, but the order is stable: registers are fastest, shared memory and L1 hits take tens of cycles, and a load that misses all the way to device memory takes several hundred. Most of performance tuning is about turning device-memory accesses into register and shared-memory accesses.
Shared memory: load once, reuse many times
Shared memory pays off when several threads of a block need the same input. A 1D stencil is a good first example: each output is the sum of the input element and its RADIUS neighbors on each side. With RADIUS = 3, every input value is read by 7 different threads.
Instead of each thread making 7 global loads, the block loads its slice of the input into shared memory once, plus a halo of RADIUS extra elements on each side, then every thread reads its 7 values from shared memory.
Two things make it correct. First, a thread that falls past the end of the array still writes a zero into its tile slot, so nothing reads uninitialized shared memory. Second, __syncthreads() is a barrier: no thread continues until every thread of the block has reached it, so all loads are finished before anyone reads a neighbor's slot. Every thread must reach the barrier, which is why the kernel never returns early. Chapter 5 covers barriers in depth.
#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) #define RADIUS 3 #define BLOCK 256 // Version 1: every thread reads its 7 inputs straight from global memory. __global__ void stencilGlobal(const float *in, float *out, int n) { int g = blockIdx.x * blockDim.x + threadIdx.x; if (g >= n) return; float sum = 0.0f; for (int k = -RADIUS; k <= RADIUS; k++) { int j = g + k; if (j >= 0 && j < n) sum += in[j]; } out[g] = sum; } // Version 2: the block stages its inputs (plus halo) in shared memory. __global__ void stencilShared(const float *in, float *out, int n) { __shared__ float tile[BLOCK + 2 * RADIUS]; int g = blockIdx.x * blockDim.x + threadIdx.x; // global index int l = threadIdx.x + RADIUS; // index inside the tile tile[l] = (g < n) ? in[g] : 0.0f; // every slot gets a value if (threadIdx.x < RADIUS) { // first RADIUS threads load the halos int left = g - RADIUS, right = g + BLOCK; tile[l - RADIUS] = (left >= 0 && left < n) ? in[left] : 0.0f; tile[l + BLOCK] = (right < n) ? in[right] : 0.0f; } __syncthreads(); // all loads done before any reads if (g < n) { float sum = 0.0f; for (int k = -RADIUS; k <= RADIUS; k++) sum += tile[l + k]; out[g] = sum; } } int main() { const int n = (1 << 22) + 5; // not a multiple of BLOCK const size_t bytes = n * sizeof(float); float *h_in = (float *)malloc(bytes), *h_out = (float *)malloc(bytes); for (int i = 0; i < n; i++) h_in[i] = (i % 17) * 0.25f; float *d_in, *d_out; CUDA_CHECK(cudaMalloc(&d_in, bytes)); CUDA_CHECK(cudaMalloc(&d_out, bytes)); CUDA_CHECK(cudaMemcpy(d_in, h_in, bytes, cudaMemcpyHostToDevice)); int blocks = (n + BLOCK - 1) / BLOCK; cudaEvent_t a, b; CUDA_CHECK(cudaEventCreate(&a)); CUDA_CHECK(cudaEventCreate(&b)); bool ok = true; for (int version = 1; version <= 2; version++) { CUDA_CHECK(cudaMemset(d_out, 0, bytes)); if (version == 1) stencilGlobal<<<blocks, BLOCK>>>(d_in, d_out, n); // warm-up else stencilShared<<<blocks, BLOCK>>>(d_in, d_out, n); CUDA_CHECK(cudaEventRecord(a)); for (int r = 0; r < 10; r++) { if (version == 1) stencilGlobal<<<blocks, BLOCK>>>(d_in, d_out, n); else stencilShared<<<blocks, BLOCK>>>(d_in, d_out, n); } CUDA_CHECK(cudaEventRecord(b)); CUDA_CHECK(cudaEventSynchronize(b)); float ms; CUDA_CHECK(cudaEventElapsedTime(&ms, a, b)); CUDA_CHECK(cudaMemcpy(h_out, d_out, bytes, cudaMemcpyDeviceToHost)); int errors = 0; for (int i = 0; i < n; i++) { float ref = 0.0f; for (int k = -RADIUS; k <= RADIUS; k++) if (i + k >= 0 && i + k < n) ref += h_in[i + k]; if (fabsf(h_out[i] - ref) > 1e-4f) errors++; } printf("%s: %.3f ms per launch, errors: %d\n", version == 1 ? "global loads" : "shared tile ", ms / 10, errors); ok = ok && errors == 0; } printf(ok ? "PASS\n" : "FAIL\n"); CUDA_CHECK(cudaFree(d_in)); CUDA_CHECK(cudaFree(d_out)); free(h_in); free(h_out); return 0; }
Modern GPUs cache global loads in L1, so the 7 overlapping reads of the global version often hit the cache. With a reuse factor of 7, shared memory wins by a modest margin or not at all. The payoff grows with reuse: in matrix multiplication (Chapter 8) each loaded value is used dozens of times, and shared memory makes the kernel several times faster. Measure, don't assume.
Sizing shared memory at launch time
__shared__ float tile[BLOCK + 2 * RADIUS] fixes the size at compile time. If the size depends on a runtime value, declare an unsized extern array and pass the byte count as the third launch parameter:
__global__ void kernel(const float *in, float *out, int n) { extern __shared__ float tile[]; // size set by the launch // ... } size_t smem = (threads + 2 * RADIUS) * sizeof(float); kernel<<<blocks, threads, smem>>>(d_in, d_out, n);
Constant memory: one value for the whole warp
__constant__ variables live in device memory but are read through a dedicated constant cache. That cache is designed for one pattern: every thread of a warp reads the same address. Then a single read is broadcast to all 32 threads. If threads of a warp read different addresses, the reads are serialized, and an ordinary global load would be faster.
Polynomial coefficients are the textbook fit. Every thread evaluates the same polynomial at a different x, so at each step of the loop all threads read the same coefficient. You fill constant memory from the host with cudaMemcpyToSymbol.
#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) #define DEGREE 8 __constant__ float c_coef[DEGREE + 1]; // same for every thread: ideal for constant memory __host__ __device__ float horner(const float *coef, float x) { float r = coef[DEGREE]; for (int k = DEGREE - 1; k >= 0; k--) r = r * x + coef[k]; // at step k, all threads read coef[k]: one broadcast return r; } __global__ void evalPoly(const float *x, float *y, int n) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += blockDim.x * gridDim.x) y[i] = horner(c_coef, x[i]); } int main() { float h_coef[DEGREE + 1]; for (int k = 0; k <= DEGREE; k++) h_coef[k] = 1.0f / (k + 1); CUDA_CHECK(cudaMemcpyToSymbol(c_coef, h_coef, sizeof(h_coef))); const int n = 1 << 20; const size_t bytes = n * sizeof(float); float *h_x = (float *)malloc(bytes), *h_y = (float *)malloc(bytes); for (int i = 0; i < n; i++) h_x[i] = -1.0f + 2.0f * i / (n - 1); // x in [-1, 1] float *d_x, *d_y; CUDA_CHECK(cudaMalloc(&d_x, bytes)); CUDA_CHECK(cudaMalloc(&d_y, bytes)); CUDA_CHECK(cudaMemcpy(d_x, h_x, bytes, cudaMemcpyHostToDevice)); evalPoly<<<256, 256>>>(d_x, d_y, n); CUDA_CHECK(cudaGetLastError()); CUDA_CHECK(cudaMemcpy(h_y, d_y, bytes, cudaMemcpyDeviceToHost)); int errors = 0; for (int i = 0; i < n; i++) { float ref = horner(h_coef, h_x[i]); if (fabsf(h_y[i] - ref) > 1e-5f * fmaxf(1.0f, fabsf(ref))) errors++; } printf("p(-1) = %.6f, p(0) = %.6f, p(1) = %.6f\n", h_y[0], h_y[n / 2], h_y[n - 1]); printf(errors == 0 ? "PASS\n" : "FAIL\n"); CUDA_CHECK(cudaFree(d_x)); CUDA_CHECK(cudaFree(d_y)); free(h_x); free(h_y); return 0; }
Unified memory
cudaMallocManaged returns one pointer that works on both CPU and GPU. The driver moves pages to whichever processor touches them. It is the fastest way to get a correct program, and Chapters 1 and 2 used it for that reason.
The cost is that migration happens on demand, page by page, while your kernel runs. The first kernel to touch freshly initialized data can be much slower than the same kernel on data already in device memory. You can move the data ahead of time with a prefetch. The function's signature changed in CUDA 13:
int device; cudaGetDevice(&device); #if CUDART_VERSION >= 13000 cudaMemLocation loc = {}; loc.type = cudaMemLocationTypeDevice; loc.id = device; cudaMemPrefetchAsync(data, bytes, loc, 0 /* flags */, 0 /* stream */); #else cudaMemPrefetchAsync(data, bytes, device, 0 /* stream */); #endif kernel<<<blocks, threads>>>(data, n); // data is already resident on the GPU
On Linux with a modern GPU, pages migrate on demand and the CPU and GPU can even touch managed memory at the same time. On Windows, managed memory is migrated as a whole when a kernel is launched, and the CPU must not touch it until the GPU work is finished. Always synchronize before the CPU reads managed data.
Pinned host memory
The GPU copies host memory with DMA, and DMA needs memory the operating system promises not to move or swap out. Ordinary malloc memory is pageable, so the driver first copies it into an internal pinned buffer, then transfers that: two copies instead of one. Allocating with cudaMallocHost gives you pinned (page-locked) memory that the GPU can read directly.
Pinned memory is also required for cudaMemcpyAsync to overlap with kernels (Chapter 6). Don't pin everything, though: pinned pages are taken away from the OS, and allocating them is slow. Pin the buffers you transfer often and reuse them.
#include <cstdio> #include <cstdlib> #include <cstring> #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) // Average host-to-device bandwidth in GB/s over 'reps' copies. float h2dBandwidth(float *d, const float *h, size_t bytes, int reps) { cudaEvent_t a, b; CUDA_CHECK(cudaEventCreate(&a)); CUDA_CHECK(cudaEventCreate(&b)); CUDA_CHECK(cudaMemcpy(d, h, bytes, cudaMemcpyHostToDevice)); // warm-up CUDA_CHECK(cudaEventRecord(a)); for (int r = 0; r < reps; r++) CUDA_CHECK(cudaMemcpy(d, h, bytes, cudaMemcpyHostToDevice)); CUDA_CHECK(cudaEventRecord(b)); CUDA_CHECK(cudaEventSynchronize(b)); float ms; CUDA_CHECK(cudaEventElapsedTime(&ms, a, b)); CUDA_CHECK(cudaEventDestroy(a)); CUDA_CHECK(cudaEventDestroy(b)); return (bytes * (double)reps / 1e9) / (ms / 1e3); } int main() { const size_t n = 1 << 24, bytes = n * sizeof(float); // 64 MB float *pageable = (float *)malloc(bytes); float *pinned; CUDA_CHECK(cudaMallocHost(&pinned, bytes)); for (size_t i = 0; i < n; i++) pageable[i] = pinned[i] = (float)i; float *d; CUDA_CHECK(cudaMalloc(&d, bytes)); printf("pageable: %5.1f GB/s\n", h2dBandwidth(d, pageable, bytes, 5)); printf("pinned : %5.1f GB/s\n", h2dBandwidth(d, pinned, bytes, 5)); // Correctness: copy back into a cleared buffer and compare. memset(pageable, 0, bytes); CUDA_CHECK(cudaMemcpy(pageable, d, bytes, cudaMemcpyDeviceToHost)); printf(memcmp(pageable, pinned, bytes) == 0 ? "PASS\n" : "FAIL\n"); CUDA_CHECK(cudaFree(d)); CUDA_CHECK(cudaFreeHost(pinned)); free(pageable); return 0; }
The ratio you see depends on the machine: the PCIe generation, the CPU's memory speed and the OS. On some systems the gap is large, on others small. Measuring it on your own hardware is the point of the program.
Summary
- Host and device memory are separate. Explicit code allocates with
cudaMalloc, copies withcudaMemcpyand frees withcudaFree. - PCIe copies are much slower than device memory. Copy once and keep data on the GPU.
- Registers are fastest, then shared memory and L1, then L2, then device memory.
- Shared memory is per block. Use it when threads of a block reuse each other's data. Every slot must be written before it is read, with a
__syncthreads()in between. - Constant memory suits small data that a whole warp reads at the same address.
- Unified memory is convenient. Prefetch it when performance matters.
- Pinned host memory speeds up transfers and is required for async copies.
Exercises
1. Bigger radius. Change RADIUS in stencil_1d.cu to 16, then 64. How do the two timings change, and why?
Solution
Both versions slow down because each output now sums 33 or 129 values. The gap between them is smaller than you might expect. On an Ampere laptop GPU we measured: radius 16, shared about 10% slower; radius 64, shared about 15% faster. The global version's repeated loads mostly hit the L1 cache, and the shared version pays for its extra halo loads and the barrier.
The lesson: the hardware cache already captures simple, regular reuse. Shared memory earns its keep when reuse is high and you control exactly what stays on chip, as in the tiled matrix multiply of Chapter 8. Also note that RADIUS must stay ≤ BLOCK, because the first RADIUS threads load the halos.
2. Reverse a block. Write a kernel that reverses each block's 256-element chunk of an array in place using shared memory. Make it correct when n is not a multiple of 256.
Solution
__global__ void reverseChunks(float *data, int n) { __shared__ float tile[256]; int base = blockIdx.x * blockDim.x; int count = min(blockDim.x, n - base); // elements in this chunk (last may be short) int t = threadIdx.x; if (t < count) tile[t] = data[base + t]; __syncthreads(); // reached by every thread if (t < count) data[base + t] = tile[count - 1 - t]; }
The key is reversing within count, not blockDim.x. Otherwise the last, shorter chunk reads slots nobody wrote.
3. Constant memory done wrong. Change evalPoly so each thread uses c_coef[i % (DEGREE + 1)] as a scale factor. Would this access pattern suit constant memory?
Solution
No. Neighboring threads now read different addresses, so the constant cache serializes up to 9 reads per warp. A normal global array (read through L1) handles this pattern better.
Check your understanding
Does cudaMalloc zero the memory it returns?
No. Device memory from cudaMalloc holds whatever was there before. Use cudaMemset or write every element before reading.
Thread 5 writes tile[5] and thread 40 reads it right after, with no barrier. What can go wrong?
Thread 40 may run before thread 5 has written, and read a stale value. A __syncthreads() between the write and the read prevents this race.
Further reading & credits
- Using Shared Memory in CUDA C/C++ (NVIDIA blog)
- How to Optimize Data Transfers in CUDA C/C++ (NVIDIA blog)
- Programming Guide: unified memory
- 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: what actually happens on the hardware when your kernel runs. Continue to The Execution Model.
Practice These Concepts
Reinforce what you just learned with hands-on GPU coding challenges.
Use CUDA constant memory to store a sine lookup table. Compute sin(x) for 1024 values using the lookup table instead of calling sin() directly. This demonstrates constant memory caching for read-only data accessed by all threads.
Sign in to track your progress across challenges.