Attention Mechanism
The attention mechanism (Attention Mechanism) is an important technique in deep learning that mimics the way attention is allocated in human visual and cognitive processes. Just as you unconsciously focus your attention on keywords when reading, the attention mechanism enables neural networks to dynamically focus on the most relevant parts of the input data.
Basic concepts
The core idea of the attention mechanism is:Dynamically assign different weights according to the importance of different parts of the input to the current task. This weight assignment is not fixed but is dynamically computed based on the context.
Mathematical Expression
The attention mechanism can usually be expressed as:
Attention(Q, K, V) = softmax(QK^T/√d_k)V
Where:
- Q (Query): the query item for which the output is currently computed
- K (Key): the key used to match the query
- V (Value): the actual value corresponding to the key
- d_k: the dimension of the keys, used to scale the dot-product result
Why do we need the attention mechanism?
- Solve the long-range dependency problem: traditional RNNs struggle to capture relationships between distant words
- Parallel computing capability: compared with the sequential processing of RNNs, attention can be computed in parallel
- Interpretability: attention weights can intuitively show what the model focuses on
Self-Attention Mechanism (Self-Attention)
Self-attention is a special form of the attention mechanism that allows each element in the input sequence to establish connections with all other elements in the sequence.
How It Works
- For each element in the input sequence, compute its similarity score with all elements
- Use the softmax function to convert these scores into weights (between 0 and 1)
- Use these weights to compute a weighted sum of the corresponding values to obtain the output
Example
Simplified self-attention implementation example
import
torch
import
torch.
nn
.
functional
as
F
def
self_attention
(
query
,
key
,
value
)
:
scores
=
torch.
matmul
(
query
,
key.
transpose
(
2
,
1
)
)
/
(
query.
size
(
1
)
**
0.5
)
weights
=
F.
softmax
(
scores
,
dim
=
1
)
return
torch.
matmul
(
weights
,
value
)
Advantages of self-attention
- Global context awareness: every position can directly access information from all positions in the sequence
- Position independence: does not depend on sequence order, suitable for processing various structured data
- Efficient computation: compared with the O(n) complexity of RNNs, self-attention can be computed in parallel
Multi-Head Attention
Multi-head attention is an extension of self-attention that runs the attention mechanism multiple times in parallel and then concatenates the results.
Structural components
- Multiple attention heads: typically uses 8 or more parallel attention heads
- Linear transformation layers: each head has its own Q, K, V transformation matrices
- Concatenation and output: concatenate the outputs of each head and pass them through a linear layer

