Transformer model
The Transformer is a deep learning model based on the attention mechanism, first proposed by Vaswani et al. in their 2017 paper 'Attention is All You Need'.
It completely revolutionized the field of natural language processing (NLP) and gradually expanded to almost all areas of AI, such as computer vision.
The core idea of the Transformer is to completely abandon the traditional word-by-word processing approach (RNN) and instead use the attention mechanism to let the model see the entire sentence at once, while determining the relationship of each word with every other word, thereby achieving faster training and stronger comprehension.
Why is the Transformer needed?
Before the Transformer appeared, the NLP field mainly relied on RNN (recurrent neural network) family models (such as LSTM and GRU), which process text sequentially and had two key drawbacks.
Limitations of RNNs
RNNs process text like humans 'reading word by word', which brings the following problems:
- **Vanishing gradient: ** When processing long text, the model 'forgets' earlier information. For example, in 'I borrowed a book about quantum physics at the library yesterday', by the time it reads 'book' it has long forgotten that 'I' is the subject, making long-range dependencies extremely hard to capture.
- **No parallelism: ** RNNs must process each word in order and cannot exploit the GPU's parallel computing capability, making training on very long texts extremely slow.
The Transformer's solution
Through the self-attention mechanism, the model processes all words simultaneously and dynamically computes the strength of the association between every pair of words, completely solving the two problems above.
RNN sequential processing vs Transformer parallel + global attention comparison
Overall Transformer architecture
The Transformer consists of two main parts, the Encoder and the Decoder, each formed by stacking multiple layers of identical modules.
An analogy: the encoder is like a 'reader', interpreting the input Chinese sentence as a set of semantically rich vectors; the decoder is like a 'translator', referring to these vectors to generate the English output word by word.
Below is the Transformer architecture diagram, with the encoder on the left and the decoder on the right.

Complete Transformer encoder + decoder architecture (orange arrows indicate Cross-Attention information flow)
The Transformer model consists of two parts, the Encoder and the Decoder, each built from multiple stacked layers of identical modules.

Encoder
The encoder is formed by stacking NN identical layers, each containing two sublayers:
- **Multi-Head Self-Attention: ** Computes the relevance of each word in the input sequence to every other word.
- **Feed-Forward Neural Network: ** Applies an independent nonlinear transformation to each word.
Each sublayer is followed by a residual connection and layer normalization.
Decoder
The decoder is also formed by stacking NN identical layers, each containing three sublayers:
- **Masked Multi-Head Self-Attention: ** Computes the relevance of each word in the output sequence to preceding words (using a mask to prevent future information leakage).
- **Encoder-Decoder Attention: ** Computes the relevance between the output sequence and the input sequence.
- **Feed-Forward Neural Network: ** Applies an independent nonlinear transformation to each word.
Likewise, each sublayer is followed by a residual connection and layer normalization.
Before the Transformer appeared, mainstream models in NLP were RNN-based architectures, such as Long Short-Term Memory networks (LSTM) and Gated Recurrent Units (GRU). These models captured dependencies in sequences by processing input data sequentially, but had the following problems:
-
Vanishing gradient problem: Long-range dependencies are difficult to capture.
-
Limitations of sequential computation: Cannot fully exploit the parallel computing capability of modern hardware, resulting in low training efficiency.
The Transformer solves these problems by introducing the self-attention mechanism, allowing the model to process the entire input sequence simultaneously and dynamically assign different weights to each position in the sequence.
Core: The self-attention mechanism
Self-attention is the most important component of the Transformer. It answers one question: 'When processing this word, which other words in the sentence should I focus on?'
What are Q, K, and V?
Each word's vector is linearly transformed into three roles: Query, Key, and Value.
The origin of Q, K, V and the attention computation flow
Understanding Q/K/V with a search engine analogy:
Q (Query) = the keyword you type in the search box, representing 'what do I want to look up?'
K (Key) = the title tag of each web page, representing 'which words can I match?'
V (Value) = the actual content of each web page, representing 'what information can I provide?'
Attention weight = the similarity between Q and each K, and the final result = the weighted sum of all V using the weights.
Attention formula
[ \text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V ]
Where:
- (Q) is the query matrix, (K) is the key matrix, and (V) is the value matrix.
- (d_k) is the dimension of the vectors, used to scale the dot product and prevent exploding gradients.
- softmax converts the raw scores into a probability distribution between 0 and 1 (the weights sum to 1)
Multi-Head Attention
A single attention perspective is limited, like looking at a problem from only one angle.
Multi-head attention splits the input into h subspaces, each 'head' independently learning different attention patterns, and finally concatenates the results.

