AI Logic

Architectures

DenseNet

Updated:

Architecture of DenseNet. The left panel shows the overall flow of DenseNet-121 (7Γ—7 convolution and max pooling, four dense blocks with transition layers in between, global average pooling, fully connected layer) and the output shape of each stage. The right panel shows the inside of a dense block (each layer H receives the concatenated outputs x of all preceding layers) and the order of operations in one layer and in a transition layer

Background and overview

DenseNet (Dense Convolutional Network) is a convolutional neural network in which each layer inside a block receives the concatenated outputs of all preceding layers as input. It was published in 2016 by Huang et al. at Cornell University and accepted at CVPR 2017.

In an ordinary CNN, each layer receives only the output of the layer just before it, so LL layers have LL connections. DenseNet directly connects every pair of layers with the same feature-map size, giving L(L+1)/2L(L+1)/2 connections for LL layers.

Methods that made networks of more than 100 layers trainable, such as ResNet and Highway Networks, share a common idea: create short paths from earlier layers to later ones. DenseNet takes this to its conclusion by connecting all layers directly. Unlike ResNet, however, it concatenates the outputs of earlier layers along the channel dimension instead of adding them.

The main results of the paper are:

  • On CIFAR-10 and CIFAR-100 (with data augmentation), it achieved error rates of 3.46% and 17.18%, the best results at the time.
  • On ImageNet, DenseNet-201 with about 20M parameters had about the same error rate as ResNet-101 with over 40M.
  • It needed about one third of the parameters of ResNet for the same accuracy (CIFAR-10).

Because each layer can use the features of earlier layers directly, there is no need to relearn the same features again and again, and each layer can be very narrow (e.g. 12–40 channels).

Theory: concatenating all preceding layers

The key to DenseNet is making the input of each layer the concatenation of the outputs of all preceding layers.

Let x0\boldsymbol{x}_0 be the image entering the network, Hβ„“(β‹…)H_\ell(\cdot) the transformation of the β„“\ell-th layer, and xβ„“\boldsymbol{x}_\ell its output. In an ordinary CNN and in ResNet, each layer computes:

xβ„“=Hβ„“(xβ„“βˆ’1)(ordinaryΒ CNN)\boldsymbol{x}_\ell = H_\ell(\boldsymbol{x}_{\ell-1}) \qquad \text{(ordinary CNN)} xβ„“=Hβ„“(xβ„“βˆ’1)+xβ„“βˆ’1(ResNet)\boldsymbol{x}_\ell = H_\ell(\boldsymbol{x}_{\ell-1}) + \boldsymbol{x}_{\ell-1} \qquad \text{(ResNet)}

ResNet adds the identity mapping so that gradients flow directly to earlier layers, but the paper points out that mixing by summation may impede the flow of information. A DenseNet layer computes:

xβ„“=Hβ„“([x0,x1,…,xβ„“βˆ’1])\boldsymbol{x}_\ell = H_\ell\big([\boldsymbol{x}_0, \boldsymbol{x}_1, \ldots, \boldsymbol{x}_{\ell-1}]\big)

[β‹…][\cdot] denotes concatenation along channels. The feature maps of earlier layers reach all later layers as they are, without being mixed by addition.

One layer computes as follows:

  1. Concatenate the outputs of all preceding layers along the channel dimension.
  2. Apply batch normalization (BN), ReLU and a 3Γ—3 convolution, in that order (following the pre-activation variant of ResNet).
  3. Pass the kk output feature maps on to later layers.

Growth rate

The number of feature maps kk produced by each layer is called the growth rate. If k0k_0 feature maps enter a block, the input of the β„“\ell-th layer has k0+kΓ—(β„“βˆ’1)k_0 + k \times (\ell - 1) feature maps, growing by kk per layer.

The paper views the whole set of feature maps as the network's "collective knowledge (global state)". Each layer merely appends its own kk feature maps and leaves the rest unchanged. Once written, information can be read by any layer, so it does not have to be copied from layer to layer. This is why even narrow layers such as k=12k = 12 give sufficient accuracy.

Blocks and transition layers

Feature maps cannot be concatenated if their height and width differ, so the network is divided into several dense blocks. Inside a block, the height and width stay the same (3Γ—3 convolutions use one pixel of zero padding on each side), and transition layers between blocks reduce them. A transition layer consists of BN, a 1Γ—1 convolution and 2Γ—2 average pooling.

DenseNet-B: bottleneck layers

