18.1 Convolution as a linear map
Every vision tower starts with a convolution. A ViT’s patch embedding is a convolution whose kernel equals its stride, and Whisper’s encoder starts with two 1-D convolutions over the log-mel frames. To build Conv2d on an autograd engine you need more than the definition: a Python loop over output pixels is far too slow, and a vectorized version needs im2col for the forward pass and col2im for the backward pass. The details are unforgiving. Get the output size wrong and the Whisper stem hands 1501 positions to an encoder whose position table has 1500; get the row order of im2col wrong and the weights multiply the wrong pixels while every shape still lines up.
Concepts from other sections (9)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- patch embedding: a convolution with kernel equal to stride, equivalent to one linear map applied to each flattened patch. Read more: 14.3 Vision transformer encoder in AI Engineering
- Log-mel: Whisper’s features, of the mel spectrogram with a floor, an 8-unit clip, and the map . Read more: 18.6 Mel scale and filterbanks
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3
- Linear map: a function between vector spaces with ; once bases are chosen, every linear map is a matrix. Read more: Chapter 9: Linear Algebra
- Jacobian: the matrix of partial derivatives of a function . Read more: 10.2 Jacobians, the multivariable chain rule, and numeric JVP/VJP
- Vector-Jacobian product (VJP): , one step of reverse-mode differentiation. Read more: 10.3 Calculus 3 problem set: vectors, gradients, the chain rule, Hessians, multiple integrals, Lagrange
- receptive field: the region of the input that a given neuron depends on, which grows with depth. Read more: Chapter 3: Neural Architectures and Their History in AI Engineering
- Upstream gradient: , the gradient arriving at an op’s output. Read more: 14.3 Matrix differentials, the trace trick, and closed-form VJPs
- Inner product: . Read more: 9.6 Inner products, projections, cosine similarity, and top-k
This section builds convolution up from a sliding dot product to a matrix, then to im2col and col2im, and finally to the backward pass. It leans on two ideas from earlier chapters: that a linear map is a matrix and its adjoint is the transpose (see Gaussian elimination and LU with partial pivoting and Orthogonality, Householder QR, and orthogonal initialization), and that a backward pass multiplies by a transposed Jacobian (Scalar reverse mode: the Value graph). It is also worth glancing at the naive loop in ml/06-neural-architectures/code/conv2d.c from AI Engineering before you start; this section explains why that loop is correct and how to make it fast.
The reference implementation is python/tinyllm/sig/conv.py, with its interface in course/contracts/py/tinyllm/sig/conv.pyi. It provides conv_out_size, conv1d_direct and conv2d_direct (with stride, padding, dilation, and groups), correlate_vs_convolve, im2col and its adjoint col2im, and conv_matrix, the doubly block Toeplitz form. As you read, try to predict each step before you see it.
Learning objectives
- Distinguish deep learning’s convolution (cross-correlation) from signal processing’s, and convert one into the other.
- Compute the output size of any convolution from , , , , and , and explain how groups split channels.
- Write a convolution as a doubly block Toeplitz matrix and as one im2col matmul, with the correct row order.
- Explain why col2im, the adjoint of im2col, adds where windows overlap, and use the pair to derive a convolution’s backward pass.
Notation
Section titled “Notation”The symbols used throughout the section are collected here.
| Symbol | Meaning | Type / shape |
|---|---|---|
| input batch, NCHW (2-D) or NCL (1-D) | float64[N, C, H, W] | |
| weights, KCRS (2-D) or KCR (1-D) | float64[K, C/g, R, S] | |
| bias, one per output channel | float64[K] | |
| , , | stride, zero padding, dilation (per axis) | ints |
| groups: channels split into independent convs | int | |
| , | output height and width | ints |
| row-major flattening | ||
| doubly block Toeplitz matrix of a single-channel conv | float64[P*Q, H*W] |
Correlation and convolution
Section titled “Correlation and convolution”The cross-correlation of an image with a kernel slides over and takes a dot product at each position: Signal processing’s convolution flips the kernel first, , which is the same as correlating with rotated by 180 degrees. Flipping is what makes convolution commutative and makes the convolution theorem (see DFT and FFT) hold.
A learned kernel does not care: whatever it would learn flipped, it learns unflipped. So every framework computes the correlation and calls it a convolution, and conv2d_direct does the same. correlate_vs_convolve returns both to make the difference visible: on one row the true convolution is exactly numpy.convolve(..., 'valid').
Output size, stride, padding, dilation, and groups
Section titled “Output size, stride, padding, dilation, and groups”Once you know what each output computes, the next question is how many outputs there are. A kernel of size with dilation places its taps samples apart, so it spans input samples. Padding adds zeros at each end, and a stride moves the window samples per output. The first window starts at 0; the last must end inside the padded input. The number of outputs is Output position , tap reads padded index , which is input index .
Groups split the input channels into blocks of and the output channels into blocks of ; output channel only sees input block . That is why the weight’s second axis is , not . Depthwise convolution is . Whisper’s stem uses , , which keeps 3000 frames at and halves them to 1500 at .
A convolution is a matrix
Section titled “A convolution is a matrix”Each output is a fixed linear combination of inputs, so for a single-channel image there is a matrix with . Row of holds the kernel’s taps in the columns of the pixels that window touches, and zeros elsewhere. Each block of rows repeats the same pattern shifted by one column (Toeplitz), and the blocks repeat shifted by one image row (block Toeplitz), hence “doubly block Toeplitz”. Taps that land in the zero padding have no column.
conv_matrix builds explicitly. It is , mostly zeros, and only for understanding. The forward pass is ; the backward pass with respect to is , because a vector-Jacobian product is a multiplication by the transposed Jacobian.
im2col and col2im
Section titled “im2col and col2im”The Toeplitz matrix is the right picture but the wrong computation. The practical form keeps the matrix structure but moves it to the data. im2col copies every receptive field of into a column: row index , column index , shape . Flattening the weights in the same order gives , and one large matmul that BLAS runs at full speed. The row order matters: any other order still produces the right shapes, but pairs each weight with the wrong pixel.
im2col is a linear map that copies. Its adjoint, col2im, sends every column entry back to the pixel it came from and adds where windows overlap. Adjoint means for all . With stride smaller than the kernel, a pixel sits in several windows; assigning instead of adding loses all but the last contribution.
The gradient of a convolution is a convolution
Section titled “The gradient of a convolution is a convolution”The im2col form makes the backward pass a matter of matrix calculus. With where and upstream gradient (shaped like ), the rules of Matrix differentials, the trace trick, and closed-form VJPs give The weight gradient is a correlation of the input with the upstream gradient, and the input gradient is a “transposed convolution” of the upstream gradient with the weights: both are convolutions again. Conv layers and pooling on autograd in AI Engineering implements Conv2d’s backward exactly this way.
Working it by hand
Section titled “Working it by hand”Take this image and kernel:
The output is on each axis (conv_out_size(4, 2) = 3). The correlation is , which fills this table:
The flipped kernel is , so the true convolution is : exactly the negative of the table. In im2col form, column of im2col(x, 2, 2) is the window in order, and gives , the same entry.
Designing the interface
Section titled “Designing the interface”The module exposes five core functions (plus conv1d_direct, the 1-D twin of conv2d_direct, and correlate_vs_convolve):
def conv_out_size(n, k, stride=1, pad=0, dilation=1) -> int: ...def conv2d_direct(x, w, b, stride=(1, 1), pad=(0, 0), dilation=(1, 1), groups=1) -> NDArray: ...def im2col(x, kh, kw, stride=(1, 1), pad=(0, 0), dilation=(1, 1)) -> NDArray: # [N, C*kh*kw, P*Q]def col2im(cols, x_shape, kh, kw, stride=(1, 1), pad=(0, 0), dilation=(1, 1)) -> NDArray: # adjoint, sums overlapsdef conv_matrix(in_shape, w, stride=(1, 1), pad=(0, 0)) -> NDArray: # T with vec(y) = T vec(x)conv_out_size is the single owner of the size formula, and everything else calls it. The forward functions follow PyTorch’s conventions (NCHW input, KCRS weights, symmetric padding, no kernel flip) so that their outputs can be compared to F.conv2d and F.conv1d value for value. im2col and col2im follow the layout of F.unfold and F.fold. Shapes that do not fit are rejected with an error rather than producing a silently wrong array, and inputs are never modified.
Building it step by step
Section titled “Building it step by step”The design follows from a chain of small decisions, each forced by the one before.
- Size first, because everything else indexes into it. Every function needs and before it can allocate, so one function,
conv_out_size, owns the formula, and every other function calls it. An oversized kernel is an error, not an empty output, while an exact fit (span equal to the padded input) is one output. - Pad once, then forget about padding. Zero-padding the input by on each side turns “input index ” into “padded index ”, so no inner loop needs a bounds check. Symmetric padding is what PyTorch does.
- Loop over taps, not over outputs. For a fixed tap , the pixels read by all outputs form a strided slice of the padded input: rows (exactly of them) and likewise for columns. So the conv is slice-and-accumulate steps, each a small matrix product over channels, instead of Python iterations. This is the same loop that im2col uses to fill its columns, which is why the two agree.
- Groups are independent convs on channel blocks. Group reads input channels and writes output channels . Slicing both and running the ungrouped computation per group is the definition; both and must be divisible by and the weight’s second axis must be .
- No flip. The direct conv reads with weight , the same index direction for both, which is correlation. True convolution is that same function applied to
w[::-1, ::-1]. - im2col is the tap loop with storage. Instead of multiplying each tap’s slice by the weights immediately, store it at row : the result is a
[N, C, R, S, P, Q]array, reshaped to[N, CRS, PQ]. Row-major reshaping makes the row index , the same order in which a[K, C, R, S]weight flattens to[K, CRS]. - col2im is the transpose of a copy, so it adds. im2col copies pixel into every column entry whose window contains it. The transpose of “copy to positions ” is “sum the entries at back into ”. So col2im is the same tap loop with
+=in place of=, followed by cropping the padding away (gradients that land in padding belong to no pixel). - The Toeplitz matrix is the same index map written into a matrix. Row , tap reads input pixel ; if it is inside the image, put at that pixel’s column. Taps in the padding have no column, because the padding is zeros.
In the listings below, signatures are shortened (type hints dropped) and argument validation is elided as ...; the bodies are as in the solution.
Start with the size formula and its two validity conditions:
def conv_out_size(n, k, stride=1, pad=0, dilation=1) -> int: if n < 1 or k < 1 or stride < 1 or dilation < 1 or pad < 0: raise ValueError(...) # A dilated kernel spans d (k - 1) + 1 input samples; the first window # starts at 0 and the last one must end inside the padded input. span = dilation * (k - 1) + 1 if n + 2 * pad < span: # "<", not "<=": an exact fit gives one output raise ValueError(...) return (n + 2 * pad - span) // stride + 1 # the "+1" counts the first windowWritten with span, the formula is , the same as the one derived earlier. Check it against Whisper’s stem: , , , gives .
The direct 2-D conv pads once, then for each group and each tap takes one strided slice and one einsum:
def conv2d_direct(x, w, b, stride=(1, 1), pad=(0, 0), dilation=(1, 1), groups=1): # ... validate ndim, normalize stride/pad/dilation to pairs ... n, c, h, wd = x.shape kout, cg, r, s = w.shape _check_groups(c, kout, cg, groups, "conv2d_direct") # g | C, g | K, cg == C/g p = conv_out_size(h, r, sh, ph, dh) q = conv_out_size(wd, s, sw, pw, dw) xp = np.pad(x, ((0, 0), (0, 0), (ph, ph), (pw, pw))) # same p on both sides kg = kout // groups y = np.zeros((n, kout, p, q)) for g in range(groups): xg = xp[:, g * cg : (g + 1) * cg] # this group's input channels wg = w[g * kg : (g + 1) * kg] # this group's output channels for i in range(r): for j in range(s): # Every output (op, oq) reads padded pixel (op*sh + i*dh, oq*sw + j*dw) # for tap (i, j): one strided slice with exactly P rows and Q columns. seg = xg[ :, :, i * dh : i * dh + sh * (p - 1) + 1 : sh, j * dw : j * dw + sw * (q - 1) + 1 : sw, ] # [N, C/g, P, Q] # Contract over input channels: y[n,k,p,q] += w[k,c,i,j] * seg[n,c,p,q]. y[:, g * kg : (g + 1) * kg] += np.einsum( "kc,ncpq->nkpq", wg[:, :, i, j], seg ) if b is not None: y += np.asarray(b, dtype=np.float64)[None, :, None, None] # one bias per output channel return yThe slice end start + s * (P - 1) + 1 is the index just past the last pixel the last output reads, so the slice has exactly elements whatever the remainder in the size formula. conv1d_direct is the same code with one spatial axis.
im2col stores those same slices instead of contracting them:
def im2col(x, kh, kw, stride=(1, 1), pad=(0, 0), dilation=(1, 1)): # ... validate, normalize pairs ... p = conv_out_size(h, kh, sh, ph, dh) q = conv_out_size(w, kw, sw, pw, dw) xp = np.pad(x, ((0, 0), (0, 0), (ph, ph), (pw, pw))) cols = np.empty((n, c, kh, kw, p, q)) for i in range(kh): for j in range(kw): cols[:, :, i, j] = xp[ # the same strided slice as conv2d_direct :, :, i * dh : i * dh + sh * (p - 1) + 1 : sh, j * dw : j * dw + sw * (q - 1) + 1 : sw, ] # Rows ordered (c, r, s), columns (p, q): the layout of F.unfold, and the # order in which a KCRS weight flattens to [K, C*R*S]. return cols.reshape(n, c * kh * kw, p * q)With it, an ungrouped conv is w.reshape(K, -1) @ im2col(x, R, S) (a [K, CRS] matrix times [N, CRS, PQ], broadcast over ), reshaped to [N, K, P, Q]. That product agrees with conv2d_direct and with the Toeplitz matrix, three views of one map.
col2im is the same loop with the arrow reversed and +=:
def col2im(cols, x_shape, kh, kw, stride=(1, 1), pad=(0, 0), dilation=(1, 1)): # ... normalize pairs, compute p and q from x_shape ... if cols.shape != (n, c * kh * kw, p * q): raise ValueError(...) blocks = cols.reshape(n, c, kh, kw, p, q) # undo im2col's reshape xp = np.zeros((n, c, h + 2 * ph, w + 2 * pw)) # accumulate into the padded frame for i in range(kh): for j in range(kw): # Add, never assign: overlapping windows each send their share # back to the same pixel (the adjoint of a copy is a sum). xp[ :, :, i * dh : i * dh + sh * (p - 1) + 1 : sh, j * dw : j * dw + sw * (q - 1) + 1 : sw, ] += blocks[:, :, i, j] # Contributions that landed in the padding belong to no input pixel. return xp[:, :, ph : ph + h, pw : pw + w].copy()Within one +=, the strided slice never hits the same pixel twice (consecutive outputs are apart), so NumPy’s buffered += is safe; overlaps come from different taps , which are separate statements.
Finally, the Toeplitz matrix writes one entry per (output, tap) pair inside the image:
def conv_matrix(in_shape, w, stride=(1, 1), pad=(0, 0)): # ... validate, normalize pairs ... t = np.zeros((p * q, h * wd)) for op in range(p): for oq in range(q): row = op * q + oq # row-major vec(y) for i in range(r): for j in range(s): a, bcol = op * sh + i - ph, oq * sw + j - pw # unpadded input index # Taps that land in the zero padding have no column. if 0 <= a < h and 0 <= bcol < wd: t[row, a * wd + bcol] = w[i, j] # row-major vec(x) return tHere the padding offset is explicit because there is no padded array: the matrix acts on the original image.
The full solution is conv.py.
Why this design
Section titled “Why this design”The direct conv does multiply-adds, the minimum for a direct method, but in vectorized steps rather than a Python loop per output. A loop over output pixels is Python iterations (2.25 million for a 1500x1500 output); a loop over taps is (9 for a 3x3 kernel). Both compute the same sums; only the second is fast in NumPy.
im2col uses times the input’s memory, because each pixel is copied once per window it appears in. That is the price of turning the conv into one BLAS matmul, and the reason production libraries use implicit GEMM, which never materializes the columns.
conv_matrix exists but is never used for compute. is , quadratic in image size and almost all zeros. It exists to make “a conv is a linear map” concrete and to check the other two forms against it, and it gives the backward pass for free in theory: .
There is no separate transposed-conv routine because the adjoint of im2col is exactly what the input gradient needs (). One pair of functions covers forward and backward, and their adjointness is a property one inner product can check.
The tradeoff accepted is speed: everything is float64 and single-threaded. The point is to get the index map right once, so that the autograd layers in AI Engineering can build on it.
What can go wrong
Section titled “What can go wrong”A correct implementation has to survive a specific set of checks. It must reproduce the hand-worked correlation above and its negated convolution, so everyone agrees on “no flip”. The output-size function must get the Whisper stem, the ViT patch conv, dilation, and an exact fit right, and reject bad arguments, since every vision and speech layer sizes itself with it. conv2d_direct must match PyTorch’s F.conv2d on a plain case, a strided and dilated case with groups, a depthwise case, and a patch embedding; conv1d_direct must match F.conv1d on three cases including Whisper’s stride-2 stem. im2col must equal F.unfold and col2im must equal F.fold, which pins down row order and summed overlaps. The direct loop, the grouped im2col matmul, and the Toeplitz matrix must agree with each other. The gradients dW, dx, and db computed from im2col and col2im must equal PyTorch’s autograd. The adjoint identity must hold with overlapping windows, and correlating with a flipped kernel must give the convolution, with one row equal to numpy.convolve. Finally, shapes that do not fit (groups that do not divide, the wrong channel count, an oversized kernel, wrong cols) must be rejected, with inputs untouched, so model-definition bugs fail loudly.
The bugs these checks catch are worth knowing by symptom. The table pairs each with how the solution avoids it.
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
| flipping the kernel (true convolution) | every output differs from PyTorch; pretrained weights give garbage | reads x[o*s + r*d] with w[r], same direction; only correlate_vs_convolve flips (step 5) |
| leaving dilation out of the kernel span | dilated layers get too many outputs | span = dilation * (k - 1) + 1 in conv_out_size |
| col2im assigning instead of adding | wrong input gradients wherever windows overlap | xp[...] += blocks[:, :, i, j] (step 7) |
| im2col rows in order | shapes fine, values wrong for | builds [N, C, R, S, P, Q] and reshapes, giving rows (step 6) |
| every group reading the first group’s channels | grouped and depthwise convs wrong | slices xp[:, g*cg:(g+1)*cg] and w[g*kg:(g+1)*kg] per group |
| all the padding on one side | outputs shifted by | np.pad(..., (ph, ph), (pw, pw)), symmetric |
| Toeplitz columns without the padding offset | shifted against the direct conv | conv_matrix uses op*sh + i - ph (step 8) |
| dropping the in the size formula | one output too few everywhere | (n + 2*pad - span) // stride + 1 |
| rejecting an exact fit | a kernel as large as the input raises | raises only when n + 2*pad < span |
| not checking that groups divide the output channels | silent zero channels | _check_groups tests c % groups, kout % groups, and cg == c // groups |
Warning: The im2col row-order bug is invisible to shape checks. Only a value comparison, against
F.unfoldor the direct conv, catches it.
Where this leads
Section titled “Where this leads”Within this chapter, Resampling and interpolation applies its sinc filter bank in resample_audio as one strided conv1d_direct, and the problem set works output sizes, receptive fields, the Toeplitz form, and the adjoint by hand. In AI Engineering, Conv layers and pooling on autograd builds Conv2d, Conv1d, and pooling with im2col forward and col2im backward; the Vision transformer encoder uses a PatchEmbed that is a conv with kernel equal to stride; and the Whisper encoder sizes its stem’s output with conv_out_size.
Each piece of the solution has a production counterpart that adds speed or generality:
| Solution piece | Production equivalent | What it adds | Where to look |
|---|---|---|---|
im2col + matmul | PyTorch aten/src/ATen/native/ConvolutionMM2d.cpp (slow_conv2d) | the same unfold-then-GEMM path, threaded, for CPU fallbacks | slow_conv2d_forward_out_cpu |
conv2d_direct | oneDNN / cuDNN | Winograd and FFT algorithms, implicit GEMM without materializing columns, autotuning per shape | cuDNN cudnnFindConvolutionForwardAlgorithm |
col2im | F.fold / conv_transpose2d | the adjoint as a first-class layer (upsampling in decoders) | aten/src/ATen/native/Col2Im.cpp |
the C loop in conv2d.c | an optional C kernel | im2col in C with a blocked matmul, benchmarked against the naive loop | c/src/kernels/conv.c |
Further reading
Section titled “Further reading”- Dumoulin and Visin, “A guide to convolution arithmetic for deep learning” (2016, free).
- Chellapilla, Puri, Simard, “High performance convolutional neural networks for document processing” (2006), the im2col paper.
- Goodfellow, Bengio, Courville, Deep Learning, ch. 9 (free).
Key terms
Section titled “Key terms”- Cross-correlation: sliding a kernel over a signal and taking a dot product at each position, with no flip; what deep learning calls convolution.
- Dilation: spacing a kernel’s taps samples apart, so a size- kernel spans samples.
- Groups: splitting input and output channels into blocks that are convolved independently; is depthwise convolution.
- Doubly block Toeplitz matrix: the matrix of a 2-D convolution, with .
- im2col: copying every receptive field into a column, ordered , so a convolution becomes one matmul.
- col2im: the adjoint of im2col, which sums column entries back into the pixels they came from.
Summary
Section titled “Summary”- A deep-learning “convolution” is a cross-correlation: no kernel flip. Flipping the kernel gives the true convolution of signal processing.
- One formula sizes every conv output: .
- A conv is linear, so it is a matrix: the doubly block Toeplitz with . im2col turns it into one matmul with the flattened weights.
- col2im is the adjoint of im2col (it sums overlapping windows), so the backward pass of a conv is built from the same two functions.
- Looping over taps instead of outputs makes the NumPy version fast; the Toeplitz matrix is for understanding and checking only.
Review questions
Section titled “Review questions”- Why is the weight’s second axis and not ?
Answer
Each output channel only sees the input channels of its own group, and a group has $C/g$ of them. Storing $C$ would mean weights for channels the output never reads. For depthwise convolution ($g = C$) the axis is 1. - Why does col2im add where im2col copies?
Answer
im2col is a linear map that copies each pixel into every window containing it. Its transpose sends each column entry back to its pixel, and when a pixel was copied to several places, the transpose sums all of their contributions. That is what $\langle \operatorname{im2col}(x), y\rangle = \langle x, \operatorname{col2im}(y)\rangle$ requires, and it is the input gradient of a conv. Assigning keeps only the last window's contribution. - What goes wrong, visibly and invisibly, if im2col’s rows are ordered ?
Answer
Visibly, nothing: the shape is still `[N, CRS, PQ]` and the matmul with `w.reshape(K, -1)` runs. Invisibly, the weights flatten in $(c, r, s)$ order, so for $C > 1$ weight $(c, r, s)$ multiplies the pixel of some other channel and tap. Only a value check (against `F.unfold` or the direct conv) catches it. - Why does
conv_matrixsubtract the padding whileconv2d_directdoes not?Answer
`conv2d_direct` works on an explicitly padded copy of the input, so padded index $os + rd$ is directly usable. `conv_matrix` acts on the unpadded image (its columns are the original $HW$ pixels), so it converts to the input index $os + rd - p$ and drops taps that land outside, where the padding's zeros contribute nothing. - With , , and instead of 1, how many frames does Whisper’s stem produce, and why does it matter?
Answer
$\lfloor (3000 - 3)/2 \rfloor + 1 = 1499$, one short of the 1500 positions the encoder's positional table expects; the stem's $p = 1$ gives exactly 1500. An off-by-one here makes the shapes disagree downstream (or silently drops a frame if the code slices to fit).