Convolutional Layer

A convolutional layer computes each output from a small neighborhood of its input. It takes a weighted sum of the neighborhood, adds a bias, and applies an activation function. The weights form the kernel or filter , and the same kernel is used at every position. Two sliding-window operators differ only in one sign:

  • Cross-correlation slides the kernel as it is. CNNs and PyTorch’s conv2d compute it, although deep learning calls it “convolution”.
  • Convolution rotates the kernel by before sliding it. Signal processing uses it.

In 2D they read


Here and are the row and column of the output. The indices and run over the entries of the kernel. In 1D the second index drops out. A -tap kernel indexed from its center gives . Lecture and Prince write these entries as .

The cross-correlation is a whole map of outputs. The layer adds the same scalar bias to every entry of that map. This equals adding the matrix , whose entries all equal . Sharing one bias across positions, like sharing the kernel, keeps the layer equivariant to shifts. The activation function then acts on each entry. Inputs and hidden layers have several channels, also called feature maps, and an RGB image has three. Output channel has its own bias and adds one cross-correlation per input channel :

The input is , each kernel is , and the biases form . A layer with output channels and kernels therefore has weights and biases. PyTorch stores the weights as a tensor. The count does not depend on the size of the image.

Three hyperparameters set the output size:

  • Padding adds values on each side of the input. The added values can be filled in three ways:
    • Zero padding uses zeros.
    • Circular padding wraps around and copies the values at the opposite edge.
    • Reflect padding mirrors the values next to the edge.
  • Stride evaluates the kernel only at every -th position.
  • Dilation spaces the kernel taps positions apart, so weights cover inputs.

Along each spatial axis an input of size gives

which reduces to when . Two settings have names:

  • Valid convolution uses . With stride its output is shorter than the input.
  • Same convolution uses and , so its output has the size of the input.

A convolutional layer is a dense layer whose weight matrix is sparse, with the same values repeated along each diagonal band.

Three topics have their own notes:

Flipped Convolution in Hand Calculations

Lecture and PyTorch’s conv2d compute . Some homework problems use the convolution instead, which rotates the kernel by . Others write for the unflipped CNN operation. For a learned kernel the choice does not matter, because training finds the rotated weights. For a hand calculation it changes the answer whenever the kernel is not symmetric. Check whether each problem’s sum reads or . 2.1.1. Linear Filters compares the two operations and writes cross-correlation as .

Notation Across the Course

This note follows the lecture: kernel , bias , kernel size , and channel counts and . One homework writes , and for kernel size, padding and stride. It also writes for the number of filters and for the input shape. Another writes , and with . The discussions write , , and .

Intuition

A RGB image has input values. A dense layer with the same number of hidden units would need billion weights. Images also have structure that a dense layer ignores. Nearby pixels are strongly related, and a tree shifted a few pixels to the left is still a tree. A dense layer treats every pair of pixels alike, so it must learn what a tree looks like separately at every position. A convolutional layer builds in three assumptions instead:

  • Locality: each unit looks only at a small neighborhood.
  • Weight sharing: the same detector runs at every position, which respects translation.
  • Hierarchy: stacking layers lets small parts combine into larger wholes.

Sliding one kernel across the input turns a single weighted sum into a whole map of outputs. The figure shows a kernel of size three. Every output uses the same three weights, and the outputs at the edge reach into the padding. The operation is the convolution of signal processing without the flip. It is also the same sliding window as the linear filters of image processing. The difference is that the network learns the kernel from data instead of using a hand-designed one.

\usepackage{tikz}
\begin{document}
\definecolor{hot}{HTML}{D9483B}
\definecolor{cold}{HTML}{2F80ED}
\definecolor{mid}{HTML}{8A8A8A}
\begin{tikzpicture}[x=1.15cm,y=1cm]
\foreach \i in {1,...,7} {
\node[circle,draw,minimum size=0.62cm,inner sep=0pt] (x\i) at (\i,0) {$x_{\i}$};
\node[circle,draw,minimum size=0.62cm,inner sep=0pt] (h\i) at (\i,2.4) {$h_{\i}$};
}
\node[circle,draw=mid,dashed,minimum size=0.62cm,inner sep=0pt] (x0) at (0,0) {$0$};
\node[circle,draw=mid,dashed,minimum size=0.62cm,inner sep=0pt] (x8) at (8,0) {$0$};
\draw[mid,dashed] (x0) -- (h1);
\draw[mid,dashed] (x1) -- (h1);
\draw[mid,dashed] (x2) -- (h1);
\draw[cold,very thick] (x2) -- node[pos=0.25,left] {$\omega_1$} (h3);
\draw[cold,very thick] (x3) -- node[pos=0.25,left] {$\omega_2$} (h3);
\draw[cold,very thick] (x4) -- node[pos=0.25,right] {$\omega_3$} (h3);
\draw[hot,very thick] (x5) -- node[pos=0.25,left] {$\omega_1$} (h6);
\draw[hot,very thick] (x6) -- node[pos=0.25,left] {$\omega_2$} (h6);
\draw[hot,very thick] (x7) -- node[pos=0.25,right] {$\omega_3$} (h6);
\node[circle,draw=cold,very thick,minimum size=0.62cm,inner sep=0pt] at (3,2.4) {};
\node[circle,draw=hot,very thick,minimum size=0.62cm,inner sep=0pt] at (6,2.4) {};
\node[left] at (-0.4,0) {input};
\node[left] at (-0.4,2.4) {output};
\node[mid] at (0,-0.75) {padding};
\node[mid] at (8,-0.75) {padding};
\node at (4,-1.4) {the same three weights produce every output};
\end{tikzpicture}
\end{document}

One kernel is not enough. A weighted sum blurs its neighborhood, and the ReLU discards every negative response, so a single map loses information. A layer therefore runs many kernels in parallel, one per output channel, and the next layer sums over all of them. Each layer looks at a neighborhood of the layer below. Units deep in the network therefore see a large part of the image, even though every kernel is small. 5.2.1a. Receptive Field follows this growth layer by layer.

Properties

(Counting Kernel Positions) The output size formula counts the positions where the kernel fits inside the padded input.

Padding on both sides gives values. A dilated kernel spans of them, so its first tap can sit at positions. A stride of keeps the first position and every -th one after it. Counting offsets from the first position, the last kept offset is the largest multiple of that is at most . This gives the floor in the formula. The floor means that some input columns at the far edge are never covered when the stride does not divide evenly. With , , and , the formula gives outputs. They start at positions , and , so the eighth input is never used.

(Banded Weight Matrix) A convolution is a dense layer with most weights fixed at zero and the rest tied together.

Write a 1D layer without the activation as . For a valid convolution with on inputs, is a matrix. Every row holds the kernel, shifted one column to the right of the row above:

Each diagonal is constant, which makes a Toeplitz matrix. The other settings change the matrix as follows:

  • Zero padding adds one row at each end with the kernel cut off, on top and at the bottom.
  • Stride keeps every -th row.
  • 2D inputs make block Toeplitz: a Toeplitz arrangement of blocks that are themselves Toeplitz.
  • Channels add a grid of such blocks.

A dense layer on the same input would have free weights, while the convolution has . A locally connected layer keeps the band but gives each row its own values. It has weights for a valid output and respects locality but not translation.

(Full-Size Kernel Equals a Dense Layer) A kernel as large as the input, with no padding, turns the convolutional layer into a fully connected layer.

Take and . The kernel then fits at exactly one position, and each filter outputs one number:

This is a weighted sum of every input value plus a bias, which is one unit of a dense layer. The filter’s kernels, stacked into a block, form that unit’s row of the weight matrix. The layer has weights, the same as a dense layer from inputs to outputs. For example, ten filters on a image compute the same function as a dense layer from inputs to outputs. With padding the equivalence fails. The kernel then slides over several positions, and each filter outputs a whole map with shared weights. The full-size kernel also loses both inductive biases of a convolution. It sits at only one position, so no weights are shared. Its window covers the whole image, so there is no locality. A larger kernel therefore makes a layer closer to fully connected and less dependent on how the pixels are arranged.

(Unfolding Into a Matrix Product) GPUs compute a convolution as one large matrix product over unfolded patches.

Not Taught in Lecture

Lecture did not cover im2col. A homework problem on the Muon optimizer introduced it.

The unfolding is called im2col. Each receptive-field patch of the input holds values, and each becomes one column of a matrix . Flattening every dimension of the kernel except gives a matrix . The layer output is then

which is reshaped to . The product costs multiply-accumulate operations, each of which multiplies two numbers and adds the result to a running sum. Optimizers that act on weight matrices, such as Muon, use the same flattened for a convolutional kernel.

(Channels Prevent Information Loss) A layer needs many output channels because one weighted sum followed by a ReLU discards information.

A single kernel averages its neighborhood, and the ReLU clips every negative result to zero. Computing several convolutions in parallel keeps different pieces of information in different channels. A common reading treats each channel as a detector for one pattern at the scale of its receptive field. First-layer channels often look like edge detectors and fit this reading well. Deeper channels are harder to interpret, so the reading is a useful simplification rather than an exact description. Convolutional networks usually double the number of channels each time they halve the height and width. The next layer then has a quarter of the positions and four times the weights per position. Its computation therefore stays about the same.

(Shared Weights Sum Their Gradients) The gradient of a shared weight is the sum of its gradients at every position where it is used.

Consider a model in which every weight is tied to one value , such as . The chain rule gives , one term per use. Take a single-channel 2D valid layer with a scalar bias . Its kernel is indexed from , and its output is . Its forward pass and upstream gradient are

A weight touches every output, and an input touches every output whose window covers it. The chain rule therefore gives

Each gradient is itself a sliding-window operation:

  • The weight gradient reads , so it is a cross-correlation, .
  • The input gradient reads , so it is a full convolution, . Terms where falls outside the output count as zero. This is the same as a transposed convolution of with the kernel.
  • The bias gradient sums over all positions.

One SGD step subtracts times a weighted sum of input patches from the kernel. A trained kernel is therefore its initialization plus a weighted sum of patches of the layer’s input. In the first layer these are patches of the training images. The sum has one term for each of the output positions. For independent zero-mean inputs with variance and upstream gradients with variance , its variance is . The typical size of a weight gradient therefore grows in proportion to the image side length.

Examples

(Easy) Shapes and Parameter Counts

A layer receives a image (channels, height, width). It has filters of size , stride and padding .

(Medium) A 1D Convolution as a Matrix

A signal is filtered by the kernel with zero padding , no bias and no activation.

(Hard) Backpropagating Through a 2D Convolution

A layer computes the valid cross-correlation . It maps the input to a output with the kernel :

See Also