32.10  Transposed Convolution

The CNN layers we have seen so far, such as convolutional layers (Section 6.2) and pooling layers (Section 6.5), typically reduce (downsample) the spatial dimensions (height and width) of the input, or keep them unchanged. In semantic segmentation that classifies at pixel-level, it will be convenient if the spatial dimensions of the input and output are the same. For example, the channel dimension at one output pixel can hold the classification results for the input pixel at the same spatial position.

To achieve this, especially after the spatial dimensions are reduced by CNN layers, we can use another type of CNN layers that can increase (upsample) the spatial dimensions of intermediate feature maps. In this section, we will introduce transposed convolution, which is also called fractionally-strided convolution (Dumoulin and Visin 2016), for reversing downsampling operations by the convolution.

32.10.1 Basic Operation

Ignoring channels for now, let’s begin with the basic transposed convolution operation with stride of 1 and no padding. Suppose that we are given a \(n_h \times n_w\) input tensor and a \(k_h \times k_w\) kernel. Sliding the kernel window with stride of 1 for \(n_w\) times in each row and \(n_h\) times in each column yields a total of \(n_h n_w\) intermediate results. Each intermediate result is a \((n_h + k_h - 1) \times (n_w + k_w - 1)\) tensor that are initialized as zeros. To compute each intermediate tensor, each element in the input tensor is multiplied by the kernel so that the resulting \(k_h \times k_w\) tensor replaces a portion in each intermediate tensor. Note that the position of the replaced portion in each intermediate tensor corresponds to the position of the element in the input tensor used for the computation. In the end, all the intermediate results are summed over to produce the output.

As an example, Figure 32.10.1 illustrates how transposed convolution with a \(2\times 2\) kernel is computed for a \(2\times 2\) input tensor.

Figure 32.10.1: Transposed convolution with a \(2\times 2\) kernel. The shaded portions are a portion of an intermediate tensor as well as the input and kernel tensor elements used for the computation.

We can implement this basic transposed convolution operation trans_conv for a input matrix X and a kernel matrix K.

def trans_conv(X, K):
    h, w = K.shape
    Y = d2l.zeros((X.shape[0] + h - 1, X.shape[1] + w - 1))
    for i in range(X.shape[0]):
        for j in range(X.shape[1]):
            Y[i: i + h, j: j + w] += X[i, j] * K
    return Y
def trans_conv(X, K):
    n_h, n_w = X.shape
    # Add each scaled kernel X[i, j] * K, zero-padded into place at (i, j)
    return tf.add_n([tf.pad(X[i, j] * K, [[i, n_h - 1 - i], [j, n_w - 1 - j]])
                     for i in range(n_h) for j in range(n_w)])
def trans_conv(X, K):
    h, w = K.shape
    Y = d2l.zeros((X.shape[0] + h - 1, X.shape[1] + w - 1))
    for i in range(X.shape[0]):
        for j in range(X.shape[1]):
            Y = Y.at[i: i + h, j: j + w].add(X[i, j] * K)
    return Y
def trans_conv(X, K):
    h, w = K.shape
    Y = d2l.zeros((X.shape[0] + h - 1, X.shape[1] + w - 1))
    for i in range(X.shape[0]):
        for j in range(X.shape[1]):
            Y[i: i + h, j: j + w] += X[i, j] * K
    return Y

In contrast to the regular convolution (in Section 6.2) that reduces input elements via the kernel, the transposed convolution broadcasts input elements via the kernel, thereby producing an output that is larger than the input. We can construct the input tensor X and the kernel tensor K from Figure 32.10.1 to validate the output of the above implementation of the basic two-dimensional transposed convolution operation.

X = d2l.tensor([[0.0, 1.0], [2.0, 3.0]])
K = d2l.tensor([[0.0, 1.0], [2.0, 3.0]])
trans_conv(X, K)
tensor([[ 0.,  0.,  1.],
        [ 0.,  4.,  6.],
        [ 4., 12.,  9.]])
<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[ 0.,  0.,  1.],
       [ 0.,  4.,  6.],
       [ 4., 12.,  9.]], dtype=float32)>
Array([[ 0.,  0.,  1.],
       [ 0.,  4.,  6.],
       [ 4., 12.,  9.]], dtype=float32)
array([[ 0.,  0.,  1.],
       [ 0.,  4.,  6.],
       [ 4., 12.,  9.]])

