Dual Attention Network for Scene Segmentation
- Publication
- CVPR 2019Conference
- First submitted to arXiv
- arXiv:1809.02983
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{segmentationdanet2018,
title = {{Dual Attention Network for Scene Segmentation}},
author = {Jun Fu and Jing Liu and Haijie Tian and Yong Li and Yongjun Bao and Zhiwei Fang and Hanqing Lu},
year = {2018},
eprint = {1809.02983},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1809.02983}
}
In 2018, everyone in semantic segmentation was looking for ways to let each pixel "see farther." PSPNet used pooling of different sizes, DeepLab used convolutions with different atrous rates, and EncNet used global encoding. The methods differed, but all of them compressed the context of a region and then handed it out to each pixel.
By then, Transformer self-attention had already shown in machine translation that every position can see every other position directly, with content deciding whom to look at and how much. Non-local Networks and SAGAN had also just brought the trick into images.
Jun Fu, Jing Liu and colleagues at the Institute of Automation, Chinese Academy of Sciences (along with collaborators from JD.com) attached self-attention to a segmentation network, and attached two at once: one working over space, one over channels. That's DANet.
Defining the Problem
The authors cite two kinds of errors common in scene segmentation.
The first is things that look too alike. A field and grass look almost the same up close, and a small patch of pixels on its own is hard to tell apart.
The second is things of the same kind that look different. A car may be large or small, half occluded, or in shadow, so the features computed for pixels of the same class vary a lot. The authors call this intra-class inconsistency.
A convolution's receptive field is local, so both problems need context from a wider range. The mainstream approach at the time was multi-scale fusion, such as ASPP, pyramid pooling, large kernels, or encoder–decoders that join mid- and high-level features. The authors argue that these approaches can handle objects of different sizes but don't exploit, at a global scale, the relationships between objects, or between objects and background.
Another school used RNNs, such as 2D LSTMs or DAG-RNNs, to pass information across the image. But these methods learn the global relationships implicitly, so how well they work depends on how well the network's long-term memory is learned.
The authors also made a finer observation. Lighting or viewing angle can make some pedestrians and traffic lights inconspicuous. If a large region's context is simply spread evenly over every pixel, the conspicuous cars and buildings nearby end up drowning out these inconspicuous objects.
So the context DANet wants is selective: each pixel should seek out the pixels similar to itself, however far away they are.
Solving the Problem
Overall Architecture

The backbone is a pretrained ResNet. Its last two blocks drop downsampling in favor of atrous convolution, so the output feature map is 1/8 of the input, the same setting as DeepLab and PSPNet.
Next, the features split into two branches, each first reduced in dimension by a convolution layer, then fed into the position attention module (PAM) and the channel attention module (CAM) respectively. Each branch's output goes through a convolution layer, the two are added element-wise, and one more convolution layer outputs each pixel's class. The authors say they don't concatenate because concatenation takes more GPU memory.
Let's follow a concrete size through it. The Cityscapes ablations crop images to 768×768 with output stride 8, so the backbone's output is 96×96 with 2,048 channels. The official code first reduces the channels to 512 with a 3×3 convolution, so the features entering the two modules are 512×96×96.
Position Attention: Every Pixel Looks at Every Pixel

Look at (A). The input is the feature .
First, goes through separate convolutions to give two new feature maps, and , which are flattened into matrices, where is the number of pixels. In our example, .
Second, multiply the transpose of with and apply a softmax to each row to get the spatial attention :
is the influence of position on position . The more alike the features at the two positions, the larger .
Third, goes through one more convolution to give ; takes a weighted average of , which is multiplied by a learnable coefficient and added back to the original :
starts at 0, so at the beginning of training the module does nothing and its output equals its input; the network then gradually learns how much of the attention result to add in. This design comes from SAGAN.
This is Transformer self-attention, with , and playing query, key and value. Each pixel's new feature is a weighted average of all pixels' features, with weights set by similarity regardless of distance. A pixel on the left side of one car can get information directly from another car on the far side of the frame.
How big is this matrix? On a 768×768 training crop, , and the matrix has about 85 million values, about 340MB in 32-bit floats, for one module on one image. Feed a full 1024×2048 Cityscapes image straight in, and becomes ; the matrix grows to about 1.07 billion values, about 4.3GB (both figures are our estimates from the paper's settings). In their conclusion, the authors also say that reducing the computational complexity is future work.
Channel Attention: Letting Related Channels Help Each Other
Look at (B). The authors' idea is that each channel of the deep features can be seen as the response to some class, and some channels are correlated with each other; for example, the "car" channel and the "road" channel often show up together.
Channel attention is computed almost exactly like position attention, just with the matrix multiplication turned the other way.
Flatten into , multiply it by its own transpose to get a matrix, then apply a softmax:
is the influence of channel on channel . Then, as before, take the weighted sum, multiply by a learnable (starting from 0) and add back to :
In our example, , so the attention matrix is 512×512, only about 260,000 values, more than 300 times smaller than position attention's.
There are two deliberate choices here. First, channel attention uses directly, with no convolution in front; the authors say this preserves the original relationships between channels. Second, it uses spatial information from all positions to compute the correlations between channels, whereas SENet and EncNet first pool the whole image into a vector and then decide each channel's weight.
Discussion
Ablations
The experiments are mainly on Cityscapes: 5,000 street scenes at 2048×1024, 19 classes, fine annotations only. Training uses PyTorch, synchronized BatchNorm, a poly learning rate and batch size 8, with random 768 crops and horizontal flips for the ablations.
Validation set results (the paper's Table 1):
| Backbone | Setting | mIoU |
|---|---|---|
| ResNet-50 | Dilated FCN | 70.03 |
| + PAM | 75.74 | |
| + CAM | 74.28 | |
| + PAM + CAM | 76.34 | |
| ResNet-101 | Dilated FCN | 72.54 |
| + PAM + CAM | 77.57 |
Each module helps on its own, with position attention adding 5.7 points and channel attention 4.3, and together they reach 76.34. But together they're only 0.6 above position attention alone, so a large share of the two modules' contributions overlaps.
Stacking on a few tricks DeepLab v3 used (the paper's Table 2), random-scaling data augmentation brings it to 78.83, multi-grid in the last ResNet block (atrous rates 4, 8 and 16) to 79.94, and averaging over 8 scales at test time to 81.50, 2.2 above DeepLab v3's 79.30 on the same validation set.
On the test set, DANet trained with fine annotations only gets 81.5, above DenseASPP (80.6), PSANet (80.1) and PSPNet (78.4).
What the Attention Actually Looks At

Each row of can be turned back into an map that shows where a given pixel is looking. Columns 2 and 3 are such "sub-attention maps."
In the first row, point #1 is on a building, and its attention lights up every building in the frame with fairly clean boundaries, even the ones far away. Point #2 is on a car, and its attention concentrates on cars. In the third row, point #2 is on a pedestrian; it ignores the rider right next to it and lights up on another pedestrian far off in the frame. For DANet, a distant member of the same class matters more than a neighbor of a different class, the exact opposite of the saying that a near neighbor is better than a distant relative.
Channel attention is harder to visualize, so the authors picked two channels to look at. Channel 11 corresponds to cars in all three images, and channel 4 to vegetation.
Other Datasets
On PASCAL Context (59 classes plus background), DANet-50 is 5.8 above the dilated FCN with the same backbone (44.3), and DANet-101 reaches 52.6, above EncNet's 51.7. On COCO Stuff (171 classes) it gets 39.7, where the previous best method had 35.7. On the PASCAL VOC 2012 test set it gets 82.6, tied with PSPNet and slightly below EncNet's 82.9.
Judging from these numbers, the more classes and the messier the scenes in a dataset, the bigger DANet's lead. One possible reason (our guess) is that VOC images mostly contain only one or two foreground objects, so there are only so many same-class pixels to find across the image.
What the Paper Says and What the Code Does
DANet's official code is public and has over two thousand stars to date. Anyone who reads it soon notices that channel attention differs from the paper:
# CAM_Module.forward (excerpt from the official da_att.py)
proj_query = x.view(m_batchsize, C, -1)
proj_key = x.view(m_batchsize, C, -1).permute(0, 2, 1)
energy = torch.bmm(proj_query, proj_key)
energy_new = torch.max(energy, -1, keepdim=True)[0].expand_as(energy) - energy
attention = self.softmax(energy_new)
The paper's Equation 3 applies a softmax directly to the similarity . The code adds a line: first take each row's maximum, subtract the similarity from it, and only then apply the softmax.
Adding or subtracting the same constant across a whole row leaves a softmax unchanged, so that maximum actually cancels out, and the line's effect is . The more similar a channel, the lower its weight. The paper says "related channels reinforce each other"; the code does "the less alike a channel, the more you listen to it."
As early as September 2018, someone asked in issue #9 what this line does, and the authors' entire answer was "Prevent loss divergence during training." When #15 and #106 later asked the same thing, the authors only replied with a pointer to #9. From 2021 on, commenters pointed out one after another that guarding against numerical overflow should be written as , and that PyTorch's softmax already takes care of that anyway; writing amounts to turning the attention upside down.
Best of all is issue #48. Someone suggested changing it to energy - max, that is, writing it the way the paper means, and the authors replied "we have tried the form you provide, but the performance is not good" (written the paper's way, it actually works worse).
So the passage the paper uses to explain channel attention (each channel is a class response, and related responses should reinforce each other) and what the official implementation computes are two different things. The version that actually produced the results has the similarity flipped, and the authors' only explanation is "Prevent loss divergence during training."
There are plenty of reproduction reports too. Someone trained for 240 epochs with the README command and reported only 73.5 in issue #30 (the authors explained that the score shown during training covers only some of the images, and test.py has to be run separately); in the same thread, someone pointed out that the paper gives a Cityscapes learning rate of 0.01 while the README command uses 0.003, and only then did the authors add that 0.003 is for both modules plus three losses (one main loss and two auxiliary losses). In issue #41, someone got 75.05 with test.py at single scale with data augmentation plus multi-grid, and another user got 78.93, against the paper's 79.94 for the same setting.
Conclusion
DANet is one of the first networks to put self-attention fully into semantic segmentation. Position attention lets each pixel find similar pixels directly across the whole image, adding 5 to 6 points over a dilated FCN on Cityscapes; channel attention adds a little more; together, they took the best results of the time on Cityscapes, PASCAL Context and COCO Stuff.
Its cost is just as direct. The position attention matrix grows with the square of the pixel count, and a single full Cityscapes image needs several GB. Later, CCNet's criss-cross attention and OCRNet's object region attention both looked for ways to get similar global context with less computation.
If you want to use DANet's channel attention, first decide whether you want the paper version or the code version. The two do exactly opposite things, and according to the authors, the one that works is the code version.