Back to paper library
arXiv 2018CVPR 2019SegmentationPaper notes

DANet

Look Everywhere

Original paper

Dual Attention Network for Scene Segmentation

Paper authors

Jun Fu · Jing Liu · Haijie Tian …

Show all 7 authors

Jun Fu · Jing Liu · Haijie Tian · Yong Li · Yongjun Bao · Zhiwei Fang · Hanqing Lu

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}
}
On this page

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

Original Figure 2: DANet overview. A street image passes through ResNet to get features, which split into an upper and a lower branch, each first going through a convolution layer. The upper branch is the position attention module, which produces an (H×W)×(H×W) spatial attention matrix that is multiplied with the features and then added element-wise to the original features; the lower branch is the channel attention module, which produces a C×C channel attention matrix, likewise multiplied and added. The outputs of the two branches pass through convolutions and are fused by addition to give the segmentation result.
Original Figure 2, Fu et al., from PDF page 3, arXiv license, scholarly quotation.

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

Original Figure 3: details of the two modules. (A) Position attention: feature A passes through convolutions to give B, C and D; B and C are reshaped and multiplied, and a softmax gives the (H×W)×(H×W) attention S; S is multiplied with D, reshaped, and added to A to give E. (B) Channel attention: A is reshaped and multiplied with its own transpose, and a softmax gives the C×C attention X; X is multiplied with A, reshaped, and added to A to give E.
Original Figure 3, Fu et al., from PDF page 4, arXiv license, scholarly quotation.

Look at (A). The input is the feature A∈RC×H×WA \in \mathbb{R}^{C \times H \times W}.

First, AA goes through separate convolutions to give two new feature maps, BB and CC, which are flattened into C×NC \times N matrices, where N=H×WN = H \times W is the number of pixels. In our example, N=96×96=9,216N = 96 \times 96 = 9{,}216.

Second, multiply the transpose of CC with BB and apply a softmax to each row to get the spatial attention S∈RN×NS \in \mathbb{R}^{N \times N}:

sji=exp⁡(Bi⋅Cj)∑i=1Nexp⁡(Bi⋅Cj)s_{ji} = \frac{\exp(B_i \cdot C_j)}{\sum_{i=1}^{N} \exp(B_i \cdot C_j)}

sjis_{ji} is the influence of position ii on position jj. The more alike the features at the two positions, the larger sjis_{ji}.

Third, AA goes through one more convolution to give DD; SS takes a weighted average of DD, which is multiplied by a learnable coefficient α\alpha and added back to the original AA:

Ej=α∑i=1NsjiDi+AjE_j = \alpha \sum_{i=1}^{N} s_{ji} D_i + A_j

α\alpha 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 CC, BB and DD 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, N=9,216N = 9{,}216, 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 NN becomes 128×256=32,768128 \times 256 = 32{,}768; 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.

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 AA into C×NC \times N, multiply it by its own transpose to get a C×CC \times C matrix, then apply a softmax:

xji=exp⁡(Ai⋅Aj)∑i=1Cexp⁡(Ai⋅Aj)x_{ji} = \frac{\exp(A_i \cdot A_j)}{\sum_{i=1}^{C} \exp(A_i \cdot A_j)}

xjix_{ji} is the influence of channel ii on channel jj. Then, as before, take the weighted sum, multiply by a learnable β\beta (starting from 0) and add back to AA:

Ej=β∑i=1CxjiAi+AjE_j = \beta \sum_{i=1}^{C} x_{ji} A_i + A_j

In our example, C=512C = 512, 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 AA 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):

BackboneSettingmIoU
ResNet-50Dilated FCN70.03
+ PAM75.74
+ CAM74.28
+ PAM + CAM76.34
ResNet-101Dilated FCN72.54
+ PAM + CAM77.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

Original Figure 6: attention visualizations for three Cityscapes validation images. Each row, from left to right: the image (with points #1 and #2 marked), the sub-attention map for point #1, the sub-attention map for point #2, the 11th and 4th channels of the channel attention output, the segmentation result and the annotation. In the first row, point #1 is on a building and its sub-attention map lights up the building regions; point #2 is on a car and lights up the car.
Original Figure 6, Fu et al., from PDF page 7, arXiv license, scholarly quotation.

Each row of SS can be turned back into an H×WH \times W 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:

python
# 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 Ai⋅AjA_i \cdot A_j. 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 softmax(−Ai⋅Aj)\mathrm{softmax}(-A_i \cdot A_j). 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 x−max⁡(x)x - \max(x), and that PyTorch's softmax already takes care of that anyway; writing max⁡(x)−x\max(x) - x 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.