Skip to content

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.

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 nn, kk, ss, pp, and dd, and explain how groups split channels.
  • Write a convolution as a doubly block Toeplitz matrix and as one im2col matmul, with the correct (c,r,s)(c, r, s) row order.
  • Explain why col2im, the adjoint of im2col, adds where windows overlap, and use the pair to derive a convolution’s backward pass.

The symbols used throughout the section are collected here.

SymbolMeaningType / shape
xxinput batch, NCHW (2-D) or NCL (1-D)float64[N, C, H, W]
wwweights, KCRS (2-D) or KCR (1-D)float64[K, C/g, R, S]
bbbias, one per output channelfloat64[K]
ss, pp, ddstride, zero padding, dilation (per axis)ints
gggroups: channels split into gg independent convsint
PP, QQoutput height and widthints
vec⁡(⋅)\operatorname{vec}(\cdot)row-major flattening
TTdoubly block Toeplitz matrix of a single-channel convfloat64[P*Q, H*W]

The cross-correlation of an image xx with a kernel ww slides ww over xx and takes a dot product at each position: y[i,j]=∑r,sw[r,s] x[i+r,j+s].y[i, j] = \sum_{r, s} w[r, s]\, x[i + r, j + s]. Signal processing’s convolution flips the kernel first, y[i,j]=∑r,sw[r,s] x[i−r,j−s]y[i,j] = \sum_{r,s} w[r,s]\,x[i - r, j - s], which is the same as correlating with ww 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 kk with dilation dd places its taps dd samples apart, so it spans d(k−1)+1d(k-1) + 1 input samples. Padding adds pp zeros at each end, and a stride ss moves the window ss samples per output. The first window starts at 0; the last must end inside the padded input. The number of outputs is out=⌊n+2p−d(k−1)−1s⌋+1.\text{out} = \left\lfloor \frac{n + 2p - d(k - 1) - 1}{s} \right\rfloor + 1 . Output position oo, tap rr reads padded index os+rdo s + r d, which is input index os+rd−po s + r d - p.

Groups split the CC input channels into gg blocks of C/gC/g and the KK output channels into gg blocks of K/gK/g; output channel kk only sees input block ⌊k/(K/g)⌋\lfloor k / (K/g) \rfloor. That is why the weight’s second axis is C/gC/g, not CC. Depthwise convolution is g=Cg = C. Whisper’s stem uses k=3k = 3, p=1p = 1, which keeps 3000 frames at s=1s = 1 and halves them to 1500 at s=2s = 2.

Each output is a fixed linear combination of inputs, so for a single-channel image there is a matrix TT with vec⁡(y)=Tvec⁡(x)\operatorname{vec}(y) = T \operatorname{vec}(x). Row (p,q)(p, q) of TT 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 TT explicitly. It is PQ×HWPQ \times HW, mostly zeros, and only for understanding. The forward pass is TxT x; the backward pass with respect to xx is T⊤gT^\top g, because a vector-Jacobian product is a multiplication by the transposed Jacobian.

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 xx into a column: row index (c,r,s)(c, r, s), column index (p,q)(p, q), shape [N,CRS,PQ][N, C R S, P Q]. Flattening the weights in the same (c,r,s)(c, r, s) order gives Wflat∈RK×CRSW_{\text{flat}} \in \mathbb{R}^{K \times CRS}, and Y=Wflat⋅im2col⁡(x),Y∈RN×K×PQ,Y = W_{\text{flat}} \cdot \operatorname{im2col}(x), \qquad Y \in \mathbb{R}^{N \times K \times PQ}, 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 ⟨im2col⁡(x),y⟩=⟨x,col2im⁡(y)⟩\langle \operatorname{im2col}(x), y \rangle = \langle x, \operatorname{col2im}(y) \rangle for all x,yx, y. 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 Y=WflatXcY = W_{\text{flat}} X_c where Xc=im2col⁡(x)X_c = \operatorname{im2col}(x) and upstream gradient GG (shaped like YY), the rules of Matrix differentials, the trace trick, and closed-form VJPs give ∂L∂Wflat=∑nGnXc,n⊤,∂L∂x=col2im⁡(Wflat⊤G),∂L∂bk=∑n,p,qG[n,k,p,q].\frac{\partial L}{\partial W_{\text{flat}}} = \sum_n G_n X_{c,n}^\top, \qquad \frac{\partial L}{\partial x} = \operatorname{col2im}\Big(W_{\text{flat}}^\top G\Big), \qquad \frac{\partial L}{\partial b_k} = \sum_{n, p, q} G[n, k, p, q]. 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.

