CUDA memory: shared, global, constant and texture
Clear, exam-focused notes on CUDA memory spaces: global, shared, constant and texture memory — what they are, how they behave, and how to use them in code.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
GPUs have several distinct memory spaces with different latency, scope and caching. An engineer uses the right space (global, shared, constant, texture) to get correct results and to improve performance by reducing memory latency and global-memory traffic.
Key ideas
Start from first principles: a GPU executes many threads in parallel. Memory access cost often limits performance, so CUDA provides different memory spaces with different trade-offs.
Global memory — the device DRAM visible to all threads; the host accesses it via CUDA APIs (e.g., cudaMemcpy/Unified Memory), not by directly dereferencing device pointers. It has high capacity (GBs) but high latency and depends on memory coalescing for high throughput. Use global memory for large arrays shared across the GPU.
Shared memory — on-chip memory private to a thread-block (all threads in the block can access it). It is low-latency compared to global memory and used to share data between threads in the same block and to implement tiling. Shared memory size is limited per Streaming Multiprocessor (SM); kernels and optimisations use it for blocking (tiling) to reduce global-memory accesses.
Definition: shared memory is declared with the keyword
__shared__and has block scope and lifetime equal to the block.Important property: banked access. Shared memory is partitioned into banks. If multiple threads in a warp access the same bank but different addresses, a bank conflict occurs and accesses are serialized (slow). If all threads access the same address, many architectures support broadcast (fast). To reason about bank conflicts draw a table: columns = thread lane index (0..31), rows = bank number (0..31), map address -> bank = (address / wordSize) mod numBanks; label conflicting accesses.
Constant memory — read-only memory for kernels. Declared with
__constant__. Data is cached on-chip. Best when many threads read the same address (broadcast to whole warp) because the constant cache supplies a single value to all threads efficiently. Use constant memory for small read-only parameters and lookup tables.Definition: constant memory is read-only device memory declared with
__constant__, visible to device code and typically written from host withcudaMemcpyToSymbol. Size limit: user-accessible constant memory is 64 KB (per module), cached on-chip; use it for small tables and scalars.Texture memory — read-only memory accessed via special texture fetches. Texture caching is optimized for spatial locality and supports special addressing modes (wrap, clamp) and optional filtering (useful for images). Modern CUDA supports texture objects (recommended) and linear-texture resources for arrays in device memory. Use textures for irregular read-only access patterns that have 2D locality or need interpolation.
Definition: texture memory is a read-only access path with dedicated cache(s) and a fetch API (texture objects or texture references). Texture memory provides cached reads and coordinate addressing.
Caching and locality rules (exact statements to learn):
- Global memory accesses are fastest when, within a warp, threads access consecutive, properly aligned addresses so their requests fall into as few 32/64/128-byte segments as possible (depending on bytes per thread access: 1/2/4/8/16). This is called memory coalescing.
- Shared memory is fastest when accesses avoid bank conflicts (map threads to different banks or use broadcast when reading the same address).
- Constant memory gives warp-wide broadcasts when all threads read the same address; otherwise, reads may cause different cache lines to be fetched, and accesses with multiple distinct addresses within a warp are serialized.
- Texture memory caches data with spatial locality; two nearby threads reading nearby addresses will likely hit the texture cache.
What to draw for exams:
- Draw a simple block diagram: CPU and PCIe connection to GPU; GPU DRAM labelled Global Memory; multiple SMs each with on-chip Shared Memory and Registers; a small Constant Cache and Texture Cache attached to SMs. Label arrows showing that global memory goes through a large DRAM controller and higher latency than shared memory.
Assumptions behind common derivations:
- Warp = 32 threads (on most NVIDIA GPUs); an SM executes warps in SIMD-like fashion.
- Shared memory is sized per SM and shared among resident thread-blocks; choosing block size and shared memory per block affects occupancy.
Formulas
For a programming topic the key syntax lines to remember:
__global__ void kernelName(args) — declare a kernel launched from host.
__device__ — device-only function or variable.
__host__ — host function.
__shared__ type name[size] — declare shared memory array with block scope.
__constant__ type name[size] — declare constant memory symbol.
cudaMalloc(&dptr, bytes) — allocate device (global) memory.
cudaMemcpy(dst, src, bytes, cudaMemcpyHostToDevice) — copy between host and device.
cudaMemcpyToSymbol(symbol, hostPtr, bytes) — copy host data into a __constant__ symbol.
Texture-object creation (summary):
cudaResourceDesc resDesc = {}; resDesc.resType = cudaResourceTypeLinear; resDesc.res.linear.devPtr = dptr; resDesc.res.linear.sizeInBytes = n*sizeof(float); resDesc.res.linear.desc = cudaCreateChannelDesc<float>();
cudaTextureDesc texDesc = {}; cudaCreateTextureObject(&texObj, &resDesc, &texDesc, NULL);
In device code: val = tex1Dfetch<float>(texObj, index); to read from a linear texture object.
Note: API details vary; check CUDA reference for exact prototypes.
Worked examples
Example 1 — sum of an array using shared memory per-block reduction (complete CUDA C++ program). This simple tree reduction assumes blockDim.x is a power of two; for other sizes add bounds checks inside the loop.
// reduction_shared.cu
#include <stdio.h>
#include <cuda_runtime.h>
__global__ void blockReduceSum(const float *in, float *out, int n) {
extern __shared__ float sdata[]; // size supplied at launch
unsigned int tid = threadIdx.x;
unsigned int idx = blockIdx.x * blockDim.x + tid;
// load element or 0
sdata[tid] = (idx < n) ? in[idx] : 0.0f;
__syncthreads();
// reduce in shared memory (binary tree)
for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
if (tid < s) sdata[tid] += sdata[tid + s];
__syncthreads();
}
// write block result
if (tid == 0) out[blockIdx.x] = sdata[0];
}
int main() {
const int n = 8;
float h_in[n];
for (int i = 0; i < n; ++i) h_in[i] = float(i+1); // 1,2,...,8
float *d_in, *d_partial;
int blockSize = 4; // small for demo
int gridSize = (n + blockSize - 1) / blockSize;
cudaMalloc(&d_in, n * sizeof(float));
cudaMalloc(&d_partial, gridSize * sizeof(float));
cudaMemcpy(d_in, h_in, n * sizeof(float), cudaMemcpyHostToDevice);
blockReduceSum<<<gridSize, blockSize, blockSize * sizeof(float)>>>(d_in, d_partial, n);
float h_partial[2];
cudaMemcpy(h_partial, d_partial, gridSize * sizeof(float), cudaMemcpyDeviceToHost);
float total = 0.0f;
for (int i = 0; i < gridSize; ++i) total += h_partial[i];
printf("Sum = %.1f\n", total);
cudaFree(d_in); cudaFree(d_partial);
return 0;
}
Sample input: none (program initializes array 1..8).
Exact output:
Sum = 36.0
Example 2 — using constant memory together with a texture object (read-only) to add a constant to every element in device array (complete CUDA C++ program).
// const_texture_example.cu
#include <stdio.h>
#include <cuda_runtime.h>
__constant__ float d_add; // constant symbol
__global__ void addConstViaTexture(cudaTextureObject_t texObj, float *out, int n) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) {
float v = tex1Dfetch<float>(texObj, idx); // read via texture
out[idx] = v + d_add; // add constant from constant memory
}
}
int main() {
const int n = 8;
float h_in[n];
for (int i = 0; i < n; ++i) h_in[i] = float(i);
float *d_in, *d_out;
cudaMalloc(&d_in, n * sizeof(float));
cudaMalloc(&d_out, n * sizeof(float));
cudaMemcpy(d_in, h_in, n * sizeof(float), cudaMemcpyHostToDevice);
// copy host scalar into constant memory
float h_add = 10.0f;
cudaMemcpyToSymbol(d_add, &h_add, sizeof(float));
// create texture object for linear device memory
cudaResourceDesc resDesc = {};
resDesc.resType = cudaResourceTypeLinear;
resDesc.res.linear.devPtr = d_in;
resDesc.res.linear.desc = cudaCreateChannelDesc<float>();
resDesc.res.linear.sizeInBytes = n * sizeof(float);
cudaTextureDesc texDesc = {};
texDesc.addressMode[0] = cudaAddressModeClamp;
texDesc.filterMode = cudaFilterModePoint;
texDesc.readMode = cudaReadModeElementType;
cudaTextureObject_t texObj = 0;
cudaCreateTextureObject(&texObj, &resDesc, &texDesc, NULL);
int blockSize = 4;
int gridSize = (n + blockSize - 1) / blockSize;
addConstViaTexture<<<gridSize, blockSize>>>(texObj, d_out, n);
float h_out[n];
cudaMemcpy(h_out, d_out, n * sizeof(float), cudaMemcpyDeviceToHost);
for (int i = 0; i < n; ++i) printf("out[%d] = %.1f\n", i, h_out[i]);
cudaDestroyTextureObject(texObj);
cudaFree(d_in); cudaFree(d_out);
return 0;
}
Sample input: none (program initializes array 0..7 and constant 10.0).
Exact output:
out[0] = 10.0 out[1] = 11.0 out[2] = 12.0 out[3] = 13.0 out[4] = 14.0 out[5] = 15.0 out[6] = 16.0 out[7] = 17.0
Notes: the texture example uses a linear resource (device linear memory) and tex1Dfetch on the texture object. API details (channel descriptor creation) depend on CUDA version.
Common mistakes
- Thinking texture memory is always faster — it helps when access has spatial locality or benefits from texture cache, but not for random, uncorrelated reads.
- Forgetting to set extern shared memory size at kernel launch when using
extern __shared__. - Not coalescing global memory accesses (consecutive thread accesses spaced wrongly) — this kills throughput.
- Not destroying texture objects or forgetting to use the correct resource descriptor.
For your exam
Types of questions:
- Definitions and differences between memory spaces (short notes).
- Draw and label memory hierarchy diagram and explain flows (diagram question).
- Small code fragment: predict output, or show how to declare constant/shared memory (programming question).
- Derivation/analysis: show how to compute number of global memory transactions for a warp given access pattern (derivation).
- Optimisation question: explain how to transform naive kernel to use shared memory tiling for reduced global traffic.
What a full-marks answer includes:
- Correct definitions (scope, lifetime, caching behavior) for each memory type.
- A clear diagram if asked, with labels: SM, shared memory, registers, global memory, constant/texture caches.
- Correct syntax for declarations and copies (e.g.,
__shared__,__constant__,cudaMemcpyToSymbol). - Correct explanation of coalescing and bank conflicts with short examples of patterns that cause conflicts.
Quick check
- Which memory space should you use for a small read-only lookup table accessed by many threads?
- What keyword declares shared memory in device code?
- Give one reason to use a texture object instead of plain global memory reads.
Answers: 1) Constant memory. 2) shared. 3) Texture provides a specialized cache optimized for spatial locality and can offer higher hit-rate for 2D data and filtering/coordinate modes.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?