Conv2D from Scratch
🧩 What is a 2D convolution? A convolution layer slides a small stack of filters over an image. At every position, each filter takes the dot product with the patch under it and writes one number into its output map. The same weights are reused at every position, which is why a conv layer has few parameters and finds a pattern wherever it appears.
It comes up as the "write a layer by hand" question for anyone working on vision or perception models, and as the classic test of whether you can turn nested loops into one matrix product without losing track of axes.
The Prompt
Conv2D is all index bookkeeping, so the interviewer grades the output-size formula, the padding, and whether you can vectorize it without a bug in the patch layout.
"Implement the forward pass of a 2D convolution in NumPy. Input
(N, C, H, W), weights(F, C, KH, KW), a bias, a stride and a padding. Then add 2x2 max pooling."
Clarifying Questions
You: Is this a true convolution with a flipped kernel, or cross-correlation like PyTorch's conv2d?
Interviewer: Cross-correlation, no flip. Match PyTorch.
You: Padding is zeros, the same on all four sides? And stride is one integer for both directions?
Interviewer: Yes to both. No dilation, no groups.
You: If (H + 2P - KH) isn't divisible by the stride, I'll drop the last partial window, which gives
floor((H + 2P - KH) / S) + 1 rows. Is that right?
Interviewer: Yes, that's what PyTorch does.
You: Do you need the backward pass too?
Interviewer: Forward first. If there is time, the gradients.
What You'll Build
out_size(H, K, S, P) -> int: the output length along one axis.conv2d_loops(x, w, b, stride, pad) -> (N, F, OH, OW): the reference version.conv2d(x, w, b, stride, pad) -> (N, F, OH, OW): im2col and one matrix product.maxpool2d(x, k=2, stride=2) -> (N, C, OH, OW): max over each window.