Alternatively, when the input X and kernel K are both four-dimensional tensors, we can use high-level APIs to obtain the same results.

X, K = X.reshape(1, 1, 2, 2), K.reshape(1, 1, 2, 2)
tconv = nn.ConvTranspose2d(1, 1, kernel_size=2, bias=False)
tconv.weight.data = K
tconv(X)
tensor([[[[ 0.,  0.,  1.],
          [ 0.,  4.,  6.],
          [ 4., 12.,  9.]]]], grad_fn=<ConvolutionBackward0>)
X, K = tf.reshape(X, (1, 2, 2, 1)), tf.reshape(K, (2, 2, 1, 1))
tconv = tf.keras.layers.Conv2DTranspose(1, kernel_size=2, use_bias=False)
tconv.build(X.shape)
tconv.kernel.assign(K)
tconv(X)
<tf.Tensor: shape=(1, 3, 3, 1), dtype=float32, numpy=
array([[[[ 0.],
         [ 0.],
         [ 1.]],

        [[ 0.],
         [ 4.],
         [ 6.]],

        [[ 4.],
         [12.],
         [ 9.]]]], dtype=float32)>
X, K = X.reshape(1, 2, 2, 1), K.reshape(2, 2, 1, 1)
# transpose_kernel=True flips the kernel: the transpose of a convolution
tconv = nnx.ConvTranspose(1, 1, kernel_size=(2, 2), padding='VALID',
                          transpose_kernel=True, use_bias=False,
                          rngs=nnx.Rngs(0))
tconv.kernel[...] = K
tconv(X)
Array([[[[ 0.],
         [ 0.],
         [ 1.]],

        [[ 0.],
         [ 4.],
         [ 6.]],

        [[ 4.],
         [12.],
         [ 9.]]]], dtype=float32)
X, K = X.reshape(1, 1, 2, 2), K.reshape(1, 1, 2, 2)
tconv = nn.Conv2DTranspose(1, kernel_size=2)
tconv.initialize(init.Constant(K))
tconv(X)
array([[[[ 0.,  0.,  1.],
         [ 0.,  4.,  6.],
         [ 4., 12.,  9.]]]])

32.10.2 Padding, Strides, and Multiple Channels

Different from in the regular convolution where padding is applied to input, it is applied to output in the transposed convolution. For example, when specifying the padding number on either side of the height and width as 1, the first and last rows and columns will be removed from the transposed convolution output.

Keras’s Conv2DTranspose takes no numeric padding, so we remove the first and last rows and columns by slicing its output.

We use nnx.ConvTranspose without padding (padding='VALID') and remove the first and last rows and columns by slicing its output.

tconv = nn.ConvTranspose2d(1, 1, kernel_size=2, padding=1, bias=False)
tconv.weight.data = K
tconv(X)
tensor([[[[4.]]]], grad_fn=<ConvolutionBackward0>)
# Keras has no numeric padding here: apply, then remove the outer border
tconv(X)[:, 1:-1, 1:-1, :]
<tf.Tensor: shape=(1, 1, 1, 1), dtype=float32, numpy=array([[[[4.]]]], dtype=float32)>
tconv = nnx.ConvTranspose(1, 1, kernel_size=(2, 2), padding='VALID',
                          transpose_kernel=True, use_bias=False,
                          rngs=nnx.Rngs(0))
tconv.kernel[...] = K
# Apply, then remove the outer border (the effect of padding 1)
tconv(X)[:, 1:-1, 1:-1, :]
Array([[[[4.]]]], dtype=float32)
tconv = nn.Conv2DTranspose(1, kernel_size=2, padding=1)
tconv.initialize(init.Constant(K))
tconv(X)
array([[[[4.]]]])

In the transposed convolution, strides are specified for intermediate results (thus output), not for input. Using the same input and kernel tensors from Figure 32.10.1, changing the stride from 1 to 2 increases both the height and width of intermediate tensors, hence the output tensor in Figure 32.10.2.

Figure 32.10.2: Transposed convolution with a \(2\times 2\) kernel with stride of 2. The shaded portions are a portion of an intermediate tensor as well as the input and kernel tensor elements used for the computation.

The following code snippet can validate the transposed convolution output for stride of 2 in Figure 32.10.2.

