Skip to content

← CNNs from Scratch step 1 of 15

Hard Primitives

Implement 1D Convolution

A 1D cross-correlation slides a short weight vector (the kernel) along an input vector. At each position, multiply matching entries, sum the products, and add a bias. Keep the kernel in its given order; do not flip it.

For x = [1, 2, 3, 4, 5], weight = [2, -1], bias = 0.5, and stride = 2, the windows start at indices 0 and 2:

  • [1, 2] gives 1*2 + 2*(-1) + 0.5 = 0.5.
  • [3, 4] gives 3*2 + 4*(-1) + 0.5 = 2.5.

The output is [0.5, 2.5]. A window starting at index 4 would extend past the input, so it is omitted. Stride sets the distance between window starts; it does not skip entries inside a window.

Your task

Implement conv1d(x, weight, bias, stride=1):

  • x has shape (L,) and weight has shape (K,), with 1 <= K <= L. They have matching floating-point dtypes and devices.
  • bias is a Python float added once to each output element.
  • stride is a positive integer. There is no padding or dilation.
  • Return a tensor of shape ((L - K) // stride + 1,).

For output index i, use the window beginning at i * stride. In formula form, output[i] = sum(x[i * stride + k] * weight[k] for k in range(K)) + bias. Use basic tensor operations rather than a built-in convolution operation.

The diagram shows one-dimensional window positions rather than numerical products. Keep padding at 0 and dilation at 1 to match this exercise.

Loading visualization…