Course contents 06 / 14

06 / 14 · Convolutional Networks

Convolution

Why a fully connected layer fails on images, the convolution as a sliding dot product with shared weights, channels, padding, stride and dilation with their sizes and costs, receptive fields, pooling, translation equivariance, 1×1 and transposed convolutions.

On this page 10

The first section of the course made a network trainable: a loss computed stably, regularizers, initialization and normalization that keep signals at a usable scale, and optimizers that take good steps. Every network in it was fully connected and read an image as a flat vector of pixels, which works for 8×88 \times 8 digits and breaks down for photographs. This note introduces the layer that replaced it in vision: the convolution, which looks at small neighbourhoods and uses the same weights at every position. It covers the operation itself with a worked example, how channels, padding, stride and dilation set its shapes and costs, how far a unit of a deep stack can see, pooling, what translation equivariance means and where it breaks, and two variants used everywhere in the rest of the course, the 1×11 \times 1 and the transposed convolution.

Notation. An image or feature map is a tensor X∈RCin×H×WX \in \mathbb R^{C_{\text{in}} \times H \times W}: CinC_{\text{in}} channels, each an H×WH \times W grid; Xc,i,jX_{c,i,j} is channel cc at row ii and column jj, indexed from 0. A layer outputs Y∈RCout×H′×W′Y \in \mathbb R^{C_{\text{out}} \times H' \times W'}. Kernels are k×kk \times k (square for simplicity; everything holds per dimension). ss is the stride, pp the padding and dd the dilation. A batch adds a leading dimension, which PyTorch writes as (N,C,H,W)(N, C, H, W).

Baseline: a fully connected layer on pixels#

A fully connected layer treats the CinHWC_{\text{in}} H W numbers of an image as an unordered vector and connects every output to every input. Two things go wrong.

The parameter count. A 224×224224 \times 224 colour image has 150,528150{,}528 numbers. A layer that maps it to a feature map of the same size with 64 channels, 3,211,2643{,}211{,}264 outputs, needs 150,528×3,211,264≈4.8⋅1011150{,}528 \times 3{,}211{,}264 \approx 4.8 \cdot 10^{11} weights, about 1.9 terabytes in 32-bit floats. The Machine Learning course makes the same count for a 32×3232 \times 32 image; at photographic sizes the layer cannot even be stored.

No notion of position. A fully connected layer has a separate weight for every pixel. An edge detector learned in the top-left corner says nothing about an edge in the centre: the layer must learn it again, from examples, at every location. And nothing in it says that neighbouring pixels belong together; permuting the pixels of every image in the same way would leave it exactly as easy to train. Images have the opposite structure: what matters is local (edges, textures, parts), and a cat is a cat wherever it stands.

The convolution is a cross-correlation#

For one input channel, one output channel and stride 1, a convolution layer with kernel K∈Rk×kK \in \mathbb R^{k \times k} and bias bb computes

  Yi,j=b+∑m=0k−1∑n=0k−1Km,n Xi+m, j+n  \boxed{\; Y_{i,j} = b + \sum_{m=0}^{k-1} \sum_{n=0}^{k-1} K_{m,n}\, X_{i+m,\, j+n} \;}

for every position where the window fits: i=0,…,H−ki = 0, \dots, H - k and j=0,…,W−kj = 0, \dots, W - k, so the output is (H−k+1)×(W−k+1)(H - k + 1) \times (W - k + 1). Each output is the dot product of the kernel with one k×kk \times k window of the input, and the window slides over the image.

Strictly, this is a cross-correlation. The convolution of signal processing flips the kernel, ∑m,nKm,nXi−m, j−n\sum_{m,n} K_{m,n} X_{i-m,\, j-n}, which makes the operation commutative and gives it its algebraic properties. The two differ only by the flip: convolving with KK is the same as cross-correlating with KK rotated by 180 degrees. Since the kernel is learned, a network trained with one would simply learn the flipped kernel with the other, and deep-learning libraries compute the cross-correlation and call it a convolution (Goodfellow, Bengio and Courville, 2016, section 9.1). This course does the same.

Worked example. A 4×44 \times 4 input whose right half is brighter than its left, and a 3×33 \times 3 kernel that subtracts the left column of a window from its right column:

X=(1023013210230123),K=(−101−101−101),b=0.X = \begin{pmatrix} 1 & 0 & 2 & 3 \\ 0 & 1 & 3 & 2 \\ 1 & 0 & 2 & 3 \\ 0 & 1 & 2 & 3 \end{pmatrix}, \qquad K = \begin{pmatrix} -1 & 0 & 1 \\ -1 & 0 & 1 \\ -1 & 0 & 1 \end{pmatrix}, \qquad b = 0 .

The output is 2×22 \times 2. Its top-left entry multiplies the top-left window of XX by KK entry by entry and adds the nine products:

Y0,0=(−1+0+2)+(0+0+3)+(−1+0+2)=5.Y_{0,0} = (-1 + 0 + 2) + (0 + 0 + 3) + (-1 + 0 + 2) = 5 .

Sliding the window one column right gives Y0,1=3+1+3=7Y_{0,1} = 3 + 1 + 3 = 7, and the second row gives Y1,0=6Y_{1,0} = 6 and Y1,1=6Y_{1,1} = 6. All four are positive because in every window the right column is brighter than the left: the kernel is a detector of dark-to-bright vertical edges. A true convolution with the same KK flips it into a bright-to-dark detector and gives −5,−7,−6,−6-5, -7, -6, -6.

Figure

A convolution as a sliding dot product

A convolution as a sliding dot productA 4 × 4 input with rows (1, 0, 2, 3), (0, 1, 3, 2), (1, 0, 2, 3), (0, 1, 2, 3) and a 3 × 3 kernel whose rows are (−1, 0, 1). The top-left 3 × 3 window is multiplied by the kernel entry by entry; the products −1, 0, 2, 0, 0, 3, −1, 0, 2 add up to 5, the first entry of the 2 × 2 output. The other windows give 7, 6 and 6.input X1023013210230123kernel K−101−101−1011⊙=products−102003−1022Σoutput Y5−1 + 2 + 3 − 1 + 2 = 53766next: 7, 6, 64A convolution as a sliding dot productA 4 × 4 input with rows (1, 0, 2, 3), (0, 1, 3, 2), (1, 0, 2, 3), (0, 1, 2, 3) and a 3 × 3 kernel whose rows are (−1, 0, 1). The top-left 3 × 3 window is multiplied by the kernel entry by entry; the products −1, 0, 2, 0, 0, 3, −1, 0, 2 add up to 5, the first entry of the 2 × 2 output. The other windows give 7, 6 and 6.input X1023013210230123kernel K−101−101−1011⊙products−102003−1022Σoutput Y5−1 + 2 + 3 − 1 + 2 = 53766next: 7, 6, 64
The worked example of the text. The kernel with columns −1, 0, 1 responds to a dark-to-bright change from left to right, and all four outputs are positive: in every window the right column is brighter than the left one. The kernel is not flipped; this is the cross-correlation that libraries call a convolution. The dashed frame is the second window, one pixel to the right. The same 9 weights are used at every window.
  1. Place the kernel on the top-left 3×33 \times 3 window of the input.
  2. Multiply window and kernel entry by entry: nine products.
  3. Add the products and the bias: Y0,0=5Y_{0,0} = 5.
  4. Slide the window by the stride and repeat: 77, then 66 and 66 on the next row.

It is still a linear layer. Flatten XX into a vector of 16 numbers and YY into 4. The map X↦YX \mapsto Y is linear, so it is a 4×164 \times 16 matrix. Each row has the nine entries of KK in the positions of its window and zeros elsewhere, and all four rows contain the same nine numbers. A fully connected layer between the same shapes has 64 free weights; the convolution has 9. Everything said about linear layers in the backpropagation note, including how gradients flow through them, applies unchanged; the gradient with respect to KK simply adds up the contributions of all the positions that share it.

Channels and the weight shape#

A colour image has three channels and a hidden feature map has dozens or hundreds. A convolution reads all input channels at once: its filter for output channel oo is a Cin×k×kC_{\text{in}} \times k \times k block, one k×kk \times k kernel per input channel, and the results are added:

Yo,i,j=bo+∑c=0Cin−1∑m=0k−1∑n=0k−1Wo,c,m,n Xc, i+m, j+n,o=0,…,Cout−1.\begin{aligned} Y_{o,i,j} &= b_o + \sum_{c=0}^{C_{\text{in}}-1} \sum_{m=0}^{k-1} \sum_{n=0}^{k-1} W_{o,c,m,n}\, X_{c,\, i+m,\, j+n}, \\ o &= 0, \dots, C_{\text{out}} - 1 . \end{aligned}

The weight tensor is W∈RCout×Cin×k×kW \in \mathbb R^{C_{\text{out}} \times C_{\text{in}} \times k \times k}, in this order in PyTorch’s nn.Conv2d, and the bias b∈RCoutb \in \mathbb R^{C_{\text{out}}} has one entry per output channel. The layer has

Cout (Cin k2+1) parametersand costsCout Cin k2 H′W′ multiply-adds.C_{\text{out}}\,(C_{\text{in}}\, k^2 + 1) \ \text{parameters} \qquad\text{and costs}\qquad C_{\text{out}}\, C_{\text{in}}\, k^2\, H' W' \ \text{multiply-adds}.

The parameters do not depend on the size of the image; the cost grows with the size of the output. Papers usually report this count of multiply-adds and call it FLOPs, as the ResNet paper does explicitly (He et al., 2016, section 3.3), although a multiply-add is two floating-point operations.

Worked example. The first layer of a ResNet for 224×224224 \times 224 images is a 7×77 \times 7 convolution from 3 to 64 channels with stride 2 and padding 3, without bias since batch normalization follows. Its output is 112×112112 \times 112 (the size formula is in the next section). It has 64⋅3⋅49=9,40864 \cdot 3 \cdot 49 = 9{,}408 weights and costs 9,408⋅112⋅112=118,013,9529{,}408 \cdot 112 \cdot 112 = 118{,}013{,}952 multiply-adds per image, about 3% of the 3.8 billion of a whole ResNet-50 (He et al., 2016, Table 1). The same input mapped to a 224×224×64224 \times 224 \times 64 map by a 3×33 \times 3 convolution with padding 1 has 64⋅3⋅9+64=1,79264 \cdot 3 \cdot 9 + 64 = 1{,}792 parameters, against the 4.8⋅10114.8 \cdot 10^{11} of the fully connected baseline.