Take this image and kernel: x=(1201013121001012),w=(100−1).x = \begin{pmatrix} 1 & 2 & 0 & 1 \\ 0 & 1 & 3 & 1 \\ 2 & 1 & 0 & 0 \\ 1 & 0 & 1 & 2 \end{pmatrix}, \qquad w = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}. The output is 4−2+1=34 - 2 + 1 = 3 on each axis (conv_out_size(4, 2) = 3). The correlation is y[i,j]=x[i,j]−x[i+1,j+1]y[i, j] = x[i, j] - x[i+1, j+1], which fills this table:

j=0j = 0j=1j = 1j=2j = 2
i=0i = 01−1=01 - 1 = 02−3=−12 - 3 = -10−1=−10 - 1 = -1
i=1i = 10−1=−10 - 1 = -11−0=11 - 0 = 13−0=33 - 0 = 3
i=2i = 22−0=22 - 0 = 21−1=01 - 1 = 00−2=−20 - 2 = -2

The flipped kernel is (−1001)\begin{pmatrix} -1 & 0 \\ 0 & 1 \end{pmatrix}, so the true convolution is −x[i,j]+x[i+1,j+1]-x[i, j] + x[i+1, j+1]: exactly the negative of the table. In im2col form, column (0,1)(0, 1) of im2col(x, 2, 2) is the window (2,0,1,3)(2, 0, 1, 3) in (r,s)(r, s) order, and Wflat=(1,0,0,−1)W_{\text{flat}} = (1, 0, 0, -1) gives 2−3=−12 - 3 = -1, the same entry.

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 overlaps
def 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.

The design follows from a chain of small decisions, each forced by the one before.

  1. Size first, because everything else indexes into it. Every function needs PP and QQ 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.
  2. Pad once, then forget about padding. Zero-padding the input by pp on each side turns “input index os+rd−pos + rd - p” into “padded index os+rdos + rd”, so no inner loop needs a bounds check. Symmetric padding is what PyTorch does.
  3. Loop over taps, not over outputs. For a fixed tap (i,j)(i, j), the pixels read by all outputs form a strided slice of the padded input: rows idh,idh+sh,…i d_h, i d_h + s_h, \dots (exactly PP of them) and likewise for columns. So the conv is R⋅SR \cdot S slice-and-accumulate steps, each a small matrix product over channels, instead of P⋅QP \cdot Q Python iterations. This is the same loop that im2col uses to fill its columns, which is why the two agree.
  4. Groups are independent convs on channel blocks. Group gg reads input channels [gC/g,(g+1)C/g)[g C/g, (g+1) C/g) and writes output channels [gK/g,(g+1)K/g)[g K/g, (g+1) K/g). Slicing both and running the ungrouped computation per group is the definition; both CC and KK must be divisible by gg and the weight’s second axis must be C/gC/g.
  5. No flip. The direct conv reads x[os+rd]x[os + rd] with weight w[r]w[r], the same index direction for both, which is correlation. True convolution is that same function applied to w[::-1, ::-1].
  6. im2col is the tap loop with storage. Instead of multiplying each tap’s slice by the weights immediately, store it at row (c,i,j)(c, i, j): the result is a [N, C, R, S, P, Q] array, reshaped to [N, CRS, PQ]. Row-major reshaping makes the row index c⋅RS+i⋅S+jc \cdot RS + i \cdot S + j, the same order in which a [K, C, R, S] weight flattens to [K, CRS].
  7. col2im is the transpose of a copy, so it adds. im2col copies pixel xkx_k into every column entry whose window contains it. The transpose of “copy xkx_k to positions AkA_k” is “sum the entries at AkA_k back into xkx_k”. 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).
  8. The Toeplitz matrix is the same index map written into a matrix. Row (op,oq)(o_p, o_q), tap (i,j)(i, j) reads input pixel (opsh+i−ph, oqsw+j−pw)(o_p s_h + i - p_h,\ o_q s_w + j - p_w); if it is inside the image, put w[i,j]w[i, j] 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 window

Written with span, the formula is ⌊(n+2p−span)/s⌋+1\lfloor (n + 2p - \text{span})/s \rfloor + 1, the same as the one derived earlier. Check it against Whisper’s stem: n=3000n = 3000, k=3k = 3, p=1p = 1, s=2s = 2 gives ⌊2999/2⌋+1=1500\lfloor 2999/2 \rfloor + 1 = 1500.

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 y

The slice end start + s * (P - 1) + 1 is the index just past the last pixel the last output reads, so the slice has exactly PP 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 NN), 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 s≥1s \ge 1 apart), so NumPy’s buffered += is safe; overlaps come from different taps (i,j)(i, j), 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 t

Here the padding offset −p-p is explicit because there is no padded array: the matrix acts on the original image.

The full solution is conv.py.

The direct conv does NK(C/g)RSPQN K (C/g) R S P Q multiply-adds, the minimum for a direct method, but in gRSg R S vectorized steps rather than a Python loop per output. A loop over output pixels is PQPQ Python iterations (2.25 million for a 1500x1500 output); a loop over taps is RSRS (9 for a 3x3 kernel). Both compute the same sums; only the second is fast in NumPy.

im2col uses RSR S 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. TT is PQ×HWPQ \times HW, 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: T⊤T^\top.

There is no separate transposed-conv routine because the adjoint of im2col is exactly what the input gradient needs (∂L/∂x=col2im⁡(Wflat⊤G)\partial L/\partial x = \operatorname{col2im}(W_{\text{flat}}^\top G)). 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.

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 ⟨im2col⁡x,y⟩=⟨x,col2im⁡y⟩\langle \operatorname{im2col} x, y\rangle = \langle x, \operatorname{col2im} y\rangle 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.

PitfallSymptomHow the solution avoids it
flipping the kernel (true convolution)every output differs from PyTorch; pretrained weights give garbagereads x[o*s + r*d] with w[r], same direction; only correlate_vs_convolve flips (step 5)
leaving dilation out of the kernel spandilated layers get too many outputsspan = dilation * (k - 1) + 1 in conv_out_size
col2im assigning instead of addingwrong input gradients wherever windows overlapxp[...] += blocks[:, :, i, j] (step 7)
im2col rows in (r,s,c)(r, s, c) ordershapes fine, values wrong for C>1C > 1builds [N, C, R, S, P, Q] and reshapes, giving (c,r,s)(c, r, s) rows (step 6)
every group reading the first group’s channelsgrouped and depthwise convs wrongslices xp[:, g*cg:(g+1)*cg] and w[g*kg:(g+1)*kg] per group
all the padding on one sideoutputs shifted by ppnp.pad(..., (ph, ph), (pw, pw)), symmetric
Toeplitz columns without the padding offsetTxT x shifted against the direct convconv_matrix uses op*sh + i - ph (step 8)
dropping the +1+1 in the size formulaone output too few everywhere(n + 2*pad - span) // stride + 1
rejecting an exact fita kernel as large as the input raisesraises only when n + 2*pad < span
not checking that groups divide the output channelssilent 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.unfold or the direct conv, catches it.

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 pieceProduction equivalentWhat it addsWhere to look
im2col + matmulPyTorch aten/src/ATen/native/ConvolutionMM2d.cpp (slow_conv2d)the same unfold-then-GEMM path, threaded, for CPU fallbacksslow_conv2d_forward_out_cpu
conv2d_directoneDNN / cuDNNWinograd and FFT algorithms, implicit GEMM without materializing columns, autotuning per shapecuDNN cudnnFindConvolutionForwardAlgorithm
col2imF.fold / conv_transpose2dthe adjoint as a first-class layer (upsampling in decoders)aten/src/ATen/native/Col2Im.cpp
the C loop in conv2d.can optional C kernelim2col in C with a blocked matmul, benchmarked against the naive loopc/src/kernels/conv.c
  • 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).
  • 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 dd samples apart, so a size-kk kernel spans d(k−1)+1d(k-1)+1 samples.
  • Groups: splitting input and output channels into gg blocks that are convolved independently; g=Cg = C is depthwise convolution.
  • Doubly block Toeplitz matrix: the matrix TT of a 2-D convolution, with vec⁡(y)=Tvec⁡(x)\operatorname{vec}(y) = T \operatorname{vec}(x).
  • im2col: copying every receptive field into a column, ordered (c,r,s)(c, r, s), so a convolution becomes one matmul.
  • col2im: the adjoint of im2col, which sums column entries back into the pixels they came from.
  • 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: ⌊(n+2p−d(k−1)−1)/s⌋+1\lfloor (n + 2p - d(k-1) - 1)/s \rfloor + 1.
  • A conv is linear, so it is a matrix: the doubly block Toeplitz TT with vec⁡(y)=Tvec⁡(x)\operatorname{vec}(y) = T \operatorname{vec}(x). 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.
  1. Why is the weight’s second axis C/gC/g and not CC?
    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.
  2. 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.
  3. What goes wrong, visibly and invisibly, if im2col’s rows are ordered (r,s,c)(r, s, c)?
    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.
  4. Why does conv_matrix subtract the padding while conv2d_direct does 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.
  5. With n=3000n = 3000, k=3k = 3, s=2s = 2 and p=0p = 0 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).