Transformer Architecture
The Transformer architecture is a deep learning model based on the Self-Attention mechanism, first proposed by the Google team in the 2017 paper"Attention Is All You Need"in which it was first proposed.
Transformer completely transformed the field of Natural Language Processing (NLP) and became the core foundation of modern large language models (such as GPT, BERT, etc.).
Similar to Recurrent Neural Networks (RNN), Transformer is designed to handle sequential input data such as natural language, and is suitable for tasks like machine translation and text summarization. However, unlike RNN, Transformer does not need to process sequences step by step; instead, it can process the entire input in parallel all at once.
This chapter will take you through an in-depth understanding of Transformer's core ideas, architectural components, and working principles, helping you master the fundamentals of this revolutionary technology.
Transformer Architecture Diagram
The encoder is on the left, and the decoder is on the right.

1. Input Processing (Bottom)
- Embeddings/Projections (Embedding/Projection Layer)
- Function: Convert input words (or tokens) into numeric vectors (e.g. "cat" → [0.2, -0.5, 0.7...]).
- Analogy: It is like assigning a unique "ID number" to each word, but smarter (containing semantic information).
2. Encoder (Left Side)
-
Multi-Headed Self-Attention
- Function: Allow the model to attend to all words in the input simultaneously and compute the relationships between them.
- Example: In the sentence "cat chases mouse", the model learns that the association between "cat" and "mouse" is stronger than that between "cat" and "chase".
- Key Point:Process all words in parallel, unlike RNN which needs to compute them one by one.
-
Norm (Layer Normalization)
- Function: Stabilize the training process and prevent values from becoming too large or too small (similar to "adjusting the volume" to an appropriate range).
-
Feed-Forward Network
- Function: Further process the representation of each word (e.g. extract more complex features).
- Analogy: Like performing an in-depth interpretation of the vector for "cat", adding details (e.g. "a cat is a mammal").
3. Decoder (Right Side)
-
Masked Multi-Headed Self-Attention
- Function: Prevent the model from "cheating" during training (it can only see the current and previous words, not future ones).
- Example: When generating "I love __", the model can only predict the next word based on "I" and "love", and cannot know in advance that the answer is "you".
-
Multi-Headed Cross-Attention
- Function: Let the decoder ask the encoder: "Regarding the input, what should I focus on?"
- Scenario: In translation tasks, when the decoder generates English, it references the Chinese input processed by the encoder.
-
Norm and Feed-Forward Network
- Similar to the encoder, it normalizes and deeply processes the decoder's representations.
4. Output (Top)
- Linear (Linear Layer)
- Function: Map the decoder's output to the vocabulary (e.g. predict that the next word "you" has the highest probability).
- Example: Given the input "I love", the model may output "you" with 80% probability and "eat" with 10% probability...
The Core Idea of Transformer
Self-Attention Mechanism (Self-Attention)
The core idea of Transformer is to rely entirely on the attention mechanism (without recurrent or convolutional structures) to capture global dependencies in the input sequence, thereby achieving efficient parallel computation and stronger long-distance dependency modeling.
Example
Simplified Self-Attention Computation Example
def
self_attention
(
query
,
key
,
value
)
:
scores
=
torch.
matmul
(
query
,
key.
transpose
(
2
,
1
)
)
Compute similarity
weights
=
torch.
softmax
(
scores
,
dim
=
1
)
Convert to a Probability Distribution
output
=
torch.
matmul
(
weights
,
value
)
Weighted Sum
return
output
** Formula:**
[ \text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V ]
- (Q) (Query), (K) (Key), (V) (Value) are matrices obtained through input linear transformations.
- (\sqrt{d_k}) is a scaling factor that prevents the dot product from becoming too large and causing gradient vanishing.
Multi-Head Attention
- Execute the self-attention mechanism multiple times in parallel (multiple "heads"), with each head learning different attention patterns, and finally concatenate the results.
- Advantage: Capture richer contextual information (e.g. local/global dependencies, syntactic/semantic features).
Positional Encoding
- Transformer itself has no recurrent or convolutional structure and cannot directly perceive sequence order, so positional information needs to be explicitly injected.
- Use sine/cosine functions or learnable positional encoding:

Feed-Forward Network (FFN)
- The representation at each position is further transformed through a two-layer fully connected network (with non-linear activation such as ReLU).
- Formula: ( \text{FFN}(x) = \max(0, xW_1 + b_1)W_2 + b_2 ).
Residual Connection & Layer Norm
- Residual Connection: Add the input directly to the output (e.g. ( x + \text{Sublayer}(x) )), alleviating gradient vanishing.
- Layer Normalization: Normalize the output of each layer to speed up training.
Parallel Processing Capability
Unlike traditional RNN/LSTM, Transformer can process the entire sequence in parallel, greatly improving training efficiency.
Global Dependency Modeling
No matter how far apart two words are, Transformer can directly establish dependencies between them, solving the long-distance dependency problem.
Encoder-Decoder Structure
Transformer adopts the classic encoder-decoder architecture, but each part is stacked from multiple identical layers of modules.
Encoder (Encoder)
| Component | Description | Importance |
|---|---|---|
| Multi-Head Attention | Capture semantic information from different subspaces | ★★★★★ |
| Feed-forward network | Non-linear transformation and feature extraction | ★★★★ |
| Residual Connection | Alleviate the gradient vanishing problem | ★★★★ |
| Layer Normalization | Stabilize the training process | ★★★★ |