How these weights are initialized is in Normalization and initialization; the fan-in of a convolution and PyTorch’s default initialization are in the Generative Models course, which also draws the shapes. What the first layers learn is the subject of Convolutional architectures and its transfer-learning section.

Padding, stride and dilation#

Three hyperparameters change which inputs each output reads. None of them changes the number of weights.

  • Padding pp adds pp rows and columns of zeros on every side. Without it, every layer shrinks the map by k−1k - 1, and border pixels are read by fewer windows than central ones. With p=(k−1)/2p = (k - 1)/2 for odd kk and stride 1, the output has the size of the input (“same” padding).
  • Stride ss moves the window by ss pixels instead of 1, so the layer computes only every ss-th output in each direction. Stride 2 halves the resolution and cuts the cost by 4.
  • Dilation dd spreads the kernel: its taps read every dd-th pixel, so a 3×33 \times 3 kernel with d=2d = 2 covers a 5×55 \times 5 area with 9 weights. In general the kernel spans d (k−1)+1d\,(k - 1) + 1 pixels.

With all three, the output entry (i,j)(i, j) reads the padded input at rows si+dms i + d m and columns sj+dns j + d n, and the output size is

  H′=⌊H+2p−d (k−1)−1s⌋+1  \boxed{\; H' = \left\lfloor \frac{H + 2p - d\,(k - 1) - 1}{s} \right\rfloor + 1 \;}

and the same for W′W' (Dumoulin and Visin, 2016). Why: the padded input has H+2pH + 2p rows, and the kernel spans e=d(k−1)+1e = d(k-1) + 1 of them, so a window can start at any row from 00 to H+2p−eH + 2p - e. The stride allows only the multiples of ss in that range, and there are ⌊(H+2p−e)/s⌋+1\lfloor (H + 2p - e)/s \rfloor + 1 of them. Substituting ee gives the formula. When ss does not divide H+2p−eH + 2p - e, the floor drops the last rows of the input: they are never read.

Worked example. The 4×44 \times 4 input of the previous section with k=3k = 3: without padding H′=⌊1/1⌋+1=2H' = \lfloor 1/1 \rfloor + 1 = 2, as computed; with p=1p = 1, H′=⌊3/1⌋+1=4H' = \lfloor 3/1 \rfloor + 1 = 4; with p=1p = 1 and s=2s = 2, H′=⌊3/2⌋+1=2H' = \lfloor 3/2 \rfloor + 1 = 2. The ResNet stem above: ⌊(224+6−6−1)/2⌋+1=⌊111.5⌋+1=112\lfloor (224 + 6 - 6 - 1)/2 \rfloor + 1 = \lfloor 111.5 \rfloor + 1 = 112. AlexNet’s first layer used 11×1111 \times 11 kernels with stride 4 on 224×224224 \times 224 crops (Krizhevsky, Sutskever and Hinton, 2012, section 3.5); with padding 2 that gives ⌊217/4⌋+1=55\lfloor 217/4 \rfloor + 1 = 55.

Figure

Stride and dilation change which inputs an output reads

Stride and dilation change which inputs an output readsThree 7 × 7 grids: a 5 × 5 input with zero padding p = 1 and a 3 × 3 kernel. Marked are the cells read by the first output and by its right neighbour. Stride 1, dilation 1: the windows move by one cell and overlap, output 5 × 5. Stride 2: the windows move by two cells, output 3 × 3. Dilation 2: the kernel reads every other cell and spans 5 × 5, output 3 × 3.stride 1, dilation 1output 5 × 5extent 3 × 3stride 2, dilation 1output 3 × 3extent 3 × 3stride 1, dilation 2output 3 × 3extent 5 × 5read by y₀₀read by y₀₁zero paddingStride and dilation change which inputs an output readsThree 7 × 7 grids: a 5 × 5 input with zero padding p = 1 and a 3 × 3 kernel. Marked are the cells read by the first output and by its right neighbour. Stride 1, dilation 1: the windows move by one cell and overlap, output 5 × 5. Stride 2: the windows move by two cells, output 3 × 3. Dilation 2: the kernel reads every other cell and spans 5 × 5, output 3 × 3.stride 1, dilation 1output 5 × 5extent 3 × 3stride 2, dilation 1output 3 × 3extent 3 × 3stride 1, dilation 2output 3 × 3extent 5 × 5read by y₀₀read by y₀₁zero padding
A 5 × 5 input (white cells) with a zero border of width p = 1 (grey), and a 3 × 3 kernel: 9 weights in all three cases. Amber cells are read by the first output, blue cells by its right neighbour, cells with both colours by both. The stride sets how far the window moves, the dilation how far apart the cells inside it are. Output sizes from the formula of the text: ⌊(5 + 2 − 2d − 1)/s⌋ + 1.

How far a unit sees: the receptive field#

The receptive field of a unit is the set of input pixels that can affect its value. For one 3×33 \times 3 layer it is 3×33 \times 3. A unit of a second 3×33 \times 3 layer reads a 3×33 \times 3 window of the first layer, whose units together read a 5×55 \times 5 window of the input. Depth makes the field grow, and stride and dilation make it grow faster.

For a stack of layers with kernel sizes klk_l, strides sls_l and dilations dld_l, the width rlr_l of the receptive field after layer ll follows

  rl=rl−1+(kl−1) dl jl−1,jl=jl−1 sl,r0=j0=1  \boxed{\; r_l = r_{l-1} + (k_l - 1)\, d_l\, j_{l-1}, \qquad j_l = j_{l-1}\, s_l, \qquad r_0 = j_0 = 1 \;}

(Araujo, Norris and Sim, 2019). Here jlj_l is the jump of layer ll: the distance, in input pixels, between the receptive fields of two neighbouring units of that layer. The reasoning:

  • A unit of layer ll reads klk_l units of layer l−1l - 1 in each direction, spaced dld_l apart.
  • Neighbouring units of layer l−1l - 1 have fields shifted by jl−1j_{l-1} input pixels, so its first and last tap are (kl−1) dl jl−1(k_l - 1)\, d_l\, j_{l-1} input pixels apart.
  • Each tap sees rl−1r_{l-1} pixels, so together they cover rl−1+(kl−1) dl jl−1r_{l-1} + (k_l - 1)\, d_l\, j_{l-1}.
  • A stride sls_l makes the units of layer ll themselves sls_l times further apart than those of layer l−1l - 1: jl=jl−1slj_l = j_{l-1} s_l.

Pooling layers count as layers with their own window and stride.

Worked examples.

  • Stride 1. A stack of LL layers of 3×33 \times 3 with stride 1 has jl=1j_l = 1 and rL=1+2Lr_L = 1 + 2L: five layers see 11×1111 \times 11 pixels. Growth is linear and slow.
  • Downsampling. With stride 2 in every second layer, the jump doubles every two layers: r=3,5,9,13,21,29,45,61r = 3, 5, 9, 13, 21, 29, 45, 61 after 1 to 8 layers.
  • Dilation. With dilations 1,2,4,…,2L−11, 2, 4, \dots, 2^{L-1} and stride 1, rL=1+2(1+2+⋯+2L−1)=2L+1−1r_L = 1 + 2(1 + 2 + \dots + 2^{L-1}) = 2^{L+1} - 1: 3, 7, 15, 31, up to 511 after 8 layers, with no loss of resolution. This is the context module of Yu and Koltun (2016), section 2, built for segmentation, where the output must keep the size of the input.
  • VGG-16. The convolutional part of VGG-16 (Simonyan and Zisserman, 2015), five groups of two or three 3×33 \times 3 layers each followed by a 2×22 \times 2 max pool with stride 2, gives its last convolutional unit a field of 196×196196 \times 196 pixels, and 212×212212 \times 212 after the last pooling.
Figure

The receptive field grows with depth

The receptive field grows with depthThe width of the receptive field for a stack of 1 to 8 convolutions of size 3 × 3, on a log scale. With stride 1 it grows by 2 per layer, to 17. If every second layer has stride 2, it grows geometrically, to 61. With a dilation that doubles from layer to layer it is 2 to the power L + 1 minus 1, up to 511.24816326412825651212345678number of 3 × 3 layersreceptive field, pixels (log scale)1761511stride 1stride 2 every second layerdilation 1, 2, 4, …The receptive field grows with depthThe width of the receptive field for a stack of 1 to 8 convolutions of size 3 × 3, on a log scale. With stride 1 it grows by 2 per layer, to 17. If every second layer has stride 2, it grows geometrically, to 61. With a dilation that doubles from layer to layer it is 2 to the power L + 1 minus 1, up to 511.24816326412825651212345678number of 3 × 3 layersreceptive field, pixels (log scale)stride 1: 17stride 2 every second layer: 61dilation 1, 2, 4, …: 511
Values from the recursion of the text; the same stack with all weights equal to 1 gives the same widths from its gradient in the Code section. With stride 1 each layer adds k − 1 = 2 pixels. A stride of 2 doubles the spacing between neighbouring units of its output, so the kernel of the next layer spans twice as many pixels. A doubling dilation also gives exponential growth, faster still, and without losing resolution: the output keeps the size of the input.

The receptive field says which pixels can matter, not how much. In a trained network, the influence of the input on a unit is concentrated near the centre of its field and falls off roughly like a Gaussian, so the effective receptive field covers only a fraction of the theoretical one (Luo et al., 2016). For a classifier, the practical rule is that the units feeding the final decision should have fields at least as large as the objects to recognize.

Pooling#

A pooling layer summarizes each window of every channel by one number, with no weights. Max pooling and average pooling with window kk and stride ss compute, channel by channel,

Yc,i,j=max⁡0≤m,n<kXc, si+m, sj+nor  Yc,i,j=1k2∑m=0k−1∑n=0k−1Xc, si+m, sj+n.\begin{gathered} Y_{c,i,j} = \max_{0 \le m, n < k} X_{c,\, s i + m,\, s j + n} \\ \text{or}\ \ Y_{c,i,j} = \frac{1}{k^2} \sum_{m=0}^{k-1} \sum_{n=0}^{k-1} X_{c,\, s i + m,\, s j + n} . \end{gathered}

The common choice k=s=2k = s = 2 halves the height and width and keeps the number of channels. Pooling does three things: it lowers the resolution, so later layers are cheaper and their fields larger; it summarizes a window by its strongest (or average) response; and, for max pooling, it makes the output insensitive to where exactly inside a window the response occurred. In backpropagation, max pooling passes the gradient only to the position of the maximum, and average pooling spreads it evenly.

Worked example. A 4×44 \times 4 feature map that is zero except for a single 1 at row 0, column 0. Max pooling with k=s=2k = s = 2 gives (1000)\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}. Move the 1 to column 1, inside the same window: the output does not change. Move it to column 2, into the next window: the output becomes (0100)\begin{pmatrix} 0 & 1 \\ 0 & 0 \end{pmatrix}, the old output shifted by one. A shift of one input pixel is absorbed; a shift of two input pixels moves the output by one.

