AI Logic

Architectures

DeepLab v3+

Updated:

Architecture of DeepLab v3+. The left panel shows the overall flow. The encoder in the left column (DeepLab v3) passes the input image through the early part of the DCNN (low-level features, 1/4 of the image) and the later part, where downsampling is replaced by atrous convolution (1/16), then applies ASPP (1×1 convolution, 3×3 with rates 6, 12 and 18, image-level features) and a 1×1 convolution (256 channels). The decoder in the right column upsamples this by 4× with bilinear interpolation, concatenates it with the low-level features reduced to 48 channels by a 1×1 convolution, applies two 3×3 convolutions (256 channels), and upsamples by 4× with bilinear interpolation to output a class per pixel. The right panel shows atrous separable convolution: the input features go through a 3×3 depthwise convolution with rate r, then a 1×1 pointwise convolution. Using it in ASPP and the decoder cuts multiply-adds by 33–41%. Below are the changes to the Xception backbone

Background and overview

DeepLab v3+ is a semantic segmentation method (the task of assigning each pixel of an image the class of the object or region it shows) that uses DeepLab v3 as an encoder and adds a simple decoder that refines its output together with low-level features at 1/4 of the image resolution, combining multi-scale context with sharp object boundaries. It was proposed by Chen et al. at Google in 2018 (ECCV 2018).

Segmentation networks followed two main lines. Spatial pyramid pooling models such as DeepLab v3 are good at gathering multi-scale context with filters at different atrous rates, but their output is coarse and boundaries are blurry. Encoder-decoder models such as U-Net recover resolution step by step, which gives sharp boundaries. v3+ merges the strengths of both. It also turns the convolutions in ASPP and the decoder into atrous separable convolutions and uses a modified Xception as the backbone, improving both speed and accuracy.

The main results of the paper are:

  • 89.0% mIoU on the PASCAL VOC 2012 test set (with additional JFT-300M pretraining; 87.8% with ImageNet and COCO only), without any post-processing.
  • 82.1% mIoU on the Cityscapes test set of street scenes.
  • On mIoU measured only on pixels near object boundaries, adding the decoder improves results by 4.8 points with ResNet-101 and 5.4 points with Xception for the narrowest boundary band.

The problem: sharper boundaries without more computation

DeepLab v3+ addresses the problem of fixing the coarse output of DeepLab v3 without greatly increasing computation.

DeepLab v3 applies ASPP to a feature map at 1/16 of the image and finally upsamples it 16× in one step with bilinear interpolation. The semantic information about the whole image is rich, but boundary details lost to pooling and strides inside the backbone are not recovered by upsampling.

The straightforward way to get finer output is to use more atrous convolution and keep the feature map at 1/8 or 1/4. According to the paper, however, this is too expensive:

  • To get an output stride (the ratio between the input and feature-map resolutions) of 16 with ResNet-101, the last 3 residual blocks (9 layers) are made atrous.
  • With an output stride of 8, 26 residual blocks (78 layers) are affected, and all of them have to be computed on large feature maps.

Encoder-decoder models, on the other hand, are fast because they do not use atrous convolution in the encoder, and their decoder can gradually recover boundaries. v3+ therefore does the heavy context computation in the encoder at 1/16 and borrows boundary information from the shallow layers of the backbone.

As an everyday analogy, v3 colors a shrunken copy of a map and then enlarges it, so the borders between colors bleed. v3+ overlays the original detailed map (the low-level features) partway through the enlargement and redraws the borders before finishing.

Theory: DeepLab v3 as the encoder, plus a simple decoder

DeepLab v3+ takes the last feature map of v3 (the 256 channels after ASPP, before the logits) as the encoder output, refines it in the decoder together with low-level features at 1/4 of the image, and then upsamples it to the input size. The left side of the figure at the top of the article shows the overall flow.

The encoder is the same as DeepLab v3:

  1. Downsampling in the later stages of a backbone trained on ImageNet (ResNet-101 or a modified Xception) is replaced by atrous convolution, keeping the feature map at 1/16 of the image.
  2. ASPP (a 1×1 convolution, 3×3 convolutions with rates 6, 12 and 18, and image-level features) is applied, the branches are concatenated, and a 1×1 convolution reduces them to 256 channels.

