BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Optimization challenges5 of 14 in topic

876. Fast 2D valid convolution

MediumOptimization challenges Pro

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.

Functiondef 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

  • kernel has 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).
Topics
Optimization challenges
Similar questions
  • Vectorise pairwise Euclidean distancesMedium
  • Group-by mean without a Python loopMedium
  • Top-k indices for every rowMedium
  • IoU matrix for two sets of boxesMedium
All Optimization challenges problems
Report
876 / 903
Python 3solution.pyPython idle
1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np
​
def conv2d_valid(img, kernel):
img = np.asarray(img, dtype=float)
k = np.asarray(kernel, dtype=float)
kh, kw = k.shape
H, W = img.shape
out = np.zeros((H - kh + 1, W - kw + 1))
for i in range(H - kh + 1):
for j in range(W - kw + 1):
out[i, j] = np.sum(img[i:i + kh, j:j + kw] * k)
return out
​

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS