Densely Connected Networks (DenseNet)

ResNet significantly changed the view of how to parametrize the functions in deep networks. DenseNet (dense convolutional network) is to some extent the logical extension of this :cite:Huang.Liu.Van-Der-Maaten.ea.2017. To understand how to arrive at it, let us take a small detour to mathematics.

From ResNet to DenseNet

Recall the Taylor expansion for functions. For the point $x = 0$ it can be written as

f(x) = f(0) + f’(0) x + \frac{f’’(0)}{2!} x^2 + \frac{f’’’(0)}{3!} x^3 + \ldots.

The key point is that it decomposes a function into increasingly higher order terms. In a similar vein, ResNet decomposes functions into

f(\mathbf{x}) = \mathbf{x} + g(\mathbf{x}).

That is, ResNet decomposes $f$ into a simple linear term and a more complex nonlinear one. What if we want to capture (not necessarily add) information beyond two terms? One solution was DenseNet :cite:Huang.Liu.Van-Der-Maaten.ea.2017.

The main difference between ResNet (left) and DenseNet (right) in cross-layer connections: use of addition and use of concatenation. :label:fig_densenet_block

As shown in :numref:fig_densenet_block, the key difference between ResNet and DenseNet is that in the latter case outputs are concatenated (denoted by $[,]$) rather than added. As a result, we perform a mapping from $\mathbf{x}$ to its values after applying an increasingly complex sequence of functions:

$$\mathbf{x} \to \left[ \mathbf{x}, f_1(\mathbf{x}), f_2([\mathbf{x}, f_1(\mathbf{x})]), f_3([\mathbf{x}, f_1(\mathbf{x}), f_2([\mathbf{x}, f_1(\mathbf{x})])]), \ldots\right].$$

In the end, all these functions are combined in MLP to reduce the number of features again. In terms of implementation this is quite simple: rather than adding terms, we concatenate them. The name DenseNet arises from the fact that the dependency graph between variables becomes quite dense. The last layer of such a chain is densely connected to all previous layers. The dense connections are shown in :numref:fig_densenet.

Dense connections in DenseNet. :label:fig_densenet

The main components that compose a DenseNet are dense blocks and transition layers. The former define how the inputs and outputs are concatenated, while the latter control the number of channels so that it is not too large.

Dense Blocks

DenseNet uses the modified “batch normalization, activation, and convolution” structure of ResNet (see the exercise in :numref:sec_resnet). First, we implement this convolution block structure.

```{.python .input} from d2l import mxnet as d2l from mxnet import np, npx from mxnet.gluon import nn npx.set_np()

def conv_block(num_channels): blk = nn.Sequential() blk.add(nn.BatchNorm(), nn.Activation(‘relu’), nn.Conv2D(num_channels, kernel_size=3, padding=1)) return blk

  1. ```{.python .input}
  2. #@tab pytorch
  3. from d2l import torch as d2l
  4. import torch
  5. from torch import nn
  6. def conv_block(input_channels, num_channels):
  7. return nn.Sequential(
  8. nn.BatchNorm2d(input_channels), nn.ReLU(),
  9. nn.Conv2d(input_channels, num_channels, kernel_size=3, padding=1))

```{.python .input}

@tab tensorflow

from d2l import tensorflow as d2l import tensorflow as tf

class ConvBlock(tf.keras.layers.Layer): def init(self, numchannels): super(ConvBlock, self)._init() self.bn = tf.keras.layers.BatchNormalization() self.relu = tf.keras.layers.ReLU() self.conv = tf.keras.layers.Conv2D( filters=num_channels, kernel_size=(3, 3), padding=’same’)

  1. self.listLayers = [self.bn, self.relu, self.conv]
  2. def call(self, x):
  3. y = x
  4. for layer in self.listLayers.layers:
  5. y = layer(y)
  6. y = tf.keras.layers.concatenate([x,y], axis=-1)
  7. return y
  1. A *dense block* consists of multiple convolution blocks, each using the same number of output channels. In the forward propagation, however, we concatenate the input and output of each convolution block on the channel dimension.
  2. ```{.python .input}
  3. class DenseBlock(nn.Block):
  4. def __init__(self, num_convs, num_channels, **kwargs):
  5. super().__init__(**kwargs)
  6. self.net = nn.Sequential()
  7. for _ in range(num_convs):
  8. self.net.add(conv_block(num_channels))
  9. def forward(self, X):
  10. for blk in self.net:
  11. Y = blk(X)
  12. # Concatenate the input and output of each block on the channel
  13. # dimension
  14. X = np.concatenate((X, Y), axis=1)
  15. return X