AlexNet used overlapping max pooling, 3×33 \times 3 windows with stride 2, and found it lowered its top-1 and top-5 errors by 0.4 and 0.3 points against 2×22 \times 2 windows with stride 2 (Krizhevsky, Sutskever and Hinton, 2012, section 3.4). Later networks often replace pooling inside the network by strided convolutions, as ResNet does, but keep one special case at the end: global average pooling averages each channel over the whole map, turning C×H×WC \times H \times W into a vector of CC numbers for the classifier (Lin, Chen and Yan, 2014). It has no parameters, and the network then accepts images of any size.

Equivariance and invariance#

Write TaT_a for the translation that moves an image aa pixels to the right, (TaX)i,j=Xi, j−a(T_a X)_{i,j} = X_{i,\, j - a}. A map ff is equivariant to translations if translating the input translates the output, f(TaX)=Taf(X)f(T_a X) = T_a f(X), and invariant if it leaves the output unchanged, f(TaX)=f(X)f(T_a X) = f(X). A feature map should be equivariant: the edge has moved, so its detection should move. A class label should be invariant: the cat is still a cat.

A convolution with stride 1 is equivariant. In one dimension, with the input extended indefinitely,

((TaX)⋆K)j=∑nKn (TaX)j+n=∑nKn Xj+n−a=(X⋆K)j−a=(Ta(X⋆K))j.\big((T_a X) \star K\big)_j = \sum_n K_n\, (T_a X)_{j+n} = \sum_n K_n\, X_{j+n-a} = (X \star K)_{j-a} = \big(T_a (X \star K)\big)_j .

The first and last steps are the definitions, the middle ones substitute TaT_a and recognize the convolution at position j−aj - a. The bias and any pointwise nonlinearity are the same at every position, so they keep the property, and so does a whole stack of such layers (Goodfellow, Bengio and Courville, 2016, section 9.2). On a finite image the identity holds exactly with circular padding and, with zero padding, everywhere except near the borders.

Equivariance holds only for translations. A rotated or rescaled pattern produces a different response, and the network learns such variations from data and augmentation.

Stride and pooling break it. A layer with stride ss computes every ss-th output of a stride-1 layer, so translating the input by a multiple of ss translates the output by a/sa/s, while a translation by one pixel picks a different subset of outputs. In the Code section, a random 3×33 \times 3 filter applied to a random 16×1616 \times 16 image with stride 1 and circular padding commutes with a one-pixel shift up to rounding (10−610^{-6}). With stride 2 the one-pixel shift changes the output by up to 10.6510.65, while a two-pixel shift moves it by exactly one position. A network with five stride-2 stages is exactly equivariant only to shifts by multiples of 32 pixels, and even small shifts of the input can change the predictions of standard classifiers (Azulay and Weiss, 2019). Blurring before every subsampling step, as signal processing prescribes, restores much of the lost stability (Zhang, 2019).

A classifier gets invariance from pooling. Global average pooling of an equivariant map is invariant to circular shifts of the input, since a sum over all positions does not depend on their order; local max pooling adds tolerance to shifts within a window, as in the worked example above.

Pointwise convolutions: mixing channels#

With k=1k = 1 the formula of the channels section becomes

Yo,i,j=bo+∑c=0Cin−1Wo,c Xc,i,j:Y_{o,i,j} = b_o + \sum_{c=0}^{C_{\text{in}}-1} W_{o,c}\, X_{c,i,j} :

the same linear map from CinC_{\text{in}} to CoutC_{\text{out}} numbers, applied to the channel vector of every pixel separately. This 1×11 \times 1 or pointwise convolution does not look at neighbours at all. It mixes channels, and it changes their number cheaply: from 256 to 64 channels it costs 256⋅64=16,384256 \cdot 64 = 16{,}384 weights and as many multiply-adds per pixel, a ninth of a 3×33 \times 3 layer between the same channels. Followed by a nonlinearity, it is a small fully connected network applied at every position, the “network in network” of Lin, Chen and Yan (2014). The next note uses it to shrink the channels before an expensive layer (the Inception and ResNet bottlenecks) and to mix channels after a per-channel convolution (MobileNet).

Transposed convolution: going up in resolution#

Segmentation, generation and autoencoders need the opposite of a strided convolution: a layer that turns a small map into a larger one. Since a convolution is linear, y=Cxy = C x for a sparse matrix CC with H′W′H' W' rows and HWH W columns. The transposed convolution computes C⊤yC^\top y: it maps a vector of size H′W′H' W' to one of size HWH W, with the same sparsity pattern and the same shared weights. It is not an inverse, C⊤C≠IC^\top C \ne I, but it has the right shapes and the right connectivity. It is also exactly the backward pass of the convolution with respect to its input, which is how libraries implement it and how the Code section checks it.

