PyTorch Attention Mechanism
The attention mechanism is one of the most important concepts in deep learning.
The attention mechanism teaches a model to "focus" on the most relevant parts of the input, achieving great success in fields such as natural language processing and computer vision.
This section introduces the core principles of attention mechanisms, their PyTorch implementation, and various attention variants in detail.
Applicable versions:The code in this article is based on PyTorch 2.0+.
nn.MultiheadAttention'sbatch_firstThe parameter was introduced in PyTorch 1.9; earlier versions need to handle dimensions manually.
1. Fundamentals of Attention Mechanisms
1.1 Why Attention Is Needed
Traditional sequence-to-sequence (Seq2Seq) models have a fundamental problem: the Encoder needs to compress all information into a fixed-length vector. For long sequences, this vector becomes an information bottleneck -- the longer the sentence, the more severe the information loss.
The core idea of attention is: let the Decoder "see" all the hidden states of the Encoder when generating each output, and dynamically assign different attention weights according to the current context. This is like human translation, where each word translated requires looking back at the corresponding part of the original text.
1.2 The Essence of Attention Mechanisms
An attention mechanism can be seen as a weighted sum operation. Given a Query, a Key, and a Value, weights are assigned by computing the similarity between the Query and each Key, and then a weighted sum of the Values is computed:
[\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V]$$
Where:
- Q (Query): the query vector, representing "what information I am looking for"
- K (Key): the key vector, representing "what information I have here" (used for matching)
- V (Value): the value vector, representing "what I can actually provide"
- $$d_k$$: the dimension of Key; $$\sqrt{d_k}$$ is used for scaling to prevent the dot product from becoming too large and causing the softmax gradient to vanish
Why divide by $$\sqrt{d_k}$$? When $$d_k$$ is large, the variance of the dot product of Q and K grows linearly with the dimension, causing the input to softmax to be too large and the gradient to approach zero. Scaling restores the variance to 1, ensuring normal gradient flow.
Example
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
import
math
def
scaled_dot_product_attention
(
Q
,
K
,
V
,
mask
=
None
)
:
"""
Scaled Dot-Product Attention
Parameters:
Q: query tensor [batch, n_heads, seq_len_q, d_k]
K: key tensor [batch, n_heads, seq_len_k, d_k]
V: value tensor [batch, n_heads, seq_len_v, d_v]
mask: mask tensor, masked positions set to False/0
Returns:
output: attention output [batch, n_heads, seq_len_q, d_v]
attention_weights: attention weights [batch, n_heads, seq_len_q, seq_len_k]
"""
d_k
=
Q.
size
(
1
)
1. Compute QK^T / sqrt(d_k)
scores
=
torch.
matmul
(
Q
,
K.
transpose
(
2
,
1
)
)
/
math
.
sqrt
(
d_k
)
2. Apply the mask (optional)
Masked positions are set to a very small value, approaching 0 after softmax
if
mask
is
not
None
:
scores
=
scores.
masked_fill
(
mask
==
0
,
1e9
)
3. Softmax normalization -> attention weights
attention_weights
=
F.
softmax
(
scores
,
dim
=
1
)
4. Weighted sum
output
=
torch.
matmul
(
attention_weights
,
V
)
return
output
,
attention_weights
Testing
batch_size
,
n_heads
=
2
,
4
seq_len_q
,
seq_len_k
=
5
,
6
d_k
,
d_v
=
8
,
16
Q
=
torch.
randn
(
batch_size
,
n_heads
,
seq_len_q
,
d_k
)
K
=
torch.
randn
(
batch_size
,
n_heads
,
seq_len_k
,
d_k
)
V
=
torch.
randn
(
batch_size
,
n_heads
,
seq_len_k
,
d_v
)
output
,
attn_weights
=
scaled_dot_product_attention
(
Q
,
K
,
V
)
(
f
"Output shape: {output.shape}"
)
[2, 4, 5, 16]
(
f
"Attention weights shape: {attn_weights.shape}"
)
[2, 4, 5, 6]
(
f
"Row sum of weights (should be 1.0): {attn_weights[0, 0, 0].sum().item():.4f}"
)
The essence of attention weights is a probability distribution -- after softmax, each row sums to 1. A larger weight means the model "pays more attention" to that position.
2. PyTorch Attention Modules
2.1 Multi-Head Attention
Multi-Head Attention allows the model to simultaneously attend to information from different representation subspaces at different positions. It projects Q, K, and V into multiple subspaces through different linear projections, computes attention independently in each subspace, and finally concatenates the results and applies another linear transformation.
This is like having multiple people examine the same piece of text from different angles at once -- some focus on grammatical structure, some on semantic associations, and some on long-range dependencies. The multi-head mechanism allows the model to capture richer patterns.
$$\text{MultiHead}(Q,K,V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)W^O$$
$$\text{where head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)$$
Example
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
import
math
class
MultiHeadAttention
(
nn.
Module
)
:
def
init
(
self
,
d_model
,
n_heads
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
assert
d_model % n_heads
==
0
,
"d_model must be divisible by n_heads"
self
.
d_model
=
d_model
self
.
n_heads
=
n_heads
self
.
d_k
=
d_model // n_heads
Dimension of each head
Linear projection of Q, K, and V (computes all heads at once, more efficient)
self
.
w_q
=
nn.
Linear
(
d_model
,
d_model
)
self
.
w_k
=
nn.
Linear
(
d_model
,
d_model
)
self
.
w_v
=
nn.
Linear
(
d_model
,
d_model
)
Output projection
self
.
w_o
=
nn.
Linear
(
d_model
,
d_model
)
self
.
dropout
=
nn.
Dropout
(
dropout
)
def
forward
(
self
,
query
,
key
,
value
,
mask
=
None
)
:
"""
Parameters:
query: [batch, seq_len_q, d_model]
key: [batch, seq_len_k, d_model]
value: [batch, seq_len_k, d_model]
mask: [batch, 1, 1, seq_len_k] or [batch, 1, seq_len_q, seq_len_k]
"""
batch_size
=
query.
size
(
0
)
1. Linear projection, then split into heads
[batch, seq_len, d_model] → [batch, seq_len, n_heads, d_k]
→ [batch, n_heads, seq_len, d_k]
Q
=
self
.
w_q
(
query
)
.
view
(
batch_size
,
1
,
self
.
n_heads
,
self
.
d_k
)
.
transpose
(
1
,
2
)
K
=
self
.
w_k
(
key
)
.
view
(
batch_size
,
1
,
self
.
n_heads
,
self
.
d_k
)
.
transpose
(
1
,
2
)
V
=
self
.
w_v
(
value
)
.
view
(
batch_size
,
1
,
self
.
n_heads
,
self
.
d_k
)
.
transpose
(
1
,
2
)
2. Scaled dot-product attention
scores
=
torch.
matmul
(
Q
,
K.
transpose
(
2
,
1
)
)
/
math
.
sqrt
(
self
.
d_k
)
if
mask
is
not
None
:
scores
=
scores.
masked_fill
(
mask
==
0
,
1e9
)
attn_weights
=
F.
softmax
(
scores
,
dim
=
1
)
attn_weights
=
self
.
dropout
(
attn_weights
)
3. Weighted sum
context
=
torch.
matmul
(
attn_weights
,
V
)
4. Merge heads: [batch, n_heads, seq_len, d_k] -> [batch, seq_len, d_model]
context
=
context.
transpose
(
1
,
2
)
.
contiguous
(
)
.
view
(
batch_size
,
1
,
self
.
d_model
)
5. Output projection
output
=
self
.
w_o
(
context
)
return
output
,
attn_weights
Testing
d_model
,
n_heads
=
128
,
8
seq_len
,
batch
=
10
,
4
layer
=
MultiHeadAttention
(
d_model
,
n_heads
)
query
=
torch.
randn
(
batch
,
seq_len
,
d_model
)
key
=
torch.
randn
(
batch
,
seq_len
,
d_model
)
value
=
torch.
randn
(
batch
,
seq_len
,
d_model
)
output
,
attn_weights
=
layer
(
query
,
key
,
value
)
(
f
"Output shape: {output.shape}"
)
[4, 10, 128]
(
f
"Attention weights shape: {attn_weights.shape}"
)
[4, 8, 10, 10]
(
f
"Per-head dimension d_k = {d_model // n_heads}"
)
2.2 PyTorch's Built-in MultiheadAttention
PyTorch provides a highly optimized nn.MultiheadAttention, which uses fused kernels under the hood and is faster than a manual implementation in most scenarios. It is recommended for production use.
Example
import
torch
import
torch.
nn
as
nn
class
TransformerAttention
(
nn.
Module
)
:
"""A self-attention layer using PyTorch's built-in MultiheadAttention"""
def
init
(
self
,
d_model
,
n_heads
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
self
.
attention
=
nn.
MultiheadAttention
(
embed_dim
=
d_model
,
num_heads
=
n_heads
,
dropout
=
dropout
,
batch_first
=
True
,
Input format is [batch, seq, features]
PyTorch 2.0+ can enable the Flash Attention backend:
attn_implementation="flash_attention_2" # requires installing flash-attn
)
self
.
layernorm
=
nn.
LayerNorm
(
d_model
)
def
forward
(
self
,
x
,
key_padding_mask
=
None
)
:
"""
Self-attention: Q, K, and V are all x
Parameters:
x: [batch, seq_len, d_model]
key_padding_mask: [batch, seq_len], True means the position is padding
"""
attn_output
,
attn_weights
=
self
.
attention
(
x
,
x
,
x
,
self-attention
key_padding_mask
=
key_padding_mask
)
Pre-Norm residual connection (more stable to train than Post-Norm)
output
=
self
.
layernorm
(
x + attn_output
)
return
output
,
attn_weights
Testing
d_model
,
n_heads
=
128
,
8
seq_len
,
batch
=
10
,
4
model
=
TransformerAttention
(
d_model
,
n_heads
)
x
=
torch.
randn
(
batch
,
seq_len
,
d_model
)
Create a padding mask: True means the position should be ignored
key_padding_mask
=
torch.
zeros
(
batch
,
seq_len
,
dtype
=
torch.
bool
)
key_padding_mask
[
0
,
7
:
]
=
True
The last 3 positions of the first sample are padding
key_padding_mask
[
1
,
5
:
]
=
True
The last 5 positions of the second sample are padding
output
,
attn_weights
=
model
(
x
,
key_padding_mask
=
key_padding_mask
)
(
f
"Output shape: {output.shape}"
)
[4, 10, 128]
(
f
"Attention weights shape: {attn_weights.shape}"
)
[4, 10, 10]
Note the mask type:
nn.MultiheadAttention'skey_padding_maskUse True = ignore convention, as opposed to the convention in some custom implementations where 0 = ignore. Be sure to confirm when using it.
3. Variants of the Attention Mechanism
3.1 Self-Attention
Self-attention is a special form of the attention mechanism in which Q, K, and V all come from the same input sequence. It lets every position in the sequence attend directly to all other positions, thereby capturing global dependencies. It is the core component of the Transformer and the key to why it outperforms RNNs: an RNN must pass information step by step, while self-attention does it in one step.
Example
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
import
math
class
SelfAttention
(
nn.
Module
)
:
"""Multi-head self-attention layer with causal masking support (for autoregressive generation)"""
def
init
(
self
,
d_model
,
n_heads
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
assert
d_model % n_heads
==
0
self
.
d_model
=
d_model
self
.
n_heads
=
n_heads
self
.
d_k
=
d_model // n_heads
self
.
w_q
=
nn.
Linear
(
d_model
,
d_model
)
self
.
w_k
=
nn.
Linear
(
d_model
,
d_model
)
self
.
w_v
=
nn.
Linear
(
d_model
,
d_model
)
self
.
out_proj
=
nn.
Linear
(
d_model
,
d_model
)
self
.
dropout
=
nn.
Dropout
(
dropout
)
def
_split_heads
(
self
,
x
,
batch_size
)
:
"""[batch, seq, d_model] → [batch, n_heads, seq, d_k]"""
return
x.
view
(
batch_size
,
1
,
self
.
n_heads
,
self
.
d_k
)
.
transpose
(
1
,
2
)
def
forward
(
self
,
x
,
causal
=
False
)
:
"""
Self-attention: Q, K, and V all come from the same input x
Parameters:
x: [batch, seq_len, d_model]
causal: whether to use causal masking (prevents seeing future positions)
"""
batch_size
,
seq_len
,
_
=
x.
size
(
)
Projection + split into heads
Q
=
self
._split_heads
(
self
.
w_q
(
x
)
,
batch_size
)
K
=
self
._split_heads
(
self
.
w_k
(
x
)
,
batch_size
)
V
=
self
._split_heads
(
self
.
w_v
(
x
)
,
batch_size
)
Compute attention scores
scores
=
torch.
matmul
(
Q
,
K.
transpose
(
2
,
1
)
)
/
math
.
sqrt
(
self
.
d_k
)
Causal mask: set the upper triangular matrix to -inf to prevent seeing future tokens
if
causal:
causal_mask
=
torch.
triu
(
torch.
ones
(
seq_len
,
seq_len
,
device
=
x.
device
,
dtype
=
torch.
bool
)
,
diagonal
=
1
)
scores
=
scores.
masked_fill
(
causal_mask.
unsqueeze
(
0
)
.
unsqueeze
(
0
)
,
float
(
'-inf'
)
)
attn_weights
=
F.
softmax
(
scores
,
dim
=
1
)
attn_weights
=
self
.
dropout
(
attn_weights
)
Weighted sum + merge heads
context
=
torch.
matmul
(
attn_weights
,
V
)
context
=
context.
transpose
(
1
,
2
)
.
contiguous
(
)
.
view
(
batch_size
,
seq_len
,
self
.
d_model
)
return
self
.
out_proj
(
context
)
,
attn_weights
Testing
d_model
,
n_heads
=
256
,
8
seq_len
,
batch
=
20
,
2
attn
=
SelfAttention
(
d_model
,
n_heads
)
x
=
torch.
randn
(
batch
,
seq_len
,
d_model
)
Without causal masking (Encoder scenario)
output_enc
,
weights_enc
=
attn
(
x
,
causal
=
False
)
(
f
"[Encoder] output: {output_enc.shape}, weights: {weights_enc.shape}"
)
With causal masking (Decoder / autoregressive generation scenario)
output_dec
,
weights_dec
=
attn
(
x
,
causal
=
True
)
(
f
"[Decoder] output: {output_dec.shape}, weights: {weights_dec.shape}"
)
Verify causality: the first token should not attend to later tokens
(
f
"When causal=True, weights[0,0,0,5:] (should all be 0): {weights_dec[0, 0, 0, 5:].tolist()[:5]}"
)
3.2 Cross-Attention
In cross-attention, Q comes from one sequence (e.g., the Decoder), while K and V come from another sequence (e.g., the Encoder). It is the bridge of the Encoder-Decoder architecture: it lets the Decoder dynamically "look up" all of the Encoder's outputs when generating each token.
Example
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
import
math
class
CrossAttention
(
nn.
Module
)
:
"""Cross-attention: Q comes from the target sequence, K/V from the source sequence"""
def
init
(
self
,
d_model
,
n_heads
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
assert
d_model % n_heads
==
0
self
.
d_model
=
d_model
self
.
n_heads
=
n_heads
self
.
d_k
=
d_model // n_heads
self
.
w_q
=
nn.
Linear
(
d_model
,
d_model
)
self
.
w_k
=
nn.
Linear
(
d_model
,
d_model
)
self
.
w_v
=
nn.
Linear
(
d_model
,
d_model
)
self
.
out_proj
=
nn.
Linear
(
d_model
,
d_model
)
self
.
dropout
=
nn.
Dropout
(
dropout
)
def
forward
(
self
,
target
,
source
,
mask
=
None
)
:
"""
Parameters:
target: target sequence [batch, target_len, d_model] -> provides Q
source: source sequence [batch, source_len, d_model] -> provides K, V
mask: optional mask
"""
batch_size
=
target.
size
(
0
)
target_len
=
target.
size
(
1
)
source_len
=
source.
size
(
1
)
Projection + split into heads
Q
=
self
.
w_q
(
target
)
.
view
(
batch_size
,
target_len
,
self
.
n_heads
,
self
.
d_k
)
.
transpose
(
1
,
2
)
K
=
self
.
w_k
(
source
)
.
view
(
batch_size
,
source_len
,
self
.
n_heads
,
self
.
d_k
)
.
transpose
(
1
,
2
)
V
=
self
.
w_v
(
source
)
.
view
(
batch_size
,
source_len
,
self
.
n_heads
,
self
.
d_k
)
.
transpose
(
1
,
2
)
Attention computation
scores
=
torch.
matmul
(
Q
,
K.
transpose
(
2
,
1
)
)
/
math
.
sqrt
(
self
.
d_k
)
if
mask
is
not
None
:
scores
=
scores.
masked_fill
(
mask
==
0
,
float
(
'-inf'
)
)
attn_weights
=
F.
softmax
(
scores
,
dim
=
1
)
attn_weights
=
self
.
dropout
(
attn_weights
)
Weighted sum + merge heads
context
=
torch.
matmul
(
attn_weights
,
V
)
context
=
context.
transpose
(
1
,
2
)
.
contiguous
(
)
.
view
(
batch_size
,
target_len
,
self
.
d_model
)
return
self
.
out_proj
(
context
)
,
attn_weights
Testing
d_model
,
n_heads
=
256
,
8
batch
=
2
target_len
,
source_len
=
10
,
15
cross_attn
=
CrossAttention
(
d_model
,
n_heads
)
target
=
torch.
randn
(
batch
,
target_len
,
d_model
)
Decoder output
source
=
torch.
randn
(
batch
,
source_len
,
d_model
)
Encoder output
output
,
weights
=
cross_attn
(
target
,
source
)
(
f
"Target sequence shape: {target.shape}"
)
(
f
"Source sequence shape: {source.shape}"
)
(
f
"Output shape: {output.shape}"
)
[2, 10, 256]
(
f
"Weights shape: {weights.shape}"
)
[2, 8, 10, 15]
Meaning of the weights: how much each target position attends to each source position
Self-attention vs. cross-attention:In self-attention, Q/K/V have the same shape (a $$seq \times seq$$ weight matrix); in cross-attention, the length of Q can differ from the length of K (a $$target \times source$$ weight matrix).
3.3 Positional Encoding
The attention mechanism itself haspermutation invariance-- shuffling the input order does not change the output. But language and images are ordered, so positional information must be injected explicitly through positional encoding. The original Transformer uses sine/cosine functions to generate fixed positional encodings:
$$PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d_{model}}}\right), \quad PE_{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i/d_{model}}}\right)$$
Example
import
torch
import
torch.
nn
as
nn
import
math
class
PositionalEncoding
(
nn.
Module
)
:
"""Sine/cosine positional encoding (original Transformer scheme)"""
def
init
(
self
,
d_model
,
max_len
=
5000
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
self
.
dropout
=
nn.
Dropout
(
p
=
dropout
)
Precompute the positional encoding matrix [max_len, d_model]
pe
=
torch.
zeros
(
max_len
,
d_model
)
position
=
torch.
arange
(
0
,
max_len
,
dtype
=
torch.
float
)
.
unsqueeze
(
1
)
div_term: controls the decay rate across dimensions of different frequencies
div_term
=
torch.
exp
(
torch.
arange
(
0
,
d_model
,
2
)
.
float
(
)
(
math
.
log
(
10000.0
)
/ d_model
)
)
pe
[
:
,
0
::
2
]
=
torch.
sin
(
position * div_term
)
Even dimensions
pe
[
:
,
1
::
2
]
=
torch.
cos
(
position * div_term
)
Odd dimensions
pe
=
pe.
unsqueeze
(
0
)
[1, max_len, d_model]
self
.
register_buffer
(
'pe'
,
pe
)
Not involved in training
def
forward
(
self
,
x
)
:
"""
x: [batch, seq_len, d_model]
Return: x + positional_encoding
"""
x
=
x +
self
.
pe
[
:
,
:x.
size
(
1
)
,
:
]
return
self
.
dropout
(
x
)
Testing
d_model
=
128
seq_len
=
50
batch
=
4
pe
=
PositionalEncoding
(
d_model
)
x
=
torch.
randn
(
batch
,
seq_len
,
d_model
)
output
=
pe
(
x
)
(
f
"Input shape: {x.shape}"
)
(
f
"Output shape: {output.shape}"
)
(
f
"Positional encoding shape: {pe.pe.shape}"
)
[1, 5000, 128]
4. Visual Applications of the Attention Mechanism
The attention mechanism applies not only to sequential data but also shines in computer vision. Below we introduce three classic visual attention modules:
4.1 Channel Attention
Channel attention (e.g., SENet) lets the network learn "which channels matter more." It uses global pooling on each channel to compress spatial information, then a two-layer fully connected network to learn the dependencies among channels.
Example
import
torch
import
torch.
nn
as
nn
class
SEBlock
(
nn.
Module
)
:
"""Squeeze-and-Excitation Block (channel attention)"""
def
init
(
self
,
channels
,
reduction
=
16
)
:
super
(
)
.
init
(
)
self
.
squeeze
=
nn.
AdaptiveAvgPool2d
(
1
)
Global average pooling
self
.
excitation
=
nn.
Sequential
(
nn.
Linear
(
channels
,
channels // reduction
,
bias
=
False
)
,
nn.
ReLU
(
inplace
=
True
)
,
nn.
Linear
(
channels // reduction
,
channels
,
bias
=
False
)
,
nn.
Sigmoid
(
)
Output channel weights from 0 to 1
)
def
forward
(
self
,
x
)
:
x: [batch, channels, H, W]
b
,
c
,
_
,
_
=
x.
size
(
)
Squeeze: [B, C, H, W] → [B, C, 1, 1] → [B, C]
y
=
self
.
squeeze
(
x
)
.
view
(
b
,
c
)
Excitation: learn channel weights [B, C]
y
=
self
.
excitation
(
y
)
.
view
(
b
,
c
,
1
,
1
)
Channel weighting: multiply each channel by its corresponding weight
return
x * y.
expand_as
(
x
)
Testing
se
=
SEBlock
(
channels
=
256
,
reduction
=
16
)
x
=
torch.
randn
(
4
,
256
,
32
,
32
)
output
=
se
(
x
)
(
f
"Input: {x.shape} -> Output: {output.shape}"
)
4.2 Spatial Attention
Spatial attention lets the network learn "which positions matter more." It compresses along the channel dimension (taking the mean and max), then uses a convolution to learn a spatial weight map.
Example
import
torch
import
torch.
nn
as
nn
class
SpatialAttention
(
nn.
Module
)
:
"""Spatial attention module"""
def
init
(
self
,
kernel_size
=
7
)
:
super
(
)
.
init
(
)
padding
=
kernel_size //
2
Input 2 channels (mean + max), output 1 channel (attention map)
self
.
conv
=
nn.
Conv2d
(
2
,
1
,
kernel_size
,
padding
=
padding
,
bias
=
False
)
self
.
sigmoid
=
nn.
Sigmoid
(
)
def
forward
(
self
,
x
)
:
x: [batch, channels, H, W]
Channel compression: take the mean and max -> one [B, 1, H, W] each
avg_out
=
torch.
mean
(
x
,
dim
=
1
,
keepdim
=
True
)
max_out
,
_
=
torch.
max
(
x
,
dim
=
1
,
keepdim
=
True
)
Concatenate -> [B, 2, H, W]
scale
=
torch.
cat
(
[
avg_out
,
max_out
]
,
dim
=
1
)
Convolution + Sigmoid -> spatial weight map [B, 1, H, W]
scale
=
self
.
sigmoid
(
self
.
conv
(
scale
)
)
Spatial weighting
return
x * scale
Testing
spatial_attn
=
SpatialAttention
(
kernel_size
=
7
)
x
=
torch.
randn
(
4
,
256
,
32
,
32
)
output
=
spatial_attn
(
x
)
(
f
"Input: {x.shape} -> Output: {output.shape}"
)
4.3 CBAM (Convolutional Block Attention Module)
CBAM combines channel attention and spatial attentionin seriesApplication: first use channel attention to select important channels, then spatial attention to select important positions. The two are complementary, and the combination outperforms either used alone.
Example
import
torch
import
torch.
nn
as
nn
class
CBAM
(
nn.
Module
)
:
"""CBAM: channel attention + spatial attention"""
def
init
(
self
,
channels
,
reduction
=
16
,
kernel_size
=
7
)
:
super
(
)
.
init
(
)
Channel attention
self
.
channel_attn
=
nn.
Sequential
(
nn.
AdaptiveAvgPool2d
(
1
)
,
nn.
Flatten
(
)
,
nn.
Linear
(
channels
,
channels // reduction
,
bias
=
False
)
,
nn.
ReLU
(
inplace
=
True
)
,
nn.
Linear
(
channels // reduction
,
channels
,
bias
=
False
)
,
nn.
Sigmoid
(
)
)
Spatial attention
self
.
spatial_attn
=
nn.
Sequential
(
nn.
Conv2d
(
2
,
1
,
kernel_size
,
padding
=
kernel_size //
2
,
bias
=
False
)
,
nn.
Sigmoid
(
)
)
def
forward
(
self
,
x
)
:
1. Channel attention
b
,
c
,
_
,
_
=
x.
size
(
)
ca
=
self
.
channel_attn
(
x
)
.
view
(
b
,
c
,
1
,
1
)
x
=
x * ca
2. Spatial attention
avg_out
=
torch.
mean
(
x
,
dim
=
1
,
keepdim
=
True
)
max_out
,
_
=
torch.
max
(
x
,
dim
=
1
,
keepdim
=
True
)
sa
=
self
.
spatial_attn
(
torch.
cat
(
[
avg_out
,
max_out
]
,
dim
=
1
)
)
x
=
x * sa
return
x
Testing
cbam
=
CBAM
(
channels
=
256
)
x
=
torch.
randn
(
4
,
256
,
32
,
32
)
output
=
cbam
(
x
)
(
f
"Input: {x.shape} -> Output: {output.shape}"
)
5. Applications of the Attention Mechanism in NLP
5.1 Transformer Encoder
The Transformer Encoder is formed by stacking N identical layers, each containing two sublayers:Multi-head self-attentionandFeed-forward network. Each sublayer uses a residual connection and layer normalization.
Example
import
torch
import
torch.
nn
as
nn
import
math
class
TransformerEncoderLayer
(
nn.
Module
)
:
"""Single-layer Transformer Encoder"""
def
init
(
self
,
d_model
,
n_heads
,
d_ff
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
Multi-head self-attention
self
.
self_attn
=
nn.
MultiheadAttention
(
d_model
,
n_heads
,
dropout
=
dropout
,
batch_first
=
True
)
Feed-forward network (two linear layers + activation)
self
.
ffn
=
nn.
Sequential
(
nn.
Linear
(
d_model
,
d_ff
)
,
nn.
GELU
(
)
,
GELU is more commonly used than ReLU
nn.
Dropout
(
dropout
)
,
nn.
Linear
(
d_ff
,
d_model
)
)
Layer normalization (Pre-Norm style, more stable training)
self
.
norm1
=
nn.
LayerNorm
(
d_model
)
self
.
norm2
=
nn.
LayerNorm
(
d_model
)
self
.
dropout
=
nn.
Dropout
(
dropout
)
def
forward
(
self
,
x
,
key_padding_mask
=
None
)
:
Sublayer 1: self-attention
residual
=
x
x
=
self
.
norm1
(
x
)
Pre-Norm
attn_out
,
_
=
self
.
self_attn
(
x
,
x
,
x
,
key_padding_mask
=
key_padding_mask
)
x
=
residual +
self
.
dropout
(
attn_out
)
Sublayer 2: feed-forward network
residual
=
x
x
=
self
.
norm2
(
x
)
Pre-Norm
x
=
residual +
self
.
dropout
(
self
.
ffn
(
x
)
)
return
x
class
TransformerEncoder
(
nn.
Module
)
:
"""Multi-layer Transformer Encoder"""
def
init
(
self
,
d_model
,
n_heads
,
d_ff
,
num_layers
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
self
.
layers
=
nn.
ModuleList
(
[
TransformerEncoderLayer
(
d_model
,
n_heads
,
d_ff
,
dropout
)
for
_
in
range
(
num_layers
)
]
)
self
.
final_norm
=
nn.
LayerNorm
(
d_model
)
def
forward
(
self
,
x
,
key_padding_mask
=
None
)
:
for
layer
in
self
.
layers
:
x
=
layer
(
x
,
key_padding_mask
)
return
self
.
final_norm
(
x
)
Testing
d_model
,
n_heads
,
d_ff
=
128
,
4
,
512
num_layers
,
seq_len
,
batch
=
3
,
20
,
4
encoder
=
TransformerEncoder
(
d_model
,
n_heads
,
d_ff
,
num_layers
)
x
=
torch.
randn
(
batch
,
seq_len
,
d_model
)
Padding mask: True = ignore that position
key_padding_mask
=
torch.
zeros
(
batch
,
seq_len
,
dtype
=
torch.
bool
)
key_padding_mask
[
0
,
15
:
]
=
True
output
=
encoder
(
x
,
key_padding_mask
=
key_padding_mask
)
(
f
"Input: {x.shape} -> Output: {output.shape}"
)
5.2 Attention Visualization
Visualizing attention weights is an important means of understanding and debugging Transformer models. A heatmap lets you see intuitively which information the model attends to at each position.
Example
import
torch
import
matplotlib.
pyplot
as
plt
import
numpy
as
np
def
visualize_attention
(
attention_weights
,
tokens
=
None
,
save_path
=
None
)
:
"""
Visualize multi-head attention weights
Parameters:
attention_weights: [n_heads, seq_len, seq_len]
tokens: list of tokens (optional)
save_path: save path (optional)
"""
n_heads
=
attention_weights.
shape
[
0
]
seq_len
=
attention_weights.
shape
[
1
]
fig
,
axes
=
plt.
subplots
(
1
,
n_heads
,
figsize
=
(
n_heads *
3
,
3.5
)
)
if
n_heads
==
1
:
axes
=
[
axes
]
for
head
in
range
(
n_heads
)
:
ax
=
axes
[
head
]
attn
=
attention_weights
[
head
]
.
detach
(
)
.
cpu
(
)
.
numpy
(
)
im
=
ax.
imshow
(
attn
,
cmap
=
'Blues'
,
aspect
=
'auto'
,
vmin
=
0
,
vmax
=
attn.
max
(
)
)
ax.
set_title
(
f
'Head {head + 1}'
,
fontsize
=
10
,
fontweight
=
'bold'
)
ax.
set_xlabel
(
'Key'
)
ax.
set_ylabel
(
'Query'
)
if
tokens
is
not
None
:
ax.
set_xticks
(
range
(
len
(
tokens
)
)
)
ax.
set_yticks
(
range
(
len
(
tokens
)
)
)
ax.
set_xticklabels
(
tokens
,
rotation
=
90
,
fontsize
=
8
)
ax.
set_yticklabels
(
tokens
,
fontsize
=
8
)
plt.
tight_layout
(
)
if
save_path:
plt.
savefig
(
save_path
,
dpi
=
150
,
bbox_inches
=
'tight'
)
plt.
show
(
)
Simulate attention weights after training
n_heads
,
seq_len
=
4
,
8
attention_weights
=
torch.
softmax
(
torch.
randn
(
n_heads
,
seq_len
,
seq_len
)
,
dim
=
1
)
tokens
=
[
'The'
,
'cat'
,
'sat'
,
'on'
,
'the'
,
'mat'
,
'.'
,
'[PAD]'
]
visualize_attention
(
attention_weights
,
tokens
)
6. A Complete Attention Classifier
6.1 Attention-Based Text Classification
Below is a complete text classification model: it uses a Transformer Encoder to extract features, then attention pooling to compress a variable-length sequence into a fixed-length vector, and finally feeds it into a classifier.
Example
import
torch
import
torch.
nn
as
nn
import
math
class
AttentionClassifier
(
nn.
Module
)
:
"""Text classification model based on Transformer + attention pooling"""
def
init
(
self
,
vocab_size
,
embed_dim
,
hidden_dim
,
num_classes
,
n_heads
=
4
,
num_layers
=
2
,
dropout
=
0.1
)
:
super
(
)
.
init
(
)
self
.
embed_dim
=
embed_dim
Token embedding
self
.
embedding
=
nn.
Embedding
(
vocab_size
,
embed_dim
,
padding_idx
=
0
)
self
.
pos_encoding
=
PositionalEncoding
(
embed_dim
,
dropout
=
dropout
)
Transformer encoder
encoder_layer
=
nn.
TransformerEncoderLayer
(
d_model
=
embed_dim
,
nhead
=
n_heads
,
dim_feedforward
=
hidden_dim
,
dropout
=
dropout
,
batch_first
=
True
,
activation
=
'gelu'
)
self
.
transformer
=
nn.
TransformerEncoder
(
encoder_layer
,
num_layers
)
Attention pooling: learn an importance weight for each position
self
.
attn_pool
=
nn.
Sequential
(
nn.
Linear
(
embed_dim
,
1
)
Output a scalar weight for each position
)
Classification head
self
.
classifier
=
nn.
Sequential
(
nn.
Linear
(
embed_dim
,
hidden_dim
)
,
nn.
GELU
(
)
,
nn.
Dropout
(
dropout
)
,
nn.
Linear
(
hidden_dim
,
num_classes
)
)
def
forward
(
self
,
x
)
:
"""
x: [batch, seq_len] — token ids
Return: logits [batch, num_classes], attn_weights [batch, seq_len]
"""
Token embedding + positional encoding
mask
=
(
x
==
0
)
padding mask
x
=
self
.
embedding
(
x
)
math
.
sqrt
(
self
.
embed_dim
)
x
=
self
.
pos_encoding
(
x
)
Transformer encoding
x
=
self
.
transformer
(
x
,
src_key_padding_mask
=
mask
)
Attention pooling: compute a weight for each position and take the weighted sum
scores
=
self
.
attn_pool
(
x
)
.
squeeze
(
1
)
[batch, seq_len]
scores
=
scores.
masked_fill
(
mask
,
float
(
'-inf'
)
)
Ignore padding
attn_weights
=
torch.
softmax
(
scores
,
dim
=
1
)
[batch, seq_len]
pooled
=
torch.
bmm
(
attn_weights.
unsqueeze
(
1
)
,
x
)
.
squeeze
(
1
)
[batch, embed_dim]
Classification
logits
=
self
.
classifier
(
pooled
)
return
logits
,
attn_weights
Testing
model
=
AttentionClassifier
(
vocab_size
=
10000
,
embed_dim
=
128
,
hidden_dim
=
256
,
num_classes
=
5
)
Simulated input (with padding)
x
=
torch.
randint
(
1
,
10000
,
(
16
,
50
)
)
x
[
:
,
10
:
]
=
0
The last 10 positions are padding
logits
,
attn_weights
=
model
(
x
)
(
f
"Input: {x.shape}"
)
(
f
"Logits: {logits.shape}"
)
[16, 5]
(
f
"Attention weights: {attn_weights.shape}"
)
[16, 50]
6.2 Comparison of Common Attention Variants
| Type | Q source | K/V source | Core use | Typical application |
|---|---|---|---|---|
| Self-Attention | Itself | Itself | Global interaction within a sequence | Transformer, BERT, ViT |
| Cross-Attention | Target sequence | Source sequence | Cross-sequence information fusion | Machine translation, image captioning, Stable Diffusion |
| Channel Attention | Global pooling features | Same as above | Learn channel importance | SENet, CBAM |
| Spatial Attention | Channel-compressed features | Same as above | Learn spatial position importance | CBAM, Spatial Transformer |
| Sparse Attention | Subset of positions | Subset of positions | Reduce computational complexity for long sequences | Longformer, BigBird |
7. Best Practices and Common Issues
7.1 Usage Tips
- Mask consistency: ensure the padding mask and causal mask use consistent directions (True = ignore vs. 1 = keep). Different APIs may have different conventions.
- Number of heads: typically set it to a factor of $$d_{model}$$; 8 or 16 are common. Too many heads reduce the per-head dimension $$d_k$$, which can hurt performance.
- Residual Connection: always use a residual connection + layer normalization around the attention layer; this is necessary for training deep Transformers.
- Learning rate warmup: gradients fluctuate greatly early in Transformer training, so using a warmup + cosine decay scheduler can significantly improve stability.
- Flash Attention: PyTorch 2.0+ supports
nn.functional.scaled_dot_product_attentionautomatically calling Flash Attention, with major gains in both memory and speed.
7.2 Common Issues
| Problem | Reason | Solution |
|---|---|---|
| Attention weights are all uniformly distributed | Input not normalized or learning rate too large | Check input scale, use LayerNorm, lower the learning rate |
| Training loss does not decrease | Positional encoding missing or mask incorrect | Confirm positional encoding was added, check mask direction |
| Out of memory (long sequences) | Attention matrix $$O(n^2)$$ complexity | Use Flash Attention, gradient checkpointing, or sparse attention |
| Attention degrades during inference | Inconsistent mask between training and inference | Ensure the padding mask uses the same logic in training and inference |
Attention is a core technique of modern deep learning. From NLP to CV, from speech to protein structure prediction, nearly all cutting-edge models are built on attention. Understanding its principles and implementation is the crucial first step toward mastering models such as Transformer, ViT, Stable Diffusion, and GPT.