Positional Encoding
The Transformer processes all words simultaneously and naturally has no 'sense of order' -- 'the cat eats the fish' and 'the fish eats the cat' would be treated the same.
Positional encoding is like giving each word a "seat number," telling the model where each word sits in the sentence.
Analogy: Just as you label "Question 1, Question 2" on an exam paper, positional encoding lets the Transformer know that "I" is the first word and "love" is the second.
Since the Transformer has no explicit sequence information (such as time steps in an RNN), positional encoding is used to add position information to each word in the input sequence. Sine and cosine functions are typically used to generate positional encodings:
[ PE_{(pos, 2i)} = \sin\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right) ] [ PE_{(pos, 2i+1)} = \cos\left(\frac{pos}{10000^{2i/d_{\text{model}}}}\right) ]
Where:
(pos) is the word's position, and (i) is the dimension index.
Positional encoding is added to the word embedding, injecting position information into the model
Encoder-Decoder Architecture
The Transformer model consists of two parts: the encoder and the decoder:
- ** Encoder:** Converts the input sequence into a series of hidden representations. Each encoder layer contains a self-attention mechanism and a feedforward neural network.
- ** Decoder:** Generates the target sequence based on the encoder's output. Each decoder layer contains two attention mechanisms (self-attention and encoder-decoder attention) and a feedforward neural network.
Residual connections and layer normalization
After the output of each sublayer (self-attention, feedforward network), two operations are performed: residual connection and layer normalization, which help stabilize training in deep networks.
Residual connections let gradients "short-circuit" through, and layer normalization stabilizes training
- **Residual Connection:** Adds the sublayer's input directly to its output (output = F(x) + x), avoiding the vanishing gradient problem in deep networks and allowing the model to "selectively ignore" a layer's transformation.
- **Layer Normalization:** Normalizes the activation values of each layer, making training more stable and convergence faster.
Advantages of Transformer
Compared with traditional RNN architectures, the Transformer has the following significant advantages:
Parallel computation
Processes the entire sequence at once, fully exploiting GPU parallelism, with training speed far surpassing RNNs.
Long-distance dependencies
The self-attention mechanism keeps the "communication distance" between any two words at 1, no longer limited by sequence length.
Highly scalable
Stacking more layers and increasing dimensions improves performance, giving rise to powerful models such as BERT and GPT.
Applications of Transformer
The Transformer architecture has been widely applied across all areas of AI; the following introduces it by category.
Natural Language Processing (NLP)
Machine Translation (Google Translate)
Text Generation (GPT series)
Text classification
Question answering systems
Sentiment analysis
Summarization
Computer Vision (CV)
Image Classification (Vision Transformer / ViT)
Object detection
Image generation
Multimodal Tasks
Image-Text Alignment (CLIP)
Text-to-Image Generation (DALL-E / Stable Diffusion)
Video understanding
Applications of Transformer
-
Natural Language Processing (NLP):
-
Machine translation (such as Google Translate)
-
Text generation (such as GPT series models)
-
Text classification, question answering systems, and so on.
Machine translation (such as Google Translate)
-Text generation (such as GPT series models)
-Text classification, question answering systems, and so on.
-
Computer Vision (CV):
-
Image classification (such as Vision Transformer)
-
Object detection, image generation, and so on.
Image classification (such as Vision Transformer)
-Object detection, image generation, and so on.
-
Multimodal Tasks:
-
Tasks that combine text and images (such as CLIP and DALL-E).
Tasks that combine text and images (such as CLIP and DALL-E).
PyTorch Implementation Example
The following is a complete PyTorch Transformer example with detailed comments to help beginners understand each step:
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
--- Define the Transformer Model ---
class
TransformerModel
(
nn.
Module
)
:
def
init
(
self
,
input_dim
,
model_dim
,
num_heads
,
num_layers
,
output_dim
)
:
super
(
TransformerModel
,
self
)
.
init
(
)
Token embedding: maps token indices to model_dim-dimensional vectors
self
.
embedding
=
nn.
Embedding
(
input_dim
,
model_dim
)
Positional encoding: learnable position vectors, supporting a maximum length of 1000
self
.
positional_encoding
=
nn.
Parameter
(
torch.
zeros
(
1
,
1000
,
model_dim
)
)
PyTorch's built-in Transformer (includes encoder + decoder)
self
.
transformer
=
nn.
Transformer
(
d_model
=
model_dim
,
Vector dimension
nhead
=
num_heads
,
Number of heads in multi-head attention
num_encoder_layers
=
num_layers
,
Number of encoder layers
num_decoder_layers
=
num_layers
Number of decoder layers
)
Final linear layer: maps vectors back to the vocabulary size (for predicting the next word)
self
.
fc
=
nn.
Linear
(
model_dim
,
output_dim
)
def
forward
(
self
,
src
,
tgt
)
:
src_seq_length
=
src.
size
(
1
)
tgt_seq_length
=
tgt.
size
(
1
)
Token embedding + positional encoding (the two are added together)
src
=
self
.
embedding
(
src
)
self
.
positional_encoding
[
:
,
:src_seq_length
,
:
]
tgt
=
self
.
embedding
(
tgt
)
self
.
positional_encoding
[
:
,
:tgt_seq_length
,
:
]
Through the Transformer (encoder reads src, decoder generates tgt)
transformer_output
=
self
.
transformer
(
src
,
tgt
)
The linear layer outputs vocabulary probabilities for each position
output
=
self
.
fc
(
transformer_output
)
return
output
--- Hyperparameter Settings ---
input_dim
=
10000
Vocabulary size (how many distinct words there are)
model_dim
=
512
Vector dimension of each word (the original paper uses 512)
num_heads
=
8
Number of attention heads (must evenly divide model_dim)
num_layers
=
6
Number of encoder/decoder layers (the original paper uses 6)
output_dim
=
10000
Output dimension (the same as the vocabulary size)
--- Initialize the Model, Loss Function, and Optimizer ---
model
=
TransformerModel
(
input_dim
,
model_dim
,
num_heads
,
num_layers
,
output_dim
)
criterion
=
nn.
CrossEntropyLoss
(
)
Multi-class cross-entropy loss
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
0.001
)
Adam optimizer
--- Construct Sample Data (replace with real corpus in actual use) ---
src: source sequence (e.g., Chinese), shape = (sequence length=10, batch size=32)
src
=
torch.
randint
(
0
,
input_dim
,
(
10
,
32
)
)
tgt: target sequence (e.g., English), shape = (sequence length=20, batch size=32)
tgt
=
torch.
randint
(
0
,
input_dim
,
(
20
,
32
)
)
--- Forward Propagation ---
output
=
model
(
src
,
tgt
)
output.shape = (20, 32, 10000): the predicted distribution over the vocabulary at each position
--- Compute the Loss ---
view(-1, output_dim) flattens (20,32,10000) into (640, 10000)
loss
=
criterion
(
output.
view
(
1
,
output_dim
)
,
tgt.
view
(
1
)
)
--- Backpropagation + Update Weights ---
optimizer.
zero_grad
(
)
Clear the gradients from the previous step
loss.
backward
(
)
Compute gradients
optimizer.
step
(
)
Update parameters
(
f
"Loss: {loss.item():.4f}"
)
The code above uses random data only to demonstrate the flow. For real training, you need to:
Summary
The evolution from RNN to Transformer represents an important paradigm shift in the field of deep learning.
The Evolution Path from RNN to Transformer
The three major innovations of the Transformer completely transformed the landscape of deep learning:
- Self-attention mechanism-- Lets any two words "talk" directly, saying goodbye to vanishing gradients.
- Full Parallelization-- A qualitative leap in training speed, making large-scale pretraining possible.
- General-Purpose Architecture-- From NLP to CV and multimodal, the Transformer has become the "universal building block" of the AI era.
Master the Transformer, and you hold the key to understanding modern AI models such as GPT, BERT, and Stable Diffusion.
Quick Reference of Related Terms
| Term | English | Description |
|---|---|---|
| Self-attention | Self-Attention | A mechanism that computes the relevance between elements within a sequence |
| Multi-Head Attention | Multi-Head Attention | Multiple attention heads computed in parallel, capturing information from different feature subspaces |
| Positional encoding | Positional Encoding | A technique that provides the model with position information of elements in the sequence |
| Residual Connection | Residual Connection | Adds the input directly to the sublayer's output, alleviating vanishing gradients |
| Layer Normalization | Layer Normalization | Normalizes each layer's activation values, speeding up training convergence |
| Encoder | Encoder | Encodes the input sequence into contextual representations |
| Decoder | Decoder | Generates the target sequence from the encoder's output |
| Cross-attention | Cross-Attention | The attention mechanism by which the decoder attends to the encoder's output |
| Masked attention | Masked Attention | A mechanism in the decoder that prevents attending to information from future positions |
| Feed-forward network | Feed-Forward Network | A fully connected layer applied independently to each position |