GPU by Example
6 / 16

The memory model

9 min readChapter 6 of 16

A kernel's performance is usually decided by where its data lives, not by how clever its arithmetic is. CUDA gives you five kinds of memory with different scopes, lifetimes, and speeds. This chapter is the map.

The five spaces#

MemoryScopeLifetimePhysicallyTypical latency
RegistersOne threadKernelSM register file~1 cycle
SharedOne blockKernelSM (L1/shared store)~20–30 cycles
LocalOne threadKernelDevice DRAM (cached)~400+ cycles
GlobalAll threads, all blocksUntil freedDevice DRAM~400–800 cycles
ConstantAll threads, all blocksApplicationDevice DRAM + constant cache~1–10 cached

Two axes are doing the work here: scope (who can see it) and lifetime (how long it exists). A register is private and dies with the thread. Global memory is shared by every thread in the grid and survives until you free it.

GPU SM REGISTERS per thread SHARED + L1 per block FUNCTIONAL UNITS FP32 · INT · LD/ST · SFU WARP SCHEDULERS L2 CACHE shared by SMs GLOBAL MEMORY DRAM · 24–80 GB ~200 cyc ~500 cyc
Registers and shared memory are on the SM. Global memory is off-chip, behind L2. Local memory looks private but lives in DRAM.

Global memory#

Global memory is the GPU's DRAM: the 24 GB on your graphics card. It is allocated by the host (cudaMalloc, cudaMallocManaged) and is visible to every thread in every block for as long as the allocation lives.

global.cuCUDA C++
__global__ void addOne(float* data, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) data[i] += 1.0f;
}

Three properties you will rely on:

  • Persistent. Data written by one kernel is still there for the next kernel, until cudaFree.
  • Grid-wide. Any block can read any address. That is why cross-block races exist.
  • Slow. Hundreds of cycles, but enormous bandwidth when accesses are coalesced. The performance chapter is mostly about keeping this memory system busy.

A kernel returns void; writing to global memory is the only way it can return results to the host.

Shared memory#

Shared memory is a per-block scratchpad on the SM. It is small (tens of KB, configurable) and fast (tens of cycles). Every thread in the block sees the same array.

shared.cuCUDA C++
__global__ void example(const float* in, float* out) {
    __shared__ float tile[256];          // static: size known at compile time

    tile[threadIdx.x] = in[blockIdx.x * blockDim.x + threadIdx.x];
    __syncthreads();                     // wait for every thread's write

    if (threadIdx.x == 0) {
        float sum = 0.0f;
        for (int i = 0; i < blockDim.x; ++i) sum += tile[i];
        out[blockIdx.x] = sum;
    }
}

The declaration allocates 256 × 4 = 1 KB per block, not per thread. If the SM can host eight blocks, it holds eight copies, one per block.

Dynamic size, when you only know the amount at launch time:

CUDA C++
extern __shared__ float tile[];          // size comes from the launch

kernel<<<grid, block, 4096>>>(in, out);  // 4096 bytes of shared memory per block

Only one dynamic array per kernel is allowed; if you need several, allocate one buffer and partition it manually with correct alignment.

Shared memory is the subject of Chapter 8, including bank conflicts and tiled matrix multiplication. For now: it is fast, it is per-block, and it needs __syncthreads() between writing and reading.

Registers#

Registers are where your variables actually live. The compiler allocates them per thread; you do not address them directly. A kernel using 40 registers with 256 threads per block consumes 40 × 256 = 10,240 registers, and the SM has 65,536 — so registers alone allow six such blocks.

Too many registers per thread reduces occupancy. Too few, and values spill to local memory. You can influence the trade-off:

CUDA C++
__global__ void __launch_bounds__(256, 4) kernel(...) {
    // compiler targets 256 threads/block and at least 4 blocks/SM
}
TerminalShell
$ nvcc -Xptxas -v kernel.cu
ptxas info: Used 32 registers, 1024 bytes smem, 380 bytes cmem[0]

