AI Logic

Convolution Types

Transposed Convolution

Updated:

A 3×3 input enlarged to 7×7 by a transposed convolution with a 3×3 kernel and stride 2. The left side shows two input cells each written into a 3×3 region of the output, with values summed in the overlapping column. The right side shows the equivalent ordinary convolution: a 3×3 kernel applied to a 9×9 grid formed by inserting zeros between and around the input cells

Background and Overview

Transposed convolution is a learnable layer that traces the input-output shape correspondence of an ordinary convolution in reverse, enlarging (upsampling) a small feature map into a large one. It multiplies the whole kernel by the value of one input cell, writes the result into a wide region of the output, and sums wherever the regions overlap.

As an analogy, it is like pressing a kernel-shaped stamp for each input cell, inked with that cell's value. With stride 2, the stamp moves 2 cells at a time, so the output is roughly twice the size of the input.

In contrast to convolutions that shrink an image, per-pixel prediction and image generation require restoring small feature maps to the original resolution. Fixed methods such as bilinear interpolation can enlarge them, but transposed convolution can learn the upsampling itself as weights.

Transposed convolution is not a method proposed by a particular paper but a general name for an operation derived from convolution. This article explains it mainly through the definitions and relationships in Dumoulin and Visin's tutorial "A guide to convolution arithmetic for deep learning" (2016), following the formulas in the PyTorch documentation.

Transposed convolution is also called "deconvolution" or "fractionally strided convolution." However, deconvolution in mathematics means "the inverse of convolution," which is a different thing. Both Dumoulin and Visin and the DCGAN paper point out that calling it deconvolution is a misnomer.

Definition and Computation

Writing convolution as a matrix

An ordinary convolution can be written as a matrix multiplication by flattening the input and output into column vectors. Applying a 3×3 kernel (stride 1, no padding) to a 4×4 input gives a 2×2 output. With the input as a 16-dimensional vector x\boldsymbol{x} and the output as a 4-dimensional vector y\boldsymbol{y}, it can be written using a sparse 4×164 \times 16 matrix CC built from the kernel weights.

y=Cx\boldsymbol{y} = C\boldsymbol{x}

Transposed convolution multiplies by the transpose of this matrix

Transposed convolution multiplies by C⊤C^{\top} (16×416 \times 4), the transpose of the CC built from the same kernel.

x′=C⊤y\boldsymbol{x}' = C^{\top}\boldsymbol{y}

A 4-dimensional vector becomes a 16-dimensional one, so a 2×2 feature map expands to 4×4. The connectivity (which input cells relate to which output cells) is exactly the reverse of the original convolution. Multiplying by C⊤C^{\top} is the same computation as finding the gradient with respect to the input during backpropagation through a convolution, so implementations usually compute it with the convolution's backward pass.

Transposed convolution is not the inverse of convolution. It only returns a feature map of the same size as the original convolution's input; it does not recover the original input values (C⊤CC^{\top}C is generally not the identity matrix).

Computation steps (the stamping view)

A transposed convolution with stride ss, padding pp, and a k×kk \times k kernel is computed as follows (left side of the figure at the top).

  1. Take one input cell: Take the value yijy_{ij} at input position (i,j)(i, j).
  2. Multiply the whole kernel: Multiply every weight of the k×kk \times k kernel by yijy_{ij}.
  3. Write into the output: Add the result into the k×kk \times k region whose top-left corner is output position (s⋅i,s⋅j)(s \cdot i, s \cdot j).
  4. Repeat for every cell, summing overlaps: When k>sk > s, values are summed where a stamp overlaps the stamps of neighboring cells.
  5. Trim the edges: Finally, remove pp cells from each of the top, bottom, left, and right of the output.

An equivalent ordinary convolution (right side of the figure at the top)

Dumoulin and Visin show that the same result can be produced with an ordinary convolution. Stretch the input by inserting s−1s - 1 zeros between cells, pad it with k−p−1k - p - 1 cells of zeros around the border, then apply a k×kk \times k convolution with stride 1. Because the stride appears to move by "1/s1/s of a cell," this is also called fractionally strided convolution. Since it involves many multiplications by zero and is inefficient, practical implementations do not use this method.

Output size

In the PyTorch documentation for nn.ConvTranspose2d, the output height is given by the following formula (the width is the same).

Hout=(Hin−1)×stride−2×padding+dilation×(kernel_size−1)+output_padding+1H_{\text{out}} = (H_{\text{in}} - 1) \times \text{stride} - 2 \times \text{padding} + \text{dilation} \times (\text{kernel\_size} - 1) + \text{output\_padding} + 1

With dilation equal to 1, this matches Dumoulin and Visin's Relationship 14, o′=s(i′−1)+a+k−2po' = s(i' - 1) + a + k - 2p (where aa is output_padding). For example, with a 3×3 input, k=3k = 3, s=2s = 2, and p=0p = 0, the output is 2×(3−1)+3=72 \times (3 - 1) + 3 = 7, that is, 7×7.

Where It Is Used

Transposed convolution is used as a network component wherever feature maps should be enlarged in a learned way.

Use caseExampleRole
Semantic segmentationFCN (Long et al., 2015)Enlarges coarse predictions to the pixel resolution of the input
Image generationDCGAN (Radford et al., 2016)Enlarges a small feature map made from a 100-dimensional noise vector into a 64×64 image
Encoder-decoder networksAutoencoders, etc.Restores a compressed representation to the original size in the decoder

FCN: FCN, which adapts image classification networks to per-pixel prediction, restores its final coarse predictions to the input size with transposed convolution (called backwards convolution, or deconvolution, in the paper). The paper views upsampling with output stride ff as "convolution with input stride 1/f1/f." The 2× upsampling layers are initialized to bilinear interpolation and their weights are then learned. With frozen weights the layer performs a fixed interpolation; with learning it learns how to interpolate.

DCGAN: DCGAN lists replacing pooling in the generator with transposed convolution (fractionally-strided convolution in the paper) as one of its guidelines for stable training. The generator uses neither fully connected nor pooling layers and enlarges a small feature map into a 64×64 image with four transposed convolutions.

Practical Considerations

If the kernel size is not divisible by the stride, checkerboard artifacts are likely. In transposed convolution, the number of overlapping stamps differs from one output cell to another. With k=3k = 3 and s=2s = 2, cells where two stamps overlap alternate with cells that receive only one (left side of the figure at the top). Odena et al. (2016) showed that although the network could in principle avoid this by tuning its weights, in practice it cannot avoid it fully, and grid-like artifacts tend to remain in generated images. As remedies, they suggest using a kernel size divisible by the stride (such as k=4k = 4 for s=2s = 2), or enlarging with nearest-neighbor interpolation or similar and then applying an ordinary convolution.

  • The output size may not be uniquely determined: With stride 2 or more, inputs of different sizes can give outputs of the same size (for example, with k=3k = 3, s=2s = 2, p=1p = 1, both 5×5 and 6×6 inputs become 3×3). The transposed convolution that traces this in reverse uses output_padding to choose which size to return to. output_padding only determines the output size; it does not actually add zeros.
  • padding works in the opposite direction from ordinary convolution: In transposed convolution, padding is the amount trimmed from the output edges. According to the PyTorch documentation, it is defined so that a Conv2d and a ConvTranspose2d built with the same arguments have exactly inverse input and output shapes.
  • The weight shape differs from ordinary convolution: The weight shape of nn.ConvTranspose2d is (in_channels, out_channels / groups, kH, kW), the reverse order of input and output compared with (out_channels, in_channels / groups, kH, kW) for nn.Conv2d. Take care when loading weights or initializing them yourself.

Comparison with Other Upsampling Methods and How to Choose

The table below compares ways to enlarge feature maps from the same viewpoints.

MethodHow it enlargesLearned weightsCheckerboard artifactsComputation
Interpolation (nearest, bilinear)Fills values by a fixed ruleNoneDo not occurSmall
Transposed convolutionWrites the kernel for each input cell and sums overlapsYes (the upsampling itself)Likely when kk is not divisible by ssMedium
Interpolation + ordinary convolutionEnlarges by interpolation, then convolvesYes (the transformation after enlarging)UnlikelyLarger, since it convolves at the enlarged size

Rough guidelines for choosing:

  • Learning the upsampling as well: Use transposed convolution, with a kernel size divisible by the stride, such as k=4k = 4 for s=2s = 2.
  • Avoiding artifacts in image generation: Odena et al. report that enlarging with nearest-neighbor interpolation and then convolving gave the best results.
  • Keeping computation as light as possible: Enlarge with bilinear interpolation alone. As in FCN, another option is a transposed convolution initialized to bilinear interpolation and trained if needed.

Using dilated convolution, which sees a wide range without lowering resolution, avoids shrinking the feature map in the first place and reduces the need to enlarge it again. The choice between them depends on the trade-off with computation (dilated convolution computes on large feature maps).

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# Transposed convolution: in PyTorch, use nn.ConvTranspose2d
# Output size = (H_in - 1) * stride - 2 * padding + dilation * (kernel_size - 1) + output_padding + 1

x = torch.randn(1, 16, 3, 3)
up = nn.ConvTranspose2d(16, 8, kernel_size=3, stride=2)  # (3 - 1) * 2 + 3 = 7
print(up(x).shape)              # torch.Size([1, 8, 7, 7])
print(tuple(up.weight.shape))   # (16, 8, 3, 3): in the order (in_channels, out_channels, kH, kW)

# The standard 2x upsampling setting: k = 4, s = 2, p = 1 (k is divisible by s)
up2 = nn.ConvTranspose2d(16, 8, kernel_size=4, stride=2, padding=1)
print(up2(torch.randn(1, 16, 32, 32)).shape)  # (32 - 1) * 2 - 2 + 3 + 1 = 64 → [1, 8, 64, 64]

# output_padding: a stride-2 convolution maps both 5×5 and 6×6 to 3×3, so choose the size to return to
down = nn.Conv2d(8, 8, kernel_size=3, stride=2, padding=1)
print(down(torch.randn(1, 8, 5, 5)).shape, down(torch.randn(1, 8, 6, 6)).shape)  # both 3×3
y = torch.randn(1, 8, 3, 3)
print(nn.ConvTranspose2d(8, 8, 3, stride=2, padding=1, output_padding=0)(y).shape)  # 5×5
print(nn.ConvTranspose2d(8, 8, 3, stride=2, padding=1, output_padding=1)(y).shape)  # 6×6


# Check that transposed convolution = the gradient of a convolution with respect to its input (multiplying by C^T)
w = torch.randn(8, 4, 3, 3)                      # Conv2d weights: (out=8, in=4, 3, 3)
inp = torch.randn(1, 4, 7, 7, requires_grad=True)
out = F.conv2d(inp, w, stride=2)                 # [1, 8, 3, 3]
g = torch.randn_like(out)
(grad_inp,) = torch.autograd.grad(out, inp, g)   # C^T g
tconv = F.conv_transpose2d(g, w, stride=2)       # transposed convolution with the same weights
print(torch.allclose(grad_inp, tconv, atol=1e-5))  # True


# For comparison: enlarge with nearest-neighbor interpolation, then convolve (less prone to checkerboard artifacts)
resize_conv = nn.Sequential(
  nn.Upsample(scale_factor=2, mode="nearest"),
  nn.Conv2d(16, 8, kernel_size=3, padding=1),
)
print(resize_conv(torch.randn(1, 16, 32, 32)).shape)  # [1, 8, 64, 64]

FAQ

Q. Can transposed convolution recover the input before a convolution?
A.

No. Transposed convolution only returns a feature map of the same size as the original convolution's input; it is not the inverse operation. To make it act more like a reconstruction, the weights are tuned by learning, as in an autoencoder.

Q. Are deconvolution and transposed convolution the same thing?
A.

Layers called "deconvolution" in the deep learning literature usually refer to transposed convolution. However, deconvolution in mathematics is the inverse of convolution, which is a different thing. To avoid confusion, Dumoulin and Visin recommend the name transposed convolution.

Q. Why is kernel_size=4, stride=2, padding=1 so common?
A.

The output is exactly twice the input, and because the kernel size 4 is divisible by the stride 2, every output cell receives the same number of overlapping stamps. When the number of overlaps is uneven, checkerboard artifacts are more likely.

References

  1. V. Dumoulin and F. Visin, "A guide to convolution arithmetic for deep learning," arXiv:1603.07285, 2016.
  2. J. Long, E. Shelhamer, and T. Darrell, "Fully Convolutional Networks for Semantic Segmentation," CVPR, 2015.
  3. A. Radford, L. Metz, and S. Chintala, "Unsupervised Representation Learning with Deep Convolutional Generative Adversarial Networks," ICLR, 2016.
  4. A. Odena, V. Dumoulin, and C. Olah, "Deconvolution and Checkerboard Artifacts," Distill, 2016.
  5. PyTorch Documentation, "torch.nn.ConvTranspose2d."