CUDA Shared Memory

Parallel Algorithms

David Mayerich

Scalable Tissue Imaging and Modeling (STIM) Laboratory

Department of Electrical and Computer Engineering

Cullen College of Engineering

University of Houston

David Mayerich

STIM Laboratory, University of Houston

Thread Communication

  • Communication requires synchronization in device functions:
                                                  __syncthreads()

    • synchronize all threads in a block to this point

    • execution continues when all threads reach __syncthreads()

David Mayerich

STIM Laboratory, University of Houston

__global__ void sumNeighbors(int* globalPtr) {
  int i = threadIdx.x;			// put the thread index into a register
  // ...						// execute code on the device
  __syncthreads();				// synchronize all threads in the block
  // ...						// resume computation
}

Synchronization Costs

  • All threads in a warp will hit the __syncthreads() barrier at the same time

  • __syncthreads() is assumed to be lightweight w/ very little overhead

  • What efficiency costs would you expect?

    • no divergence: execution of all threads in a warp reach the barrier at the same time

    • all warps in the block are executed until they reach the barrier

    • occupancy can reduce within an SM if only one block is assigned

David Mayerich

STIM Laboratory, University of Houston

Finite Difference Stencils

  • Calculate the gradient \(\nabla f(x)\) given a set of \(N\) equally spaced samples \(f_i = f[x_i]\) where \(i\in [0,N-1]\) and \(h=x_i - x_{i-1}\) is the sample spacing

David Mayerich

STIM Laboratory, University of Houston

\frac{\partial}{\partial x}f(x) \approx \frac{f(x+h) - f(x-h)}{2h}
  • Representable as a stencil operation:

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

5
0
4
6
2
9
2
7
1
2
4
0
8
5
1
8
0
5
7
6
6
-\frac{1}{2}
0
\frac{1}{2}
\sum
3
-1
1.5
0
-1
-0.5
\nabla f[x_i] \approx \frac{f[x_{i+1}] - f[x_{i-1}]}{2h}
-0.5

Finite Difference Stencils

  • Calculate the gradient \(\nabla f(x)\) given a set of \(N\) equally spaced samples \(f_i = f[x_i]\) where \(i\in [0,N-1]\) and \(h=x_i - x_{i-1}\) is the sample spacing

David Mayerich

STIM Laboratory, University of Houston

\frac{\partial}{\partial x}f(x) \approx \frac{f(x+h) - f(x-h)}{2h}
\nabla f[x_i] \approx \frac{f[x_{i+1}] - f[x_{i-1}]}{2h}
  • Representable as a stencil operation:

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

5
0
4
6
2
9
2
7
1
2
4
0
8
5
1
8
0
5
7
6
6
-0.5
3
-1
1.5
0
-1
-0.5
-\frac{1}{2}
0
\frac{1}{2}
\sum
  • How would you configure a grid to evaluate \(\nabla f(x)\)?

Finite Difference Stencils

David Mayerich

STIM Laboratory, University of Houston

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

5
0
4
6
2
9
2
7
1
2
4
0
8
5
1
8
0
5
7
6
6
  • What work is each thread doing?

  • Is it limited by compute or memory?

\frac{1}{280}
\frac{-4}{105}
\frac{1}{5}
\frac{-4}{5}
0
\frac{4}{5}
\frac{-1}{5}
\frac{4}{105}
\frac{-1}{280}

thread 0

\frac{1}{280}
\frac{-4}{105}
\frac{1}{5}
\frac{-4}{5}
0
\frac{4}{5}
\frac{-1}{5}
\frac{4}{105}
\frac{-1}{280}

thread 1

\frac{1}{280}
\frac{-4}{105}
\frac{1}{5}
\frac{-4}{5}
0
\frac{4}{5}
\frac{-1}{5}
\frac{4}{105}
\frac{-1}{280}

thread 2

(really badly)

  • Stencils expand with order (accuracy)

    • Second-order \(O(h^2)\) solution:

    • \(O(h^8)\) solution:

\begin{bmatrix} \frac{-1}{2} & 0 & \frac{1}{2} \end{bmatrix}
\begin{bmatrix} \frac{1}{280} & \frac{-4}{105} & \frac{1}{5} & \frac{-4}{5} & 0 & \frac{4}{5} & \frac{-1}{5} & \frac{4}{105} & \frac{-1}{280} \end{bmatrix}

Shared Memory on CUDA Architecture

David Mayerich

STIM Laboratory, University of Houston

streaming multiprocessor (SM)

\cdots
\cdots
\cdots
\cdots

warp scheduler

shared memory

\cdots
\cdots

global memory

streaming

multi-

processor

(SM)

Shared Memory Allocation

  • Shared memory is a fast per-block cache

    • declared during grid configuration

    • global to all threads within a block

    • lifetime of the grid

  • Combined with L1 cache on modern Nvidia GPUs

David Mayerich

