GPU by Example
8 / 16

Shared memory

7 min readChapter 8 of 16

Global memory is far away. Shared memory is a small scratchpad on the SM that every thread in a block can read and write. Used well, it turns repeated trips to DRAM into one trip plus a lot of on-chip reuse.

A block-wide scratchpad#

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

__global__ void blockSum(const float* in, float* out) {
    __shared__ float tile[256];                 // 1 KB per block

    int i = blockIdx.x * blockDim.x + threadIdx.x;
    tile[threadIdx.x] = in[i];
    __syncthreads();                            // all writes visible

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

int main() {
    const int n = 1024;
    float *in, *out;
    cudaMallocManaged(&in, n * sizeof(float));
    cudaMallocManaged(&out, 4 * sizeof(float));
    for (int i = 0; i < n; ++i) in[i] = 1.0f;

    blockSum<<<4, 256>>>(in, out);
    cudaDeviceSynchronize();

    for (int b = 0; b < 4; ++b) printf("block %d sum = %.1f\n", b, out[b]);
    cudaFree(in); cudaFree(out);
    return 0;
}
Outputreference run
block 0 sum = 256.0
block 1 sum = 256.0
block 2 sum = 256.0
block 3 sum = 256.0

Three things to notice:

  • __shared__ float tile[256] allocates 1 KB per block, not per thread.
  • Every thread writes one element, then __syncthreads() makes all 256 writes visible before any thread reads.
  • Thread 0 reads the whole tile. The data never goes back to DRAM between the write and the read.

Remove the __syncthreads() and thread 0 may read elements that have not been written yet. The program still compiles and usually still runs — it just produces wrong sums occasionally. That is a race condition.

The shape of the win#

A tiled algorithm loads a chunk of global memory once, then every thread reads that chunk many times from shared memory. The reuse factor is what pays for the extra copy.

  • Global memory: ~500 cycles, ~1–3 TB/s for the whole GPU.
  • Shared memory: ~25 cycles, ~20 TB/s per SM.
  • Registers: ~1 cycle, effectively unlimited bandwidth per thread.

If each element is used once, shared memory adds overhead. If each element is used 16 times (as in matrix multiplication), it removes most of the DRAM traffic.

Bank conflicts#

Shared memory is divided into 32 banks, each 4 bytes wide. A warp can service one 4-byte word per bank per cycle. If two lanes in the same warp access different words in the same bank, the accesses serialise — a bank conflict.

For a 32×32 float array, the bank of tile[row][col] is (row * 32 + col) % 32 = col:

CUDA C++
tile[ty][tx]       // lane accesses column = lane  → banks 0..31, no conflict
tile[tx][0]        // addresses 0, 32, 64, ...      → all map to bank 0, 32-way conflict

A classic fix is to add padding so rows no longer align to the bank count:

CUDA C++
__shared__ float tile[32][33];   // bank = (row*33 + col) % 32 = (row + col) % 32

Now a column access hits 32 different banks. The cost is 32 extra floats of shared memory per tile.

Tiled matrix multiplication#

This is the canonical shared-memory example. Each block computes a 16×16 tile of C = A × B. To do it, the block loads one 16×16 tile of A and one of B, multiplies them into registers, then moves to the next tile along the K dimension.

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

constexpr int TILE = 16;

__global__ void matmul(const float* A, const float* B, float* C, int N) {
    __shared__ float As[TILE][TILE];
    __shared__ float Bs[TILE][TILE];

    int row = blockIdx.y * TILE + threadIdx.y;
    int col = blockIdx.x * TILE + threadIdx.x;
    float acc = 0.0f;

    for (int t = 0; t < N / TILE; ++t) {
        // Stage one tile of A and one tile of B.
        As[threadIdx.y][threadIdx.x] = A[row * N + t * TILE + threadIdx.x];
        Bs[threadIdx.y][threadIdx.x] = B[(t * TILE + threadIdx.y) * N + col];
        __syncthreads();

        // Each thread accumulates its own C[row][col] over the tile.
        for (int k = 0; k < TILE; ++k) {
            acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
        }
        __syncthreads();   // before overwriting the tiles next iteration
    }
    C[row * N + col] = acc;
}

int main() {
    const int N = 64;
    const size_t bytes = N * N * sizeof(float);
    float *A, *B, *C;
    cudaMallocManaged(&A, bytes);
    cudaMallocManaged(&B, bytes);
    cudaMallocManaged(&C, bytes);

    // A[row][col] = row + 1, B = all ones  ->  C[row][col] = N * (row + 1)
    for (int r = 0; r < N; ++r) {
        for (int c = 0; c < N; ++c) {
            A[r * N + c] = (float)(r + 1);
            B[r * N + c] = 1.0f;
        }
    }

    dim3 block(TILE, TILE);
    dim3 grid(N / TILE, N / TILE);
    matmul<<<grid, block>>>(A, B, C, N);
    cudaDeviceSynchronize();

    printf("C[0][0]      = %.1f\n", C[0]);
    printf("C[63][63]    = %.1f\n", C[63 * N + 63]);
    cudaFree(A); cudaFree(B); cudaFree(C);
    return 0;
}
Outputreference run
C[0][0]      = 64.0
C[63][63]    = 4096.0

Why there are two __syncthreads()#

  • The first one guarantees every thread's tile writes are visible before the multiply reads them.
  • The second guarantees every thread has finished reading the tiles before the next loop iteration overwrites them.

Drop either one and the result depends on timing. This is the most common shared-memory bug: one sync, not two.

The reuse arithmetic#

For an N × N × N matrix multiply:

  • Naive kernel: each output reads N elements of A and N of B → 2N³ global reads.
  • Tiled kernel: each block loads 2 × TILE² elements per K-step, and there are N/TILE steps and (N/TILE)² blocks → 2N³/TILE global reads.

With TILE = 16, that is 16× less global traffic. The arithmetic is identical; only the data movement changed.

Shared memory is a limited resource#

The amount per block is fixed at compile time (static) or launch time (dynamic). The SM has a finite pool, and blocks compete for it:

CUDA C++
extern __shared__ float tile[];            // dynamic
kernel<<<grid, block, TILE * TILE * sizeof(float)>>>(...);

If each block asks for 48 KB and the SM has 100 KB usable, only two blocks fit no matter how few threads they contain. Always check the occupancy impact before making a tile bigger.

When not to use shared memory#

  • Data used once per thread: staging it just adds a copy and a sync.
  • Data already in registers: moving it to shared is a downgrade.
  • Tiny blocks: the sync and the staging cost may exceed the savings.
  • Irregular access patterns whose conflicts you cannot reason about: start with global memory and profile.

Modern GPUs also cache global loads in L1/L2 aggressively. Sometimes a straightforward global-memory kernel is within a few percent of a hand-tiled shared-memory version. Measure.

Exercises#

  • Remove __syncthreads() from blockSum. Run it ten times. Does it always fail? Why is "sometimes correct" worse than "always wrong"?
  • Change TILE to 32 in the matmul. How much shared memory per block? How many blocks fit on an SM with 100 KB?
  • Pad Bs to [TILE][TILE + 1]. Does the runtime change at this size? At N = 2048?
  • Rewrite the multiply so each thread computes a 2×2 block of C instead of one element. How does register use change?
  • Explain why the second __syncthreads() cannot be replaced by __syncwarp().