-maxrregcount=32 caps registers globally; __launch_bounds__ does it per kernel. Both can cause spills if pushed too far.

Local memory: the spill zone#

Local memory holds thread-private variables that cannot live in registers. The compiler uses it for:

  • arrays indexed with a value it cannot determine at compile time,
  • large structures or arrays,
  • any value that does not fit when registers run out.
local.cuCUDA C++
__global__ void bad(float* out, int n) {
    float tmp[8];
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i >= n) return;

    for (int k = 0; k < 8; ++k) tmp[k] = 0.0f;
    tmp[i % 8] = 1.0f;        // dynamic index -> tmp lives in local memory
    out[i] = tmp[3];
}

Even though tmp is declared inside the kernel, i % 8 is not a compile-time constant, so the array is placed in local memory (DRAM). Each thread's array is laid out so that consecutive threads access consecutive words — accesses are coalesced — but the latency is global-memory latency.

If a small array must stay in registers, index it with compile-time constants or unroll the loop so every index is known.

Constant memory#

Constant memory is read-only to kernels, writable from the host, and cached in a small dedicated cache per SM. It is ideal for coefficients, filter weights, and configuration values that every thread reads identically.

constant.cuCUDA C++
#include <cstdio>
#include <cuda_runtime.h>

__constant__ float coeffs[4];        // 16 bytes, visible to all threads

__global__ void poly(float* out, const float* x, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        float v = x[i];
        out[i] = ((coeffs[0] * v + coeffs[1]) * v + coeffs[2]) * v + coeffs[3];
    }
}

int main() {
    const int n = 8;
    float h_coeffs[4] = {1.0f, -2.0f, 3.0f, 4.0f};
    cudaMemcpyToSymbol(coeffs, h_coeffs, sizeof(h_coeffs));

    float *x, *y;
    cudaMallocManaged(&x, n * sizeof(float));
    cudaMallocManaged(&y, n * sizeof(float));
    for (int i = 0; i < n; ++i) x[i] = (float)i;

    poly<<<1, n>>>(y, x, n);
    cudaDeviceSynchronize();

    for (int i = 0; i < n; ++i) {
        printf("x=%d  y=%d\n", i, (int)y[i]);
    }
    cudaFree(x); cudaFree(y);
    return 0;
}
Outputreference run
x=0  y=4
x=1  y=6
x=2  y=10
x=3  y=22
x=4  y=48
x=5  y=94
x=6  y=166
x=7  y=270

cudaMemcpyToSymbol copies from host memory into the __constant__ variable. Kernels never write it. A __constant__ variable has a distinct instance per device and lives for the life of the application.

Unified memory, in one paragraph#

Normally a pointer is valid only on the processor whose memory it points to. Unified memory (cudaMallocManaged) creates an allocation with one virtual address that is valid on both CPU and GPU. The driver migrates pages on demand; you can read data[i] on the host and in a kernel without an explicit copy.

It is convenient and correct, but migration is not free. Chapter 7 shows the explicit path, when to prefer it, and how to prefetch.

What lives where: a checklist#

  • Values used by one thread, small and fixed → registers.
  • Values shared by threads in a block → shared memory (plus __syncthreads).
  • Values shared by the whole grid, or larger than on-chip memory → global memory.
  • Read-only values every thread reads identically → constant memory.
  • Anything you did not explicitly place → decided by the compiler; check -Xptxas -v.

Exercises#

  • Compile local.cu with -Xptxas -v and look for local memory in the output. Replace i % 8 with 3 and recompile. What changed?
  • How many bytes of shared memory does a block of 512 threads use if it declares __shared__ float tile[512]? How much for the whole SM with four resident blocks?
  • Load the polynomial coefficients into shared memory instead of constant memory. Which is faster, and why might it not matter at this size?
  • cudaMemcpyToSymbol takes the symbol, not a pointer. What happens if you pass &coeffs?
  • Explain why a kernel cannot return a value with return x; and must write to global memory instead.