Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Parallel convolution on the GPU

Parallel convolution on the GPU: what convolution is, how to map it to CUDA threads, tiling with shared memory and an optimized kernel, with two runnable CUDA C++ examples (naive and tiled) and exam-style notes.

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

Parallel convolution is a core building block in image processing, computer vision and neural networks. Engineers implement convolution on GPUs to exploit massive parallelism for real-time filters, feature extraction and deep-learning layers.

Key ideas

Start with definitions and then build the GPU mapping.

  • Convolution (discrete 2D): the output pixel at coordinates (y,x) for an input image I and kernel (filter) K of size k × k is O(y,x) = sum_{i=0..k-1} sum_{j=0..k-1} I(y + i - r, x + j - r) · K(i,j), where r = (k-1)/2 is the radius (assume k odd). This formula assumes zero outside-image values (zero-padding) unless otherwise specified. Note: this is the cross-correlation convention (no kernel flip), which matches the CUDA code below. For true convolution you would flip the kernel indices: O(y,x) = sum_{i=0..k-1} sum_{j=0..k-1} I(y + r - i, x + r - j) · K(i,j) = sum_{i=-r..r} sum_{j=-r..r} I(y + i, x + j) · K(r - i, r - j). If K is symmetric, convolution equals correlation.

  • Kernel / Filter: a small matrix K applied over the image. If sum of K's elements = 1, we call it a normalized filter (e.g., box/average filter).

  • Padding / boundaries and output size: how we treat positions where the kernel extends outside the image and what output size we want. Common boundary choices: zero-padding (outside values = 0), mirror/reflect, replicate/clamp. Common sizing policies: same (output size = input size; requires padding) and valid (no padding; output shrinks by k−1 in each dimension). Here we use zero-padding and same-sized output unless stated.

  • Separable kernel: a kernel K is separable if K = v · w^T for vectors v and w, so 2D convolution can be done as two 1D convolutions (cost reduced from O(k^2) to O(2k)).

  • Complexity (sequential): For an image of W×H and kernel k×k, naive work is O(W·H·k^2).

  • GPU mapping: GPUs provide many threads. The usual mapping is one thread per output pixel: each thread computes O(y,x). This maps well because computations are independent (no write conflicts) and data-parallel.

  • Memory considerations:

    • Global memory: large but high latency. Reads from image and kernel go here. For small read-only kernels, prefer constant memory (cached and warp-broadcast) to reduce traffic; read-only/texture caches can also help for image sampling.
    • Shared memory: small per-block fast memory (on-chip). Use it to cache a tile of the image that many threads in a block will reuse. This reduces global memory traffic and increases throughput.
    • Coalesced memory access: threads in a warp should read neighbouring addresses to get high bandwidth.
    • Bank conflicts: shared memory is organized in banks; arrange indexing to minimize many threads accessing same bank.
  • Tiling (halo region): For a block that computes a tile of B×B output pixels, it must read a tile of input of size (B + 2r) × (B + 2r) into shared memory. The extra margin is called the halo and supplies neighbor pixels needed by border output pixels of the tile.

  • Synchronization: threads in a block must call __syncthreads() after loading the shared tile before threads compute using it.

  • Derivation students are asked to draw: draw a grid of blocks covering the image. For one block, draw a square labelled output tile B×B. Around it draw halo width r on all sides to show the shared-memory tile size (B+2r). Label thread indices: tx in [0..B-1], ty in [0..B-1]; global coordinates x = blockIdx.x·B + tx, y = blockIdx.y·B + ty.

  • Assumptions: k odd; kernel small (3,5,7), shared memory fits tile; single-channel (grayscale) images; zero-padding for boundaries. If kernel separable, prefer two-pass convolution.

Formulas

For programming, remember these index and launch formulas and kernel launch syntax:

x = blockIdx.x * blockDim.x + threadIdx.x — x coordinate (pixel column) handled by this thread.

y = blockIdx.y * blockDim.y + threadIdx.y — y coordinate (pixel row).

index = y * width + x — row-major 2D to 1D indexing.