Read entry by entry, every input pixel of the transposed convolution paints a copy of the kernel, scaled by its value, onto the output, with copies placed ss pixels apart; where copies overlap, they add. The output size inverts the formula of the convolution:

Hout=(Hin−1) s−2p+d (k−1)+1+pout,H_{\text{out}} = (H_{\text{in}} - 1)\, s - 2p + d\,(k - 1) + 1 + p_{\text{out}},

where poutp_{\text{out}}, output_padding in PyTorch, resolves the ambiguity created by the floor: a 3×33 \times 3 convolution with stride 2 and padding 1 maps both 7 and 8 rows to 4, and poutp_{\text{out}} chooses which one to return.

Checkerboard artifacts. When kk is not divisible by ss, the copies overlap unevenly (Odena, Dumoulin and Olah, 2016). With k=3k = 3 and s=2s = 2, a copy covers 3 output pixels and the next one starts 2 pixels later, so one pixel in every two receives two copies and the other one. On a 4×44 \times 4 input of ones with a kernel of ones, the 9×99 \times 9 output alternates between 1, 2 and 4 in a checkerboard. With k=4k = 4 and s=2s = 2, every interior pixel receives exactly two copies in each direction, four in all, and the interior is flat.

Figure

Transposed convolution with stride 2: uneven overlap

Transposed convolution with stride 2: uneven overlapTwo grids of numbers, how many copies of the kernel overlap at each output pixel. Left, a 3 × 3 kernel: the interior alternates between 1, 2 and 4, a checkerboard. Right, a 4 × 4 kernel: the interior is 4 everywhere, with uneven values only at the border.kernel 3 × 3, stride 23 is not divisible by 2: checkerboard112121211112121211224242422112121211224242422112121211224242422112121211112121211kernel 4 × 4, stride 24 is divisible by 2: even interior1122222211112222221122444444222244444422224444442222444444222244444422224444442211222222111122222211Transposed convolution with stride 2: uneven overlapTwo grids of numbers, how many copies of the kernel overlap at each output pixel. Left, a 3 × 3 kernel: the interior alternates between 1, 2 and 4, a checkerboard. Right, a 4 × 4 kernel: the interior is 4 everywhere, with uneven values only at the border.kernel 3 × 3, stride 23 is not divisible by 2: checkerboard112121211112121211224242422112121211224242422112121211224242422112121211112121211kernel 4 × 4, stride 24 is divisible by 2: even interior1122222211112222221122444444222244444422224444442222444444222244444422224444442211222222111122222211
A 4 × 4 input of ones and a kernel of ones, so each output pixel equals the number of kernel copies that land on it. Every input pixel paints a copy of the kernel, and the copies are 2 pixels apart. With k = 3, neighbouring copies overlap in a one-pixel strip at every other position, and even a constant input gives the 1–2–4 pattern. With k = 4 the overlap is even. A trained kernel can compensate, but the tendency remains.

A trained kernel can in principle cancel the pattern, but generators that use k=3k = 3, s=2s = 2 often show it, and even kernels divisible by the stride leave a tendency towards it. The usual remedy, resizing by interpolation followed by an ordinary convolution, is discussed with autoencoders in the Generative Models course; Semantic segmentation uses both.

What changed#

Fully connected layerConvolution
Inputs per outputall CinHWC_{\text{in}} H Wa k×kk \times k window of every channel
Parameters, 224×224×3→224×224×64224 \times 224 \times 3 \to 224 \times 224 \times 644.8⋅10114.8 \cdot 10^{11}1,7921{,}792 (3×33 \times 3)
Depends on image sizeparameters and costcost only
Translationmust be learned at every positionequivariant (stride 1), detected everywhere
Field of viewthe whole image in one layergrows with depth, stride and dilation
Changing resolutionfixed by the weight matrixstride and pooling down, transposed convolution up

Limitations#

  • Locality is a prior, and a strong one. A convolution can relate distant pixels only through depth or pooling; long-range dependencies need many layers, and the effective field is smaller than the theoretical one. Vision Transformers drop the prior and let every patch attend to every other.
  • Equivariance only to translations, and only with stride 1. Rotations, scalings and changes of viewpoint must be learned; subsampling makes even translation equivariance approximate.
  • Borders are special. With zero padding, units near the border see partly artificial input, and equivariance fails there.
  • Cost is in the large maps. The parameters sit in the deep, many-channel layers, but the multiply-adds concentrate where the maps are large; the two budgets must be read separately.
  • Transposed convolutions overlap unevenly unless the kernel size is a multiple of the stride, and even then can leave artifacts.

