In-depth analysis of Transformer
In-depth analysis of Transformer
In 2017, Google published the paper "Attention Is All You Need," proposing the Transformer architecture. No one expected this paper to completely change the field of AI.
Today's GPT, Claude, Gemini, Llama... almost all mainstream large language models are essentially variants of the Transformer.
Understanding the Transformer means understanding 90% of modern LLMs.
In this article, we will delve into every component of the Transformer: self-attention, multi-head attention, positional encoding, feed-forward network, layer normalization... not just explaining "what," but also "why."
This is one of the modules with the highest technical depth. We will demonstrate the core calculations with code to ensure you not only understand the formulas but can also implement them yourself.
Transformer forward pass: RNN limitations
Before the advent of Transformer, sequence tasks (such as translation and text generation) mainly used RNN (Recurrent Neural Network) and its variants LSTM, GRU.
How RNN works
The core idea of RNN is "processing one by one": the input sequence enters the network word by word, and the output at each step contains information from all previous words.
Example
============================================
Simplified RNN forward propagation demonstration
============================================
import
math
class
SimpleRNN:
"""A simplified RNN implementation to demonstrate the principle"""
def
init
(
self
,
input_size:
int
,
hidden_size:
int
)
:
"""Initialize RNN parameters"""
import
random
random
.
seed
(
42
)
Set a random seed to ensure reproducibility
Weights input to the hidden layer
self
.
Wx
=
[
[
random
.
uniform
(
0.1
,
0.1
)
for
_
in
range
(
hidden_size
)
]
for
_
in
range
(
input_size
)
]
weights from hidden layer to hidden layer
self
.
Wh
=
[
[
random
.
uniform
(
0.1
,
0.1
)
for
_
in
range
(
hidden_size
)
]
for
_
in
range
(
hidden_size
)
]
bias
self
.
b
=
[
0.0
for
_
in
range
(
hidden_size
)
]
def
step
(
self
,
x:
list
,
h_prev:
list
)
list
:
"""Single-step RNN: takes input x and previous hidden state h_prev, outputs new hidden state"""
hidden_size
=
len
(
h_prev
)
h_new
=
[
0.0
for
_
in
range
(
hidden_size
)
]
h_new = tanh(Wx·x + Wh·h_prev + b)
for
i
in
range
(
hidden_size
)
:
Calculate Wx·x
wx_sum
=
sum
(
x
[
j
]
self
.
Wx
[
j
]
[
i
]
for
j
in
range
(
len
(
x
)
)
)
Calculate Wh·h_prev
wh_sum
=
sum
(
h_prev
[
j
]
self
.
Wh
[
j
]
[
i
]
for
j
in
range
(
hidden_size
)
)
Add bias, pass through tanh
h_new
[
i
]
=
math
.
tanh
(
wx_sum + wh_sum +
self
.
b
[
i
]
)
return
h_new
def
forward
(
self
,
sequence:
list
)
list
:
"""Process the complete sequence"""
hidden_size
=
len
(
self
.
b
)
h
=
[
0.0
for
_
in
range
(
hidden_size
)
]
Initial hidden state
hidden_states
=
[
]
for
x
in
sequence:
h
=
self
.
step
(
x
,
h
)
hidden_states.
append
(
h
)
return
hidden_states
Test: Demonstrate with a simple vector sequence
input_size
=
4
hidden_size
=
3
rnn
=
SimpleRNN
(
input_size
,
hidden_size
)
Assume the input sequence is 4 words, each represented by a 4-dimensional vector
sequence
=
[
[
1.0
,
0.0
,
0.0
,
0.0
]
,
Word 1
[
0.0
,
1.0
,
0.0
,
0.0
]
,
Word 2
[
0.0
,
0.0
,
1.0
,
0.0
]
,
Word 3
[
0.0
,
0.0
,
0.0
,
1.0
]
,
Word 4
]
hidden_states
=
rnn.
forward
(
sequence
)
(
"Runoob Simple RNN Demo"
)
(
"="
40
)
for
i
,
h
in
enumerate
(
hidden_states
)
:
(
f
"Step {i+1} hidden state: {[f'{v:.4f}' for v in h]}"
)
Output:
Runoob Simple RNN Demo
========================================
Step 1 hidden state: ['0.0204', '-0.0434', '0.0556']
Step 2 hidden state: ['-0.0061', '-0.0529', '0.0775']
Step 3 hidden state: ['0.0641', '-0.0409', '0.0655']
Step 4 hidden state: ['0.0143', '-0.0805', '0.0277']
RNN looks reasonable, but it has three fatal problems:
Problem one: Vanishing gradient, difficulty in remembering long-term dependencies
RNN has a "chain-like" structure, and the gradient for each step must be backpropagated to the first step. After multiple multiplications, the gradient will exponentially decay to almost 0.
For example, in the sentence "I went to Paris in 2010,... , that is my favorite city"—"city" should refer to "Paris," but there are too many words in between, making it difficult for RNN to learn this long-range dependency.
LSTM and GRU alleviate this problem, but do not completely solve it.
Problem two: inability to compute in parallel, slow training
RNN must wait for step t-1 to finish before calculating step t. This means:
- Even with 100 GPUs, it can only process word by word.
- The longer the sequence, the longer the training time.
- It is difficult to scale to ultra-large-scale data.
Problem three: Information at the beginning of the sequence is easily "overwritten"
The hidden state of an RNN is updated step by step, and later information continuously overwrites earlier information. Important information at the beginning of a sentence may be almost "diluted" by the end.
The emergence of the Transformer solved these three problems at once.
| Features | RNN/LSTM | Transformer |
|---|---|---|
| Calculation method | Sequential, step by step | Parallel, compute all at once |
| Long-range dependencies | Weak, gradient vanishing | Strong, direct connection at any distance |
| Positional information | Naturally sequential | Requires positional encoding |
| Training speed | Slow | Fast (parallelizable) |
Self-Attention
Self-attention is the core of the Transformer. Its idea is simple: every word must "communicate" with every word in the sentence to see which ones are important to it, and then it is weighted and summed according to the importance.
First, look at the overall architecture diagram:

Intuitive understanding of Q, K, V
Self-attention uses three vectors to describe each word:
- Q (Query)——"Who am I looking for?"——the identity marker for this word
- K (Key)——"Who am I?"——the identity marker for this word
- V (Value)——"What do I have?"——the actual content of this word
The calculation process is:
- Each word uses Q to "match" with the K of all words to get attention scores
- Softmax is used to normalize the scores, summing up to 1
- V is the weighted sum of all words using normalized scores
See the figure for a clearer view:

Attention score calculation formula
The complete formula is:
Attention(Q, K, V) = softmax( Q·Kᵀ / √dₖ ) · V
Let's implement it step by step using pure Python:
Example
============================================
Pure Python implementation of Self-Attention
============================================
import
math
def
softmax
(
x:
list
)
list
:
"""Calculate Softmax: convert a set of numbers into a probability distribution that sums to 1"""
Subtract the maximum value to prevent numerical overflow
max_val
=
max
(
x
)
exp_x
=
[
math
.
exp
(
v - max_val
)
for
v
in
x
]
sum_exp
=
sum
(
exp_x
)
return
[
v / sum_exp
for
v
in
exp_x
]
def
matrix_multiply
(
A:
list
,
B:
list
)
list
:
"""Matrix multiplication: A is m×n, B is n×p, output is m×p"""
m
=
len
(
A
)
n
=
len
(
B
)
p
=
len
(
B
[
0
]
)
result
=
[
[
0.0
for
_
in
range
(
p
)
]
for
_
in
range
(
m
)
]
for
i
in
range
(
m
)
:
for
j
in
range
(
p
)
:
for
k
in
range
(
n
)
:
result
[
i
]
[
j
]
=
A
[
i
]
[
k
]
- B
[
k
]
[
j
]
return
result
def
transpose
(
matrix:
list
)
list
:
"""Matrix transpose"""
return
list
(
map
(
list
,
zip
(
*matrix
)
)
)
class
SelfAttention:
"""Pure Python implementation of the self-attention layer"""
def
init
(
self
,
d_model:
int
,
d_k:
int
)
:
"""
Initialize self-attention layer
d_model: Input/output dimension
d_k: Dimension of Q/K (usually d_k = d_model / num_heads)
"""
import
random
random
.
seed
(
42
)
runoob: fixed random seed
self
.
d_model
=
d_model
self
.
d_k
=
d_k
Initialize the projection matrices for Q, K, V
In practice, these are trained
self
.
Wq
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_k
)
]
for
_
in
range
(
d_model
)
]
self
.
Wk
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_k
)
]
for
_
in
range
(
d_model
)
]
self
.
Wv
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_k
)
]
for
_
in
range
(
d_model
)
]
def
forward
(
self
,
X:
list
)
list
:
"""
Forward pass of self-attention
X: Input sequence, shape [seq_len, d_model]
Returns: Output sequence, shape [seq_len, d_k]
"""
seq_len
=
len
(
X
)
Step 1: Calculate Q, K, V
Q = X·Wq, K = X·Wk, V = X·Wv
Q
=
matrix_multiply
(
X
,
self
.
Wq
)
K
=
matrix_multiply
(
X
,
self
.
Wk
)
V
=
matrix_multiply
(
X
,
self
.
Wv
)
(
" Q's shape:"
,
len
(
Q
)
,
"×"
,
len
(
Q
[
0
]
)
)
(
"K shape:"
,
len
(
K
)
,
"×"
,
len
(
K
[
0
]
)
)
(
" V's shape:"
,
len
(
V
)
,
"×"
,
len
(
V
[
0
]
)
)
Step 2: Calculate attention score Q·Kᵀ
K_transposed
=
transpose
(
K
)
scores
=
matrix_multiply
(
Q
,
K_transposed
)
(
"Original attention score:"
)
for
i
,
row
in
enumerate
(
scores
)
:
(
f
" Line {i}: {[f'{v:.4f}' for v in row]}"
)
Step 3: Scaling: Divide by √d_k
This is to prevent Softmax from entering the gradient saturation region
scale_factor
=
math
.
sqrt
(
self
.
d_k
)
scores_scaled
=
[
[
v / scale_factor
for
v
in
row
]
for
row
in
scores
]
(
"\n Scaled attention scores:"
)
for
i
,
row
in
enumerate
(
scores_scaled
)
:
(
f
" Line {i}: {[f'{v:.4f}' for v in row]}"
)
Step 4: Softmax normalization
attention_weights
=
[
]
for
row
in
scores_scaled:
attention_weights.
append
(
softmax
(
row
)
)
(
"\n Attention weights (after Softmax):"
)
for
i
,
row
in
enumerate
(
attention_weights
)
:
(
f
" Line {i}: {[f'{v:.4f}' for v in row]}"
)
Step 5: Weighted Sum V
output
=
matrix_multiply
(
attention_weights
,
V
)
return
output
,
attention_weights
============================================
Demonstration: Run self-attention with a simple example
============================================
Assume we have a 4-word sentence, where each word is represented by an 8-dimensional vector
For demonstration, we use one-hot + small random noise
d_model
=
8
d_k
=
6
Input sequence: 4 words, each 8-dimensional
X
=
[
[
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
Word 0
[
0.0
,
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
Word 1
[
0.0
,
0.0
,
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
Word 2
[
0.0
,
0.0
,
0.0
,
1.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
Word 3
]
(
"="
50
)
(
"Runoob Self-Attention Demo"
)
(
"="
50
)
(
f
"Input sequence length: {len(X)}"
)
(
f
"Input dimension: {len(X[0])}"
)
(
)
attn
=
SelfAttention
(
d_model
=
d_model
,
d_k
=
d_k
)
output
,
attention_weights
=
attn.
forward
(
X
)
(
"\n"
"="
50
)
(
"Self-attention output:"
)
(
"="
50
)
for
i
,
row
in
enumerate
(
output
)
:
(
f
"Output for word {i}: {[f'{v:.4f}' for v in row]}"
)
Running this code will show the complete computation process: Q/K/V generation, attention score calculation, scaling, Softmax, and finally the weighted output.
Why divide by √dₖ?
This is an important detail. Assuming each element of Q and K is a random variable with mean 0 and variance 1, the variance of their dot product is dₖ.
If dₖ is large (e.g., 512), the dot product value will be large, causing Softmax to enter the "saturation region"—where the gradient is almost 0, and training stalls.
After dividing by √dₖ, the variance returns to 1, and the Softmax gradient becomes healthy.
Scaling the dot product is one of the key techniques for stable Transformer training.
Multi-Head Attention
Single-head self-attention is powerful, but it has a problem: each word can only "attend" once. What if we want a word to attend to multiple different aspects simultaneously?
For example, in the sentence "In the zoo, the tiger chases the rabbit":
- The "tiger" might need one head to attend to "zoo" (location)
- Another head to attend to "rabbit" (object of action)
- A third head to attend to "chases" (action)
Multi-head attention is to split Q/K/V into multiple "heads," where each head learns a different attention pattern, and then combine them.
Calculation steps for multi-head attention
- Split Q/K/V into h parts along the last dimension (h is the number of heads)
- Each head performs self-attention independently
- Concatenate the outputs of all heads
- Pass through a linear projection layer to get the final output
The formula is:
Original prompt (Chinese, left untranslated)
MultiHead(Q, K, V) = Concat(head₁, head₂, ..., headₕ) · Wₒ
其中 headᵢ = Attention(Q·Wqᵢ, K·Wkᵢ, V·Wvᵢ)
Example
============================================
Pure Python implementation of Multi-Head Attention
============================================
import
math
import
random
random
.
seed
(
42
)
runoob: fixed random seed
def
softmax
(
x:
list
)
list
:
"""Calculate Softmax"""
max_val
=
max
(
x
)
exp_x
=
[
math
.
exp
(
v - max_val
)
for
v
in
x
]
sum_exp
=
sum
(
exp_x
)
return
[
v / sum_exp
for
v
in
exp_x
]
def
matrix_multiply
(
A:
list
,
B:
list
)
list
:
"""Matrix multiplication"""
m
=
len
(
A
)
n
=
len
(
B
)
p
=
len
(
B
[
0
]
)
result
=
[
[
0.0
for
_
in
range
(
p
)
]
for
_
in
range
(
m
)
]
for
i
in
range
(
m
)
:
for
j
in
range
(
p
)
:
for
k
in
range
(
n
)
:
result
[
i
]
[
j
]
=
A
[
i
]
[
k
]
- B
[
k
]
[
j
]
return
result
def
transpose
(
matrix:
list
)
list
:
"""Matrix transpose"""
return
list
(
map
(
list
,
zip
(
*matrix
)
)
)
class
MultiHeadAttention:
"""Pure Python implementation of the multi-head attention layer"""
def
init
(
self
,
d_model:
int
,
num_heads:
int
)
:
"""
Initialize multi-head attention
d_model: Model dimension (must be divisible by num_heads)
num_heads: Number of attention heads
"""
assert
d_model % num_heads
==
0
,
"d_model must be divisible by num_heads"
self
.
d_model
=
d_model
self
.
num_heads
=
num_heads
self
.
d_k
=
d_model // num_heads
Dimension of each head
Initialize projection matrices
self
.
Wq
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_model
)
]
self
.
Wk
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_model
)
]
self
.
Wv
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_model
)
]
self
.
Wo
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_model
)
]
def
split_heads
(
self
,
X:
list
)
list
:
"""
Split the last dimension into num_heads heads
Input shape: [seq_len, d_model]
Output shape: [num_heads, seq_len, d_k]
"""
seq_len
=
len
(
X
)
Reshape: [seq_len, num_heads, d_k]
reshaped
=
[
]
for
row
in
X:
head_rows
=
[
]
for
h
in
range
(
self
.
num_heads
)
:
start
=
h *
self
.
d_k
end
=
start +
self
.
d_k
head_rows.
append
(
row
[
start:end
]
)
reshaped.
append
(
head_rows
)
Transpose: [num_heads, seq_len, d_k]
result
=
[
]
for
h
in
range
(
self
.
num_heads
)
:
head_data
=
[
reshaped
[
i
]
[
h
]
for
i
in
range
(
seq_len
)
]
result.
append
(
head_data
)
return
result
def
combine_heads
(
self
,
heads:
list
)
list
:
"""
Concatenate multiple heads
Input shape: [num_heads, seq_len, d_k]
Output shape: [seq_len, d_model]
"""
seq_len
=
len
(
heads
[
0
]
)
result
=
[
]
for
i
in
range
(
seq_len
)
:
combined
=
[
]
for
h
in
range
(
self
.
num_heads
)
:
combined.
extend
(
heads
[
h
]
[
i
]
)
result.
append
(
combined
)
return
result
def
attention_single_head
(
self
,
Q:
list
,
K:
list
,
V:
list
)
list
:
"Single-head self-attention"
Q·K^T
scores
=
matrix_multiply
(
Q
,
transpose
(
K
)
)
Scale
scale
=
math
.
sqrt
(
self
.
d_k
)
scores_scaled
=
[
[
v / scale
for
v
in
row
]
for
row
in
scores
]
Softmax
weights
=
[
softmax
(
row
)
for
row
in
scores_scaled
]
Weighted sum V
output
=
matrix_multiply
(
weights
,
V
)
return
output
,
weights
def
forward
(
self
,
X:
list
)
list
:
"Multi-head attention forward propagation"
seq_len
=
len
(
X
)
Step 1: Calculate Q, K, V
Q
=
matrix_multiply
(
X
,
self
.
Wq
)
K
=
matrix_multiply
(
X
,
self
.
Wk
)
V
=
matrix_multiply
(
X
,
self
.
Wv
)
Step 2: Split into multiple heads
Q_heads
=
self
.
split_heads
(
Q
)
K_heads
=
self
.
split_heads
(
K
)
V_heads
=
self
.
split_heads
(
V
)
Step 3: Each head performs self-attention independently
output_heads
=
[
]
all_weights
=
[
]
for
h
in
range
(
self
.
num_heads
)
:
out
,
weights
=
self
.
attention_single_head
(
Q_heads
[
h
]
,
K_heads
[
h
]
,
V_heads
[
h
]
)
output_heads.
append
(
out
)
all_weights.
append
(
weights
)
Step 4: Combine all heads
combined
=
self
.
combine_heads
(
output_heads
)
Step 5: Final Linear Projection
output
=
matrix_multiply
(
combined
,
self
.
Wo
)
return
output
,
all_weights
============================================
Demonstrate multi-head attention
============================================
d_model
=
12
num_heads
=
3
12 / 3 = 4 dimensions per head
Input sequence: 4 words, each 12 dimensions
X
=
[
[
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
[
0.0
,
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
[
0.0
,
0.0
,
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
[
0.0
,
0.0
,
0.0
,
1.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
,
0.0
]
,
]
(
"="
50
)
(
"Runoob Multi-head Attention Demo"
)
(
"="
50
)
(
f
"d_model = {d_model}, num_heads = {num_heads}"
)
(
f
"Dimension of each head: d_k = {d_model // num_heads}"
)
(
)
mha
=
MultiHeadAttention
(
d_model
=
d_model
,
num_heads
=
num_heads
)
output
,
all_weights
=
mha.
forward
(
X
)
(
"\nAttention weights for each head:"
)
for
h
in
range
(
num_heads
)
:
(
f
"Head {h}:"
)
for
i
,
row
in
enumerate
(
all_weights
[
h
]
)
:
(
f
" Position {i}: {[f'{v:.4f}' for v in row]}"
)
(
"\n"
"="
50
)
(
"Final output shape of multi-head attention:"
,
len
(
output
)
,
"×"
,
len
(
output
[
0
]
)
)
(
"="
50
)
for
i
,
row
in
enumerate
(
output
)
:
(
f
"Position {i}: {[f'{v:.4f}' for v in row[:6]]}..."
)
The power of multi-head attention lies in: different heads automatically learn different types of attention patterns.
For example, in a translation task:
- Some heads focus on grammatical relationships (subject-verb-object)
- Some heads focus on coreference relationships (who the pronoun refers to)
- Some heads focus on locally adjacent words
These patterns are not manually designed, but are automatically learned by the model during training.
Positional Encoding
Self-attention has a problem: it is a "bag-of-words" model—it does not care about word order. "I love you" and "You love me" might be the same to self-attention.
But order is crucial for language. We need to "inject" positional information into the model.
Sinusoidal Positional Encoding
The original Transformer uses sinusoidal positional encoding:
PE(pos, 2i) = sin(pos / 10000^(2i/d_model))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
Where:
- pos is the position (0, 1, 2, ...)
- i is the dimension index
- d_model is the model dimension
This design is very clever:
- Each position has a unique encoding
- Relative positions can be represented by a linear combination (sin(a+b) = sin a cos b + cos a sin b)
- It can be extrapolated to sequences longer than the training sequence
Example
============================================
Implement sinusoidal positional encoding
============================================
import
math
def
sinusoidal_positional_encoding
(
seq_len:
int
,
d_model:
int
)
list
:
"""
Calculate sine positional encoding
Returns: positional encoding matrix of shape [seq_len, d_model]
"""
pe
=
[
[
0.0
for
_
in
range
(
d_model
)
]
for
_
in
range
(
seq_len
)
]
for
pos
in
range
(
seq_len
)
:
for
i
in
range
(
0
,
d_model
,
2
)
:
Use sin for even dimensions
div_term
=
math
.
pow
(
10000
,
2
- i / d_model
)
pe
[
pos
]
[
i
]
=
math
.
sin
(
pos / div_term
)
Use cos for odd dimensions (if there is a next dimension)
if
i +
1
<
d_model:
pe
[
pos
]
[
i +
1
]
=
math
.
cos
(
pos / div_term
)
return
pe
Demo: Generate positional encoding
seq_len
=
10
d_model
=
8
pe
=
sinusoidal_positional_encoding
(
seq_len
,
d_model
)
(
"="
50
)
(
"Runoob Sine Positional Encoding Demo"
)
(
"="
50
)
(
f
"Sequence length: {seq_len}, Dimension: {d_model}"
)
(
)
for
pos
in
range
(
seq_len
)
:
(
f
"Position {pos:2d}: {[f'{v:.4f}' for v in pe[pos]]}"
)
Look at the relative position relationship
(
"\n"
"="
50
)
(
"Verify the linear relationship of relative positions"
)
(
"="
50
)
(
"Encoding difference between position 0 and position 1:"
)
diff
=
[
pe
[
1
]
[
i
]
- pe
[
0
]
[
i
]
for
i
in
range
(
d_model
)
]
(
[
f
'{v:.4f}'
for
v
in
diff
]
)
RoPE: Rotary Positional Embedding
Although sinusoidal positional encoding is classic, better solutions have emerged later. Current mainstream large models (such as LLaMA) useRoPE (Rotary Positional Embedding).
The idea behind RoPE is to "rotate" the positional information into the Query and Key.
Specifically, it rotates each pair of dimensions of Q and K:
Original prompt (Chinese, left untranslated)
[ q₁, q₂, q₃, q₄, ... ]
↓ 旋转
[ q₁·cos mθ - q₂·sin mθ,
q₁·sin mθ + q₂·cos mθ,
q₃·cos mθ' - q₄·sin mθ',
q₃·sin mθ' + q₄·cos mθ',
... ]
Advantages of RoPE:
- Naturally incorporates relative positional information
- Good extrapolation ability (can be used even when length exceeds training)
- The effect is usually better than sinusoidal positional encoding
ALiBi: Attention with distance decay
Another simple and effective solution isALiBi (Attention with Linear Biases).
It does not add positional encoding, but directly adds a bias to the attention score: the farther apart, the lower the score.
The advantage of ALiBi is that it is simple and particularly friendly to length extrapolation.
| Positional Encoding Methods | Principle | Advantages | Representative Models |
|---|---|---|---|
| Sinusoidal Positional Encoding | sin/cos functions | Extrapolatable, simple computation | Original Transformer, BERT |
| Learnable positional encoding | Direct embedding training | Strong expressive power | GPT-1/2 |
| RoPE | Rotated Q/K | Relative position, good effect | LLaMA, PaLM |
| ALiBi | Attention score with bias | Simple, good for long sequences | MPT, BLOOM |
Feed-Forward Network (FFN) layer
In each Transformer layer, there is a Feed-Forward Network (FFN) after the attention.
FFN structure
The FFN in the original Transformer is:
FFN(x) = max(0, x·W₁ + b₁) · W₂ + b₂
That is: Linear layer -> ReLU activation -> Linear layer.
Usually the intermediate dimension is larger than the input dimension (e.g., d_model=512, intermediate dimension=2048).
ReLU vs SwiGLU
Originally, ReLU was used, but the mainstream now isSwiGLU:
SwiGLU(x) = (x·W₁ ⊗ sigmoid(x·V₁)) · W₂
Where ⊗ is element-wise multiplication.
SwiGLU performs better than ReLU on many tasks, and LLaMA, PaLM, etc., use it.
Why is FFN important?
- Attention is "information aggregation," FFN is "information processing"
- FFN has a large number of parameters, which is the main place where the model "stores" knowledge
- Without FFN, the expressive power of the Transformer will be greatly reduced
Example
============================================
Implementing FFN: ReLU version and SwiGLU version
============================================
import
math
import
random
random
.
seed
(
42
)
runoob
def
relu
(
x:
float
)
float
:
"""ReLU activation function: max(0, x)"""
return
max
(
0.0
,
x
)
def
sigmoid
(
x:
float
)
float
:
"""Sigmoid activation function"""
if
x
<
50
:
Prevent numerical overflow
return
0.0
return
1.0
/
(
1.0
math
.
exp
(
-x
)
)
def
linear
(
x:
list
,
W:
list
,
b:
list
)
list
:
"""Linear layer: y = x·W + b"""
output_size
=
len
(
b
)
output
=
[
0.0
for
_
in
range
(
output_size
)
]
for
i
in
range
(
output_size
)
:
sum_wx
=
sum
(
x
[
j
]
- W
[
j
]
[
i
]
for
j
in
range
(
len
(
x
)
)
)
output
[
i
]
=
sum_wx + b
[
i
]
return
output
class
FFNReLU:
"""ReLU version FFN"""
def
init
(
self
,
d_model:
int
,
d_ff:
int
)
:
self
.
d_model
=
d_model
self
.
d_ff
=
d_ff
Randomly initialized parameters (obtained through training in practice)
self
.
W1
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_ff
)
]
for
_
in
range
(
d_model
)
]
self
.
b1
=
[
0.0
for
_
in
range
(
d_ff
)
]
self
.
W2
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_ff
)
]
self
.
b2
=
[
0.0
for
_
in
range
(
d_model
)
]
def
forward
(
self
,
x:
list
)
list
:
Forward propagation
First layer: Linear + ReLU
hidden
=
linear
(
x
,
self
.
W1
,
self
.
b1
)
hidden
=
[
relu
(
v
)
for
v
in
hidden
]
Second layer: Linear
output
=
linear
(
hidden
,
self
.
W2
,
self
.
b2
)
return
output
class
FFNSwiGLU:
"""SwiGLU version FFN (a more modern choice)"""
def
init
(
self
,
d_model:
int
,
d_ff:
int
)
:
self
.
d_model
=
d_model
self
.
d_ff
=
d_ff
SwiGLU requires two linear layers for gating, plus one output layer
self
.
W1
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_ff
)
]
for
_
in
range
(
d_model
)
]
self
.
V1
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_ff
)
]
for
_
in
range
(
d_model
)
]
self
.
W2
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_ff
)
]
def
forward
(
self
,
x:
list
)
list
:
"""Forward propagation: SwiGLU"""
Calculate two linear transformations
x1
=
linear
(
x
,
self
.
W1
,
[
0.0
for
_
in
range
(
self
.
d_ff
)
]
)
x2
=
linear
(
x
,
self
.
V1
,
[
0.0
for
_
in
range
(
self
.
d_ff
)
]
)
SwiGLU: x1 * sigmoid(x2)
hidden
=
[
a * sigmoid
(
b
)
for
a
,
b
in
zip
(
x1
,
x2
)
]
Output layer
output
=
linear
(
hidden
,
self
.
W2
,
[
0.0
for
_
in
range
(
self
.
d_model
)
]
)
return
output
Demonstrate FFN
d_model
=
8
d_ff
=
16
Test input
x
=
[
0.1
,
0.2
,
0.3
,
0.4
,
0.5
,
0.6
,
0.7
,
0.8
]
(
"="
50
)
(
"Runoob FFN Demo"
)
(
"="
50
)
(
f
"Input: {[f'{v:.4f}' for v in x]}"
)
ffn_relu
=
FFNReLU
(
d_model
,
d_ff
)
output_relu
=
ffn_relu.
forward
(
x
)
(
f
"\nReLU FFN output: {[f'{v:.4f}' for v in output_relu]}"
)
ffn_swiglu
=
FFNSwiGLU
(
d_model
,
d_ff
)
output_swiglu
=
ffn_swiglu.
forward
(
x
)
(
f
"SwiGLU FFN output: {[f'{v:.4f}' for v in output_swiglu]}"
)
Layer Normalization
Another important component in the Transformer is Layer Normalization.
What does Layer Normalization do
Layer Normalization normalizes the features of each sample to a mean of 0 and a variance of 1:
LN(x) = γ ⊗ ((x - μ) / √σ²) + β
Where:
- μ is the mean of x, and σ² is the variance of x
- γ (scale) and β (shift) are learnable parameters
- ⊗ is element-wise multiplication
Example
============================================
Implement Layer Normalization
============================================
import
math
def
layer_norm
(
x:
list
,
gamma:
list
,
beta:
list
,
eps:
float
=
1e-6
)
list
:
"""
Layer normalization
x: input vector
gamma: scaling parameter
beta: offset parameter
eps: small constant to prevent division by zero
"""
Calculate mean
mean
=
sum
(
x
)
/
len
(
x
)
Calculate variance
var
=
sum
(
(
v - mean
)
**
2
for
v
in
x
)
/
len
(
x
)
Normalization + Scale Offset
normalized
=
[
]
for
xi
,
gi
,
bi
in
zip
(
x
,
gamma
,
beta
)
:
normalized.
append
(
gi *
(
xi - mean
)
/
math
.
sqrt
(
var + eps
)
- bi
)
return
normalized
Demonstration layer normalization
d_model
=
6
input vector
x
=
[
1.0
,
2.0
,
3.0
,
4.0
,
5.0
,
6.0
]
gamma is initialized to 1, and beta is initialized to 0
gamma
=
[
1.0
for
_
in
range
(
d_model
)
]
beta
=
[
0.0
for
_
in
range
(
d_model
)
]
(
"="
50
)
(
"Runoob Layer Normalization Demo"
)
(
"="
50
)
(
f
"Input: {[f'{v:.4f}' for v in x]}"
)
output
=
layer_norm
(
x
,
gamma
,
beta
)
(
f
"Output: {[f'{v:.4f}' for v in output]}"
)
Verify mean and variance
mean_out
=
sum
(
output
)
/
len
(
output
)
var_out
=
sum
(
(
v - mean_out
)
**
2
for
v
in
output
)
/
len
(
output
)
(
f
"\nOutput mean: {mean_out:.4f}"
)
(
f
"Output variance: {var_out:.4f}"
)
Pre-Norm vs Post-Norm
There are two ways to place layer normalization:
- Post-NormSublayer -> Residual -> Normalization (Original Transformer)
- Pre-NormNormalization -> Sublayer -> Residual (Current mainstream)
Pre-Norm trains more stably, and almost all large models now use it.
RMS Norm
RMS NormIt is a simplified version of layer normalization, only calculating the root mean square and not subtracting the mean:
RMS(x) = sqrt(mean(x²))
RMSNorm(x) = γ ⊗ (x / RMS(x))
RMS Norm is faster to compute and has similar effects, used by models like LLaMA.
Encoder-Decoder vs Decoder-Only Architecture
The original Transformer is an Encoder-Decoder architecture, but most large language models now are Decoder-Only.
Encoder-Decoder: Used for tasks like translation
Encoder-Decoder Architecture:
- Encoder: Reads the input sequence (such as a source language sentence) and generates contextual representations
- Decoder: Generates the target sequence (such as the translation result) based on the Encoder's output
There are two types of attention in the Decoder:
- Masked self-attention: Can only look at previous words (cannot look at the future)
- Cross-attention: Focuses on the Encoder's output
Suitable tasks: machine translation, speech recognition, summarization generation (requires "rewriting" the input into the output).
Decoder-Only: GPT series, used for generation
The Decoder-Only architecture only has a Decoder, no Encoder. Its characteristics are:
- Only masked self-attention (causal attention)
- Autoregressive generation: outputting one word at a time
- Suitable for the pre-training + fine-tuning paradigm
Current GPT, LLaMA, Claude, Gemini... are almost all Decoder-Only.
Encoder-Only: BERT series, used for understanding
The Encoder-Only architecture only has an Encoder. Its characteristics are:
- Bidirectional attention: each word can see all words
- Suitable tasks: classification, named entity recognition, extractive question answering
- Pre-trained with "Masked Language Model" (MLM)
| Architecture | Components | Attention types | Representative models | Applicable tasks |
|---|---|---|---|---|
| Encoder-Decoder | Encoder + Decoder | Bidirectional + Mask + Cross | T5, BART | Translation, Summarization |
| Decoder-Only | Decoder | Masked (Causal) | GPT, LLaMA, Claude | Text generation |
| Encoder-Only | Encoder | Bidirectional | BERT, RoBERTa | Classification, NER |
Why has Decoder-Only become mainstream? Because it is simple, and under large-scale pre-training, its generation capability is extremely strong. "One-size-fits-all" is actually better than "specially designed."
Flash Attention: Making attention computation fast and memory-efficient
The time and memory complexity of standard self-attention is O(n²), which becomes slow and requires too much VRAM when the sequence length is long (e.g., n=8192).
Flash Attentionis a key optimization that made long sequence training feasible when it appeared in 2022.
Memory bottleneck of standard attention
Standard self-attention needs to store intermediate results (the attention weight matrix) for backpropagation. For n=8192, this is 8192×8192 ≈ 67 million elements, which alone consumes tens of GB of VRAM.
Optimization principle of Flash Attention
The core idea of Flash Attention is:
- Block computation: Divide Q/K/V into small blocks and compute block by block
- Online Softmax: Do not save the complete attention matrix, but recalculate it during the backward pass using mathematical techniques
- Utilizing SRAM: Place the blocks into the GPU's fast cache (SRAM) to reduce HBM access
The result is:
- Memory complexity is reduced from O(n²) to O(n)
- 2-4 times faster
- Identical accuracy (mathematically equivalent)
Most large model training now uses Flash Attention or its variants (Flash Attention v2, Memory-Efficient Attention, etc.).
KV Cache: Inference Acceleration Principle
After training optimization, inference (generation) also needs optimization.KV CacheIs the key to inference acceleration.
Problem: Redundant computation in autoregressive generation
During autoregressive generation, calculating K and V for all previous tokens every time a new token is generated is wasteful.
For example, when generating the 100th token, the K/V for the previous 99 tokens have already been calculated and do not need to be recalculated.
How to implement KV Cache
The idea behind KV Cache is simple:
- Cache the K and V for all previous positions
- When generating a new token, only calculate the K/V for the new token and append it to the cache
- Use the complete K/V for attention
This reduces the computational complexity per step from O(n²) to O(n), significantly improving generation speed.
Instance
============================================
Demonstrate the principle of KV Cache
============================================
import
math
import
random
random
.
seed
(
42
)
def
softmax
(
x
)
:
max_val
=
max
(
x
)
exp_x
=
[
math
.
exp
(
v - max_val
)
for
v
in
x
]
sum_exp
=
sum
(
exp_x
)
return
[
v / sum_exp
for
v
in
exp_x
]
def
matmul
(
A
,
B
)
:
m
=
len
(
A
)
n
=
len
(
B
)
p
=
len
(
B
[
0
]
)
result
=
[
[
0.0
for
_
in
range
(
p
)
]
for
_
in
range
(
m
)
]
for
i
in
range
(
m
)
:
for
j
in
range
(
p
)
:
for
k
in
range
(
n
)
:
result
[
i
]
[
j
]
=
A
[
i
]
[
k
]
- B
[
k
]
[
j
]
return
result
def
transpose
(
matrix
)
:
return
list
(
map
(
list
,
zip
(
*matrix
)
)
)
class
SimpleAttentionWithKVCache:
"""Simple self-attention with KV Cache"""
def
init
(
self
,
d_model:
int
)
:
self
.
d_model
=
d_model
self
.
Wq
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_model
)
]
self
.
Wk
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_model
)
]
self
.
Wv
=
[
[
random
.
normalvariate
(
0
,
0.1
)
for
_
in
range
(
d_model
)
]
for
_
in
range
(
d_model
)
]
def
forward
(
self
,
x_new:
list
,
kv_cache:
tuple
=
None
)
tuple
:
"""
"""Generate in one step, with KV Cache
x_new: Current new input (single position)
kv_cache: Previous K and V, (K_cache, V_cache)
Returns: (output, new kv_cache)
"""
Calculate Q, K, V for the current position
q
=
matmul
(
[
x_new
]
,
self
.
Wq
)
k
=
matmul
(
[
x_new
]
,
self
.
Wk
)
v
=
matmul
(
[
x_new
]
,
self
.
Wv
)
Update KV Cache
if
kv_cache
is
None
:
K_full
=
k
V_full
=
v
else
:
K_cache
,
V_cache
=
kv_cache
K_full
=
K_cache + k
V_full
=
V_cache + v
Attention: only take Q of the current position
scores
=
matmul
(
q
,
transpose
(
K_full
)
)
scale
=
math
.
sqrt
(
self
.
d_model
)
scores_scaled
=
[
[
v / scale
for
v
in
row
]
for
row
in
scores
]
weights
=
[
softmax
(
row
)
for
row
in
scores_scaled
]
output
=
matmul
(
weights
,
V_full
)
return
output
[
0
]
,
(
K_full
,
V_full
)
Demonstrate KV Cache generation process
d_model
=
4
Simulate 4 steps of generation
inputs
=
[
[
1.0
,
0.0
,
0.0
,
0.0
]
,
[
0.0
,
1.0
,
0.0
,
0.0
]
,
[
0.0
,
0.0
,
1.0
,
0.0
]
,
[
0.0
,
0.0
,
0.0
,
1.0
]
,
]
attn
=
SimpleAttentionWithKVCache
(
d_model
)
(
"="
50
)
(
"Runoob KV Cache Demo"
)
(
"="
50
)
kv_cache
=
None
for
step
,
x
in
enumerate
(
inputs
)
:
output
,
kv_cache
=
attn.
forward
(
x
,
kv_cache
)
K_cache
,
V_cache
=
kv_cache
(
f
"\nStep {step}:"
)
(
f
" KV Cache size: {len(K_cache)} positions"
)
(
f
" Output: {[f'{v:.4f}' for v in output]}"
)
(
"\n"
"="
50
)
(
"Note: Each step only calculates the K/V at the current position,"
)
(
Then it is appended to the Cache, no need to recalculate the previous ones!
)
(
"="
50
)
KV Cache has a small cost: it requires extra VRAM to store K and V. For a 7B model with a 4k context, the KV Cache takes up about 1-2GB of VRAM—this is worth it.
There are more advanced optimizations:
- Multi-Query Attention: Multiple heads share K/V
- Grouped Query Attention: Grouped sharing of K/V
These can further reduce VRAM usage and improve inference speed.
Summary: Complete Transformer Workflow
Let's string all the components together to summarize the complete Transformer workflow.
A Decoder-Only Transformer layer
Original prompt (Chinese, left untranslated)
x → LayerNorm → Masked Multi-Head Attention → 残差连接 →
→ LayerNorm → FFN → 残差连接 → 输出
A complete Decoder-Only model
- Input token IDs -> word embeddings
- Add positional encoding
- Through N Transformer layers
- Final LayerNorm
- Linear layer maps to vocab size
- Softmax to get the probability of the next word
Key hyperparameters
| Hyperparameters | Meaning | GPT-2 (124M) | LLaMA-7B | GPT-3 (175B) |
|---|---|---|---|---|
| d_model | Model dimension | 768 | 4096 | 12288 |
| num_heads | Number of attention heads | 12 | 32 | 96 |
| num_layers | Number of layers | 12 | 32 | 96 |
| d_ff | Intermediate dimension in FFN | 3072 | 11008 | 49152 |
| context_len | Context length | 1024 | 2048/4096 | 2048 |
Code implementation guide
If you want to implement a simplified Transformer from scratch, the steps are:
- Implement layer normalization
- Implement self-attention (with mask)
- Implement multi-head attention
- Implement FFN
- Implement the Transformer layer
- Implement positional encoding
- Assemble the complete model
- Implement the training loop
In practice, we would use frameworks like PyTorch instead of pure Python. This pure Python implementation is for demonstrating the principle, so you can understand what each step is doing.
The best way to understand the Transformer is to implement it yourself. Even a simplified version will give you new insights into many details.