Skip to content

← CNNs from Scratch step 2 of 15

Medium Primitives

Implement Conv2d

A 2D cross-correlation slides a kernel across an image or feature map. At each location, it multiplies matching values and sums the products. For several input channels, sum their contributions too. Each output channel has its own set of kernel weights.

For a single input channel [[1, 2, 3], [4, 5, 6]] and kernel [[1, 0], [0, -1]], with stride 1 and no padding, there are two windows. The first gives 1*1 + 2*0 + 4*0 + 5*(-1) = -4, and the second also gives -4. The output has one row: [[-4, -4]].

The kernel stays in its given order. Despite the common name convolution, this exercise computes cross-correlation, with no spatial kernel flip.

Your task

Implement conv2d(x, w, stride=1, padding=0):

  • x has shape (N, C_in, H, W): examples, input channels, height, width.
  • w has shape (C_out, C_in, kH, kW). Each output channel uses all input channels. The input and weights have matching floating-point dtypes and devices.
  • stride is a positive integer used for both spatial axes.
  • padding is a nonnegative integer. Add that many zeros to each of the four spatial edges of every input channel. Do not pad batch or channel axes.

All dimensions are positive, and the padded input is at least as large as the kernel in each spatial dimension. The output shape is (N, C_out, H_out, W_out), where

H_out = (H + 2 * padding - kH) // stride + 1

W_out = (W + 2 * padding - kW) // stride + 1

On the padded input, output position (i, j) uses the patch starting at (i * stride, j * stride). For each output channel, multiply that patch by its weights and sum over all input channels and kernel positions. There is no bias, dilation, or channel grouping. Trailing partial windows are omitted. Rectangular images and kernels are valid.

For example, a 1-by-1 kernel with input-channel weights [2, -1] applied to channel values [3, 5] returns 2*3 - 5 = 1 at that position. This is one output value, not separate values for each input channel.

The diagram illustrates window movement along one spatial axis. The same indexing rule applies independently to height and width here. Keep dilation at 1; the diagram does not show channel summation.

Loading visualization…