Back to paper library
Paper notesarXiv 2018ECCV 2018

CBAM

Where Are You Looking?

Original paper

CBAM: Convolutional Block Attention Module

Paper authors

Sanghyun Woo · Jongchan Park · Joon-Young Lee · In So Kweon

Publication
ECCV 2018Conference
First submitted to arXiv
arXiv:1807.06521
Cite this paper · BibTeX

The citation identifies the linked source version. It cites the original paper and its authors.

@misc{lightweightcbam2018,
  title = {{CBAM: Convolutional Block Attention Module}},
  author = {Sanghyun Woo and Jongchan Park and Joon-Young Lee and In So Kweon},
  year = {2018},
  eprint = {1807.06521},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/1807.06521}
}
On this page

In 2017, SENet won the classification task at the last ILSVRC. It adds a tiny module after each convolutional block, which first averages each channel down to a single number, then uses two fully connected layers to compute a weight for each channel and multiplies those weights back onto the original feature map. A few more parameters brought a sizable gain in accuracy.

Sanghyun Woo and colleagues from KAIST and Lunit in Korea and Adobe Research in the US took SENet as their starting point and pressed further. Is the average alone enough to set the channel weights? Besides “which channels to look at,” shouldn't the network also decide “which positions to look at”?

Defining the Problem

The authors start from the directions network design had taken. A network can go deeper, like VGG and ResNet; wider, like Wide ResNet; or increase its cardinality, like Xception and ResNeXt. We've written notes on all three directions; see Wide ResNet, Xception, and ResNeXt.

The authors wanted to work from a different direction, attention, letting the network emphasize important features and suppress unnecessary ones.

Convolution already blends channel and spatial information together, so the authors have attention follow those same two directions. Channel attention decides “what” to look at, since each channel can be seen as a feature detector; spatial attention decides “where” to look.

SENet does only the channel half, and it gathers information with average pooling alone. The authors see room for improvement on both counts, and they also want the module to stay lightweight enough to plug straight into any convolutional network.

Solving the Problem

Overall Structure

The overall structure of CBAM: the Input Feature first goes into the Channel Attention Module, and the resulting channel attention is multiplied with the input; the result then goes into the Spatial Attention Module, and the resulting spatial attention is multiplied in once more, giving the Refined Feature
Fig. 1 from the paper, excerpted from page 2 of the v2 PDF. CBAM consists of a channel submodule and a spatial submodule in sequence.

Given an intermediate feature map F∈RC×H×W\mathbf{F}\in\mathbb{R}^{C\times H\times W}, CBAM first computes a 1D channel attention map Mc∈RC×1×1\mathbf{M_c}\in\mathbb{R}^{C\times1\times1}, then a 2D spatial attention map Ms∈R1×H×W\mathbf{M_s}\in\mathbb{R}^{1\times H\times W}:

F′=Mc(F)⊗F,F′′=Ms(F′)⊗F′.\mathbf{F}'=\mathbf{M_c}(\mathbf{F})\otimes\mathbf{F},\qquad \mathbf{F}''=\mathbf{M_s}(\mathbf{F}')\otimes\mathbf{F}'.

⊗\otimes is element-wise multiplication, with broadcasting filling in wherever the shapes differ. Channel attention has one number per channel, copied across the whole plane when multiplied; spatial attention has one number per position, copied across all channels.

Details of the two submodules. The green box at the top is the Channel Attention Module: Input feature F goes through MaxPool and AvgPool to give two vectors, each fed into the same Shared MLP; the two outputs are added and passed through a sigmoid to give Channel Attention Mc. The purple box at the bottom is the Spatial Attention Module: Channel-refined feature F' is max-pooled and average-pooled along the channel axis, stacked into two maps, and passed through a conv layer and a sigmoid to give Spatial Attention Ms
Fig. 2 from the paper, excerpted from page 5 of the v2 PDF. The channel attention and spatial attention submodules.

The two submodules work symmetrically. Each first applies average pooling and max pooling along one direction to compress the information, then uses a small network to compute the attention. Let's take them one at a time.

Channel Attention

Channel attention has to compress each channel's H×WH\times W values into a single number. SENet uses average pooling; the authors argue that max pooling should be added as well.

Why? Take an extreme example. Suppose there are two channels: one is 0.1 everywhere on a 10×1010\times10 map, and the other is 10 at a single position and 0 everywhere else. Average pooling gives 0.1 for both, so the two look identical; max pooling gives 0.1 and 10, revealing that the second channel responds strongly somewhere. As the authors put it, average pooling gives a soft global statistic, while max pooling records how strong the most salient part is, so the two complement each other.

The two pooled results go into the same MLP, and the outputs are added and passed through a sigmoid:

Mc(F)=σ(MLP(AvgPool(F))+MLP(MaxPool(F))).\mathbf{M_c}(\mathbf{F})=\sigma\big(\mathrm{MLP}(\mathrm{AvgPool}(\mathbf{F}))+\mathrm{MLP}(\mathrm{MaxPool}(\mathbf{F}))\big).

The MLP has a single hidden layer of size C/rC/r, where rr is the reduction ratio, set to 16 as in SENet. Because the MLP is shared, the parameter count is the same as SENet's.

Spatial Attention

Spatial attention goes the other way, applying average pooling and max pooling along the channel axis. Each position's CC values are compressed into two numbers, turning the whole map into two H×WH\times W descriptor maps. These are stacked and passed through a 7×77\times7 convolution and then a sigmoid:

Ms(F)=σ(f7×7([AvgPool(F);MaxPool(F)])).\mathbf{M_s}(\mathbf{F})=\sigma\big(f^{7\times7}([\mathrm{AvgPool}(\mathbf{F});\mathrm{MaxPool}(\mathbf{F})])\big).

Putting It Together

Let's write out the two submodules and run a 256-channel, 14×1414\times14 feature map through them:

Python
import torch
import torch.nn as nn

class ChannelAttention(nn.Module):
    def __init__(self, C, r=16):
        super().__init__()
        self.mlp = nn.Sequential(nn.Linear(C, C // r), nn.ReLU(), nn.Linear(C // r, C))   # shared MLP

    def forward(self, F):
        avg = F.mean(dim=(2, 3))                  # [B, C]
        mx = F.amax(dim=(2, 3))                   # [B, C]
        Mc = torch.sigmoid(self.mlp(avg) + self.mlp(mx))
        print("  Channel attention Mc:", tuple(Mc[:, :, None, None].shape))
        return Mc[:, :, None, None]               # [B, C, 1, 1]

class SpatialAttention(nn.Module):
    def __init__(self, k=7):
        super().__init__()
        self.conv = nn.Conv2d(2, 1, k, padding=k // 2)

    def forward(self, F):
        avg = F.mean(dim=1, keepdim=True)         # [B, 1, H, W]
        mx = F.amax(dim=1, keepdim=True)          # [B, 1, H, W]
        desc = torch.cat([avg, mx], dim=1)        # [B, 2, H, W]
        Ms = torch.sigmoid(self.conv(desc))
        print("  Spatial descriptor:", tuple(desc.shape), "→ spatial attention Ms:", tuple(Ms.shape))
        return Ms

class CBAM(nn.Module):
    def __init__(self, C, r=16):
        super().__init__()
        self.channel, self.spatial = ChannelAttention(C, r), SpatialAttention()

    def forward(self, F):
        F1 = self.channel(F) * F                  # Eq. (1): multiply by channel attention first
        F2 = self.spatial(F1) * F1                # then by spatial attention
        return F2

F = torch.randn(2, 256, 14, 14)
cbam = CBAM(256)
out = cbam(F)
print("Output:", tuple(out.shape))
print(f"Channel part parameters {sum(p.numel() for p in cbam.channel.parameters()):,}, spatial part parameters {sum(p.numel() for p in cbam.spatial.parameters()):,}")
Text
  Channel attention Mc: (2, 256, 1, 1)
  Spatial descriptor: (2, 2, 14, 14) → spatial attention Ms: (2, 1, 14, 14)
Output: (2, 256, 14, 14)
Channel part parameters 8,464, spatial part parameters 99

The output has the same shape as the input, so CBAM can be inserted anywhere. Nearly all the parameters are in the channel part's MLP (256→16→256256\to16\to256); the spatial part is just one 2→12\to1 7×77\times7 convolution, with 99 parameters.

In a ResNet, CBAM is applied to the convolution output of each residual block, and the result is then added to the shortcut, in the same position as SENet. timm also has a ready-made version; timm.layers.create_attn("cbam", channels) returns a CbamModule.

Discussion

Unless otherwise noted, the experiments are on ImageNet-1K, reporting single-crop error on the validation set. The authors retrained every network themselves in PyTorch, SENet included, so the SE numbers in the tables are their reproductions and differ somewhat from those reported in the SENet paper.

How the Design Took Shape

Holding ResNet-50 fixed, the authors decide in turn how to compute channel attention, how to compute spatial attention, and how to combine the two.

Which pooling for channel attention. This set uses channel attention only, with r=16r=16:

Table: Excerpted from Table 1 of the paper.
SettingTop-1 errorTop-5 error
ResNet-5024.56%7.50%
+ average pooling (i.e., SE)23.14%6.70%
+ max pooling23.20%6.83%
+ average and max pooling22.80%6.52%

Max pooling alone works about as well as average pooling; using both is best, 0.34 percentage points lower than SE, with no added parameters.

How to compute spatial attention. Placed after the channel attention from the previous step, this set compares two ways of producing the descriptor maps, the authors' pooling along the channel axis and a 1×11\times1 convolution that compresses the channels into one, as well as kernel sizes of 3 and 7:

Table: Excerpted from Table 2 of the paper.
SettingTop-1 errorTop-5 error
Channel attention only22.80%6.52%
+ spatial (1×11\times1 conv, k=3k=3)22.96%6.64%
+ spatial (1×11\times1 conv, k=7k=7)22.90%6.47%
+ spatial (average and max pooling, k=3k=3)22.68%6.41%
+ spatial (average and max pooling, k=7k=7)22.66%6.31%

The two versions that produce the descriptor with a 1×11\times1 convolution actually have worse top-1 error than channel attention alone; only pooling along the channel axis brings an improvement. The larger kernel is better, which the authors explain by saying that judging which regions matter needs a wider view.

How to arrange the two submodules.

Table: Excerpted from Table 3 of the paper.
ArrangementTop-1 errorTop-5 error
Channel only (SE)23.14%6.70%
Channel first, then spatial22.66%6.31%
Spatial first, then channel22.78%6.42%
In parallel, summed then passed through a sigmoid22.95%6.59%

Sequential beats parallel, and channel first is slightly better still; that's the final CBAM.

Reading the three tables together, going from SE's 23.14% to CBAM's 22.66% is a total gain of 0.48 percentage points. Of that, 0.34 comes from the max pooling added to channel attention, and spatial attention contributes another 0.14.

Results Across Networks

Next, CBAM is plugged into a range of networks and compared with the originals and with the SE versions:

Table: Excerpted from Table 4 of the paper, ImageNet-1K top-1 error. SE and CBAM have almost identical parameter counts; CBAM's are listed here.
NetworkOriginal+ SE+ CBAMParameters (original → with module)
ResNet-1829.60%29.41%29.27%11.69M → 11.78M
ResNet-3426.69%26.13%25.99%21.80M → 21.96M
ResNet-5024.56%23.14%22.66%25.56M → 28.09M
ResNet-10123.38%22.35%21.51%44.55M → 49.33M
WideResNet-18 (1.5× wide)26.85%26.21%26.10%25.88M → 26.08M
WideResNet-18 (2× wide)25.63%24.93%24.84%45.62M → 45.97M
ResNeXt-50 (32×4d)22.85%21.91%21.92%25.03M → 27.56M
ResNeXt-101 (32×4d)21.54%21.17%21.07%44.18M → 48.96M

CBAM beats the original on every network and beats SE on most, with the largest margin on ResNet-101 (0.84 percentage points below SE). On ResNeXt-50, it ties with SE. The extra computation is tiny; ResNet-50 goes from 3.858 GFLOPs to 3.864.

The authors also tried the lightweight MobileNet. The original MobileNet has a top-1 error of 31.39%, 29.97% with SE, and 29.01% with CBAM; for the version with its width scaled to 0.7, the three are 34.86%, 32.50%, and 31.51%.

Detection

On COCO, using Faster R-CNN with CBAM added to the backbone, mAP@[.5:.95] goes from 27.0 to 28.1 for ResNet-50 and from 29.1 to 30.8 for ResNet-101.

On VOC 2007, the authors instead put CBAM inside the detector, adding one before every classifier of the SSD-based StairNet. With a VGG16 backbone, [email protected] goes from 78.9 to 79.3 (79.1 with SE); with a MobileNet backbone, from 70.1 to 70.5 (70.0 with SE). The gains in detection range from about 0.4 to 1.7 percentage points.

Where the Model Looks

The authors use Grad-CAM to show the regions the network looks at when making its decision. Grad-CAM generalizes CAM, using gradients to compute how important each position is for a given class, and it doesn't require the network to end in global average pooling.

Grad-CAM visualizations in six columns, for the classes Tailed frog, Toilet tissue, Loudspeaker, Spider web, American egret, and Tank. The first row is the input images, and the three rows below are heatmaps for ResNet50, ResNet50 + SE, and ResNet50 + CBAM, each labeled underneath with that network's softmax score P for the correct class. In the CBAM row, the red regions mostly cover the whole object and the scores are the highest; for Tank, for example, the score rises from 0.14763 and 0.15367 to 0.53005
Fig. 5 from the paper (first six columns of the top half), excerpted from page 12 of the v2 PDF. The P under each image is the network's softmax score for the correct class.

From top to bottom, each column shows the original image and then the heatmaps for ResNet-50, with SE, and with CBAM. In the American egret column, for example, the original ResNet-50's red region is concentrated around the head, while CBAM's extends along the whole body, and the score for the correct class rises from 0.64 to 0.87. The tank column is even more striking, with the score jumping from about 0.15 to 0.53.

From this, the authors conjecture that CBAM's gains come from more accurate attention, with the interference from cluttered backgrounds suppressed. These are hand-picked examples; they show what the module is doing, but to quantify it, you still have to go back to the tables above.

Conclusion

CBAM's channel attention looks at max pooling as well as average pooling, and a spatial attention step afterward decides which positions to look at. The two submodules sit in sequence on the residual branch, with almost the same parameter count as SE.

Broken down, most of the extra 0.48 percentage points over SE on ResNet-50 come from max pooling; spatial attention, which handles the other half of the work, contributes only 0.14 and keeps a pretty low profile. If you only want to make a small change, switching SE's average pooling to “average plus max” gets you most of the benefit.

As for the Grad-CAM images, CBAM is the most on target in every column, and its scores are the highest, too. Of course the examples the authors picked for the paper look good. To judge whether the module actually helps, you still have to go back to those tables.