Advantages of multi-head attention
- Capture different relationships: each head can learn to focus on different aspects of relationships
- Enhanced expressive power: stronger feature extraction capability than single-head attention
- Stable training: the combination of multiple heads can reduce the model's reliance on specific patterns
Example
Multi-head attention implementation example
class
MultiHeadAttention
(
nn.
Module
)
:
def
init
(
self
,
d_model
,
num_heads
)
:
super
(
)
.
init
(
)
self
.
d_model
=
d_model
self
.
num_heads
=
num_heads
self
.
d_k
=
d_model // num_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
.
W_o
=
nn.
Linear
(
d_model
,
d_model
)
def
forward
(
self
,
query
,
key
,
value
)
:
batch_size
=
query.
size
(
0
)
Linear transformation and splitting into multiple heads
Q
=
self
.
W_q
(
query
)
.
view
(
batch_size
,
1
,
self
.
num_heads
,
self
.
d_k
)
K
=
self
.
W_k
(
key
)
.
view
(
batch_size
,
1
,
self
.
num_heads
,
self
.
d_k
)
V
=
self
.
W_v
(
value
)
.
view
(
batch_size
,
1
,
self
.
num_heads
,
self
.
d_k
)
Compute attention
scores
=
torch.
matmul
(
Q
,
K.
transpose
(
2
,
1
)
)
/
(
self
.
d_k
**
0.5
)
weights
=
F.
softmax
(
scores
,
dim
=
1
)
output
=
torch.
matmul
(
weights
,
V
)
Concatenate multiple heads and output
output
=
output.
transpose
(
1
,
2
)
.
contiguous
(
)
.
view
(
batch_size
,
1
,
self
.
d_model
)
return
self
.
W_o
(
output
)
Applications of the attention mechanism in NLP
The attention mechanism has become a core component of modern NLP systems, especially in the Transformer architecture.
Main application scenarios
-
Machine translation:
-
Text summarization:
-
Question answering systems:
-
Language models:
Practical case: attention in BERT
BERT (Bidirectional Encoder Representations from Transformers) is a typical representative that uses the attention mechanism:
- Bidirectional self-attention: considers both left and right context simultaneously
- 12/24-layer Transformer: stacks multi-head attention layers
- Pre-training tasks: learn general representations through masked language model and next sentence prediction tasks
Example
Use the HuggingFace Transformers library to call BERT
from
transformers
import
BertModel
,
BertTokenizer
tokenizer
=
BertTokenizer.
from_pretrained
(
'bert-base-uncased'
)
model
=
BertModel.
from_pretrained
(
'bert-base-uncased'
)
inputs
=
tokenizer
(
"Hello, my dog is cute"
,
return_tensors
=
"pt"
)
outputs
=
model
(
**inputs
)
Obtain attention weights
attention
=
outputs.
attentions
Contains the attention weights of each layer
Variants and extensions of the attention mechanism
1. Scaled Dot-Product Attention
- Introduce a scaling factor (√d_k) to prevent softmax saturation
- High computational efficiency, suitable for large-scale applications
2. Additive Attention
- Use a single-layer feed-forward network to compute the compatibility function
- Suitable when the query and key dimensions differ
3. Local Attention
- Only focus on a subset of the input, reducing computational complexity
- Balances global attention and computational efficiency
4. Sparse Attention
- Only compute attention weights for some positions
- Sliding window attention as used by Longformer
Practical Exercise
Exercise 1: Implement a basic attention mechanism
Example
import
torch
import
torch.
nn
as
nn
import
torch.
nn
.
functional
as
F
class
SimpleAttention
(
nn.
Module
)
:
def
init
(
self
,
hidden_size
)
:
super
(
SimpleAttention
,
self
)
.
init
(
)
self
.
attention
=
nn.
Linear
(
hidden_size
,
1
)
def
forward
(
self
,
encoder_outputs
)
:
encoder_outputs: [batch_size, seq_len, hidden_size]
attention_scores
=
self
.
attention
(
encoder_outputs
)
.
squeeze
(
2
)
[batch_size, seq_len]
attention_weights
=
F.
softmax
(
attention_scores
,
dim
=
1
)
context_vector
=
torch.
bmm
(
attention_weights.
unsqueeze
(
1
)
,
encoder_outputs
)
[batch_size, 1, hidden_size]
return
context_vector.
squeeze
(
1
)
,
attention_weights
Exercise 2: Visualize attention weights
Example
import
matplotlib.
pyplot
as
plt
import
seaborn
as
sns
def
plot_attention
(
attention_weights
,
source_tokens
,
target_tokens
)
:
plt.
figure
(
figsize
=
(
10
,
8
)
)
sns.
heatmap
(
attention_weights
,
xticklabels
=
source_tokens
,
yticklabels
=
target_tokens
,
cmap
=
"YlGnBu"
)
plt.
xlabel
(
"Source Tokens"
)
plt.
ylabel
(
"Target Tokens"
)
plt.
title
(
"Attention Weights Visualization"
)
plt.
show
(
)
Example usage
source
=
[
"The"
,
"cat"
,
"sat"
,
"on"
,
"the"
,
"mat"
]
target
=
[
"Le"
,
"chat"
,
"s'est"
,
"assis"
,
"sur"
,
"le"
,
"tapis"
]
attention
=
torch.
rand
(
7
,
6
)
Simulated attention weights
plot_attention
(
attention
,
source
,
target
)
Summary and further learning
The attention mechanism has become a cornerstone technique of modern deep learning, especially in the field of NLP. To study in depth:
-
Read the original papers:
-
Suggested hands-on projects:
-
Extended application areas:
The development of the attention mechanism is still ongoing; understanding its core principles will help you better master modern deep learning techniques.