Although each layer outputs only kk feature maps, its input grows for later layers. A 1Γ—1 convolution is therefore inserted before the 3Γ—3 convolution to reduce the input to 4k4k feature maps before the 3Γ—3 convolution (BN-ReLU-1Γ—1 conv-BN-ReLU-3Γ—3 conv). This is called DenseNet-B.

DenseNet-C: compression in transition layers

When a block outputs mm feature maps, the 1Γ—1 convolution in the transition layer reduces them to ⌊θmβŒ‹\lfloor \theta m \rfloor. ΞΈ\theta (0<θ≀10 < \theta \le 1) is called the compression factor, and the paper uses ΞΈ=0.5\theta = 0.5. A model with ΞΈ<1\theta < 1 is called DenseNet-C, and one that uses both bottleneck layers and compression is called DenseNet-BC.

Overall architecture and training settings

DenseNet-BC for ImageNet (the left side of the figure at the top of the article shows DenseNet-121)

For ImageNet, a DenseNet-BC with four dense blocks is used. The growth rate is k=32k = 32, and the first convolution has 2k=642k = 64 channels. An image flows as follows:

  1. A 7Γ—7 convolution (stride 2) reduces it to 112Γ—112, and 3Γ—3 max pooling (stride 2) reduces it to 56Γ—56.
  2. It passes alternately through dense blocks and transition layers. Each transition layer halves the height and width (56 β†’ 28 β†’ 14 β†’ 7).
  3. 7Γ—7 global average pooling turns it into a vector, and a 1000-class fully connected layer with a softmax function outputs class probabilities.

The number of layers in each block for each model is as follows (Table 1 of the paper; each layer is a pair of 1Γ—1 and 3Γ—3 convolutions):

ModelBlock 1 (56Γ—56)Block 2 (28Γ—28)Block 3 (14Γ—14)Block 4 (7Γ—7)
DenseNet-1216122416
DenseNet-1696123232
DenseNet-2016124832
DenseNet-2646126448

The number in the name is the number of layers with weights. For example, DenseNet-121 has 1 initial convolution + (6+12+24+16)Γ—2=116(6+12+24+16) \times 2 = 116 layers inside the blocks + 3 transition layers + 1 fully connected layer = 121 layers.

The channel counts follow from the growth rate and compression factor. In DenseNet-121, block 1 starts with 64 channels, grows to 64+6Γ—32=25664 + 6 \times 32 = 256 channels over 6 layers, and the transition layer halves it to 128 channels. Computing the same way, the last block outputs 1024 channels.

DenseNet for CIFAR and SVHN

For 32Γ—32 images, three dense blocks with the same number of layers are used. The first convolution has 16 channels (2k2k for DenseNet-BC), and the blocks operate at 32Γ—32, 16Γ—16 and 8Γ—8. The paper tries depth LL and growth rate kk combinations of {L=40,k=12}\{L=40, k=12\}, {100,12}\{100, 12\} and {100,24}\{100, 24\} for DenseNet, and {100,12}\{100, 12\}, {250,24}\{250, 24\} and {190,40}\{190, 40\} for DenseNet-BC.

Training settings (Section 4.2 of the paper)

ItemCIFAR / SVHNImageNet
OptimizerSGD, Nesterov momentum 0.9Same
Mini-batch and training length64; 300 epochs for CIFAR, 40 epochs for SVHN256, 90 epochs
Learning rateStarts at 0.1, divided by 10 at 50% and 75% of trainingStarts at 0.1, divided by 10 at epochs 30 and 60
Weight Decay10βˆ’410^{-4}Same
Weight initializationHe initializationSame
DropoutOnly without data augmentation: 0.2 after each convolution except the firstNone

On ImageNet, to make the comparison with ResNet fair, the publicly available ResNet training implementation and settings are used as is, and only the model is replaced with DenseNet-BC.

Why it reaches high accuracy with few parameters

The paper explains why DenseNet achieves high accuracy with few parameters as follows:

  • Feature reuse: later layers can use the feature maps of earlier layers directly, so similar features do not have to be learned again and again. Each layer only needs to add a few new features, so layers can be narrow.
  • Implicit deep supervision: the gradient of the loss from the final classifier reaches each layer directly through short connections. This can be seen as obtaining, with a single loss, an effect similar to attaching auxiliary classifiers to intermediate layers (Deeply Supervised Nets).
  • Regularizing effect: using parameters efficiently makes overfitting less likely even on small datasets without data augmentation.

As an everyday analogy, an ordinary CNN is like a game of "telephone": each layer rephrases what it heard from the previous person and passes it on. ResNet passes on the original message with its own notes added. DenseNet collects everyone's notes in a single notebook, and each layer reads the whole notebook before adding its own page. The original information is not distorted by rephrasing, and later people can use more clues.