What you should remember#

  • A convolution layer computes Yo,i,j=bo+∑c,m,nWo,c,m,nXc, si+dm, sj+dnY_{o,i,j} = b_o + \sum_{c,m,n} W_{o,c,m,n} X_{c,\, si + dm,\, sj + dn} on the padded input: a cross-correlation (no kernel flip), linear, with weights Cout×Cin×k×kC_{\text{out}} \times C_{\text{in}} \times k \times k.
  • Parameters: Cout(Cink2+1)C_{\text{out}}(C_{\text{in}} k^2 + 1), independent of image size. Cost: CoutCink2H′W′C_{\text{out}} C_{\text{in}} k^2 H' W' multiply-adds, often called FLOPs.
  • Output size: H′=⌊(H+2p−d(k−1)−1)/s⌋+1H' = \lfloor (H + 2p - d(k-1) - 1)/s \rfloor + 1; “same” padding is p=(k−1)/2p = (k - 1)/2 for odd kk.
  • Receptive field: rl=rl−1+(kl−1)dljl−1r_l = r_{l-1} + (k_l - 1) d_l j_{l-1} with jump jl=jl−1slj_l = j_{l-1} s_l; linear growth with stride 1, exponential with repeated stride or doubling dilation.
  • A stride-1 convolution is translation-equivariant; stride and pooling make that approximate; global pooling turns it into invariance.
  • A 1×11 \times 1 convolution is a linear map across channels at every pixel; a transposed convolution is the adjoint of a convolution and overlaps unevenly when ss does not divide kk.

Code#

A convolution written as loops and checked against F.conv2d for several strides, paddings and dilations; the worked example; output sizes and costs; receptive fields read off the gradient; equivariance, pooling, the 1×11 \times 1 convolution, and the transposed convolution as a backward pass. Seeds are fixed; differences of the order of 10−610^{-6} are float32 rounding, and exact digits can differ across platforms and library versions. The script runs in about a second on a laptop CPU.

import torch
from torch import nn
import torch.nn.functional as F

# 1. a convolution written as loops: cross-correlation with channels, bias, stride, padding and dilation
def conv2d_loops(x, w, b, stride=1, padding=0, dilation=1):
    # x: (C_in, H, W), w: (C_out, C_in, k, k), b: (C_out,)
    C_out, C_in, k, _ = w.shape
    x = F.pad(x, (padding, padding, padding, padding))           # zeros on all four sides
    H_out = (x.shape[1] - dilation * (k - 1) - 1) // stride + 1
    W_out = (x.shape[2] - dilation * (k - 1) - 1) // stride + 1
    y = torch.zeros(C_out, H_out, W_out)
    for o in range(C_out):
        for i in range(H_out):
            for j in range(W_out):
                s = b[o]
                for c in range(C_in):
                    for m in range(k):
                        for n in range(k):
                            s = s + w[o, c, m, n] * x[c, stride * i + dilation * m, stride * j + dilation * n]
                y[o, i, j] = s
    return y

# the worked example: a 4 x 4 image and a 3 x 3 vertical-edge kernel, no padding, stride 1
X = torch.tensor([[1., 0, 2, 3], [0, 1, 3, 2], [1, 0, 2, 3], [0, 1, 2, 3]])
K = torch.tensor([[-1., 0, 1], [-1, 0, 1], [-1, 0, 1]])
print(conv2d_loops(X[None], K[None, None], torch.zeros(1))[0].tolist())       # [[5.0, 7.0], [6.0, 6.0]]
print(F.conv2d(X[None, None], K[None, None])[0, 0].tolist())                    # the same
print(F.conv2d(X[None, None], K.flip(0, 1)[None, None])[0, 0].tolist())         # a true convolution flips the kernel: [[-5.0, -7.0], [-6.0, -6.0]]

# random tensors, every setting at once, against the library
torch.manual_seed(0)
for s, p, d in [(1, 0, 1), (1, 1, 1), (2, 1, 1), (1, 2, 2), (2, 3, 3)]:
    x, w, b = torch.randn(3, 9, 9), torch.randn(4, 3, 3, 3), torch.randn(4)
    mine = conv2d_loops(x, w, b, s, p, d)
    ref = F.conv2d(x[None], w, b, stride=s, padding=p, dilation=d)[0]
    print((s, p, d), tuple(mine.shape), f'{(mine - ref).abs().max().item():.1e}')
# (1, 0, 1) (4, 7, 7) 2.9e-06 | (1, 1, 1) (4, 9, 9) 2.9e-06 | (2, 1, 1) (4, 5, 5) 1.9e-06
# (1, 2, 2) (4, 9, 9) 2.9e-06 | (2, 3, 3) (4, 5, 5) 1.9e-06   (stride, padding, dilation), output shape, max difference

# 2. output sizes and costs
size = lambda h, k, s=1, p=0, d=1: (h + 2 * p - d * (k - 1) - 1) // s + 1
print(size(4, 3), size(4, 3, p=1), size(4, 3, s=2, p=1), size(224, 11, s=4, p=2), size(224, 7, s=2, p=3))   # 2 4 2 55 112
stem = nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False)
print(sum(q.numel() for q in stem.parameters()), 64 * 3 * 7 * 7 * 112 * 112)    # 9408 118013952: weights, multiply-adds
print(224 * 224 * 3 * 224 * 224 * 64, sum(q.numel() for q in nn.Conv2d(3, 64, 3, padding=1).parameters()))
# 483385147392 1792: a dense layer between the same two shapes, against a 3 x 3 convolution

# 3. receptive field: which inputs reach the centre output? read it off the gradient
def receptive_field(layers, n=64):
    x = torch.zeros(1, 1, n, n, requires_grad=True)
    y = x
    for layer in layers:
        y = layer(y)
    c = y.shape[-1] // 2
    y[0, 0, c, c].backward()
    rows = (x.grad[0, 0].abs().sum(1) > 0).nonzero()
    return int(rows.max() - rows.min() + 1)

