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 replaces downsampling in the later stages of an image classification network with atrous convolution to keep feature maps at high resolution, and gathers context for objects of various sizes with ASPP (Atrous Spatial Pyramid Pooling), which runs convolutions at different atrous rates in parallel with image-level features. It was published by Chen et al. at Google in 2017 (an arXiv technical report).
DeepLab is a series. v1 and v2 refined the coarse CNN output along boundaries with a post-processing step called a conditional random field (DenseCRF). v3 revisited how atrous convolution is used, added batch normalization and image-level features to ASPP, and refined the training procedure, outperforming v2 without any post-processing.
The main results of the paper are:
85.7% mIoU on the PASCAL VOC 2012 test set (without DenseCRF). With a ResNet-101 also pretrained on JFT-300M, it reaches 86.9%.
On the validation set, it reaches 79.77% without COCO pretraining, surpassing v2 (77.69% with DenseCRF and COCO pretraining).
On the Cityscapes test set of street scenes, it scores 81.3% mIoU when also trained on coarsely annotated images.
DeepLab v3+ adds a simple decoder to DeepLab v3 to sharpen object boundaries.
The problem: lost resolution and objects of many sizes
DeepLab v3 tackles two obstacles that arise when using a classification network for segmentation:
Reduced feature-map resolution: classification networks stack pooling and strides, so the last feature map is 1/32 of the input. This helps learn abstract features that are robust to shifts, but loses the fine location information needed for per-pixel prediction.
Objects of varying size: the same image may show a small person far away and a large car up close. A receptive field (the input region that one output pixel sees) of a single size misses one or the other.
The paper groups earlier ways of capturing multi-scale context into four types:
Approach
How it works
Weakness
Image pyramid
Feeds the input at several scales through the same network and merges the features
Large, deep networks run out of GPU memory, so it tends to be used only at inference
Encoder-decoder
The encoder shrinks the input to capture long-range information, and the decoder recovers detail and resolution (e.g. U-Net)
Requires designing and computing a decoder
Context module
Stacks DenseCRF or extra convolutions after the network to capture long-range information
Requires separate post-processing, etc.
Spatial pyramid pooling
Probes the feature map with filters or pooling at several scales (SPP, v2's ASPP)
―
Using atrous convolution as its tool, DeepLab v3 redesigns both the third type (stacking modules in cascade) and the fourth (in parallel, i.e. ASPP), and finally adopts ASPP.
Theory: setting the output stride with atrous convolution
DeepLab v3 removes downsampling (stride 2) in the later stages of a classification network and turns the subsequent convolutions into atrous convolutions, extracting dense feature maps with the pretrained weights unchanged.
Atrous convolution is a convolution that samples its input at intervals. With output position i, filter w, input x and atrous rate r, it is written as:
y[i]=k∑x[i+r⋅k]w[k]
This is equivalent to convolving with an enlarged filter that has r−1 zeros inserted between filter values. r=1 is ordinary convolution; increasing r widens the field of view without adding parameters.
The paper calls the ratio between the input resolution and the resolution of the last feature map the output stride. Classification networks have an output stride of 32. To make it 16:
Set the stride of the last pooling or convolution that reduces resolution to 1 (stop downsampling).
Replace all subsequent convolutions with atrous convolutions of rate 2.
For output stride 8, do the same one stage earlier as well, giving the last two ResNet stages (block3 and block4) rates 2 and 4.
Removing downsampling makes the feature maps larger, but because the atrous rate grows by the same factor, the input region each layer sees is the same as in the original classification network. The weights trained on ImageNet can therefore be used as is.
Multi Grid: the three 3×3 convolutions inside ResNet's block4 are given different rates by multiplying base rates (r1,r2,r3). For example, with output stride 16 and Multi Grid =(1,2,4), the rates of the three convolutions in block4 are 2⋅(1,2,4)=(2,4,8).
The output stride is a knob that trades accuracy for computation. Output stride 8 yields finer feature maps than 16, but the intermediate feature maps have 4 times the area, so training is several times slower and uses more memory. Because atrous convolution adds no parameters, the stride can be switched between phases with the same weights, e.g. 16 for training and 8 for evaluation.
ASPP: atrous rates and image-level features in parallel
ASPP is a module that applies convolutions with different atrous rates and image-level features in parallel to the same feature map, then concatenates and mixes them. It was proposed in v2, and v3 added batch normalization and image-level features. The right side of the figure at the top of the article shows its contents.
With output stride 16, ASPP computes as follows:
Apply the following five branches in parallel to the output of ResNet's block4:
One 1×1 convolution
Three 3×3 convolutions with rates 6, 12 and 18
Image-level features: global average pooling down to 1×1, a 1×1 convolution, and bilinear upsampling back to the original size
Concatenate the outputs of the five branches along channels and mix them with a 1×1 convolution (256 channels, with batch normalization).
A final 1×1 convolution outputs the class scores (logits).
With output stride 8, the rates are doubled to 12, 24 and 36, so that the same input region is covered when the feature map is twice as fine.
Why image-level features are needed: the larger the atrous rate, the more of the 9 weights of a 3×3 filter fall outside the feature map (into zero padding). When the paper counted this on a 65×65 feature map, once the rate approached the feature-map size only the center weight remained effective, and the 3×3 convolution degenerated into a plain 1×1 convolution. A branch meant to capture distant context ends up seeing nothing. Adding features averaged over the whole image as a separate branch ensures that global context is included.
As an everyday analogy, ASPP looks at one photo simultaneously through a magnifying glass, the naked eye, binoculars and a telescope, also notes the overall mood of the photo (indoors or outdoors), and then weighs everything together to decide.
Comparison with cascading: the paper also tried a module that stacks copies of block4 (block5–block7) in cascade, doubling the rate each time. The best setting (ResNet-101, block7, Multi Grid (1,2,1)) reached 79.35% val mIoU, slightly below the best ASPP result (79.77%), so ASPP became the final model.
Training procedure
The accuracy of DeepLab v3 depends heavily on the training procedure as well as the architecture. The paper's procedure is:
Start from a ResNet trained on ImageNet, with output stride 16.
Train for 30K iterations on the 10,582 images of PASCAL VOC 2012 with extra annotations (trainaug). The initial learning rate is 0.007, decayed with poly (multiplying the initial learning rate by (1−max_iteriter)0.9).
Batch normalization statistics are computed over mini-batches of 16 images and trained with decay 0.9997.
Freeze the batch normalization parameters, set the output stride to 8, and train for another 30K iterations on the official trainval set with learning rate 0.001.
Other settings:
Crop size: crop to 513×513 for both training and evaluation. Large crops are needed so that convolutions with large rates do not see mostly padding.
Upsampling the logits: v1 and v2 trained with ground-truth maps downsampled to 1/8, which removes fine annotations so that errors in details are not backpropagated. v3 keeps the ground truth as is and instead upsamples the network output (logits) before computing the loss.
Data augmentation: during training, inputs are randomly scaled by 0.5–2.0× and randomly flipped left-right.
More hard images: in the final fine-tuning before testing, images containing the hard classes bicycle, chair, table, potted plant and sofa were duplicated in the training data (a simple substitute for selecting hard examples pixel by pixel).
Effect of training settings (PASCAL VOC 2012 val, output stride 16, mIoU %)
Ground truth downsampled instead of upsampling logits
76.01
Crop reduced to 321
67.22
Effect of mini-batch size (same conditions, mIoU %)
Mini-batch
4
8
12
16
mIoU
64.43
75.76
76.49
77.21
Training batch normalization requires large mini-batches, so the paper does the first phase of training at output stride 16, which leaves more memory headroom.
Experimental results
Effect of output stride (ResNet-50 with cascaded blocks up to block7, PASCAL VOC 2012 val, mIoU %)
Output stride
8
16
32
64
128
256
mIoU
75.18
73.88
70.06
59.99
42.34
20.29
Stacking blocks without atrous convolution (output stride 256) loses detail to downsampling and drops to 20.29%. The more downsampling is replaced by atrous convolution, the higher the accuracy, showing that atrous convolution is essential for deep cascades.
Inference strategies for the ASPP model (ResNet-101, Multi Grid (1,2,4), ASPP (6,12,18), image-level features, val, mIoU %)
Inference setting
mIoU
Output stride 16
77.21
Output stride 8
78.51
+ multi-scale inputs (6 scales from 0.5 to 1.75×)
79.45
+ left-right flipped inputs
79.77
+ COCO pretraining
82.70
Within ASPP, adding image-level features raised mIoU from 76.58% to 77.21%. Adding another branch with rate 24 lowered it by 0.12 points.
PASCAL VOC 2012 test (mIoU %, excerpt from Table 7 of the paper)
Method
mIoU
DeepLab v2 (with DenseCRF)
79.7
Multipath-RefineNet
84.2
PSPNet
85.4
DeepLab v3
85.7
DeepLab v3 (also pretrained on JFT-300M)
86.9
The DeepLab v3 model uses COCO pretraining and fine-tuning on trainval, without DenseCRF.
On Cityscapes (street scenes, 5000 finely annotated images, 19 classes), training only on the 2975 finely annotated training images gave 79.30% val mIoU (output stride 8, multi-scale inputs, left-right flips). A model also trained on about 20,000 coarsely annotated images scored 81.3% on the test set.
As failure cases, the paper lists distinguishing sofas from chairs and dining tables from chairs, and objects seen from rare viewpoints.
Practical notes
Keep the following points in mind when using DeepLab v3:
Thin structures and boundaries are still coarse: the ASPP output is 1/16 of the input (1/8 at evaluation) and is upsampled in one step with bilinear interpolation at the end, so object boundaries and thin parts tend to blur. If boundaries matter, consider DeepLab v3+, which adds a decoder, or the U-Net family.
Computation and memory: stages without downsampling compute on large feature maps, so the model is heavier than the classification network. Output stride 8 costs several times as much as 16.
Whether large mini-batches are possible: because batch normalization is trained, small mini-batches hurt accuracy a lot (64.43% with 4 images, 77.21% with 16). When GPU memory is short, the paper chooses to train at output stride 16.
Use large crops: branches with large rates see mostly padding when the input is small. In the paper, reducing the crop from 513 to 321 dropped mIoU from 77.21% to 67.22%.
torchvision's deeplabv3_resnet50 and deeplabv3_resnet101 differ from the paper in the details. The output stride is 8 (the last two ResNet stages use atrous convolution), the ASPP rates are 12, 24 and 36, there is a 3×3 convolution and Dropout (0.5) after ASPP, and there is an auxiliary output (aux) for training. The output is a dictionary, and the main prediction is in out. num_classes includes the background (21 for PASCAL VOC), and "ignored" pixels such as ground-truth boundaries (255 in VOC) are passed to the loss as ignore_index.
Comparison with other methods
Unlike encoder-decoder models, DeepLab v3 keeps detail by not reducing resolution too much in the first place. Comparing how each method refines its output and gathers context:
Adds a simple decoder to v3 that uses features at 1/4 resolution
Same ASPP as v3
Finer boundaries. Computation grows by the cost of the decoder
Rough guidelines for choosing:
Scene or object images where global context matters: DeepLab v3 can use a large ImageNet-trained classification network as is, and pretrained models are easy to obtain.
Fine object boundaries also matter: DeepLab v3+ is a better fit.
Few training images where boundaries matter, such as medical images: the U-Net family is a better fit.
Lighter computation: the DeepLab v3 head can also be attached to a lightweight network such as MobileNetV2.
PyTorch example
▶Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
A small implementation of DeepLab v3's ASPP following Section 3.3 of the paper.
Rates are (6, 12, 18) for output stride 16 and doubled to (12, 24, 36) for output stride 8
"""
def conv_bn_relu(c_in, c_out, kernel, dilation=1):
pad = 0 if kernel == 1 else dilation # Padding equal to the rate keeps the size unchanged
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):
def __init__(self, c_in=2048, c_out=256, rates=(6, 12, 18)):
super().__init__()
self.branches = nn.ModuleList(
[conv_bn_relu(c_in, c_out, 1)] + # 1x1 convolution
[conv_bn_relu(c_in, c_out, 3, dilation=r) for r in rates] # 3x3 convolutions with different rates
)
self.image_pool = nn.Sequential( # Image-level features
nn.AdaptiveAvgPool2d(1),
conv_bn_relu(c_in, c_out, 1),
)
self.project = conv_bn_relu(c_out * (len(rates) + 2), c_out, 1) # Concatenate, then 1x1 convolution
def forward(self, x):
size = x.shape[-2:]
outs = [b(x) for b in self.branches]
pooled = self.image_pool(x)
outs.append(F.interpolate(pooled, size=size, mode='bilinear', align_corners=False))
return self.project(torch.cat(outs, dim=1))
class DeepLabV3Head(nn.Module):
def __init__(self, num_classes=21, rates=(6, 12, 18)):
super().__init__()
self.aspp = ASPP(rates=rates)
self.classifier = nn.Conv2d(256, num_classes, 1) # Final 1x1 convolution outputs the logits
def forward(self, feat, out_size):
logits = self.classifier(self.aspp(feat))
# Upsample logits to the input size instead of downsampling the ground truth (Section 4.1)
return F.interpolate(logits, size=out_size, mode='bilinear', align_corners=False)
# Pretrained DeepLab v3 (ResNet-50) from torchvision. Details differ from the paper:
# output stride 8, ASPP rates (12, 24, 36), 3x3 conv and Dropout(0.5) after ASPP, auxiliary output aux
from torchvision.models.segmentation import deeplabv3_resnet50, DeepLabV3_ResNet50_Weights
model = deeplabv3_resnet50(weights=DeepLabV3_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1)
criterion = nn.CrossEntropyLoss(ignore_index=255) # "Ignored" pixels such as VOC boundaries are 255
# Paper's setting: SGD, initial LR 0.007, poly (power 0.9), 30K iterations
max_iter = 30000
optimizer = torch.optim.SGD(model.parameters(), lr=0.007, momentum=0.9, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda it: (1 - it / max_iter) ** 0.9)
# Momentum and weight decay are not given in the paper; these are example values
images = torch.randn(2, 3, 513, 513) # Crop to 513x513
masks = torch.randint(0, 21, (2, 513, 513))
model.train() # BN uses mini-batch statistics (needs large mini-batches)
out = model(images) # Dict: 'out' is the main output, 'aux' the auxiliary one
loss = criterion(out['out'], masks) + 0.5 * criterion(out['aux'], masks) # Choose the auxiliary loss weight yourself (example value here)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()
model.eval() # BN uses statistics accumulated during training
with torch.no_grad():
pred = model(images)['out'].argmax(1) # (N, 513, 513): class per pixel
# Example using the custom head (from a 2048-channel, 1/16 feature map)
head = DeepLabV3Head(num_classes=21)
feat = torch.randn(2, 2048, 33, 33)
logits = head(feat, out_size=(513, 513)) # (2, 21, 513, 513)
FAQ
Q. What is the difference between DeepLab v3 and v3+?
A.
v3 upsamples the ASPP output (1/16 or 1/8 of the input) in one step with bilinear interpolation at the end. v3+ uses v3 as an encoder and adds a simple decoder that upsamples its output by 4×, concatenates it with low-level features at 1/4 resolution, and refines it with 3×3 convolutions. This sharpens object boundaries.
Q. What is the output stride?
A.
It is the ratio between the resolution of the input image and that of the last feature map. Classification networks use 32, and DeepLab v3 replaces some downsampling with atrous convolution to get 16 or 8. Smaller values give finer feature maps but need more computation and memory. In the paper, training at 16 and evaluating at 8 worked best, giving 78.51% val mIoU.
Q. Why add image-level features (a global average pooling branch) to ASPP?
A.
The larger the atrous rate, the more weights of a 3×3 filter fall outside the feature map (into padding); when the rate approaches the feature-map size, only the center weight is effective and the filter becomes a plain 1×1 convolution. To reliably bring in distant context, features averaged over the whole image are added as a separate branch. In the paper, this raised mIoU from 76.58% to 77.21%.