Write a 2D convolution with stride and padding
A conv layer slides a small kernel over an image and takes a dot product at each position. (Like PyTorch, this is technically cross-correlation: the kernel is not flipped.)
Write conv2d(img, kernel, stride=1, padding=0) for a 2D image (H, W) and kernel (kh, kw). Zero-pad the image on all sides first. Output size is (H + 2p - kh) // stride + 1 by (W + 2p - kw) // stride + 1.
def conv2d(img, kernel, stride=1, padding=0)Understand the idea
A convolution slides a small kernel over an image and, at each position, multiplies the overlapping numbers and adds them up. Deep learning libraries do not flip the kernel (strictly this is cross-correlation). Padding adds a border of zeros first, and stride says how many pixels to jump between positions. Worked example: image [[1, 2, 3], [4, 5, 6], [7, 8, 9]], kernel [[1, 0], [0, -1]], stride 1, padding 0. Output size is (3 - 2) // 1 + 1 = 2 by 2. Top-left patch [[1, 2], [4, 5]] gives 1 x 1 + 5 x (-1) = -4. The other patches give 2 - 6, 4 - 8 and 5 - 9, so the output is [[-4, -4], [-4, -4]]. With padding 1 and stride 2 the size would be (3 + 2 - 2) // 2 + 1 = 2. Rule: pad, then out[r, c] = sum of kernel times the patch starting at (r x stride, c x stride). Size = (H + 2p - kh) // stride + 1. Every CNN and vision encoder is built from this operation.