876. Fast 2D valid convolution
Why it matters Convolutions are the core of CNNs. Writing one fast without a framework shows you understand im2col and strides.
conv2d_valid(img, kernel) computes a single-channel 2D cross-correlation (what deep learning calls convolution) with no padding and stride 1: out[i, j] = sum(img[i : i + kh, j : j + kw] * kernel).
Inputs: img is a list or ndarray of shape (H, W), kernel of shape (kh, kw) with kh <= H and kw <= W.
Return an ndarray of floats with shape (H - kh + 1, W - kw + 1). No rounding. np.lib.stride_tricks.sliding_window_view is available.
The starter is a correct but slow Python loop. Make it fast. The small tests check correctness. The last test runs your function on a large input and reports "fast enough" only if the call takes at most 20 times as long as a fixed 200,000-step pure Python loop on the same device. The test times both with time.perf_counter (input generation included), so the limit scales with your device and browser, and a call that is just over the limit is measured once more. Vectorised NumPy finishes far below the limit; the starter loop takes several times longer.
def conv2d_valid(img, kernel)Example 1
Input: conv2d_valid([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]], [[1.0, 0.0], [0.0, -1.0]])
Output: [[-4.0, -4.0], [-4.0, -4.0]]
Example 2
Input: img = [[1.0, 2.0], [3.0, 4.0]], kernel = [[1.0, 1.0], [1.0, 1.0]]
Output: [[10.0]]
Constraints
kernelhas shape(kh, kw)- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
sliding_window_view(img, kernel.shape) gives all patches.
Hint 2
einsum('ijkl,kl->ij', windows, kernel) does the multiply and sum.
Hint 3
Alternatively loop over the kh * kw kernel entries and add shifted slices: only 9 iterations for 3 x 3.
Common mistakes
- Flipping the kernel (that is true convolution, not what the spec asks).
- Padding the image.
- Copying all patches into a big array before multiplying (works but uses more memory).
Understand the idea
sliding_window_view gives a read-only (H', W', kh, kw) view of every patch without copying. einsum then multiplies each patch by the kernel and sums the last two axes. Frameworks use the same idea under the name im2col, turning convolution into one big matrix multiply.
Shapes and data flow
img: (H, W). windows: (H - kh + 1, W - kw + 1, kh, kw). Output: (H - kh + 1, W - kw + 1).