STIM Laboratory, University of Houston

int shared = /* shared memory in bytes */
kernelFunc<<< grid, block, shared >>>(/*...*/);	// call CUDA kernel w/ grid config
  • Grid configuration with shared memory:
  • Declaration within a kernel
__global__ void kernelFunc(/* ... */) {
  extern __shared__ float sharedPtr[];			// shared bytes available block-wide
  /* access shared memory through sharedPtr */  
}

Hopper architecture (clock cycles)

typeRTX 4090A100H800
L1 (SM)323332
shared302929
L2 (chip)273202-408265-502
global571566656

Luo et al., Dissecting the NVIDIA Hopper Architecture through Microbenchmarking and Multiple Level Analysis (2025)

Gradient Implementation: Global Memory

David Mayerich

STIM Laboratory, University of Houston

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

5
0
4
6
2
9
2
7
1
2
4
0
8
5
1
8
0
5
7
6
6
__constant__ float c_coef[9];

__global__ void gradient(float* f, float* g, int n) {
  int i = blockIdx.x * blockDim.x + threadIdx.x;
  if(i < n - 8) return;
  float sum = 0.0;
  for(int w = 0; w < 9; w++)
    sum += f[i + w] * c_coef[w];
  g[i] = sum;
}
\frac{1}{280}
\frac{-4}{105}
\frac{1}{5}
\frac{-4}{5}
0
\frac{4}{5}
\frac{-1}{5}
\frac{4}{105}
\frac{-1}{280}
\times
\times
\times
\times
\times
\times
\times
\times
\times
\sum

Gradient Implementation: Shared Memory

David Mayerich

STIM Laboratory, University of Houston

  • How many global memory instructions are executed in each thread?
  • How many global memory instructions are shared between two adjacent threads?

\(9\times\) fetches \(+ 1\) write

\(8\times\) fetches

  • How much global memory is fetched within a block?

w = 9

blockDim.x = 1024

(1024 + 8) * sizeof(float)

Gradient Implementation: Shared Memory

David Mayerich

STIM Laboratory, University of Houston

blockDim.x = 1024

w = 9

  • How many global memory instructions are executed in each thread?
  • How many global memory instructions are shared between two adjacent threads?

\(9\times\) fetches \(+ 1\) write

\(8\times\) fetches

sharedPtr

  • How much global memory is fetched within a block?

(1024 + 8) * sizeof(float)

Initializing Shared Memory

David Mayerich

STIM Laboratory, University of Houston

__constant__ float c_coef[9];

__global__ void gradient(float* f, float* g, int n) {
  int tid = threadIdx.x;	int bd = blockDim.x;	int bid = blockIdx.x;
  
  extern __shared__ float s_ptr[];		// declare a pointer for the shared space
  int ss = bd + 9 - 1;					// calculate the size of a block allocation
  for(int si = tid; si < ss; si += bd)	// round-robin copy from f to s_ptr
    s_ptr[si] = f[bid * bd + si];
  __syncthreads();						// synchronization barrier (finish copy first)
  
  if(i < n - 8) return;					// test array limits
  float sum = 0.0;
  for(int w = 0; w < 9; w++)			// for each voxel in the stencil
    sum += s_ptr[tid + w] * c_coef[w];	// apply the stencil and sum			
  g[i] = sum;							// write to output
}

copy to shared

apply stencil

Threaded Memory Copies

David Mayerich

STIM Laboratory, University of Houston

__device__ void threadedMemcpy(void* dst,	// copy destination (ex. shared memory)
							   void* src,	// copy source (ex. global memory)
                               int size,	// bytes to be copied
                               int tid,		// thread ID for round-robin copy
                               int bd) {	// block dimension for round-robin copy
  for(int i = tid; i < size; i += bd)		// for each element copied by this thread
    (char*)dst[i] = (char*)src[i];
  __syncthreads();							// stall until the copy is finished
}

apply the threaded memory copy in the kernel

__global__ void gradient(float* f, float* g, int n) {
  int tid = threadIdx.x;	int bd = blockDim.x;	int bid = blockIdx.x;
  extern __shared__ s_ptr[];			// declare a pointer for the shared space

  threadedMemcpy(s_ptr, &f[bid * bd], (bd + 8) * sizeof(float), tid, bd);
  
  /* Perform stencil operation */
}

Summary

  • Shared memory is fast: not as fast as registers, but much faster than global memory

    • \(>10\text{X}\) faster than global memory

    • often identical to L1 (SM-level) cache

  • Allocated at grid configuration and remains in scope for the duration of the kernel

  • Shared between threads in a block (this is why a block runs on a single SM)

    • generally requires communication between threads

    • use __syncthreads() to synchronize threads within a block

David Mayerich

STIM Laboratory, University of Houston

E.6 CUDA Shared Memory

By STIM Laboratory

E.6 CUDA Shared Memory

  • 122