Checking with the learned weights

The paper examined, for a DenseNet (L=40L = 40, k=12k = 12) trained on CIFAR-10, how much weight each layer assigns to the outputs of each preceding layer (Figure 5).

  1. All layers within a block spread their weights over many inputs. Features produced by early layers are used directly by deep layers.
  2. Transition layers also spread their weights over all layers of the preceding block. Information flows from the first layer to the last through few steps.
  3. Layers in the second and third blocks assigned the least weight to the outputs of the transition layer. This indicates that transition-layer outputs contain many redundant features, consistent with why DenseNet-BC, which compresses in transition layers, works well.
  4. The final classification layer uses the whole block but concentrates its weights on the last feature maps.

The paper also notes a connection to Stochastic Depth, which randomly drops ResNet blocks during training. When all layers in between are dropped, two distant layers become directly connected, so Stochastic Depth can be seen as "becoming a DenseNet-like connection with some probability". DenseNet can be said to have those connections always rather than at random.

Experimental results

Error rates on CIFAR and SVHN (%, Table 2 of the paper. C10 and C100 are without data augmentation; "+" means with translation and horizontal-flip augmentation)

ModelDepthParametersC10C10+C100C100+SVHN
ResNet (reproduced in the Stochastic Depth paper)1101.7M13.636.4144.7427.222.01
ResNet + Stochastic Depth1101.7M11.665.2337.8024.581.75
FractalNet (with dropout and drop-path)2138.6M7.334.6028.2023.731.87
Wide ResNet2836.5Mβ€”4.17β€”20.50β€”
ResNet (pre-activation)100110.2M10.564.6233.4722.71β€”
DenseNet (k=12k=12)401.0M7.005.2427.5524.421.79
DenseNet (k=12k=12)1007.0M5.774.1023.7920.201.67
DenseNet (k=24k=24)10027.2M5.833.7423.4219.251.59
DenseNet-BC (k=12k=12)1000.8M5.924.5124.1522.271.76
DenseNet-BC (k=24k=24)25015.3M5.193.6219.6417.601.74
DenseNet-BC (k=40k=40)19025.6Mβ€”3.46β€”17.18β€”

M stands for million. The table shows the following:

  • Accuracy: DenseNet-BC (L=190L=190, k=40k=40) reached 3.46% on C10+ and 17.18% on C100+, outperforming earlier methods including Wide ResNet.
  • Larger gap without data augmentation: on C10 the error fell from 7.33% to 5.19% and on C100 from 28.20% to 19.64%, a relative reduction of about 30% from the previous best (FractalNet). The paper attributes this to less overfitting thanks to efficient use of parameters.
  • Parameter efficiency: DenseNet-BC (L=100L=100) with 0.8M parameters matched the 1001-layer ResNet with 10.2M almost exactly (4.51% vs. 4.62% on C10+), with 90% fewer parameters.
  • Bigger is better: for DenseNet without compression or bottleneck layers, the error rate dropped as LL and kk grew (5.24% β†’ 4.10% β†’ 3.74% on C10+).

ImageNet error rates (validation set, %, Table 3 of the paper; single-crop / 10-crop)

Modeltop-1top-5
DenseNet-12125.02 / 23.617.71 / 6.66
DenseNet-16923.80 / 22.086.85 / 5.92
DenseNet-20122.58 / 21.466.34 / 5.54
DenseNet-26422.15 / 20.806.12 / 5.29

Compared under the same training settings as ResNet (Figure 3 of the paper), DenseNet-201 with about 20M parameters had about the same error rate as ResNet-101 with over 40M. In terms of computation, a DenseNet with about the same cost as ResNet-50 matched the accuracy of ResNet-101, which needs twice as much computation.

Practical notes

Keep the following points in mind when using DenseNet:

  • A naive implementation uses a lot of memory: re-concatenating earlier feature maps at every layer leaves large intermediate results in memory for each layer. The paper also notes that a naive implementation is memory-inefficient and points to a technical report on a memory-saving implementation. In PyTorch's torchvision, specifying memory_efficient=True reduces memory with gradient checkpointing (at the cost of slower computation).
  • The ImageNet settings are tuned for ResNet: the paper's ImageNet results use hyperparameters tuned for ResNet. The paper suggests that searching for settings suited to DenseNet could improve results further.
  • When to use dropout: the paper inserts dropout (0.2) after each convolution only for CIFAR and SVHN without data augmentation. It is not used with data augmentation or on ImageNet.

Inside a dense block, feature maps can only be concatenated if all layers have the same height and width. When building a block yourself, set the padding of 3Γ—3 convolutions to 1 to keep the size, and change the size only in transition layers.

Comparison with other models

Comparing DenseNet with other networks that have layer-skipping paths from the same perspective:

NetworkHow information from earlier layers is receivedHow it is combinedLayer widthExtra parameters
Highway NetworksCarries the input of the previous layer in a gated proportionGated weighted sumSame as inputGate weights
ResNetCarries the input from a few layers back as isAdditionSame as inputNone
GoogLeNetOutputs of parallel branches within the same moduleConcatenationSet per branchβ€”
DenseNetOutputs of all preceding layers within the blockConcatenationNarrow (grows only by the growth rate kk)None (layer weights grow with the input size)

The difference from ResNet is, in the equations, only "add or concatenate", but the resulting behavior differs greatly. With addition, information from earlier layers is mixed before being passed on; with concatenation, earlier feature maps remain intact. This is why DenseNet can keep each layer narrow and needs few parameters. On the other hand, concatenation keeps increasing the number of channels, so compression in transition layers and bottleneck layers are essential.

GoogLeNet's Inception module also concatenates outputs, but only among parallel branches within the same module. DenseNet concatenates all preceding layers along the depth direction. The paper states that DenseNet is simpler and more efficient.

Rough guidelines for choosing:

  • High accuracy with few parameters: DenseNet-BC is a candidate. Its benefit is reported to be especially large on small datasets where data augmentation is hard to use.
  • Memory or speed constraints: concatenation tends to increase memory use, so use a memory-saving implementation, or compare against ResNet, MobileNet and others.
  • A standard backbone for image classification or detection: it is common to try ResNet first, which has many pretrained weights and supporting tools.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image
from torchvision.models import densenet121, DenseNet121_Weights

"""
1. Build DenseNet-BC dense blocks and transition layers following Eq. (2) of the paper (small example for CIFAR)
2. Classify an image with torchvision's pretrained DenseNet-121
"""


class DenseLayer(nn.Module):
  """One DenseNet-B layer: BN-ReLU-1x1 conv (4k maps)-BN-ReLU-3x3 conv (k maps)"""
  def __init__(self, in_ch, growth_rate, drop_rate=0.0):
    super().__init__()
    self.bottleneck = nn.Sequential(
      nn.BatchNorm2d(in_ch), nn.ReLU(inplace=True),
      nn.Conv2d(in_ch, 4 * growth_rate, 1, bias=False),
    )
    self.conv = nn.Sequential(
      nn.BatchNorm2d(4 * growth_rate), nn.ReLU(inplace=True),
      nn.Conv2d(4 * growth_rate, growth_rate, 3, padding=1, bias=False),   # Padding 1 keeps height and width
    )
    self.drop_rate = drop_rate

  def forward(self, features):                   # features: list of outputs of all preceding layers
    x = torch.cat(features, dim=1)               # Eq. (2): concatenate [x0, x1, ..., x_{l-1}] along channels
    out = self.conv(self.bottleneck(x))
    return F.dropout(out, self.drop_rate, self.training)   # Dropout only in training


class DenseBlock(nn.Module):
  def __init__(self, num_layers, in_ch, growth_rate, drop_rate=0.0):
    super().__init__()
    self.layers = nn.ModuleList(
      [DenseLayer(in_ch + i * growth_rate, growth_rate, drop_rate) for i in range(num_layers)])

  def forward(self, x):
    features = [x]
    for layer in self.layers:
      features.append(layer(features))           # Each layer appends k maps to the "global state"
    return torch.cat(features, dim=1)            # Output has in_ch + num_layers * k maps


class Transition(nn.Sequential):
  """Transition layer: BN-ReLU-1x1 conv (compress to theta*m maps)-2x2 average pooling"""
  def __init__(self, in_ch, out_ch):
    super().__init__(nn.BatchNorm2d(in_ch), nn.ReLU(inplace=True),
                     nn.Conv2d(in_ch, out_ch, 1, bias=False), nn.AvgPool2d(2))