dim3 block(Bx, By); dim3 grid((W + Bx - 1) / Bx, (H + By - 1) / By); kernel<<<grid, block>>>(...); — block and grid size and launch syntax.

Shared tile size: if block computes B×B outputs and kernel radius r then shared tile dimensions = (B + 2*r) × (B + 2*r).

Memory access law (for coalescing): threads with consecutive threadIdx.x should access consecutive global addresses in the inner-most dimension.

Worked examples

Two runnable CUDA C++ examples. Both perform 2D convolution with a 3×3 box (average) kernel on a 4×4 image. Kernel size is k = 3 and radius r = 1. Both programs print the result matrix (6 decimal places).

Example 1 — Naive kernel (one thread per output, direct global reads):

// File: conv_naive.cu
#include <cstdio>
#include <cuda_runtime.h>

__global__ void conv2D_naive(const float* in, float* out, int width, int height, const float* kernel, int ksize) {
    int x = blockIdx.x * blockDim.x + threadIdx.x;
    int y = blockIdx.y * blockDim.y + threadIdx.y;
    if (x >= width || y >= height) return;
    int r = ksize / 2;
    float sum = 0.0f;
    for (int dy = -r; dy <= r; ++dy) {
        for (int dx = -r; dx <= r; ++dx) {
            int ix = x + dx;
            int iy = y + dy;
            if (ix >= 0 && ix < width && iy >= 0 && iy < height) {
                sum += in[iy * width + ix] * kernel[(dy + r) * ksize + (dx + r)];
            }
        }
    }
    out[y * width + x] = sum;
}

