AI Logic

Attention Mechanisms

CBAM

Updated:

CBAM architecture. Left: its position inside a ResNet residual block (channel attention and then spatial attention are applied to the output F of the residual branch's convolutions, which is then added to the shortcut x). Right: inside the two modules (channel attention passes average-pooled and max-pooled features along the spatial dimensions through a shared MLP, adds them, and applies a sigmoid to produce M_c; spatial attention concatenates the average and max along the channel dimension and applies a 7 × 7 convolution and a sigmoid to produce M_s)

Background and overview

CBAM (Convolutional Block Attention Module) is a small module that applies "channel attention" and then "spatial attention" to a convolutional feature map, strengthening important features and weakening unneeded ones. It was proposed in 2018 by Woo et al. of KAIST and other institutions in the paper "CBAM: Convolutional Block Attention Module" (ECCV 2018).

A CNN feature map FF has three axes: channels (CC), height (HH), and width (WW). Each channel detects some kind of feature, so weighting channels selects what to look at. Height and width are positions in the image, so weighting positions selects where to look. CBAM builds these two sets of weights in turn and applies them to the feature map.

It is based on the SE block of SENet, which only produces per-channel weights. CBAM changes two things:

DifferenceSE blockCBAM
Input for channel weightsAverage pooling along the spatial dimensions onlyBoth average pooling and max pooling
Position weightsNoneAdds spatial attention produced by a 7 × 7 convolution

To use the analogy of a person looking at a photo, channel attention corresponds to choosing a viewpoint, such as "focus on shape rather than color in this photo," and spatial attention corresponds to choosing a location, such as "look around the dog in the middle of the photo."

Unlike Transformer scaled dot-product attention, it does not compute relationships between tokens; it is a kind of attention that multiplies each channel and each position of the feature map by a weight between 0 and 1. In the figure at the top of the article, the left shows its position inside a ResNet residual block, and the right shows the inside of the two modules.

Theory: channel attention and spatial attention

Given an intermediate feature map F∈RC×H×WF \in \mathbb{R}^{C \times H \times W}, CBAM computes the following in order (Equation (1) of the paper):

  1. Build the channel attention weights: Aggregate FF along the spatial dimensions (height and width) with average pooling and max pooling to produce two vectors of length CC.
  2. Pass them through a shared MLP: Pass each of the two vectors through an MLP with the same weights (C→C/r→CC \to C/r \to C, with ReLU in between), add the results, and apply a sigmoid. This gives the channel attention weights Mc(F)∈RC×1×1M_c(F) \in \mathbb{R}^{C \times 1 \times 1}.
  3. Multiply the channels by the weights: F′=Mc(F)⊗FF' = M_c(F) \otimes F. The weights are broadcast along height and width.
  4. Build the spatial attention weights: Aggregate F′F' along the channel dimension with average pooling and max pooling to produce two 1×H×W1 \times H \times W maps, concatenate them, and apply a 7×77 \times 7 convolution and a sigmoid. This gives the spatial attention weights Ms(F′)∈R1×H×WM_s(F') \in \mathbb{R}^{1 \times H \times W}.
  5. Multiply the positions by the weights: F′′=Ms(F′)⊗F′F'' = M_s(F') \otimes F'. The weights are broadcast along the channel dimension. F′′F'' is the output of CBAM.

The whole process is as follows (⊗\otimes is element-wise multiplication).

F′=Mc(F)⊗F,F′′=Ms(F′)⊗F′F' = M_c(F) \otimes F, \qquad F'' = M_s(F') \otimes F'

Channel attention is as follows (Equation (2); σ\sigma is the sigmoid, W0∈RC/r×CW_0 \in \mathbb{R}^{C/r \times C}, W1∈RC×C/rW_1 \in \mathbb{R}^{C \times C/r}, with ReLU after W0W_0).

Mc(F)=σ(MLP(AvgPool(F))+MLP(MaxPool(F)))=σ(W1(W0(Favgc))+W1(W0(Fmaxc)))M_c(F) = \sigma\bigl(\mathrm{MLP}(\mathrm{AvgPool}(F)) + \mathrm{MLP}(\mathrm{MaxPool}(F))\bigr) = \sigma\bigl(W_1(W_0(F^c_{\mathrm{avg}})) + W_1(W_0(F^c_{\mathrm{max}}))\bigr)

Spatial attention is as follows (Equation (3); f7×7f^{7 \times 7} is a convolution with a 7×77 \times 7 kernel).

Ms(F)=σ(f7×7([AvgPool(F);MaxPool(F)]))=σ(f7×7([Favgs;Fmaxs]))M_s(F) = \sigma\bigl(f^{7 \times 7}([\mathrm{AvgPool}(F); \mathrm{MaxPool}(F)])\bigr) = \sigma\bigl(f^{7 \times 7}([F^s_{\mathrm{avg}}; F^s_{\mathrm{max}}])\bigr)

The reduction ratio rr is 16 in the paper's experiments. When integrated into ResNet, CBAM is applied to the output of the convolutions in the residual branch of each residual block, which is then added to the shortcut (Figure 3 of the paper).

If channel attention uses only average pooling, it becomes exactly the same as the SE block of SENet. CBAM's channel attention can be seen as the SE block with an additional max-pooled input. Since the MLP weights are shared, it has the same parameters as the SE block.

Why this design

The paper compares design choices one at a time on ImageNet-1K with ResNet-50 and gives the following reasons (Section 4.1):

  • Max pooling complements average pooling: Global average pooling is a statistic that smoothly summarizes the entire feature, while max pooling captures the strength of the most salient part. Using both gave a lower error rate than either alone.
  • Spatial attention works better when built from pooling along the channel dimension: Aggregating channels with average and max gave a lower error rate than compressing them into one channel with a learnable 1×11 \times 1 convolution.
  • Spatial attention needs a wide receptive field: Enlarging the convolution kernel from 3×33 \times 3 to 7×77 \times 7 improved results. The paper argues that deciding what matters requires looking at a wide area.
  • Arranging channel attention → spatial attention in sequence works best: Sequential was better than computing them in parallel and adding, and in sequence, channel first was slightly better.

The comparison of each choice (ResNet-50, error rates % on the ImageNet-1K validation data; Tables 1 to 3 of the paper) is as follows:

ComparedSettingTop-1 errorTop-5 error
BaselineResNet-5024.567.50
Channel attention inputAverage pooling only (same as SE)23.146.70
Channel attention inputMax pooling only23.206.83
Channel attention inputBoth average and max22.806.52
Spatial attention construction1×11 \times 1 convolution, kernel 722.906.47
Spatial attention constructionAverage and max, kernel 322.686.41
Spatial attention constructionAverage and max, kernel 722.666.31
ArrangementSpatial → channel22.786.42
ArrangementChannel and spatial in parallel22.956.59

(All spatial attention comparisons are placed after channel attention (average and max). CBAM is the last setting, "average and max, kernel 7," arranged in channel → spatial order.)

Using Grad-CAM, the paper compares which parts of the image ResNet-50, the version with SE added, and the version with CBAM added base their decisions on, and reports that the network with CBAM covered the target object regions better (Figure 5 of the paper).

Experimental results

ImageNet-1K classification: SE and CBAM were added to various networks and compared (single-crop error rates % on the validation data; excerpt from Tables 4 and 5 of the paper).

NetworkParametersGFLOPsTop-1 errorTop-5 error
ResNet-5025.56M3.85824.567.50
ResNet-50 + SE28.09M3.86023.146.70
ResNet-50 + CBAM28.09M3.86422.666.31
ResNet-10144.55M7.57023.386.88
ResNet-101 + SE49.33M7.57522.356.19
ResNet-101 + CBAM49.33M7.58121.515.69
ResNeXt-50 (32x4d)25.03M3.76822.856.48
ResNeXt-50 + SE27.56M3.77121.916.04
ResNeXt-50 + CBAM27.56M3.77421.925.91
MobileNet4.23M0.56931.3911.51
MobileNet + SE5.07M0.57029.9710.63
MobileNet + CBAM5.07M0.57629.019.99

The parameters are the same as SE, and the increase in computation is small. Only the Top-1 of ResNeXt-50 was nearly the same as SE (21.92 vs. 21.91); on the other networks, CBAM outperformed SE.

Object detection: CBAM was added to the backbone of Faster R-CNN on COCO (mAP % on the validation data; Table 6 of the paper).

BackbonemAP@.5mAP@.75mAP@[.5, .95]
ResNet-5046.228.127.0
ResNet-50 + CBAM48.229.228.1
ResNet-10148.430.729.1
ResNet-101 + CBAM50.532.630.8

On PASCAL VOC 2007, CBAM was inserted right before each classifier of the StairNet detector, which is based on SSD. mAP@.5 went from 78.9% to 79.3% with VGG16 (79.1% with SE), and from 70.1% to 70.5% with MobileNet (70.0% with SE) (Table 7 of the paper).

Practical considerations

CBAM is a module that can be used simply by inserting it into the convolutional blocks of an existing CNN.

All comparison numbers in the paper come from the authors reproducing and training every compared network in PyTorch. They may differ from the values in the original papers, and the improvements are only about 0.5 to 2 points. In some cases, such as the Top-1 of ResNeXt-50, there is almost no difference from SE, so you need to verify whether it helps on your own task.

When using it, keep the following points in mind:

  • Insert it at the output of the residual branch: In ResNet, apply CBAM after the convolutions of the residual branch and before adding the shortcut (Figure 3 of the paper). Applying it after the addition would also weaken the information from the shortcut.
  • Arrange it as channel → spatial: In the paper's comparisons, this order worked best.
  • Start with a reduction ratio rr of 16 and a 7×77 \times 7 spatial attention kernel: These are the settings of the paper's experiments. In layers where the feature map is very small (e.g., 7×77 \times 7), a 7×77 \times 7 convolution sees almost the entire map.
  • Computation increases slightly: The parameters are the same as SE, but max pooling and the spatial attention convolution add slightly more computation (GFLOPs) than SE.

Comparison with other methods

Attention mechanisms that weight features in image CNNs can be compared by "what they put weights on."

MethodChannel weightsPosition weightsHow the weights are produced
SENet (Hu et al., 2018)YesNoGlobal average pooling → fully connected → sigmoid
CBAM (Woo et al., 2018)YesYesChannel: average and max pooling → shared MLP. Spatial: average and max along the channel dimension → 7×77 \times 7 convolution
Scaled dot-product attention (Transformer)——Computes relationships between positions (QK⊤QK^\top) and mixes in information from other positions

SE and CBAM only multiply each element of the feature map by a weight between 0 and 1 to scale it up or down; they do not mix in information from other positions. Transformer attention computes relationships between positions and gathers information from other positions, with computation proportional to the square of the number of positions. CBAM's computation only scales with the size of the feature map.

Rough guidelines for choosing:

  • Strengthening an existing CNN with little extra computation: Try SE first, and try CBAM for tasks where positional information also matters (such as object detection).
  • Using relationships between distant positions in the image: Consider Transformer attention (such as the Vision Transformer).

PyTorch example

Show code
python
import torch
import torch.nn as nn


class ChannelAttention(nn.Module):
    """Channel attention (Eq. (2) of the paper). Passes average and max pooling through an MLP with the same weights and adds them"""

    def __init__(self, channels, reduction=16):
        super().__init__()
        self.mlp = nn.Sequential(                       # shared MLP: C → C/r → C (1×1 convs compute the same as fully connected layers)
            nn.Conv2d(channels, channels // reduction, 1, bias=False),
            nn.ReLU(inplace=True),
            nn.Conv2d(channels // reduction, channels, 1, bias=False),
        )

    def forward(self, x):                               # x: [B, C, H, W]
        avg = self.mlp(torch.mean(x, dim=(2, 3), keepdim=True))  # average along spatial dims → [B, C, 1, 1]
        mx = self.mlp(torch.amax(x, dim=(2, 3), keepdim=True))   # max along spatial dims
        return torch.sigmoid(avg + mx)                  # M_c: [B, C, 1, 1]


class SpatialAttention(nn.Module):
    """Spatial attention (Eq. (3) of the paper). Concatenates the average and max along channels, then a 7×7 conv"""

    def __init__(self, kernel_size=7):
        super().__init__()
        self.conv = nn.Conv2d(2, 1, kernel_size, padding=kernel_size // 2, bias=False)

    def forward(self, x):
        avg = torch.mean(x, dim=1, keepdim=True)        # average along channels → [B, 1, H, W]
        mx = torch.amax(x, dim=1, keepdim=True)         # max along channels
        return torch.sigmoid(self.conv(torch.cat([avg, mx], dim=1)))  # M_s: [B, 1, H, W]


class CBAM(nn.Module):
    """F' = M_c(F) ⊗ F, F'' = M_s(F') ⊗ F' (Eq. (1) of the paper). Channel → spatial order"""

    def __init__(self, channels, reduction=16, kernel_size=7):
        super().__init__()
        self.ca = ChannelAttention(channels, reduction)
        self.sa = SpatialAttention(kernel_size)

    def forward(self, f):
        f = self.ca(f) * f                              # broadcast along height and width
        return self.sa(f) * f                           # broadcast along channels


class BasicBlockCBAM(nn.Module):
    """Example of inserting CBAM into a ResNet residual block (Figure 3 of the paper). Applied before adding the shortcut"""

    def __init__(self, channels):
        super().__init__()
        self.body = nn.Sequential(
            nn.Conv2d(channels, channels, 3, padding=1, bias=False), nn.BatchNorm2d(channels), nn.ReLU(inplace=True),
            nn.Conv2d(channels, channels, 3, padding=1, bias=False), nn.BatchNorm2d(channels),
        )
        self.cbam = CBAM(channels)
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        return self.relu(x + self.cbam(self.body(x)))


block = BasicBlockCBAM(64)
x = torch.randn(2, 64, 56, 56)
print(block(x).shape)  # torch.Size([2, 64, 56, 56])
# CBAM itself behaves the same in training and inference (BatchNorm changes with model.train() / model.eval())

FAQ

Q. How does CBAM differ from the SE block?
A.

The SE block produces only per-channel weights from information aggregated by global average pooling. CBAM also uses max-pooled information when producing channel weights, and adds spatial attention, which produces per-position weights. In the paper's ResNet-50 comparison, the Top-1 error rate was 22.66% for CBAM versus 23.14% for SE.

Q. Is it the same as Transformer attention?
A.

No. Transformer attention computes relationships between positions and gathers information from other positions. CBAM only multiplies each channel and each position of the feature map by a weight between 0 and 1 to scale it up or down, and does not mix in information from other positions. Both are called attention in the sense of "focusing on what matters."

Q. Which layers should it be inserted into?
A.

In the paper, it is inserted into every residual block of ResNet and similar networks, at the output of the residual branch's convolutions (before adding the shortcut). In the StairNet object detector, it was applied to the features right before each classifier. Since the increase in parameters and computation is small, the paper's approach is to start by inserting it into every block.

References

  1. S. Woo, J. Park, J.-Y. Lee, and I. S. Kweon, "CBAM: Convolutional Block Attention Module," ECCV, 2018.
  2. J. Hu, L. Shen, S. Albanie, G. Sun, and E. Wu, "Squeeze-and-Excitation Networks," arXiv:1709.01507, 2017.