Convolution
Sliding a mask over an array, and meeting constant memory — the read-only cache built for exactly this.
- How to handle boundaries when every thread reads its neighbours
- What constant memory is for, and why a convolution mask is the perfect fit
- How halo elements complicate shared-memory tiling
Convolution slides a small mask over an input array, and each output element is a weighted sum of a neighbourhood:
\[r[i] = \sum_{j=0}^{m-1} a[i - r + j] \cdot \text{mask}[j], \qquad r = \lfloor m/2 \rfloor\]It is the operation underneath image filtering and convolutional networks, and unlike vector addition, each thread now needs data its neighbours also need — which is what makes the memory story interesting.
The naive version
__global__ void convolution_1d(int *array, int *mask, int *result, int n, int m) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
int r = m / 2; // mask radius
int start = tid - r; // where this thread's window begins
int temp = 0;
for (int j = 0; j < m; j++) {
// Skip positions that fall off either end of the array
if ((start + j >= 0) && (start + j < n)) {
temp += array[start + j] * mask[j];
}
}
result[tid] = temp;
}
The start = tid - r shift centres the window on the thread’s own element, and the bounds check inside the loop handles the edges by treating out-of-range neighbours as zero. Three allocations are needed on the device here: the array, the mask, and the result.
Constant memory
Notice how the mask is used: every thread reads all of it, and nobody writes it. That is precisely the access pattern __constant__ memory is designed for. It is a small (64 KB) read-only region with its own cache, and when every thread in a warp reads the same address it is broadcast in a single operation.
#define MASK_LENGTH 7
__constant__ int mask[MASK_LENGTH]; // lives on the device, not passed as an argument
__global__ void convolution_1d(int *array, int *result, int n) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
int r = MASK_LENGTH / 2;
int start = tid - r;
int temp = 0;
for (int j = 0; j <= MASK_LENGTH; j++) {
if ((start + j >= 0) && (start + j < n)) {
temp += array[start + j] * mask[j];
}
}
result[tid] = temp;
}
The mask is no longer a kernel parameter. It is uploaded once from the host with a different call:
cudaMemcpyToSymbol(mask, h_mask, bytes_m);
The trade-off is that the size must be known at compile time, which is why MASK_LENGTH is a #define.
Spot the bug. The loop above reads j <= MASK_LENGTH, so it runs MASK_LENGTH + 1 times and reads one element past the end of the mask. It should be j < MASK_LENGTH. It is in the repository as written — a good reminder that an off-by-one in CUDA reads garbage rather than crashing. Fixing it is the exercise below.
Tiling, and the halo problem
Shared memory worked for matrix multiplication because each block needed a clean rectangular tile. Convolution is messier: a block computing outputs [0 … blockDim) needs inputs from [-r … blockDim + r). Those extra r elements on each side are halo (or ghost) elements, and they belong to the neighbouring block’s tile.
03_tiled_1D_conv.cu loads the tile plus both halos into shared memory, using a zero-padded input array so the edge cases need no special branch. 04_1D_conv_cache_simplification.cu then simplifies this: because halo elements are very likely sitting in L2 cache already — a neighbouring block just read them — it loads only the core tile into shared memory and reads halos straight from global memory, trading a little latency for much simpler code and less divergence.
Going 2D
05_2D_conv.cu extends this to images with a 7×7 mask and 16×16 thread blocks. The structure is identical, with row and column indices from blockIdx/threadIdx as in the matrix multiplication lesson, and boundary checks on both axes.
| Version | Technique |
|---|---|
01_naive_1D_conv.cu | everything in global memory |
02_1D_conv_with_const_memory.cu | mask in constant memory |
03_tiled_1D_conv.cu | shared-memory tile with explicit halos |
04_1D_conv_cache_simplification.cu | core tile shared, halos from cache |
05_2D_conv.cu | 2D convolution, 7×7 mask |
Run it
cd cuda_from_scratch/04convolution
nvcc -o conv_naive 01_naive_1D_conv.cu && ./conv_naive
nvcc -o conv_const 02_1D_conv_with_const_memory.cu && ./conv_const
nvcc -o conv_2d 05_2D_conv.cu && ./conv_2d
Try it yourself. First fix the j <= MASK_LENGTH off-by-one and confirm the verification still passes. Then change MASK_LENGTH to 15 and compare the constant-memory version against the tiled one — at what mask size does tiling start to pay for its extra complexity?