class DenseNetBC(nn.Module):
  """DenseNet-BC for CIFAR: 3 dense blocks (32x32, 16x16, 8x8). With L=100, k=12, each block has 16 layers"""
  def __init__(self, depth=100, growth_rate=12, theta=0.5, num_classes=10, drop_rate=0.0):
    super().__init__()
    n = (depth - 4) // 6                         # Layers per block (1 layer = two convs, 1x1 and 3x3)
    ch = 2 * growth_rate                         # First conv has 2k channels
    layers = [nn.Conv2d(3, ch, 3, padding=1, bias=False)]
    for i in range(3):
      layers.append(DenseBlock(n, ch, growth_rate, drop_rate))
      ch += n * growth_rate
      if i < 2:
        out_ch = int(theta * ch)                 # Compression factor theta
        layers.append(Transition(ch, out_ch))
        ch = out_ch
    layers += [nn.BatchNorm2d(ch), nn.ReLU(inplace=True), nn.AdaptiveAvgPool2d(1)]
    self.features = nn.Sequential(*layers)
    self.fc = nn.Linear(ch, num_classes)
    for m in self.modules():                     # He initialization
      if isinstance(m, nn.Conv2d):
        nn.init.kaiming_normal_(m.weight)

  def forward(self, x):
    return self.fc(self.features(x).flatten(1))


model = DenseNetBC(depth=100, growth_rate=12)
print(sum(p.numel() for p in model.parameters()) / 1e6, "M")   # 0.8M in Table 2 of the paper
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, nesterov=True, weight_decay=1e-4)
model.train()                                    # BN uses mini-batch statistics
loss = F.cross_entropy(model(torch.randn(4, 3, 32, 32)), torch.randint(0, 10, (4,)))
optimizer.zero_grad()
loss.backward()
optimizer.step()

# --- Pretrained DenseNet-121 from torchvision (k=32, block layers 6, 12, 24, 16) ---
weights = DenseNet121_Weights.IMAGENET1K_V1
net = densenet121(weights=weights)               # memory_efficient=True uses gradient checkpointing to save memory (slower)
net.eval()                                       # BN uses the mean and variance accumulated during training
preprocess = weights.transforms()
image = Image.open("cat.jpg").convert("RGB")
with torch.no_grad():
  probs = net(preprocess(image).unsqueeze(0)).softmax(dim=1)   # [1, 1000]
print(weights.meta["categories"][probs.argmax().item()])

FAQ

Q. What is the difference between DenseNet and ResNet?
A.

They differ in how the outputs of earlier layers are combined. ResNet adds the input to the output (xβ„“=Hβ„“(xβ„“βˆ’1)+xβ„“βˆ’1\boldsymbol{x}_\ell = H_\ell(\boldsymbol{x}_{\ell-1}) + \boldsymbol{x}_{\ell-1}), while DenseNet concatenates the outputs of all preceding layers as input (xβ„“=Hβ„“([x0,…,xβ„“βˆ’1])\boldsymbol{x}_\ell = H_\ell([\boldsymbol{x}_0, \ldots, \boldsymbol{x}_{\ell-1}])). With concatenation, earlier features remain intact, so DenseNet can keep each layer narrow and reach the same accuracy with fewer parameters. On the other hand, the number of channels keeps growing, so memory use tends to increase.

Q. How should the growth rate k be chosen?
A.

The paper uses k=12k = 12, 24 and 40 on CIFAR and k=32k = 32 on ImageNet. Even a small value such as k=12k = 12 comes close to the best results of the time, and increasing kk tends to improve accuracy at the cost of more parameters and computation. However, on CIFAR-10 without data augmentation, raising kk from 12 to 24 slightly worsened the error rate from 5.77% to 5.83%, so on small datasets it may be better not to make it too large.

Q. What do B and C in DenseNet-BC mean?
A.

B stands for bottleneck layers: a 1Γ—1 convolution is inserted before each layer's 3Γ—3 convolution to reduce the input to 4k4k feature maps. C stands for compression: the transition layers between blocks reduce the number of feature maps by a factor of ΞΈ\theta (0.5 in the paper). A model using both is DenseNet-BC, which was the most parameter-efficient form in the paper's experiments. torchvision's DenseNet-121 and others also use this form.

References

  1. Huang, G., Liu, Z., van der Maaten, L., & Weinberger, K. Q. (2017). Densely Connected Convolutional Networks. CVPR 2017. arXiv:1608.06993.
  2. Pleiss, G., Chen, D., Huang, G., Li, T., van der Maaten, L., & Weinberger, K. Q. (2017). Memory-Efficient Implementation of DenseNets. arXiv:1707.06990.
  3. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. arXiv:1512.03385.
  4. Huang, G., Sun, Y., Liu, Z., Sedra, D., & Weinberger, K. Q. (2016). Deep Networks with Stochastic Depth. ECCV 2016. arXiv:1603.09382.
  5. PyTorch. torchvision/models/densenet.py (source code).