852. Primer causal depthwise convolution
Why it matters Short causal convolutions are back in Mamba, Hyena and many linear-attention models. Getting the direction of the kernel and the causal padding right is the whole exercise.
Paper: "Primer: Searching for Efficient Transformers for Language Modeling", So, Manke, Liu, Dai, Shazeer and Le, 2021, arXiv 2109.08668.
Primer found two changes that make Transformers train faster: squared ReLU in the feed-forward block, and a depthwise convolution of width 3 along the sequence after each Q, K and V projection. The convolution must be causal: position t may only see t, t-1 and t-2.
Write primer_dconv(x, kernel).
Inputs:
- x: a list or ndarray of shape (T, C): T positions, C channels.
- kernel: a list or ndarray of shape (3, C). kernel[0] multiplies the current position, kernel[1] the previous one and kernel[2] the one before that. Each channel has its own weights (depthwise, no mixing across channels).
- Positions before 0 count as zeros.
So y[t, c] = kernel[0, c] * x[t, c] + kernel[1, c] * x[t - 1, c] + kernel[2, c] * x[t - 2, c].
Return an ndarray of floats with shape (T, C). No rounding.
def primer_dconv(x, kernel)Example 1
Input: primer_dconv([[1.0], [2.0], [3.0], [4.0]], [[1.0], [0.5], [0.25]])
Output: [[1.0], [2.5], [4.25], [6.0]]
Example 2
Input: x = [[1.0, 10.0], [0.0, 0.0], [0.0, 0.0]], kernel = [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]
Output: [[1.0, 20.0], [3.0, 40.0], [5.0, 60.0]]
Constraints
- Python 3 with NumPy. Code runs in your browser.
- Run checks the sample tests. Submit checks the full hidden test set (Pro).
Hint 1
Pad two rows of zeros on top of x.
Hint 2
Shifted slices pad[2:], pad[1:-1], pad[:-2] line up with current, previous and the one before.
Hint 3
Broadcast each kernel row over the time axis.
Common mistakes
- Padding on both sides, which leaks future tokens.
- Reversing the kernel so
kernel[0]hits t - 2. - Mixing channels with a matrix multiply.
Understand the idea
A causal conv pads on the left only, so no output looks into the future. With x = [1, 2, 3, 4] and kernel [1, 0.5, 0.25], output 3 is 4 + 0.5 * 3 + 0.25 * 2 = 6.0. An impulse at t = 0 shows the kernel itself as the outputs move forward in time.
Shapes and data flow
x: (T, C). kernel: (3, C). Output: (T, C).