tconv = nn.ConvTranspose2d(1, 1, kernel_size=2, stride=2, bias=False)
tconv.weight.data = K
tconv(X)
tensor([[[[0., 0., 0., 1.],
          [0., 0., 2., 3.],
          [0., 2., 0., 3.],
          [4., 6., 6., 9.]]]], grad_fn=<ConvolutionBackward0>)
tconv = tf.keras.layers.Conv2DTranspose(1, kernel_size=2, strides=2,
                                        use_bias=False)
tconv.build(X.shape)
tconv.kernel.assign(K)
tconv(X)
<tf.Tensor: shape=(1, 4, 4, 1), dtype=float32, numpy=
array([[[[0.],
         [0.],
         [0.],
         [1.]],

        [[0.],
         [0.],
         [2.],
         [3.]],

        [[0.],
         [2.],
         [0.],
         [3.]],

        [[4.],
         [6.],
         [6.],
         [9.]]]], dtype=float32)>
tconv = nnx.ConvTranspose(1, 1, kernel_size=(2, 2), strides=(2, 2),
                          padding='VALID', transpose_kernel=True,
                          use_bias=False, rngs=nnx.Rngs(0))
tconv.kernel[...] = K
tconv(X)
Array([[[[0.],
         [0.],
         [0.],
         [1.]],

        [[0.],
         [0.],
         [2.],
         [3.]],

        [[0.],
         [2.],
         [0.],
         [3.]],

        [[4.],
         [6.],
         [6.],
         [9.]]]], dtype=float32)
tconv = nn.Conv2DTranspose(1, kernel_size=2, strides=2)
tconv.initialize(init.Constant(K))
tconv(X)
array([[[[0., 0., 0., 1.],
         [0., 0., 2., 3.],
         [0., 2., 0., 3.],
         [4., 6., 6., 9.]]]])

For multiple input and output channels, the transposed convolution works in the same way as the regular convolution. Suppose that the input has \(c_i\) channels, and that the transposed convolution assigns a \(k_h\times k_w\) kernel tensor to each input channel. When multiple output channels are specified, we will have a \(c_i\times k_h\times k_w\) kernel for each output channel.

As in all, if we feed \(\mathsf{X}\) into a convolutional layer \(f\) to output \(\mathsf{Y}=f(\mathsf{X})\) and create a transposed convolutional layer \(g\) with the same hyperparameters as \(f\) except for the number of output channels being the number of channels in \(\mathsf{X}\), then \(g(Y)\) will have the same shape as \(\mathsf{X}\). This can be illustrated in the following example. Note that when the stride is greater than 1, multiple input shapes can map to the same output shape under convolution, so the shape match is not guaranteed in general. In such cases, an additional output padding can be used to resolve the ambiguity.

nn.ConvTranspose2d takes it as the output_padding argument.

tf.keras.layers.Conv2DTranspose takes it as the output_padding argument.

nnx.ConvTranspose has no output_padding argument; explicit (low, high) padding pairs set the output size instead.

nn.Conv2DTranspose takes it as the output_padding argument.

X = torch.rand(size=(1, 10, 16, 16))
conv = nn.Conv2d(10, 20, kernel_size=5, padding=2, stride=3)
tconv = nn.ConvTranspose2d(20, 10, kernel_size=5, padding=2, stride=3)
tconv(conv(X)).shape == X.shape
True
# Channels last: (batch, height, width, channels)
X = tf.random.uniform((1, 16, 16, 10))
conv = tf.keras.Sequential([tf.keras.layers.ZeroPadding2D(2),
                            tf.keras.layers.Conv2D(20, kernel_size=5,
                                                   strides=3)])
tconv = tf.keras.layers.Conv2DTranspose(10, kernel_size=5, strides=3)
# Padding 2 on the transposed side removes two rows/columns per border
tconv(conv(X))[:, 2:-2, 2:-2, :].shape == X.shape
True
# Channels last: (batch, height, width, channels)
X = jax.random.normal(jax.random.PRNGKey(0), (1, 16, 16, 10))
conv = nnx.Conv(10, 20, kernel_size=(5, 5), padding=2, strides=(3, 3),
                rngs=nnx.Rngs(1))
tconv = nnx.ConvTranspose(20, 10, kernel_size=(5, 5), strides=(3, 3),
                          padding='VALID', transpose_kernel=True,
                          rngs=nnx.Rngs(2))