Decoder (Decoder)
The decoder adds the following on top of the encoder:
- Masked multi-head attention: prevent the current position from attending to future information
- Encoder-decoder attention: fuse source language information
Positional Encoding
Since Transformer has no recurrent structure, positional information needs to be explicitly injected.
Sinusoidal Positional Encoding Formula
The formula is divided into two parts, corresponding to the even and odd dimensions of the positional encoding vector: even dimension (2i), odd dimension (2i+1).

Parameter Description:
-
pos: The position of a word in the sequence (e.g. the 1st word, the 2nd word, etc.). -
i: The dimension index of the positional encoding vector (0 ≤ i < d_model/2). -
d_model: The dimension of the positional encoding (usually the same as the dimension of the word vectors, e.g. 512, 768, etc.).
Characteristics of Positional Encoding
- Sensitive to Relative Position: Can learn relative positional relationships
- Length Extensible: Can handle sequences longer than those seen during training
- Definiteness: No learning required, computed directly
Example
Positional Encoding Implementation Example
class
PositionalEncoding
(
nn.
Module
)
:
def
init
(
self
,
d_model
,
max_len
=
5000
)
:
super
(
)
.
init
(
)
position
=
torch.
arange
(
max_len
)
.
unsqueeze
(
1
)
div_term
=
torch.
exp
(
torch.
arange
(
0
,
d_model
,
2
)
(
math
.
log
(
10000.0
)
/ d_model
)
)
pe
=
torch.
zeros
(
max_len
,
d_model
)
pe
[
:
,
0
::
2
]
=
torch.
sin
(
position * div_term
)
pe
[
:
,
1
::
2
]
=
torch.
cos
(
position * div_term
)
self
.
register_buffer
(
'pe'
,
pe
)
Advantages of Transformer
Comparison with Traditional Architectures
| Feature | Transformer | RNN/LSTM | CNN |
|---|---|---|---|
| Parallelism | Fully Parallel | Sequence Processing | Local Parallelism |
| Long-distance dependencies | Direct Modeling | Step-by-Step Propagation | Limited Receptive Field |
| Training Speed | fast | Slow | Medium |
| Memory Consumption | Higher | Medium | Low |
Practical Application Advantages
- Excellent Performance: Achieve state-of-the-art on most NLP tasks
- Extensibility: The model scale can be easily scaled up (e.g. GPT-3)
- Multimodal Adaptability: Can be applied to various data such as text, images, and speech
- Transfer-Learning Friendly: The pre-training + fine-tuning paradigm is highly effective
Practical Exercise
Exercise 1: Implement Basic Self-Attention
Example
import
torch
import
torch.
nn
.
functional
as
F
def
scaled_dot_product_attention
(
Q
,
K
,
V
,
mask
=
None
)
:
d_k
=
Q.
size
(
1
)
scores
=
torch.
matmul
(
Q
,
K.
transpose
(
2
,
1
)
)
/
math
.
sqrt
(
d_k
)
if
mask
is
not
None
:
scores
=
scores.
masked_fill
(
mask
==
0
,
1e9
)
weights
=
F.
softmax
(
scores
,
dim
=
1
)
return
torch.
matmul
(
weights
,
V
)
Exercise 2: Understand Positional Encoding
- Visualize the positional encoding vectors at different positions
- Compute the similarity between positional encodings and observe positional relationships
Frequently Asked Questions
Q: Why is Transformer more suitable than RNN for long texts? A: RNN needs to pass information step by step, and long-distance dependencies are easily lost; whereas Transformer can directly establish relationships between any two words.
Q: Why does positional encoding choose the sine function? A: The sine function is periodic and can represent relative positional relationships, while also being extensible to sequence lengths not seen during training.
Q: Where is the main computational bottleneck of Transformer? A: The space complexity of the self-attention mechanism is O(n²), and processing long sequences consumes a large amount of memory.
Summary
The Transformer architecture has completely changed the way of sequence modeling through the self-attention mechanism; its core advantages lie in:
- Powerful parallel computing capability
- Efficient long-term dependency modeling
- Flexible scalability
- Excellent performance
Mastering the basic principles of Transformer is an important foundation for learning modern NLP techniques, and is also the key to understanding frontier models such as BERT and GPT.