GPU acceleration for neural networks
How GPUs speed up neural-network training and inference by mapping neural operators (matrix multiply, convolution) to massively parallel hardware, and how to reason about performance using arithmetic intensity and the roofline model.
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 let engineers train and run large neural networks far faster than CPUs by providing thousands of simple processors and very high memory bandwidth. Understanding GPU acceleration for neural networks helps you pick the right algorithm, map computation to the device (see CUDA threads, blocks, grids and warps), and estimate performance limits for training and inference in practical systems.
Key ideas
Start with terms (I define them before use):
- GPU: a processor with many simple cores designed for parallel data processing. Useful for workloads with data-parallel operations.
- FLOP: a floating-point operation (one multiply or add). Universities often count one multiply + one add as 2 FLOPs when they are separate operations; for fused multiply–add (FMA) some hardware counts it as 2 FLOPs in throughput calculations.
- GEMM: General Matrix–Matrix multiplication (C = A·B + C). This is the basic building block for many neural-network layers (fully connected, many implementations of convolution reduce to GEMM).
- Convolution (in CNNs): operation where a small kernel slides over input feature maps to form output feature maps.
- Kernel: here, a GPU function that runs many parallel threads (do not confuse with convolution kernel).
- Arithmetic intensity: the ratio of FLOPs performed to bytes moved from main (global) memory. Denote as AI = FLOPs / memory_bytes. Higher AI means computation-heavy, so bound by compute; low AI means memory-bound.
- Memory bandwidth: how many bytes per second the GPU can read/write to global memory (GB/s). Denoted B.
- Roofline model: a performance model that says: achievable performance P ≤ min(P_peak, AI × B). This gives a clear boundary between being memory-bound or compute-bound.
Exact statements and derivations universities ask for:
FLOPs for matrix multiplication: For two square matrices of size N×N, using the classical algorithm, each output element computes a dot product of length N which is N multiplies and N−1 adds — universities commonly approximate this as 2·N^3 FLOPs (counting multiply and add separately). Assumption: no optimization that reduces arithmetic (e.g., Strassen) and exact count ignores loop overhead.
FLOPs for convolution (direct, not im2col): For an input with C_in channels, output C_out channels, kernel size K×K, and output spatial size H_out×W_out, the number of multiply-adds is C_out · H_out · W_out · C_in · K · K. Counting multiply and add separately often gives 2× that number if you count each multiply and each add.
Roofline model exact statement: Given a device with peak compute P_peak (FLOPs/s) and memory bandwidth B (bytes/s), and a kernel with arithmetic intensity AI (FLOPs/byte), the upper bound for sustainable performance P is
- P ≤ P_peak (compute roof)
- P ≤ AI × B (memory roof) So combined: P ≤ min(P_peak, AI × B). Assumptions: data reuse inside device (registers/shared memory) is captured in AI; memory accesses charged are those that must go to global memory.
Mapping convolution to GEMM (common derivation): Using im2col, reshape each K×K×C_in patch into a column, then perform GEMM between weight matrix (C_out, K·K·C_in) and this im2col matrix (K·K·C_in, H_out·W_out). Draw: input feature map on left, sliding K×K window; draw arrows showing each patch flattened to column, then a large matrix multiplication.
Diagrams to draw (describe exactly):
- For convolution sliding window: draw a top-down square representing an input channel with a smaller square K×K inside at one position. Show the kernel as a small K×K matrix and an arrow labeled “element-wise multiply & sum” pointing to a single output pixel. Repeat two more windows shifted right/down to show sliding.
- For tiled matrix multiplication: draw three matrices A, B, C as large squares. Shade a T×T block of A and a T×T block of B that multiply to contribute to a T×T block of C. Label shared memory as a small block where tiles are loaded. Show arrows from global memory into shared memory tiles, and from shared memory into per-thread registers.
Notes on GPU mapping: use tiling to increase arithmetic intensity by reusing data from shared memory; keep threads working on contiguous memory addresses to enable coalesced access (see CUDA memory: shared, global, constant and texture). Take care of bank conflicts in shared memory and warp divergence (see Warps, memory bandwidth and resource partitioning). On modern GPUs, tensor cores accelerate mixed-precision matrix multiply–accumulate (e.g., FP16/BF16/TF32) at much higher throughput than FP32; where numerically valid, mixed precision can increase performance and change whether a kernel is memory- or compute-bound (ensure FLOP accounting is consistent, typically FMA = 2 FLOPs). Also consider occupancy (active warps per SM), register and shared memory limits, and the warp size (32 threads on NVIDIA) when reasoning about performance.
Formulas
F_GEMM ≈ 2·N^3 — F_GEMM: approximate FLOPs required to multiply two N×N matrices using the classical algorithm. Unit: FLOPs. Applies to classical O(N^3) algorithm. Exact count (separate multiplies and adds): 2·N^3 − N^2.
F_conv = C_out · H_out · W_out · C_in · K · K — F_conv: multiply–add count (if counting multiply+add as one pair, multiply by 2 for separate FLOP count). Units: multiply-adds. Applies to direct convolution.
AI = FLOPs / memory_bytes — arithmetic intensity: FLOPs per byte read/written from global memory. Units: FLOPs/byte. Applies when estimating roofline performance.
P_max = min(P_peak, AI × B) — roofline bound. P_max: achievable performance in FLOPs/s. P_peak: device peak FLOPs/s. B: memory bandwidth in bytes/s. Applies when global memory traffic dominates and AI is known.
Memory traffic for a kernel: estimate bytes moved = reads + writes to global memory (exclude cached/shared memory reuse). Be conservative and count worst-case unless reuse is proven.
Worked examples
Example 1 — FLOPs for convolution layer (numerical): Question: Compute FLOPs for a convolution layer with C_in=3, C_out=64, kernel 3×3, input feature map size 224×224, using direct convolution. Count multiply-adds and then separate FLOPs (multiply + add). Solution steps:
- Output spatial size H_out=W_out=224 (assume padding/stride give same size).
- Number of multiply-adds: F_conv = C_out · H_out · W_out · C_in · K · K = 64 · 224 · 224 · 3 · 3 · 3 First compute 224·224 = 50176. Then 64·50176 = 3,211,264. Then 3,211,264 · 3 = 9,633,792. Then 9,633,792 · 9 = 86,704,128 multiply-adds.
- If counting multiply and add separately as FLOPs, FLOPs = 2 × 86,704,128 = 173,408,256 FLOPs ≈ 1.734 · 10^8 FLOPs. Final answer: 86,704,128 multiply-adds (≈173,408,256 FLOPs).
Example 2 — Roofline arithmetic-intensity and bound (numerical): Question: Using Example 1, estimate arithmetic intensity and the roofline bound on a GPU with memory bandwidth B = 320 GB/s (320·10^9 bytes/s) and peak FP32 P_peak = 8.9 TFLOPS (8.9·10^12 FLOPs/s). Assume ideal reuse so that each input pixel and weight is read once from global memory, and each output pixel is written once (an optimistic lower bound; a naive kernel without tiling would read many elements multiple times from global memory). Count memory bytes roughly as: inputs bytes = C_in·H·W·4 bytes, weights bytes = C_out·C_in·K·K·4 bytes, outputs bytes = C_out·H_out·W_out·4 bytes. Solution steps:
- Compute bytes: inputs = 3·224·224·4 = 3·50176·4 = 602,112 bytes. weights = 64·3·3·3·4 = 64·27·4 = 6,912 bytes. outputs = 64·224·224·4 = 64·50176·4 = 12,845,056 bytes. total bytes ≈ 13,454,080 bytes.
- FLOPs (from Example 1) ≈ 1.734·10^8.
- AI = FLOPs / bytes ≈ 173,408,256 / 13,454,080 ≈ 12.89 FLOPs/byte.
- Memory-limited bound AI·B = 12.89 × 320·10^9 ≈ 4.1248·10^12 FLOPs/s = 4.12 TFLOPS.
- Roofline: P ≤ min(8.9 TFLOPS, 4.12 TFLOPS) = 4.12 TFLOPS. So the kernel is memory-bound in this optimistic accounting. Final answer: AI ≈ 12.9 FLOPs/byte, roofline bound ≈ 4.12 TFLOPS (memory-bound). Note: real optimized implementations use tiling and shared memory to increase AI (verify how many bytes actually come from global memory — see verify list).
Example 3 — Programming: CUDA C++ program that multiplies two 4×4 matrices where B is identity (so output equals A). Compile with nvcc. This demonstrates kernel mapping; small size chosen so output is simple and exact.
Code:
#include <cstdio> #include <cuda_runtime.h>
global void matmul_naive(const float* A, const float* B, float* C, int N) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; if (row < N && col < N) { float sum = 0.0f; for (int k = 0; k < N; ++k) sum += A[row * N + k] * B[k * N + col]; C[row * N + col] = sum; } }
int main() { const int N = 4; float h_A[NN]; float h_B[NN]; float h_C[NN]; for (int i = 0; i < NN; ++i) h_A[i] = float(i+1); // 1..16 // B = identity for (int r=0;r<N;++r) for (int c=0;c<N;++c) h_B[r*N+c] = (r==c) ? 1.0f : 0.0f;
float *d_A, *d_B, *d_C;
cudaMalloc(&d_A, N*N*sizeof(float));
cudaMalloc(&d_B, N*N*sizeof(float));
cudaMalloc(&d_C, N*N*sizeof(float));
cudaMemcpy(d_A, h_A, N*N*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_B, h_B, N*N*sizeof(float), cudaMemcpyHostToDevice);
dim3 block(16,16);
dim3 grid((N + block.x -1)/block.x, (N + block.y -1)/block.y);
matmul_naive<<<grid, block>>>(d_A, d_B, d_C, N);
cudaDeviceSynchronize();
cudaMemcpy(h_C, d_C, N*N*sizeof(float), cudaMemcpyDeviceToHost);
printf("Result C (4x4):\n");
for (int r=0;r<N;++r) {
for (int c=0;c<N;++c) printf("%.1f ", h_C[r*N+c]);
printf("\n");
}
cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);
return 0;
}
Sample input: (none; program uses built-in matrices). Sample output (exact): Result C (4x4): 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0
This output equals matrix A because B is identity.
Common mistakes
- Forgetting to count both reads and writes when estimating memory traffic.
- Using peak FLOPs as the performance estimate without applying the roofline min(AI·B, P_peak).
- Miscounting FLOPs for convolution: forgetting to multiply by C_in or C_out or kernel area K·K.
- In CUDA code: using wrong row/col indexing (row-major vs column-major) and not checking array bounds.
- Assuming im2col always reduces work; it increases memory traffic and may lower AI if implemented poorly.
For your exam
- Derivation question: Derive FLOP count for convolution layer given dimensions. Full marks: show step-by-step counting and final formula.
- Numerical question: Given layer sizes and device specs (B and P_peak), compute AI and roofline bound. Full marks: compute bytes, FLOPs, AI, multiply AI·B, compare with P_peak, state bound and whether memory/compute bound.
- Programming question: Write a CUDA kernel for matrix multiplication and show how to launch it. Full marks: correct kernel, proper indexing, correct host code for memory ops and correct sample output or correctness argument.
- Diagram question: Draw tiled matrix multiplication with labels for tiles, shared memory, thread block. Full marks: neat drawing showing tiles of A and B, shared memory, threads computing output tile, arrows for memory transfer.
Quick check
- What is arithmetic intensity and why does it matter?
- Write the approximate FLOP count for multiplying two N×N matrices using the classical algorithm.
- In the roofline model, if AI × B < P_peak, is the kernel memory-bound or compute-bound?
Answers: AI = FLOPs/byte; it shows if computation or memory limits performance.
F_GEMM ≈ 2·N^3. If AI × B < P_peak then the kernel is memory-bound.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?