# Padding 2 on the transposed side removes two rows/columns per border
tconv(conv(X))[:, 2:-2, 2:-2, :].shape == X.shape
True
X = mnp.random.uniform(size=(1, 10, 16, 16))
conv = nn.Conv2D(20, kernel_size=5, padding=2, strides=3)
tconv = nn.Conv2DTranspose(10, kernel_size=5, padding=2, strides=3)
conv.initialize()
tconv.initialize()
tconv(conv(X)).shape == X.shape
True

32.10.3 Connection to Matrix Transposition

The transposed convolution is named after the matrix transposition. To explain, let’s first see how to implement convolutions using matrix multiplications. In the example below, we define a \(3\times 3\) input X and a \(2\times 2\) convolution kernel K, and then use the corr2d function to compute the convolution output Y.

X = d2l.reshape(d2l.arange(9.0), (3, 3))
K = d2l.tensor([[1.0, 2.0], [3.0, 4.0]])
Y = d2l.corr2d(X, K)
Y
tensor([[27., 37.],
        [57., 67.]])
<tf.Tensor: shape=(2, 2), dtype=float32, numpy=
array([[27., 37.],
       [57., 67.]], dtype=float32)>
Array([[27., 37.],
       [57., 67.]], dtype=float32)
array([[27., 37.],
       [57., 67.]])

Next, we rewrite the convolution kernel K as a sparse weight matrix W containing a lot of zeros. The shape of the weight matrix is (\(4\), \(9\)), where the non-zero elements come from the convolution kernel K.

def kernel2matrix(K):
    k, W = d2l.zeros(5), d2l.zeros((4, 9))
    k[:2], k[3:5] = K[0, :], K[1, :]
    W[0, :5], W[1, 1:6], W[2, 3:8], W[3, 4:] = k, k, k, k
    return W

W = kernel2matrix(K)
W
tensor([[1., 2., 0., 3., 4., 0., 0., 0., 0.],
        [0., 1., 2., 0., 3., 4., 0., 0., 0.],
        [0., 0., 0., 1., 2., 0., 3., 4., 0.],
        [0., 0., 0., 0., 1., 2., 0., 3., 4.]])
def kernel2matrix(K):
    k = tf.concat([K[0, :], d2l.zeros(1), K[1, :]], 0)  # length 5
    # Row r holds k shifted right by the r-th window offset 0, 1, 3, 4
    return tf.stack([tf.pad(k, [[s, 4 - s]]) for s in (0, 1, 3, 4)])

W = kernel2matrix(K)
W
<tf.Tensor: shape=(4, 9), dtype=float32, numpy=
array([[1., 2., 0., 3., 4., 0., 0., 0., 0.],
       [0., 1., 2., 0., 3., 4., 0., 0., 0.],
       [0., 0., 0., 1., 2., 0., 3., 4., 0.],
       [0., 0., 0., 0., 1., 2., 0., 3., 4.]], dtype=float32)>
def kernel2matrix(K):
    k = jnp.zeros(5)
    k = k.at[:2].set(K[0, :])
    k = k.at[3:5].set(K[1, :])
    W = jnp.zeros((4, 9))
    W = W.at[0, :5].set(k)
    W = W.at[1, 1:6].set(k)
    W = W.at[2, 3:8].set(k)
    W = W.at[3, 4:].set(k)
    return W

W = kernel2matrix(K)
W
Array([[1., 2., 0., 3., 4., 0., 0., 0., 0.],
       [0., 1., 2., 0., 3., 4., 0., 0., 0.],
       [0., 0., 0., 1., 2., 0., 3., 4., 0.],
       [0., 0., 0., 0., 1., 2., 0., 3., 4.]], dtype=float32)
def kernel2matrix(K):
    k, W = d2l.zeros(5), d2l.zeros((4, 9))
    k[:2], k[3:5] = K[0, :], K[1, :]
    W[0, :5], W[1, 1:6], W[2, 3:8], W[3, 4:] = k, k, k, k
    return W

W = kernel2matrix(K)
W
array([[1., 2., 0., 3., 4., 0., 0., 0., 0.],
       [0., 1., 2., 0., 3., 4., 0., 0., 0.],
       [0., 0., 0., 1., 2., 0., 3., 4., 0.],
       [0., 0., 0., 0., 1., 2., 0., 3., 4.]])

Concatenate the input X row by row to get a vector of length 9. Then the matrix multiplication of W and the vectorized X gives a vector of length 4. After reshaping it, we can obtain the same result Y from the original convolution operation above: we just implemented convolutions using matrix multiplications.

Y == d2l.reshape(d2l.matmul(W, d2l.reshape(X, (-1, 1))), (2, 2))
tensor([[True, True],
        [True, True]])
<tf.Tensor: shape=(2, 2), dtype=bool, numpy=
array([[ True,  True],
       [ True,  True]])>
Array([[ True,  True],
       [ True,  True]], dtype=bool)
array([[ True,  True],
       [ True,  True]])

Likewise, we can implement transposed convolutions using matrix multiplications. In the following example, we take the \(2 \times 2\) output Y from the above regular convolution as input to the transposed convolution. To implement this operation by multiplying matrices, we only need to transpose the weight matrix W with the new shape \((9, 4)\).

Z = trans_conv(Y, K)
Z == d2l.reshape(d2l.matmul(d2l.transpose(W), d2l.reshape(Y, (-1, 1))), (3, 3))
tensor([[True, True, True],
        [True, True, True],
        [True, True, True]])
<tf.Tensor: shape=(3, 3), dtype=bool, numpy=
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])>
Array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]])

Consider implementing the convolution by multiplying matrices. Given an input vector \(\mathbf{x}\) and a weight matrix \(\mathbf{W}\), the forward propagation function of the convolution can be implemented by multiplying its input with the weight matrix and outputting a vector \(\mathbf{y}=\mathbf{W}\mathbf{x}\). Since backpropagation follows the chain rule and \(\nabla_{\mathbf{x}}\mathbf{y}=\mathbf{W}^\top\), the backpropagation function of the convolution can be implemented by multiplying its input with the transposed weight matrix \(\mathbf{W}^\top\). Therefore, the transposed convolutional layer can just exchange the forward propagation function and the backpropagation function of the convolutional layer: its forward propagation and backpropagation functions multiply their input vector with \(\mathbf{W}^\top\) and \(\mathbf{W}\), respectively.

32.10.4 Summary

  • In contrast to the regular convolution that reduces input elements via the kernel, the transposed convolution broadcasts input elements via the kernel, thereby producing an output that is larger than the input.
  • If we feed \(\mathsf{X}\) into a convolutional layer \(f\) to output \(\mathsf{Y}=f(\mathsf{X})\) and create a transposed convolutional layer \(g\) with the same hyperparameters as \(f\) except for the number of output channels being the number of channels in \(\mathsf{X}\), then \(g(Y)\) will have the same shape as \(\mathsf{X}\). This holds when the stride is 1; for stride > 1, an additional output_padding may be needed since multiple input shapes can share the same convolution output shape.
  • We can implement convolutions using matrix multiplications. The transposed convolutional layer can just exchange the forward propagation function and the backpropagation function of the convolutional layer.

32.10.5 Exercises

  1. In Section 32.10.3, the convolution input X and the transposed convolution output Z have the same shape. Do they have the same value? Why?
  2. Is it efficient to use matrix multiplications to implement convolutions? Why?
  3. Derive the output height of a transposed convolution with input height \(n\), kernel height \(k\), padding \(p\), and stride \(s\) from the description in this section: the intermediate results are placed \(s\) rows apart, and padding removes \(p\) rows at each border. Check the formula on conv and tconv of this section (kernel 5, padding 2, stride 3): compute the height of conv(X) for the \(16\times 16\) input, then the height of tconv(conv(X)). List all input heights that conv maps to the same output height, and give the number of extra rows (the output_padding) that tconv needs to restore each of them.
  4. Apply a transposed convolution with a \(3\times 3\) kernel of ones and stride 2, without padding, to a \(4\times 4\) input of ones, and report the \(9\times 9\) output. Explain its checkerboard pattern by counting, for each output position, the input elements that contribute to it. Prove that for stride \(s\) the interior of the output is constant if and only if \(s\) divides the kernel size \(k\), and check which of the kernel sizes 2, 3, and 4 give a constant interior for stride 2.
  5. Extend trans_conv with a stride argument and check it against the output in Figure 32.10.2. Then show that the same output results from three steps: insert \(s-1\) zeros between neighboring input elements along rows and columns, pad the result with \(k-1\) zeros on every side, and apply d2l.corr2d with the kernel rotated by 180 degrees. Prove the equivalence, verify it numerically for random inputs and kernels, and explain from it the name fractionally-strided convolution.