def ones(k, s=1, d=1):
    conv = nn.Conv2d(1, 1, k, stride=s, dilation=d, bias=False)
    nn.init.ones_(conv.weight)
    return conv

print([receptive_field([ones(3) for _ in range(L)]) for L in (1, 2, 3, 5)])               # [3, 5, 7, 11]
print([receptive_field([ones(3, d=2 ** i) for i in range(L)]) for L in (1, 2, 3, 4)])     # [3, 7, 15, 31]
print(receptive_field([ones(3), ones(3), nn.AvgPool2d(2), ones(3), ones(3), nn.AvgPool2d(2), ones(3)]))   # 24
# (average pooling here: the gradient of max pooling reaches only the maximum, which hides part of the field)

def rf(layers):                       # the recursion r_l = r_{l-1} + (k_l - 1) d_l j_{l-1}, j_l = j_{l-1} s_l
    r, j = 1, 1
    for k, s, d in layers:
        r, j = r + (k - 1) * d * j, j * s
    return r
vgg16 = []
for convs in (2, 2, 3, 3, 3):
    vgg16 += [(3, 1, 1)] * convs + [(2, 2, 1)]
print([rf([(3, 2 if i % 2 else 1, 1) for i in range(L)]) for L in range(1, 9)])   # stride 2 in every second layer
print(rf([(3, 1, 1)] * 2 + [(2, 2, 1)] + [(3, 1, 1)] * 2 + [(2, 2, 1)] + [(3, 1, 1)]), rf(vgg16[:-1]), rf(vgg16))
# [3, 5, 9, 13, 21, 29, 45, 61]
# 24 196 212: the stack above, VGG-16 at its last convolution and after its last pooling

# 4. equivariance and invariance
torch.manual_seed(1)
x = torch.randn(1, 1, 16, 16)
w = torch.randn(1, 1, 3, 3)
shift = lambda t, k: torch.roll(t, k, dims=-1)                                 # move the image k pixels right
conv = lambda t, s=1: F.conv2d(F.pad(t, (1, 1, 1, 1), mode='circular'), w, stride=s)
print(f'{(conv(shift(x, 1)) - shift(conv(x), 1)).abs().max().item():.1e}')    # 9.5e-07: shift, then convolve = convolve, then shift
print(f'{(conv(shift(x, 1), 2) - conv(x, 2)).abs().max().item():.2f}',        # stride 2: a one-pixel shift changes the output,
      f'{(conv(shift(x, 2), 2) - shift(conv(x, 2), 1)).abs().max().item():.1e}')   # a two-pixel shift moves it by one: 10.65 0.0e+00
peak = lambda col: torch.zeros(1, 1, 4, 4).index_put_((torch.tensor(0), torch.tensor(0), torch.tensor(0), torch.tensor(col)), torch.tensor(1.))
for col in (0, 1, 2):
    print(col, F.max_pool2d(peak(col), 2)[0, 0].tolist())
# 0 [[1.0, 0.0], [0.0, 0.0]] | 1 [[1.0, 0.0], [0.0, 0.0]] | 2 [[0.0, 1.0], [0.0, 0.0]]

# 5. a 1 x 1 convolution is a linear layer applied at every pixel
one = nn.Conv2d(256, 64, 1)
lin = nn.Linear(256, 64)
lin.weight.data, lin.bias.data = one.weight.data[:, :, 0, 0], one.bias.data
x = torch.randn(2, 256, 7, 7)
print(sum(q.numel() for q in one.parameters()), f'{(one(x) - lin(x.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)).abs().max().item():.1e}')
# 16448 6.0e-07

# 6. the transposed convolution is the backward pass of a convolution, and it overlaps unevenly
x = torch.randn(1, 2, 8, 8, requires_grad=True)
w = torch.randn(3, 2, 3, 3)                                                   # 3 output channels, 2 input channels
y = F.conv2d(x, w, stride=2, padding=1)
g = torch.randn_like(y)
(y * g).sum().backward()                                                      # x.grad = C^T g
print(tuple(y.shape), f'{(x.grad - F.conv_transpose2d(g, w, stride=2, padding=1, output_padding=1)).abs().max().item():.1e}')
# (1, 3, 4, 4) 0.0e+00
for k in (3, 4):
    out = F.conv_transpose2d(torch.ones(1, 1, 4, 4), torch.ones(1, 1, k, k), stride=2)[0, 0]
    print(k, tuple(out.shape), out[4].tolist())
# 3 (9, 9) [2.0, 2.0, 4.0, 2.0, 4.0, 2.0, 4.0, 2.0, 2.0]
# 4 (10, 10) [2.0, 2.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 2.0, 2.0]

Next#

One layer is now understood: its shapes, its cost and what it sees. What remains open is how to stack it. Deeper stacks see more and compute richer features, but the parameters and the cost grow quickly, and past a certain depth plain stacks stop training well. The next note follows the architectures that answered these questions one at a time, from LeNet and AlexNet through VGG’s stacked 3×33 \times 3 layers and Inception’s 1×11 \times 1 bottlenecks to residual networks, and on to the efficient designs of MobileNet and EfficientNet.

References#