int main() {
    const int W = 4, H = 4;
    float h_in[W*H] = { 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16 };
    float h_kernel[9]; for (int i=0;i<9;i++) h_kernel[i] = 1.0f/9.0f; // 3x3 average
    float h_out[W*H];

    float *d_in, *d_kernel, *d_out;
    cudaMalloc(&d_in, W*H*sizeof(float));
    cudaMalloc(&d_kernel, 9*sizeof(float));
    cudaMalloc(&d_out, W*H*sizeof(float));
    cudaMemcpy(d_in, h_in, W*H*sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(d_kernel, h_kernel, 9*sizeof(float), cudaMemcpyHostToDevice);

    dim3 block(16,16); dim3 grid((W+block.x-1)/block.x,(H+block.y-1)/block.y);
    conv2D_naive<<<grid,block>>>(d_in,d_out,W,H,d_kernel,3);
    cudaMemcpy(h_out, d_out, W*H*sizeof(float), cudaMemcpyDeviceToHost);

    printf("Naive output:\n");
    for (int y=0;y<H;y++){
        for (int x=0;x<W;x++) printf("%.6f ", h_out[y*W + x]);
        printf("\n");
    }

    cudaFree(d_in); cudaFree(d_kernel); cudaFree(d_out);
    return 0;
}

Sample input: the input image printed in code and kernel is 1/9 average.

Exact output (the program prints):

Naive output: 1.555556 2.666667 3.333333 2.444444 3.666667 6.000000 7.000000 5.000000 6.333333 10.000000 11.000000 7.666667 5.111111 8.000000 8.666667 6.000000

Example 2 — Tiled kernel using shared memory (B = 2 output per block, halo r = 1):

// File: conv_tiled.cu
#include <cstdio>
#include <cuda_runtime.h>

#define B 2 // outputs per block in each dim

__global__ void conv2D_tiled(const float* in, float* out, int width, int height, const float* kernel) {
    const int ksize = 3; const int r = 1;
    const int tileW = B + 2*r; // 4
    __shared__ float tile[tileW * tileW];

    int tx = threadIdx.x; int ty = threadIdx.y;
    int bx = blockIdx.x * B; int by = blockIdx.y * B;
    int x = bx + tx; int y = by + ty;

    // Each thread cooperatively load elements of the shared tile
    for (int j = ty; j < tileW; j += blockDim.y) {
        for (int i = tx; i < tileW; i += blockDim.x) {
            int gx = bx + i - r;
            int gy = by + j - r;
            float val = 0.0f;
            if (gx >= 0 && gx < width && gy >= 0 && gy < height) val = in[gy * width + gx];
            tile[j * tileW + i] = val;
        }
    }
    __syncthreads();

    if (x < width && y < height) {
        float sum = 0.0f;
        for (int dy = -r; dy <= r; ++dy) {
            for (int dx = -r; dx <= r; ++dx) {
                float tv = tile[(ty + dy + r) * tileW + (tx + dx + r)];
                sum += tv * kernel[(dy + r) * ksize + (dx + r)];
            }
        }
        out[y * width + x] = sum;
    }
}

int main(){
    const int W = 4, H = 4;
    float h_in[W*H] = { 1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16 };
    float h_kernel[9]; for (int i=0;i<9;i++) h_kernel[i] = 1.0f/9.0f;
    float h_out[W*H];

    float *d_in, *d_kernel, *d_out;
    cudaMalloc(&d_in, W*H*sizeof(float));
    cudaMalloc(&d_kernel, 9*sizeof(float));
    cudaMalloc(&d_out, W*H*sizeof(float));
    cudaMemcpy(d_in, h_in, W*H*sizeof(float), cudaMemcpyHostToDevice);
    cudaMemcpy(d_kernel, h_kernel, 9*sizeof(float), cudaMemcpyHostToDevice);

    dim3 block(B,B); dim3 grid((W+B-1)/B, (H+B-1)/B);
    conv2D_tiled<<<grid, block>>>(d_in, d_out, W, H, d_kernel);
    cudaMemcpy(h_out, d_out, W*H*sizeof(float), cudaMemcpyDeviceToHost);

    printf("Tiled output:\n");
    for (int y=0;y<H;y++){
        for (int x=0;x<W;x++) printf("%.6f ", h_out[y*W + x]);
        printf("\n");
    }

    cudaFree(d_in); cudaFree(d_kernel); cudaFree(d_out);
    return 0;
}

Exact output from the tiled program (should match naive):

Tiled output: 1.555556 2.666667 3.333333 2.444444 3.666667 6.000000 7.000000 5.000000 6.333333 10.000000 11.000000 7.666667 5.111111 8.000000 8.666667 6.000000

Notes on running: compile with nvcc: nvcc conv_naive.cu -o conv_naive and nvcc conv_tiled.cu -o conv_tiled.

Common mistakes

  • Using blockDim when computing global x,y: mix-up of blockDim vs tile size leads to wrong mapping.
  • Choosing shared tile too large to fit in per-SM shared memory — check device limits.
  • Ignoring coalescing: using transposed loads or non-consecutive threads for global memory reads hurts performance.
  • Assuming kernel size even; many formulas used here assume odd k.

For your exam

Types of questions you may see:

  • Definitions and short notes: define convolution, separable kernel, padding, halo, shared memory. Explain advantages of GPU implementation.
  • Derivations: derive shared tile size for block of B×B outputs, show indices mapping from threadIdx to global pixel coordinates; draw the block-tile-halo diagram.
  • Programs: write CUDA kernel (one-thread-per-pixel) to compute convolution with zero-padding. A full-marks answer includes proper boundary checks, kernel launch configuration, and copies between host and device.
  • Optimisation questions: explain tiling, show pseudocode or kernel using shared memory, discuss coalesced access and bank conflicts.
  • Numerical: compute small example manually (like 4×4 image with a 3×3 box filter). Show steps of sums and normalization.

Full-marks answers must state assumptions, include index formulas, include boundary handling, and explain synchronization and shared memory sizing.

Quick check

  1. What is the shared-memory tile size (width) needed for a block that computes B×B outputs with a k×k kernel (k odd)?
  2. Why must threads call __syncthreads() after loading the shared tile?
  3. What is the complexity (work) of naive 2D convolution for an image W×H and kernel k×k?

Answers: 1) B + (k-1) = B + 2·r. 2) To ensure all threads finished writing the tile into shared memory before any thread reads it (avoid race). 3) O(W·H·k^2).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?