I knew the math well enough but translating it into clean indexing code under pressure is a different thing.
First, clarify the input dimensions and parameters, then derive the output shape using the convolution formula. Implement the forward pass using nested loops over batch, output channels, output height, and output width, computing the dot product between the input patch and the filter, adding bias if present. Emphasize correctness and efficiency considerations like vectorization or im2col.
Pro tip: Mention that you would validate the implementation against a known library (e.g., PyTorch) on small random inputs to catch off-by-one errors in padding and stride. Also, discuss how to handle edge cases like non-divisible strides or asymmetric padding.
Confirm the input tensor shape (N, C, H, W), filter shape (K, C, R, S), stride, padding, and bias. Compute the output dimensions using H_out = floor((H + 2*pad - R)/stride) + 1 and similarly for W_out.
Create an output tensor of shape (N, K, H_out, W_out) filled with zeros. If bias is provided, initialize each output channel with the corresponding bias value.
Loop over batch (n), output channel (k), output row (i), and output column (j). For each output position, compute the sum over input channels (c) and filter rows/cols (r, s) of input[n, c, i*stride + r - pad, j*stride + s - pad] * weight[k, c, r, s], handling out-of-bounds as zero.
After the inner loops, add the bias (if any) to the accumulated sum and assign it to output[n, k, i, j].
Discuss potential optimizations like im2col or vectorization, and validate correctness by comparing with a deep learning library on small random inputs.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.