Convolutional Networks
So far, we’ve used fully connected layers in our neural networks. In this section, we’ll explore alternative layers that are better suited to data with local and sequential patterns.
As a motivating example, consider images: A grayscale image of size \(n \times n\) has \(n^2\) pixels, so a fully connected layer with \(k\) outputs needs \(n^2k\) weights. That’s expensive for large images, and it’s also redundant: We learn separate weights for recognizing the same pattern at different positions.
For data with local relationships (e.g., time series, images, and videos), we’d like a layer with three properties:
- Parameter Efficiency. Ideally, the number of parameters should be independent of the input size.
- Invariance. The rule we apply should be invariant to position: if a pattern appears somewhere else in the input, we process it with the same weights.
- Locality. Each output should depend on a small region of the input rather than the whole thing.
Today, we’ll see how convolutions give us these properties, building up from vectors to matrices to tensors.
2D Convolution
One-dimensional convolution works for data organized along a line, but data like images are more naturally organized in two dimensions. Consider a grayscale image in a matrix; its entry \(X_{ij}\) is the pixel in row \(i\), column \(j\), and we slide the kernel over both rows and columns. Let \(\mathbf X\in\mathbb R^{n\times n}\) be the image and \(\mathbf K\in\mathbb R^{k\times k}\) a square kernel, with \(1\leq k\leq n\). At each position, multiply corresponding entries of the kernel and image patch, then add them. The output feature map has side length \(q=n-k+1\):
\[ y_{ij}=\sum_{u=1}^k\sum_{v=1}^k K_{uv}X_{i+u-1,j+v-1},\qquad i,j=1,\ldots,q. \]
The figure starts with a \(7\times7\) image of a heart and a \(3\times3\) kernel, giving a \(5\times5\) feature map. The highlighted patch is the selected output’s receptive field. Blue entries are positive, orange entries are negative, and darker colors indicate larger absolute values. You can select a filter or edit its entries directly.
A three-by-three kernel slides over a seven-by-seven heart image to produce a five-by-five feature map. A box sum adds the pixels in each patch; an edge filter subtracts opposite sides. Stride changes the spacing of output windows, padding adds a zero border, and dilation spaces out samples within each window.
| Filter | Effect |
|---|---|
| Box sum | Sum of the nine pixels |
| Sharpen | Emphasizes differences from neighboring pixels |
| Vertical edges | Right minus left |
| Horizontal edges | Bottom minus top |
| Diagonal differences | Lower-right minus upper-left |
| Identity | Center pixel |
We reuse the same \(k^2\) weights for every patch, compared with \(q^2n^2\) weights for a fully connected layer with the same input and output sizes. A larger image requires more computation because there are more patches, but the number of learned weights stays the same.
GPUs are especially efficient at matrix multiplication, so convolution libraries often arrange these patch computations as matrix products. For example, NVIDIA’s implicit GEMM algorithm gathers the needed input entries as it computes, without storing a separate matrix of all the patches.
So far, the window has moved one position at a time and stayed entirely inside the image. The figure lets us change three choices about those windows:
- Stride \(s\) moves the window \(s\) input positions for each output step.
- Padding \(p\) adds \(p\) zeros on each side of the image along both axes.
- Dilation \(d\) spaces adjacent kernel samples \(d\) input positions apart.
Here \(s\) and \(d\) are positive integers, and \(p\) is a nonnegative integer. Our starting choices were \(s=d=1\) and \(p=0\). Dilation spreads out the sampled entries, so the receptive field spans a width of \(1+d(k-1)\) without adding weights. To count the outputs along one axis, subtract this width from the padded input width, count steps of size \(s\), and include the first placement:
\[ q=1+\left\lfloor\frac{n+2p-[1+d(k-1)]}{s}\right\rfloor, \qquad n+2p\geq1+d(k-1). \]
Stacking layers also expands the receptive field: each layer combines neighboring outputs of the previous one. For example, two width-two convolutions can use three original input entries for each final output. With \(L\) layers of width \(k\), stride one, and no dilation, the receptive field spans
\[ 1+L(k-1) \]
input positions along each axis, since each layer adds \(k-1\) to the span. Near a boundary, part of this span may lie in padding.
3D Convolution
Some data have depth as well as height and width. For example, a medical scan records measurements throughout a volume, so we want the kernel to move between slices as well as across each slice. To store these measurements, we need three indices instead of the one for a vector or two for a matrix. A tensor generalizes vectors and matrices to arrays with any number of indices. We can store a cubic volume as a tensor \(\mathbf X\in\mathbb R^{n\times n\times n}\), where \(X_{ij\ell}\) is the value in slice \(i\), row \(j\), and column \(\ell\). Each entry is called a voxel, the three-dimensional version of a pixel.
The layers in this volume are depth slices. Channels describe different measurements at the same position, such as red, green, and blue at one pixel. A 3D convolution slides over depth, height, and width. We’ll use one input channel here; with several channels, a filter adds their contributions at each spatial position. Each filter produces one output channel.
Our kernel becomes a smaller cube \(\mathbf K\in\mathbb R^{k\times k\times k}\). At each position, multiply its \(k^3\) entries by the corresponding input entries and add. We move the kernel in all three directions, giving a feature map \(\mathbf y\in\mathbb R^{q\times q\times q}\), where \(q=n-k+1\):
\[ y_{ij\ell}=\sum_{u=1}^k\sum_{v=1}^k\sum_{w=1}^k K_{uvw}X_{i+u-1,j+v-1,\ell+w-1},\qquad i,j,\ell=1,\ldots,q. \]
Below, the \(2\times2\times2\) kernel moves through a \(3\times3\times3\) input. The eight highlighted voxels are used to compute one output. Moving the cursor over the input moves the kernel and selects the corresponding output. Dragging rotates the volumes together.
Three-dimensional convolution adds eight products for each position of a two-by-two-by-two kernel inside a three-by-three-by-three volume. Moving the kernel along depth, rows, and columns produces a two-by-two-by-two output. The selected input cube corresponds to one selected output voxel.
A kernel of width \(k\) has \(k\), \(k^2\), or \(k^3\) weights in one, two, or three dimensions.
A convolutional network alternates convolutional layers with nonlinear activations.
Transposed Convolution
Our convolutions have taken larger inputs and produced smaller feature maps. When reconstructing an image with an autoencoder, we need to go in the other direction: the decoder needs to turn a smaller representation into a larger reconstruction. Our matrix description gives us a way to reverse the dimensions of a convolution: transpose its matrix. For the earlier example, \(\mathbf C\) has shape \(3\times4\), so \(\mathbf C^\top\) takes an input \(\mathbf X\in\mathbb R^3\) and produces four entries:
\[ \mathbf C^\top\mathbf X =\begin{bmatrix}a&0&0\\b&a&0\\0&b&a\\0&0&b\end{bmatrix} \begin{bmatrix}X_1\\X_2\\X_3\end{bmatrix} =\begin{bmatrix}aX_1\\bX_1+aX_2\\bX_2+aX_3\\bX_3\end{bmatrix}. \]
This is transposed convolution. Each input entry contributes a scaled copy of the kernel to its output window. Where windows overlap, their contributions add. Select an input below to see where its contribution goes.
For kernel (a,b), three inputs produce four outputs: aX₁, bX₁+aX₂, bX₂+aX₃, and bX₃. Each selected input contributes to two adjacent outputs, and contributions from different inputs add where they overlap.
Adversarial Inputs
Suppose our network correctly recognizes a photograph of a dog. Can we change its pixel values slightly so that it predicts a different class, even though the image still looks like a dog? An adversarial input is constructed to make a trained model give the wrong answer. We can search for one by optimizing the input while keeping the network’s weights fixed.
For a grayscale image \(\mathbf X\in[0,1]^{n\times n}\), let \(\boldsymbol\Delta\in\mathbb R^{n\times n}\) contain the changes to its pixels. The perturbed image is \(\mathbf X+\boldsymbol\Delta\). We require \(\|\boldsymbol\Delta\|\leq\epsilon\), where \(\epsilon>0\) limits the size of the change, and keep the perturbed pixel values in \([0,1]\). For example, we could limit each pixel change or their combined Euclidean length:
\[ \max_{1\leq i,j\leq n}|\Delta_{ij}|\leq\epsilon, \qquad\text{or}\qquad \|\boldsymbol\Delta\|_F=\sqrt{\sum_{i=1}^n\sum_{j=1}^n\Delta_{ij}^2}\leq\epsilon. \]
The first constraint allows every pixel to change by as much as \(\epsilon\); the second gives all the pixels a shared budget. For a color image, we also include the channel index.
Suppose the network has \(C\) classes. It produces one score, or logit, \(f_c(\mathbf X)\) for each class \(c\). Softmax converts these logits into probabilities:
\[ p_c(\mathbf X)=\frac{\exp(f_c(\mathbf X))}{\sum_{j=1}^C\exp(f_j(\mathbf X))},\qquad c=1,\ldots,C. \]
The predicted class has the largest probability. Let \(c^*\) be the correct class. An untargeted attack tries to lower its probability, without choosing which class replaces it:
\[ \min_{\|\boldsymbol\Delta\|\leq\epsilon}\ \log p_{c^*}(\mathbf X+\boldsymbol\Delta). \]
This is equivalent to maximizing the cross-entropy loss for the correct class. A targeted attack instead chooses a class \(c'\ne c^*\), such as cat, and tries to increase its probability:
\[ \min_{\|\boldsymbol\Delta\|\leq\epsilon}\ -\log p_{c'}(\mathbf X+\boldsymbol\Delta). \]
The minus sign makes the targeted objective decrease as the chosen class becomes more probable. We backpropagate to the input and update \(\boldsymbol\Delta\), keeping it within the allowed region after each step.
This connects to our norm-constrained updates in muon. Write either objective as \(\mathcal L(\mathbf X+\boldsymbol\Delta)\) and let \(\mathbf G=\nabla_{\mathbf X}\mathcal L(\mathbf X)\). For a small perturbation,
\[ \mathcal L(\mathbf X+\boldsymbol\Delta)\approx\mathcal L(\mathbf X)+\langle\mathbf G,\boldsymbol\Delta\rangle, \qquad \langle\mathbf G,\boldsymbol\Delta\rangle=\sum_{i=1}^n\sum_{j=1}^n G_{ij}\Delta_{ij}. \]
We again choose a change by optimizing an inner product under a norm constraint, now changing pixels instead of weights. For a convolution followed by a linear classifier, the logit change is exactly an inner product with the perturbation. The homework compares adversarial and random changes to this classifier under different norm constraints.