Build a 2D Convolution Forward Pass Without ML Libraries
Machine LearningModel answerLast 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
| Argument | Shape | Description |
|---|---|---|
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 None | Per-output-channel bias (optional) |
stride | int or (s_h, s_w) | Step size when sliding the kernel |
padding | int 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].
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
What this problem is really testing
The underlying operation is cross-correlation, not true mathematical convolution (the kernel is not flipped). Every major deep learning framework names this "conv2d" anyway — say that out loud if asked. The core skills being checked are: translating an index formula into correct array code, managing shape arithmetic, and handling the padding/stride/bias edge cases cleanly.
Naive vs. vectorized
A direct transcription of the formula uses seven nested loops (n, c_out, c_in, i, j, u, v) and works correctly, but is very slow in Python. A more practical approach loops only over kernel offsets (u, v) — just K_h × K_w iterations — and vectorizes everything else with NumPy.
Key observation. For a fixed offset (u, v), the input values that pair with w[:, :, u, v] across all output positions (i, j) form a strided slice of the padded input:
x_pad[:, :, u : u + s_h*(H_out-1) + 1 : s_h,
v : v + s_w*(W_out-1) + 1 : s_w]
This slice has shape (N, C_in, H_out, W_out) and is a view (no copy). Contracting it with w[:, :, u, v] (shape (C_out, C_in)) over the channel dimension yields a (N, C_out, H_out, W_out) contribution. Summing over all offsets gives the final output.
This is equivalent to im2col + GEMM in terms of multiply-add count, but never materializes the large im2col matrix (which is K_h × K_w times the input size in memory).
Complexity
- Time: $O(N \cdot C_{out} \cdot C_{in} \cdot H_{out} \cdot W_{out} \cdot K_h \cdot K_w)$ — the same as the naive loop, but the inner work runs in compiled NumPy.
- Space: $O(N \cdot C_{in} \cdot (H+2p_h)(W+2p_w))$ for the padded input, plus output. The strided slices are views.
Edge cases to handle
| Case | Handling |
|---|---|
b is None | Skip the bias addition entirely |
| Non-square kernel or stride | Track h and w dimensions separately throughout |
padding = 0 | Skip np.pad or let it be a no-op |
| Stride > kernel width | Some input pixels are skipped — the formula handles this naturally |
| Kernel larger than padded input | H_out ≤ 0; raise a clear ValueError |
| Channel mismatch | x.shape[1] != w.shape[1]; raise a ValueError |
| Integer inputs | Promote to float before accumulation to avoid truncation |
Code
import numpy as np
def _pair(v):
"""Accept an int or a length-2 sequence; return a (h, w) int tuple."""
if isinstance(v, (int, np.integer)):
return int(v), int(v)
h, w = v
return int(h), int(w)
def conv2d_forward(x, w, b=None, stride=(1, 1), padding=(0, 0)):
"""
2D convolution (cross-correlation) forward pass.
x : (N, C_in, H, W)
w : (C_out, C_in, K_h, K_w)
b : (C_out,) or None
stride, padding : int or (h, w)
returns y : (N, C_out, H_out, W_out)
"""
x = np.asarray(x)
w = np.asarray(w)
dtype = np.result_type(x.dtype, w.dtype, np.float32)
x = x.astype(dtype, copy=False)
w = w.astype(dtype, copy=False)
s_h, s_w = _pair(stride)
p_h, p_w = _pair(padding)
if s_h <= 0 or s_w <= 0:
raise ValueError("stride must be positive")
if p_h < 0 or p_w < 0:
raise ValueError("padding must be non-negative")
N, C_in, H, W = x.shape
C_out, C_in_w, K_h, K_w = w.shape
if C_in != C_in_w:
raise ValueError(f"channel mismatch: x has {C_in}, w expects {C_in_w}")
H_out = (H + 2 * p_h - K_h) // s_h + 1
W_out = (W + 2 * p_w - K_w) // s_w + 1
if H_out <= 0 or W_out <= 0:
raise ValueError("kernel is larger than the padded input")
x_pad = np.pad(x, ((0,0),(0,0),(p_h,p_h),(p_w,p_w))) if (p_h or p_w) else x
y = np.zeros((N, C_out, H_out, W_out), dtype=dtype)
h_span = s_h * (H_out - 1) + 1 # end index of strided slice (height)
w_span = s_w * (W_out - 1) + 1 # end index of strided slice (width)
for u in range(K_h):
for v in range(K_w):
# patch: (N, C_in, H_out, W_out) — a view, no copy
patch = x_pad[:, :, u:u + h_span:s_h, v:v + w_span:s_w]
# w[:, :, u, v]: (C_out, C_in) — contract over C_in
y += np.einsum("nchw,oc->nohw", patch, w[:, :, u, v])
if b is not None:
b = np.asarray(b, dtype=dtype)
if b.shape != (C_out,):
raise ValueError(f"bias must have shape ({C_out},), got {b.shape}")
y += b[None, :, None, None]
return y
Verifying correctness in an interview
Write a brute-force seven-loop reference that transcribes the formula literally and compare with np.allclose on random inputs:
x = np.random.randn(2, 3, 8, 8).astype(np.float32)
w = np.random.randn(4, 3, 2, 3).astype(np.float32)
b = np.random.randn(4).astype(np.float32)
out = conv2d_forward(x, w, b, stride=(2, 1), padding=(1, 0))
# compare against reference or PyTorch F.conv2d
assert out.shape == (2, 4, 5, 8)
Also check the shape example from the prompt:
assert conv2d_forward(np.random.randn(1,3,32,32),
np.random.randn(8,3,3,3), None, 1, 1).shape == (1,8,32,32)
Common mistakes
- Flipping the kernel — that gives true mathematical convolution, not cross-correlation.
- Padding the batch or channel axes — only the spatial dims
(H, W)get padded. - Off-by-one in the slice end —
u + s_h*H_outovershoots or returns the wrong count; useu + s_h*(H_out-1) + 1. - Wrong bias broadcast axis —
b[:, None, None]adds along the batch axis; useb[None, :, None, None]. - Integer division — use
//not/for the output size formula. - Accumulating into an int array — always promote to float before the accumulation loop.