A 2D convolution slides a small grid of weights (the kernel) across an image. At each position it multiplies every weight by the pixel underneath it, adds the products and writes that single number to the output. A Conv2D layer in a neural network does exactly this, with three differences: it skips the kernel flip that textbook convolution requires, it adds a learned bias, and it repeats the operation for every output channel. Kernel size, padding, stride and channel counts set the output shape, and generative models shrink images with strided convolutions and grow them back with transposed convolutions.
What a 2D convolution computes as the kernel slides
Picture a 3×3 kernel placed in the top-left corner of the input. The window covers nine pixels. Each of those pixels is multiplied by the kernel weight that sits over it, and the nine products are summed into one scalar, which becomes the top-left value of the output. The window then moves right by the stride, repeats the calculation, and works through the image left to right and top to bottom.
The grid of results is called a feature map, a learned representation passed on to the next layer. In a trained network, the early kernels end up responding to things like oriented edges or patches of colour, and each kernel learns to look for something different.
Two properties separate this from a fully connected layer. Each output value depends only on a local patch of the input, and the same kernel weights are reused at every position. The arithmetic is still a dot product in both cases, so the two layer types have the same functional form; what changes is connectivity and parameter sharing. Stacking layers widens what each output “sees”: three stacked 3×3 layers give a neuron in the third layer a 7×7 view of the original input.
Why CNN Conv2D layers compute cross-correlation, not a flipped convolution
Strictly speaking, the “convolutional layer” is misnamed. The operation it performs is cross-correlation. Mathematical convolution flips the kernel horizontally and vertically before sliding it, and you can get a strict convolution out of a Conv2D layer simply by flipping the kernel first and then running cross-correlation.
Because the kernels are learned from data, the layer outputs are unaffected whichever of the two operations the layer performs. The flip does show up in the backward pass, which is itself a convolution with spatially flipped filters.
The distinction shows up when you compare PyTorch output with SciPy’s. SciPy’s convolve2d performs true convolution and correlate2d performs cross-correlation. Avinash Kak’s Purdue tutorial shows the effect: the signs of the non-zero entries in the PyTorch output come out reversed compared with SciPy’s convolution. To reproduce a true convolution with a known filter in a Conv2D layer, flip the filter first, since the layer computes cross-correlation.
What do zero, same and valid padding and stride do to the output size of a 2D convolution?
For an input of width W, kernel size F, stride S and zero padding P on each side, the output width is (W − F + 2P)/S + 1, and the same formula applies to height.
Valid padding means no padding at all, so the kernel only uses actual input pixels. The output shrinks by F − 1 in each dimension: Kak’s example takes an 8×8 input through a 3×3 kernel and gets a 6×6 output. Repeat that through a deep stack and the image erodes; Kak notes there is almost nothing left of the 8×8 input after three or four such passes. The CS231n notes add a quieter cost: without padding, information at the borders gets “washed away” too quickly.
Zero padding fixes both problems by adding rings of zeros around the input. At stride 1, setting P = (F − 1)/2 keeps the output the same size as the input, which is why 3×3 kernels pair with P = 1 and 5×5 kernels with P = 2. The VGG-16 architecture is built on that pairing: 3×3 convolutions at stride 1 and pad 1, with 2×2 max pooling at stride 2 for downsampling.
TensorFlow’s Keras and PyTorch both expose this as a 'same' padding mode, with different rules for stride. TensorFlow’s Keras Conv2D pads evenly on each side and guarantees an output the same size as the input only when strides=1. PyTorch’s Conv2d accepts padding='same' but does not support any stride other than 1 in that mode.
Stride is the number of pixels the window moves per step. A stride of 2 makes the filter jump two pixels at a time and produces a spatially smaller output; strides of 3 or more are uncommon. Strides are used to downsample.
Worked example: output sizes from the formula
Every row below applies (W − F + 2P)/S + 1 to the stated inputs.
| Input W | Kernel F | Padding P | Stride S | Output | What it shows |
|---|---|---|---|---|---|
| 8 | 3 | 0 | 1 | (8 − 3 + 0)/1 + 1 = 6 | Valid padding shrinks by F − 1, as in Kak’s 8×8 to 6×6 example |
| 224 | 3 | 1 | 1 | (224 − 3 + 2)/1 + 1 = 224 | P = (F − 1)/2 preserves size at stride 1 |
| 227 | 11 | 0 | 4 | (227 − 11)/4 + 1 = 55 | AlexNet’s first layer, per the CS231n notes |
| 10 | 3 | 0 | 2 | (10 − 3)/2 + 1 = 4.5 | Not an integer: the hyperparameters do not fit |
The last row is the caveat. When the formula returns a fraction, the neurons do not tile the input evenly, and depending on the library you get an exception, silent extra zero padding or a cropped input. In PyTorch, at stride above 1, Conv2d maps several input sizes to the same output size. This becomes an ambiguity when a transposed convolution has to go back up.
How in_channels and out_channels work in a Conv2D layer
A colour image has three channels, and a kernel applied to it has a matching depth of three. A typical first-layer filter is therefore 5×5×3: spatially small, but extending through the full depth of the input. The layer cross-correlates each input channel with its own 2D slice of the kernel and sums the results across channels into a single 2D map.
in_channels is that input depth. out_channels is how many such kernels the layer holds, and each one produces one output map using all of the input channels. Keras calls the same quantity filters, the dimension of the output space. So a layer taking an RGB 256×256 image and producing 64 channels takes input of shape (3, 256, 256) and returns (64, 256, 256) when its padding preserves size.
It pays to know each framework’s tensor layout. PyTorch expects inputs shaped (batch_size, in_channels, H, W) and stores weights as (out_channels, in_channels, kernel_height, kernel_width). Keras Conv2D returns (batch_size, new_height, new_width, filters). The weight count follows directly from the shape: a VGG layer mapping 64 channels to 128 with 3×3 kernels holds (3 × 3 × 64) × 128 = 73,728 weights.
Two variations change the channel wiring. PyTorch’s groups parameter splits channels into independent groups; at groups=2 the layer behaves like two convolutions side by side, and at groups=in_channels each input channel gets its own set of filters, the depthwise case. A 1×1 convolution does no spatial work at all; its only computation happens across the channel dimension. Spacing out the kernel taps with dilation is a separate topic, covered in our explainer on atrous (dilated) convolution.
Computing a 2D convolution in NumPy and PyTorch
The plain-loop version makes the definition concrete. Kak’s tutorial writes true convolution in NumPy as a double loop over output positions that flips the kernel with numpy.flip and sums the elementwise product of each window, giving an output of (H − M + 1) × (W − N + 1) for an H×W input and an M×N kernel. Dropping the flip turns the same loop into cross-correlation, which is what the snippet below uses to check PyTorch’s behaviour.
import numpy as np
import torch
import torch.nn.functional as F
x = np.random.rand(8, 8).astype(np.float32)
k = np.random.rand(3, 3).astype(np.float32)
def corr2d(x, k):
H, W = x.shape
M, N = k.shape
out = np.zeros((H - M + 1, W - N + 1), dtype=x.dtype)
for i in range(H - M + 1):
for j in range(W - N + 1):
out[i, j] = np.sum(x[i:i+M, j:j+N] * k)
return out
def conv2d_true(x, k):
return corr2d(x, np.flip(k)) # flip both axes, then correlate
xt = torch.from_numpy(x)[None, None] # (batch, in_channels, H, W)
kt = torch.from_numpy(k)[None, None] # (out_channels, in_channels, kH, kW)
y = F.conv2d(xt, kt) # valid mode: shape (1, 1, 6, 6)
print(np.allclose(y[0, 0].numpy(), corr2d(x, k), atol=1e-5)) # True
print(np.allclose(y[0, 0].numpy(), conv2d_true(x, k), atol=1e-5)) # False for a non-symmetric kernel
PyTorch’s default is the valid mode, which is why the output is 6×6; the PyTorch documentation warns that, depending on kernel size, some of the last input columns can be lost and that adding proper padding is up to the user. With nn.Conv2d the three required constructor arguments are in_channels, out_channels and kernel_size, where a scalar kernel size means a square kernel. For production code, the loop is only a reference: with multiple input and output channels the computation becomes a matrix–matrix operation.
How do generative models downsample and upsample images with Conv2D?
Generative image models need to move in both directions: downsample an image’s spatial dimensions and upsample them back.
Strided convolutions replace pooling on the way down
The DCGAN paper by Radford, Metz and Chintala (2015) set a guideline: replace pooling layers with strided convolutions in the discriminator and fractionally-strided convolutions in the generator. The reasoning is that a fixed operation such as max pooling decides how to downsample, whereas a strided convolution lets the network learn its own spatial downsampling, and the generator learns its upsampling in the same way. The CS231n notes record the same finding: dropping pooling layers has proved important for training good generative models such as VAEs and GANs.
Published architectures show the pattern plainly. A 2020 variational autoencoder for atmospheric convection uses an encoder of 3×3 Conv2D layers at stride 2 and a decoder of 3×3 transposed convolutions at stride 2. A 2020 DCGAN for crystal-structure generation uses 2D convolutional layers with dropout and batch normalisation in both its generator and its discriminator. For how this convolutional lineage compares with denoising approaches, see our comparison of GAN and diffusion model architectures.
Transposed convolutions on the way up
A transposed convolution (ConvTranspose2d in PyTorch) increases spatial size. Where a regular convolution reduces many input elements to one output through the kernel, a transposed convolution broadcasts each input element through the kernel into a larger output. The name comes from the matrix view: written as a matrix multiplication, the operation uses the transpose of the regular convolution’s weight matrix, and it is also the gradient of Conv2d with respect to its input. It is sometimes called a deconvolution, but it does not compute a true inverse of convolution. DCGAN’s generator, for example, projects a 100-dimensional noise vector to a small spatial representation and uses four fractionally-strided convolutions to turn it into a 64×64 image.
The parameters mean something different here. When stride is greater than 1, PyTorch inserts zeros between input elements before applying the kernel, which is what raises the resolution. Padding is effectively applied to the output rather than the input, so padding of 1 removes the first and last rows and columns of the result. The output size follows its own formula: H_out = (H_in − 1) × stride − 2 × padding + dilation × (kernel_size − 1) + output_padding + 1.
output_padding exists to resolve the shape ambiguity noted in the worked example. With stride above 1, Conv2d maps several input shapes to the same output shape, so the transposed layer cannot know which one to restore; output_padding adds size on one side of the output to pick the right one. The snippet shows the round trip:
import torch
down = torch.nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1)
up = torch.nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2,
padding=1, output_padding=1)
x = torch.randn(1, 64, 32, 32)
h = down(x) # (1, 128, 16, 16): (32 - 3 + 2) // 2 + 1 = 16 (a 31x31 input also gives 16)
y = up(h) # (1, 64, 32, 32): (16 - 1)*2 - 2 + (3 - 1) + 1 + 1 = 32
# without output_padding the result would be 31x31
Checkerboard artifacts and other costs
Transposed convolutions have a known failure mode: they tend to produce checkerboard-like artifacts, alternating squares of high and low intensity, in the upsampled output. One proposed network applies fixed smoothing kernels around its transposed-convolution upsampling and strided-convolution downsampling layers. Sub-pixel convolution (pixel shuffle) is an alternative: it rearranges the channels of low-resolution feature maps into a higher-resolution map. A deconvolution layer is in fact equivalent to a convolution in low-resolution space with more output channels.
Memory is the other cost. Activation memory in convolutional networks is concentrated in the high-resolution early layers. MIT HAN Lab reports that PyTorch can use enough memory for Conv2D over the large activations of high-resolution generative models to run out even on 80GB A100 GPUs, and their Patch Conv approach splits the input into overlapping patches along the height dimension, runs them as a batch and concatenates the outputs. Once a generator has to run at production resolution, that memory profile is the kind of engineering problem TechnoLynx’s Generative & Agentic AI R&D team works on.
FAQ
What is the difference between a convolutional layer and a fully connected layer?
Both compute dot products between weights and inputs. A convolutional layer connects each neuron only to a local region of the input and shares weights across positions, while a fully connected layer connects every neuron to every input.
Are 2D CNNs still used?
Yes. A survey of video super-resolution describes 2D CNNs as the cornerstone of image-related tasks.
What is a 1×1 convolution for?
A 1×1 convolution mixes information across channels without looking at neighbouring pixels, because all of its computation happens along the channel dimension. It is mainly used to change the number of channels cheaply.