The decoder works as follows:

  1. Upsample the encoder output by 4× with bilinear interpolation (to 1/4 of the image).
  2. Apply a 1×1 convolution to low-level features of the same resolution inside the backbone (for ResNet-101, the Conv2 feature map before striding) to reduce them to 48 channels.
  3. Concatenate 1 and 2 along the channel dimension.
  4. Apply two 3×3 convolutions (256 channels) to refine the features.
  5. Upsample by 4× with bilinear interpolation to get a prediction of the same size as the input.

The decoder convolutions also use batch normalization, and the encoder and decoder are trained jointly end to end rather than part by part.

Why reduce the channels of the low-level features: low-level features often have 256 or 512 channels. Concatenating them as is would give them more weight than the 256 channels of semantic information from the encoder, and also make training harder. The paper compared 8 to 64 channels and found 48 channels to work best.

Comparison of decoder designs (PASCAL VOC 2012 val, ResNet-101, mIoU %)

Low-level feature channels816324864
mIoU77.6177.9278.1678.2177.94
Convolutions after concatenationmIoU
One 3×3 (256)78.21
Two 3×3 (256)78.85
Three 3×3 (256)78.02
One 3×3 (128)77.25
One 1×1 (256)78.07
Both Conv2 and Conv3, upsampling 2× at a time78.61

A form closer to U-Net, also using Conv3 features and upsampling 2× at a time, was tried but gave no notable improvement, so the simplest form (Conv2 only, two 3×3 convolutions) was adopted. The output stride of the last feature map of v3+ is 4; the paper does not go finer because of limited GPU resources.

The output stride of the encoder can be chosen from 32, 16 and 8 just by how atrous convolution is applied. In an ordinary encoder-decoder such as U-Net, the encoder resolution cannot be changed afterwards. v3+ can trade accuracy for speed to fit the compute budget while keeping the same weights.

Atrous separable convolution and the modified Xception

DeepLab v3+ replaces the 3×3 convolutions in ASPP and the decoder with "atrous separable convolutions" and uses a modified Xception as the backbone, increasing accuracy while reducing computation. The right side of the figure at the top of the article shows the details.

Atrous separable convolution: a depthwise separable convolution splits an ordinary convolution into two steps, greatly reducing computation:

  1. Depthwise convolution: applies one filter per input channel and looks only along the spatial dimensions.
  2. Pointwise convolution: a 1×1 convolution that mixes the channels.

v3+ calls the version with an atrous rate in the depthwise convolution of step 1 an atrous separable convolution. Using it in ASPP and the decoder cut multiply-adds by 33–41% with almost the same mIoU.

Modified Xception: based on Aligned Xception, which MSRA modified for object detection, the following changes are made:

  • Deeper network: the middle flow is repeated 16 times, as in MSRA's modification. The entry flow, however, is left unchanged to save computation and memory.
  • No max pooling: every max pooling operation is replaced by a depthwise separable convolution with stride. This allows atrous separable convolution to be used there too, so feature maps can be extracted at any resolution.
  • Extra batch normalization and ReLU: as in MobileNet, batch normalization and ReLU are added after every 3×3 depthwise convolution. Without them, ImageNet top-1 accuracy dropped by 0.75 points and top-5 by 0.29 points.

Single-model error rates on the ImageNet-1k validation set were 22.40% top-1 and 6.02% top-5 for ResNet-101 retrained with the same procedure, and 20.19% and 5.17% for the modified Xception.

Training procedure

The training procedure is the same as DeepLab v3:

  • The learning rate follows the poly schedule, with an initial learning rate of 0.007.
  • Training images are cropped to 513×513.
  • With output stride 16, the batch normalization parameters are also trained.
  • Inputs are randomly scaled for data augmentation.
  • Training uses the 10,582 images of PASCAL VOC 2012 with extra annotations (trainaug), and evaluation uses mIoU over 21 classes (including background).