```{.python .input}

@tab pytorch

class DenseBlock(nn.Module): def init(self, numconvs, inputchannels, num_channels): super(DenseBlock, self).__init() layer = [] for i in range(num_convs): layer.append(conv_block( num_channels i + input_channels, num_channels)) self.net = nn.Sequential(layer)

  1. def forward(self, X):
  2. for blk in self.net:
  3. Y = blk(X)
  4. # Concatenate the input and output of each block on the channel
  5. # dimension
  6. X = torch.cat((X, Y), dim=1)
  7. return X
  1. ```{.python .input}
  2. #@tab tensorflow
  3. class DenseBlock(tf.keras.layers.Layer):
  4. def __init__(self, num_convs, num_channels):
  5. super(DenseBlock, self).__init__()
  6. self.listLayers = []
  7. for _ in range(num_convs):
  8. self.listLayers.append(ConvBlock(num_channels))
  9. def call(self, x):
  10. for layer in self.listLayers.layers:
  11. x = layer(x)
  12. return x

In the following example, we define a DenseBlock instance with 2 convolution blocks of 10 output channels. When using an input with 3 channels, we will get an output with $3+2\times 10=23$ channels. The number of convolution block channels controls the growth in the number of output channels relative to the number of input channels. This is also referred to as the growth rate.

```{.python .input} blk = DenseBlock(2, 10) blk.initialize() X = np.random.uniform(size=(4, 3, 8, 8)) Y = blk(X) Y.shape

  1. ```{.python .input}
  2. #@tab pytorch
  3. blk = DenseBlock(2, 3, 10)
  4. X = torch.randn(4, 3, 8, 8)
  5. Y = blk(X)
  6. Y.shape

```{.python .input}

@tab tensorflow

blk = DenseBlock(2, 10) X = tf.random.uniform((4, 8, 8, 3)) Y = blk(X) Y.shape

  1. ## Transition Layers
  2. Since each dense block will increase the number of channels, adding too many of them will lead to an excessively complex model. A *transition layer* is used to control the complexity of the model. It reduces the number of channels by using the $1\times 1$ convolutional layer and halves the height and width of the average pooling layer with a stride of 2, further reducing the complexity of the model.
  3. ```{.python .input}
  4. def transition_block(num_channels):
  5. blk = nn.Sequential()
  6. blk.add(nn.BatchNorm(), nn.Activation('relu'),
  7. nn.Conv2D(num_channels, kernel_size=1),
  8. nn.AvgPool2D(pool_size=2, strides=2))
  9. return blk

```{.python .input}

@tab pytorch

def transition_block(input_channels, num_channels): return nn.Sequential( nn.BatchNorm2d(input_channels), nn.ReLU(), nn.Conv2d(input_channels, num_channels, kernel_size=1), nn.AvgPool2d(kernel_size=2, stride=2))

  1. ```{.python .input}
  2. #@tab tensorflow
  3. class TransitionBlock(tf.keras.layers.Layer):
  4. def __init__(self, num_channels, **kwargs):
  5. super(TransitionBlock, self).__init__(**kwargs)
  6. self.batch_norm = tf.keras.layers.BatchNormalization()
  7. self.relu = tf.keras.layers.ReLU()
  8. self.conv = tf.keras.layers.Conv2D(num_channels, kernel_size=1)
  9. self.avg_pool = tf.keras.layers.AvgPool2D(pool_size=2, strides=2)
  10. def call(self, x):
  11. x = self.batch_norm(x)
  12. x = self.relu(x)
  13. x = self.conv(x)
  14. return self.avg_pool(x)

Apply a transition layer with 10 channels to the output of the dense block in the previous example. This reduces the number of output channels to 10, and halves the height and width.

```{.python .input} blk = transition_block(10) blk.initialize() blk(Y).shape

  1. ```{.python .input}
  2. #@tab pytorch
  3. blk = transition_block(23, 10)
  4. blk(Y).shape

```{.python .input}

@tab tensorflow

blk = TransitionBlock(10) blk(Y).shape

  1. ## DenseNet Model
  2. Next, we will construct a DenseNet model. DenseNet first uses the same single convolutional layer and maximum pooling layer as in ResNet.
  3. ```{.python .input}
  4. net = nn.Sequential()
  5. net.add(nn.Conv2D(64, kernel_size=7, strides=2, padding=3),
  6. nn.BatchNorm(), nn.Activation('relu'),
  7. nn.MaxPool2D(pool_size=3, strides=2, padding=1))

```{.python .input}

@tab pytorch

b1 = nn.Sequential( nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2, padding=1))

  1. ```{.python .input}
  2. #@tab tensorflow
  3. def block_1():
  4. return tf.keras.Sequential([
  5. tf.keras.layers.Conv2D(64, kernel_size=7, strides=2, padding='same'),
  6. tf.keras.layers.BatchNormalization(),
  7. tf.keras.layers.ReLU(),
  8. tf.keras.layers.MaxPool2D(pool_size=3, strides=2, padding='same')])

Then, similar to the four modules made up of residual blocks that ResNet uses, DenseNet uses four dense blocks. Similar to ResNet, we can set the number of convolutional layers used in each dense block. Here, we set it to 4, consistent with the ResNet-18 model in :numref:sec_resnet. Furthermore, we set the number of channels (i.e., growth rate) for the convolutional layers in the dense block to 32, so 128 channels will be added to each dense block.

