KatInterview

Build a 2D Convolution Forward Pass Without ML Libraries

Machine LearningModel answer
MediumModel answerMachine Learningconvolutionnumpydeep-learning-fundamentals

Last updated

Implement conv2d from scratch in NumPy, correctly handling padding, stride, multi-channel inputs, and optional bias.

Task

Write a function conv2d_forward that computes the forward pass of a 2D convolution operation without using any deep learning framework (no PyTorch, TensorFlow, etc.). NumPy is allowed.

Inputs

ArgumentShapeDescription
x(N, C_in, H, W)Batch of input feature maps (NCHW layout)
w(C_out, C_in, K_h, K_w)Convolutional filter weights
b(C_out,) or NonePer-output-channel bias (optional)
strideint or (s_h, s_w)Step size when sliding the kernel
paddingint or (p_h, p_w)Zeros added to each side of height/width

Output

Return a float array y of shape (N, C_out, H_out, W_out) where:

$$H_{out} = \left\lfloor \frac{H + 2p_h - K_h}{s_h} \right\rfloor + 1, \qquad W_{out} = \left\lfloor \frac{W + 2p_w - K_w}{s_w} \right\rfloor + 1$$

Each element is defined by:

$$y[n, c_{out}, i, j] = \sum_{c_{in}} \sum_{u=0}^{K_h-1} \sum_{v=0}^{K_w-1} x_{pad}[n,, c_{in},, i \cdot s_h + u,, j \cdot s_w + v] \cdot w[c_{out}, c_{in}, u, v] ;+; b[c_{out}]$$

where $x_{pad}$ is x zero-padded by (p_h, p_w) on each spatial side.

Requirements

  • Do not call any existing convolution operator.
  • Handle b = None, non-square kernels, and asymmetric stride/padding.
  • Raise a clear error when shapes are incompatible (channel mismatch, kernel larger than padded input, etc.).

Shape check example

x: (1, 3, 32, 32)
w: (8, 3, 3, 3)
stride: (1, 1)
padding: (1, 1)
→ y: (1, 8, 32, 32)

Hints

Hint 1

Start with the output shape formula and verify it before writing any loop. Then allocate the zero output array and build up from there.

Hint 2

Rather than seven nested loops, loop only over kernel offsets (u, v) — that is K_h × K_w iterations. For each offset, a strided slice of the padded input gives all the spatial input values that interact with w[:, :, u, v] at once.

Hint 3

The bias shape is (C_out,). To add it to an (N, C_out, H_out, W_out) array without an error, reshape it to (1, C_out, 1, 1) or index it as b[None, :, None, None].