The model used for the test results is set up for the best accuracy regardless of computation, trained with output stride 8 and frozen batch normalization. With the Xception backbone, v3's Multi Grid (varying the atrous rates inside block4) gave no benefit and is not used.

Experimental results

Effect and cost of the decoder (ResNet-101, PASCAL VOC 2012 val, training output stride 16)

Eval output strideDecoderMulti-scale + flipped inputsmIoU %Multiply-adds
16No (v3)—77.2181.02B
16Yes—78.85101.28B
8No (v3)—78.51276.18B
8Yes—79.35297.92B
8No (v3)Yes79.774870.59B
8YesYes80.575247.07B

The decoder adds about 20B multiply-adds and raises mIoU by about 0.8–1.6 points. The model with the decoder at eval output stride 16 (78.85%, 101.28B) is more accurate with less computation than the model without the decoder at output stride 8 (78.51%, 276.18B). When trained at output stride 32 without atrous convolution, the decoder also raised mIoU from 75.43% to 77.37%, but it remained 1–1.5 points lower than training at 16.

Effect of the Xception backbone (PASCAL VOC 2012 val, output stride 16 for both training and evaluation, single-scale input)

SettingmIoU %Multiply-adds
Xception (no decoder)79.1768.00B
+ decoder79.9389.76B
+ decoder + atrous separable convolution79.7954.17B
+ COCO pretraining82.2054.17B
+ JFT-300M pretraining83.0354.17B

Xception is about 2 points higher than ResNet-101 under the same conditions (77.21%), and atrous separable convolution cuts computation while keeping accuracy almost unchanged. The best setting (eval output stride 8, multi-scale and flipped inputs, pretraining on COCO and JFT) reached 84.56%.

PASCAL VOC 2012 test (mIoU %, excerpt from Table 6 of the paper)

MethodmIoU
PSPNet85.4
DeepLab v385.7
DeepLab v3 (also pretrained on JFT-300M)86.9
DeepLab v3+ (Xception)87.8
DeepLab v3+ (Xception, also pretrained on JFT-300M)89.0

On Cityscapes (street scenes, trained on 2975 finely annotated images, val mIoU %), v3 with Xception scored 77.33% and adding the decoder gave 78.79%. On Cityscapes, removing the image-level feature branch was better (79.14%), and an Xception with a deeper entry flow (X-71) reached 79.55%. The model also trained on coarsely annotated images scored 82.1% on the test set (v3: 81.3%).

As failure cases, the paper lists distinguishing sofas from chairs, heavily occluded objects, and objects seen from rare viewpoints.

Practical notes

Keep the following points in mind when using DeepLab v3+:

  • Where to take the low-level features: the decoder needs low-level features at the same resolution (1/4 of the image) as the 4× upsampled encoder output. For ResNet-101 in the paper, this is the Conv2 feature map before striding. When changing the backbone, check where to take the 1/4-resolution features from.
  • Keep the low-level channels few: reduce the low-level features to about 48 channels with a 1×1 convolution before concatenation. Otherwise the semantic information from the encoder gets buried and training becomes harder.
  • Input size: the encoder's 1/16 map upsampled by 4× must match the size of the backbone's 1/4 features. The paper crops to sizes of the form "multiple of 16 + 1", such as 513×513. When the sizes do not match, interpolate one to the size of the other.
  • Choose the output stride for the compute budget: an encoder output stride of 16 gives a good balance of speed and accuracy; 8 improves accuracy slightly but increases computation a lot.
  • The image-level feature branch depends on the dataset: it helped on PASCAL VOC, but accuracy was higher without it on Cityscapes.

PyTorch's torchvision does not include DeepLab v3+ or the paper's modified Xception. It has DeepLab v3 (such as deeplabv3_resnet50), but that model has no decoder and its ASPP settings differ from the paper. Build v3+ by adding a decoder to a torchvision ResNet as in the example below, or use an external library. The official implementation of the paper is in TensorFlow.

Comparison with other methods

DeepLab v3+ sits between DeepLab v3's idea of "keeping resolution with atrous convolution" and U-Net's idea of "recovering boundaries with low-level features". Comparing how each method refines its output and gathers context:

MethodHow the output is refinedHow multi-scale context is gatheredMain strengths and weaknesses
FCN-8sUpsamples with transposed convolution and adds predictions from shallow layersAdds predictions from shallow and deep layersSimple and fast. Boundaries tend to be blurry
U-NetA thick decoder that upsamples 2× at a time, concatenating features from each stageGathers context by downsampling stage by stageFine boundaries and easy to train with little data. High-resolution stages use a lot of memory
DeepLab v3Keeps 1/16 or 1/8 with atrous convolution and upsamples 16× or 8× in one stepASPP and image-level featuresStrong on context. Boundaries are coarse, and 1/8 is computationally heavy
DeepLab v3+Upsamples v3's 1/16 by 4×, concatenates with 1/4 low-level features, and refinesSame ASPP as v3Strong on both context and boundaries. Adds the decoder's computation (about 20B multiply-adds with ResNet-101)

Rough guidelines for choosing:

  • Scene or object images where both context and boundaries matter: DeepLab v3+ is the first candidate. An encoder with output stride 16 gives a good balance of speed and accuracy.
  • Minimal computation, or a pretrained model ready to use: consider DeepLab v3, which is built into torchvision, or a lightweight backbone such as MobileNetV2.
  • Few training images, such as medical images, and thin structures to separate: the U-Net family is a better fit.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet101, ResNet101_Weights

"""
A small implementation of DeepLab v3+ following Sections 3.1 and 4.1 of the paper (ResNet-101 backbone).
torchvision has no built-in DeepLab v3+, so it is built by adding ASPP and a decoder to a ResNet
"""


def conv_bn_relu(c_in, c_out, kernel, dilation=1, separable=False):
  pad = 0 if kernel == 1 else dilation
  if separable and kernel > 1:
    # Atrous separable convolution: 3x3 depthwise (rate r) -> 1x1 pointwise
    # (The paper does not specify where BN and ReLU go inside ASPP/decoder; here they follow each step)
    return nn.Sequential(
      nn.Conv2d(c_in, c_in, kernel, padding=pad, dilation=dilation, groups=c_in, bias=False),
      nn.BatchNorm2d(c_in), nn.ReLU(inplace=True),
      nn.Conv2d(c_in, c_out, 1, bias=False),
      nn.BatchNorm2d(c_out), nn.ReLU(inplace=True),
    )
  return nn.Sequential(
    nn.Conv2d(c_in, c_out, kernel, padding=pad, dilation=dilation, bias=False),
    nn.BatchNorm2d(c_out), nn.ReLU(inplace=True),
  )


class ASPP(nn.Module):
  """ASPP from DeepLab v3. Rates (6, 12, 18) for output stride 16"""
  def __init__(self, c_in=2048, c_out=256, rates=(6, 12, 18), separable=False):
    super().__init__()
    self.branches = nn.ModuleList(
      [conv_bn_relu(c_in, c_out, 1)] +
      [conv_bn_relu(c_in, c_out, 3, dilation=r, separable=separable) for r in rates]
    )
    self.image_pool = nn.Sequential(nn.AdaptiveAvgPool2d(1), conv_bn_relu(c_in, c_out, 1))
    self.project = conv_bn_relu(c_out * (len(rates) + 2), c_out, 1)

  def forward(self, x):
    outs = [b(x) for b in self.branches]
    outs.append(F.interpolate(self.image_pool(x), size=x.shape[-2:], mode='bilinear', align_corners=False))
    return self.project(torch.cat(outs, dim=1))


class DeepLabV3Plus(nn.Module):
  def __init__(self, num_classes=21, separable=False):
    super().__init__()
    # Replace striding in the last stage (layer4) with atrous convolution for output stride 16
    r = resnet101(weights=ResNet101_Weights.IMAGENET1K_V1, replace_stride_with_dilation=[False, False, True])
    self.stem = nn.Sequential(r.conv1, r.bn1, r.relu, r.maxpool)
    self.layer1 = r.layer1                           # Low-level features: 1/4 of the image, 256 channels (Conv2 in the paper)
    self.rest = nn.Sequential(r.layer2, r.layer3, r.layer4)   # 1/16 of the image, 2048 channels
    self.aspp = ASPP(separable=separable)            # Encoder output: 256 channels
    self.reduce = conv_bn_relu(256, 48, 1)           # Reduce low-level features to 48 channels
    self.refine = nn.Sequential(                     # Two 3x3 (256) after concatenation
      conv_bn_relu(256 + 48, 256, 3, separable=separable),
      conv_bn_relu(256, 256, 3, separable=separable),
    )
    self.classifier = nn.Conv2d(256, num_classes, 1)

  def forward(self, x):                              # x: (N, 3, H, W)
    size = x.shape[-2:]
    low = self.layer1(self.stem(x))                  # 1/4
    enc = self.aspp(self.rest(low))                  # 1/16
    enc = F.interpolate(enc, size=low.shape[-2:], mode='bilinear', align_corners=False)   # Upsample by 4x
    h = self.refine(torch.cat([enc, self.reduce(low)], dim=1))
    h = self.classifier(h)
    return F.interpolate(h, size=size, mode='bilinear', align_corners=False)              # Upsample by another 4x


model = DeepLabV3Plus(num_classes=21, separable=True)
criterion = nn.CrossEntropyLoss(ignore_index=255)    # "Ignored" pixels such as VOC boundaries are 255

# Same training setup as DeepLab v3: initial LR 0.007, poly (power 0.9), 513x513 crops
max_iter = 30000                                     # Example value
optimizer = torch.optim.SGD(model.parameters(), lr=0.007, momentum=0.9)   # Momentum is an example value
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda it: (1 - it / max_iter) ** 0.9)

images = torch.randn(2, 3, 513, 513)
masks = torch.randint(0, 21, (2, 513, 513))
model.train()                                        # BN uses mini-batch statistics
loss = criterion(model(images), masks)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()

model.eval()                                         # BN uses statistics accumulated during training
with torch.no_grad():
  pred = model(images).argmax(1)                     # (N, 513, 513): class per pixel

FAQ

Q. What is the difference between DeepLab v3 and v3+?
A.

v3+ uses v3 as is for the encoder and adds a simple decoder. v3 upsamples the ASPP output (1/16 of the image) 16× in one step with bilinear interpolation, whereas v3+ first upsamples by 4×, concatenates it with the backbone's 1/4 low-level features (reduced to 48 channels), applies two 3×3 convolutions, and then upsamples by another 4×. With only about 20B extra multiply-adds on ResNet-101, val mIoU rose from 77.21% to 78.85%.

Q. How does it differ from a U-Net-style decoder?
A.

U-Net has a thick decoder that upsamples 2× four times while concatenating features from every encoder stage. The v3+ decoder is simple: it concatenates 1/4 low-level features only once. The paper also tried a form closer to U-Net that used Conv3 features and upsampled 2× at a time, but it gave no notable improvement. Instead, v3+ gathers multi-scale context thoroughly on the encoder side with atrous convolution and ASPP.

Q. What is atrous separable convolution?
A.

It is a depthwise separable convolution whose depthwise convolution has an atrous rate. A per-channel 3×3 convolution (rate rr) looks at the spatial dimensions, and a 1×1 convolution mixes the channels. v3+ replaced the 3×3 convolutions in ASPP and the decoder with it, cutting multiply-adds by 33–41% while keeping mIoU almost the same.

References

  1. Chen, L.-C., Zhu, Y., Papandreou, G., Schroff, F., & Adam, H. (2018). Encoder-Decoder with Atrous Separable Convolution for Semantic Image Segmentation. European Conference on Computer Vision (ECCV 2018). arXiv:1802.02611.
  2. Chen, L.-C., Papandreou, G., Schroff, F., & Adam, H. (2017). Rethinking Atrous Convolution for Semantic Image Segmentation. arXiv:1706.05587.
  3. Chollet, F. (2017). Xception: Deep Learning with Depthwise Separable Convolutions. CVPR 2017. arXiv:1610.02357.
  4. TensorFlow Models. DeepLab: Deep Labelling for Semantic Image Segmentation (official implementation).