In ResNet, the height and width are reduced between each module by a residual block with a stride of 2. Here, we use the transition layer to halve the height and width and halve the number of channels.

```{.python .input}

num_channels: the current number of channels

num_channels, growth_rate = 64, 32 num_convs_in_dense_blocks = [4, 4, 4, 4]

for i, num_convs in enumerate(num_convs_in_dense_blocks): net.add(DenseBlock(num_convs, growth_rate))

  1. # This is the number of output channels in the previous dense block
  2. num_channels += num_convs * growth_rate
  3. # A transition layer that halves the number of channels is added between
  4. # the dense blocks
  5. if i != len(num_convs_in_dense_blocks) - 1:
  6. num_channels //= 2
  7. net.add(transition_block(num_channels))
  1. ```{.python .input}
  2. #@tab pytorch
  3. # `num_channels`: the current number of channels
  4. num_channels, growth_rate = 64, 32
  5. num_convs_in_dense_blocks = [4, 4, 4, 4]
  6. blks = []
  7. for i, num_convs in enumerate(num_convs_in_dense_blocks):
  8. blks.append(DenseBlock(num_convs, num_channels, growth_rate))
  9. # This is the number of output channels in the previous dense block
  10. num_channels += num_convs * growth_rate
  11. # A transition layer that haves the number of channels is added between
  12. # the dense blocks
  13. if i != len(num_convs_in_dense_blocks) - 1:
  14. blks.append(transition_block(num_channels, num_channels // 2))
  15. num_channels = num_channels // 2

```{.python .input}

@tab tensorflow

def block_2(): net = block_1()

  1. # `num_channels`: the current number of channels
  2. num_channels, growth_rate = 64, 32
  3. num_convs_in_dense_blocks = [4, 4, 4, 4]
  4. for i, num_convs in enumerate(num_convs_in_dense_blocks):
  5. net.add(DenseBlock(num_convs, growth_rate))
  6. # This is the number of output channels in the previous dense block
  7. num_channels += num_convs * growth_rate
  8. # A transition layer that haves the number of channels is added
  9. # between the dense blocks
  10. if i != len(num_convs_in_dense_blocks) - 1:
  11. num_channels //= 2
  12. net.add(TransitionBlock(num_channels))
  13. return net
  1. Similar to ResNet, a global pooling layer and a fully-connected layer are connected at the end to produce the output.
  2. ```{.python .input}
  3. net.add(nn.BatchNorm(),
  4. nn.Activation('relu'),
  5. nn.GlobalAvgPool2D(),
  6. nn.Dense(10))

```{.python .input}

@tab pytorch

net = nn.Sequential( b1, *blks, nn.BatchNorm2d(num_channels), nn.ReLU(), nn.AdaptiveMaxPool2d((1, 1)), nn.Flatten(), nn.Linear(num_channels, 10))

  1. ```{.python .input}
  2. #@tab tensorflow
  3. def net():
  4. net = block_2()
  5. net.add(tf.keras.layers.BatchNormalization())
  6. net.add(tf.keras.layers.ReLU())
  7. net.add(tf.keras.layers.GlobalAvgPool2D())
  8. net.add(tf.keras.layers.Flatten())
  9. net.add(tf.keras.layers.Dense(10))
  10. return net

Training

Since we are using a deeper network here, in this section, we will reduce the input height and width from 224 to 96 to simplify the computation.

```{.python .input}

@tab all

lr, num_epochs, batch_size = 0.1, 10, 256 train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size, resize=96) d2l.train_ch6(net, train_iter, test_iter, num_epochs, lr) ```

Summary

  • In terms of cross-layer connections, unlike ResNet, where inputs and outputs are added together, DenseNet concatenates inputs and outputs on the channel dimension.
  • The main components that compose DenseNet are dense blocks and transition layers.
  • We need to keep the dimensionality under control when composing the network by adding transition layers that shrink the number of channels again.

Exercises

  1. Why do we use average pooling rather than maximum pooling in the transition layer?
  2. One of the advantages mentioned in the DenseNet paper is that its model parameters are smaller than those of ResNet. Why is this the case?
  3. One problem for which DenseNet has been criticized is its high memory consumption.
    1. Is this really the case? Try to change the input shape to $224\times 224$ to see the actual GPU memory consumption.
    2. Can you think of an alternative means of reducing the memory consumption? How would you need to change the framework?
  4. Implement the various DenseNet versions presented in Table 1 of the DenseNet paper :cite:Huang.Liu.Van-Der-Maaten.ea.2017.
  5. Design an MLP-based model by applying the DenseNet idea. Apply it to the housing price prediction task in :numref:sec_kaggle_house.

:begin_tab:mxnet Discussions :end_tab:

:begin_tab:pytorch Discussions :end_tab:

:begin_tab:tensorflow Discussions :end_tab: