CD0046 Conv2d Forward Pass

Mode B · Build & Trace 30 Min NumPy + PyTorch Oracle 4 Shape Blanks

Tesla’s Autopilot vision stack pushes every camera frame through convolutional backbones before any lane, object, or occupancy head sees it, so engineers on that team are expected to know exactly what one convolution layer computes. This screen (reported by candidates from Tesla’s Autopilot coding loop and repeated in academic and quant-firm prep lists) strips the layer down to NumPy: implement the forward pass of a single 2D convolution, conv2d_forward, with no deep learning framework inside the function.

The input volume has shape (N, C_{in}, H, W), the kernel stack has shape (C_{out}, C_{in}, K_H, K_W), the bias has one entry per output channel, and stride and padding are integers applied to both spatial axes. The output must be (N, C_{out}, H_{out}, W_{out}) using the standard floor formula for the spatial size. The interviewer accepts loops or im2col; the skeleton below takes the explicit window loop. Shapes must be exactly right for stride 2 and asymmetric kernels, and the bias must broadcast on the output-channel axis.

Fill the 4 blanks in the skeleton and narrate the tensor shape after each one. Your result must match torch.nn.functional.conv2d in float64 at rtol=1e-10 on three fixtures: stride 1 with padding 0, stride 2 with padding 1, and a 3×5 kernel. It must also return the caller’s dtype.

Skeleton Code (Fill Blanks 1-4):

01  import numpy as np
02
03
04  def conv2d_forward(x, weight, bias=None, stride=1, padding=0):
05      """Forward pass of one 2D convolution layer (cross-correlation).
06
07      x:       (N, C_in, H, W)        input volume
08      weight:  (C_out, C_in, KH, KW)  kernel stack, KH may differ from KW
09      bias:    (C_out,) or None       one scalar per output channel
10      stride:  int >= 1, same step on both spatial axes
11      padding: int >= 0, zeros on every spatial border
12      returns  (N, C_out, H_out, W_out) in the dtype of x
13      """
14      N, C_in, H, W = x.shape
15      C_out, C_in_k, KH, KW = weight.shape
16      if C_in != C_in_k:
17          raise ValueError(f"x has {C_in} channels, weight expects {C_in_k}")
18      if stride < 1 or padding < 0:
19          raise ValueError("stride must be >= 1 and padding >= 0")
20      if bias is None:
21          bias = np.zeros(C_out)
22      if bias.shape != (C_out,):
23          raise ValueError(f"bias must have shape ({C_out},)")
24
25      # TODO (Blank 1): output spatial size and zero padding
26      #   H_out, W_out: ints from the floor formula; ValueError if either < 1
27      #   x_padded: (N, C_in, H + 2*padding, W + 2*padding)
28      H_out = ...
29      W_out = ...
30      x_padded = ...
31
32      # One (N, C_out) slab per output position, stored position-major
33      # so each slab write is contiguous; collected in float64.
34      slabs = np.zeros((H_out, W_out, N, C_out), dtype=np.float64)
35
36      for i in range(H_out):              # output row
37          for j in range(W_out):          # output column
38              # TODO (Blank 2): receptive field of output position (i, j)
39              #   patch: (N, C_in, KH, KW) window of x_padded
40              patch = ...
41              # TODO (Blank 3): contract patch with every kernel, add bias
42              #   slabs[i, j]: (N, C_out), bias on the C_out axis
43              slabs[i, j] = ...
44
45      # TODO (Blank 4): return contract
46      #   out: (N, C_out, H_out, W_out), H_out before W_out, dtype of x
47      out = ...
48      return out
49
50
51  if __name__ == "__main__":
52      rng = np.random.default_rng(0)
53      x = rng.standard_normal((2, 3, 8, 11))
54      weight = rng.standard_normal((5, 3, 3, 5))
55      bias = rng.standard_normal(5)
56      y = conv2d_forward(x, weight, bias, stride=2, padding=1)
57      print(y.shape, y.dtype)
Operator contract for a NumPy conv2d forward pass: the inputs x, weight, and bias flow through four question-marked steps (output size plus zero padding, the window loop, the per-window reduce plus bias, and the return contract) to an output of shape (N, C_out, H_out, W_out); below, boxes list the allowed NumPy tools, the required fixtures, and the PyTorch test oracle

Figure 1: the input and output contract is fixed, and the four layout-sensitive steps between them are yours to write in plain NumPy.

Interactive NumPy Workspace: Switch to the split-screen workspace to fill Blanks 1-4 in the live editor and run the PyTorch parity checks.

Open in Colab ↗
Progressive Hints (Free · Zero Spoilers)
1Inspection Checklist (Where to Look)

(1) Size and Padding Contract: Each output extent depends only on its own axis (rows with H and KH, columns with W and KW), must be an integer, and must be at least one. Of the four axes of x, only two are spatial.
(2) Window Origin: Once the stride is above one, the output index and the input index stop being the same number. Decide where window (i, j) starts in the padded frame and which kernel extent bounds the rows.
(3) Reduction and Bias Axes: Count which axes of the per-window product must vanish and which must survive, then check which axis a 1D bias attaches to under NumPy’s right-aligned broadcasting.
(4) Return Layout: slabs is stored position-major while the caller expects channel-major. A correct shape alone cannot distinguish a true axis reorder from a scrambled one, and the dtype is part of the contract.

2Visual Review Map (Figure 2)
Shape map for conv2d_forward: the top row goes from x (N, C_in, H, W) to x_padded, through the given loop over (i, j), to a patch of shape (N, C_in, KH, KW); the bottom row goes from a per-window slab of shape (N, C_out) into the given slabs buffer, then to out of shape (N, C_out, H_out, W_out); every operation the candidate writes is marked with a question mark

Figure 2: The shape trace a strong candidate narrates aloud. Every blank shows the target shape it must produce, and each “?” marks an operation you write.

3Interviewer Nudge & Line Focus

Pin the exact input and output shape of each blank before writing the NumPy op:

Blank 1 (Output Size + Padding): With H = 8, padding = 1, KH = 3, and stride = 2, how many window starts fit down the rows, and what happens to the leftover row? After padding, does x_padded.shape still begin with (N, C_in)?
Blank 2 (Window Slice): At stride 2, which padded column does the window for output column j = 1 start on? If the row slice accidentally uses KW, what shape does patch take for a 3×5 kernel, and would a square-kernel test ever notice?
Blank 3 (Reduce + Bias): patch is (N, C_in, KH, KW) and weight is (C_out, C_in, KH, KW). Where do singleton axes go so the product holds both N and C_out, which three axes do you sum, and if N == C_out, which bias expression would still run but add a bias per sample?
Blank 4 (Return Layout): slabs is (H_out, W_out, N, C_out). How can an operation produce exactly (N, C_out, H_out, W_out) and still put the wrong number in nearly every cell, and what dtype must come back for a float32 input?
Answer
Login to view more content
Log in to track your progress

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *