Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Transformer model

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:

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 (slow, forgets long-range relationships) I love Study Depth Study h1 h2 h3 h4 h5 Must wait for h1->h2->h3->h4 before computing h5 Transformer parallel processing (fast, global attention) I love Study Depth Study attn 0.05 0.1 0.25 0.6 All words computed simultaneously, line thickness = attention weight

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.

Encoder x N layers Multi-head self-attention Add & Norm (residual + normalization) Feed-forward neural network Add & Norm (residual + normalization) Positional Encoding Input Embedding Input: I love learning Decoder x N layers Masked multi-head self-attention (Masked Multi-Head Attention) Add & Norm Encoder-decoder attention (Cross-Attention) Add & Norm Feed-Forward neural network Linear layer + Softmax Positional Encoding Output Embedding Output: I Love Learning K, V Output probability distribution

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:

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:

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:

  1. Vanishing gradient problem: Long-range dependencies are difficult to capture.

  2. 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.

Word vector x xWq xWk xWv Q K V Query (what do I want to look up?) Key (what can I match?) Value (what information do I provide?) Q·K^T / sqrt(dk) (similarity score) softmax x V Output Attn Mathematical formula: Attention(Q,K,V) = softmax(QK^T/sqrt(dk))*V

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:

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.

I (pos=0) love (pos=1) learning (pos=2) deep (pos=3) Token embedding [0.2, 0.8...] Token embedding [0.5, 0.1...] Token embedding [0.7, 0.3...] Token embedding [0.4, 0.6...] + + + + Positional encoding sin(0)=0.0 Positional encoding sin(1)~0.84 Positional encoding sin(2)~0.91 Positional encoding sin(3)~0.14 = vector with position information

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:


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.

x Sublayer F(x) Residual connection (skips the sublayer directly and adds it to the output) + Layer Normalization LayerNorm Output Output = LayerNorm( F(x) + x )

Residual connections let gradients "short-circuit" through, and layer normalization stabilizes training


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

-

Machine translation (such as Google Translate)

-

Text generation (such as GPT series models)

-

Text classification, question answering systems, and so on.

-

Image classification (such as Vision Transformer)

-

Object detection, image generation, and so on.

-

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

print

(

f

"Loss: {loss.item():.4f}"

)

The code above uses random data only to demonstrate the flow. For real training, you need to:

  • 1) Prepare a real parallel corpus (such as Chinese-English translation pairs);
  • 2) Do a good job of tokenization and vocabulary building;
  • 3) Implement step-by-step inference in the Decoder (autoregressive generation);
  • 4) Adjust the learning rate scheduling strategy (the original paper uses Warmup).

  • Summary

    The evolution from RNN to Transformer represents an important paradigm shift in the field of deep learning.

    RNN Sequential / Slow Vanishing Gradient Position Encoding Conveys order Self-attention mechanism Global connections Multi-head Attention Multiple perspectives Trans- former Revolution Before 2014 2017

    The Evolution Path from RNN to Transformer

    The three major innovations of the Transformer completely transformed the landscape of deep learning:

    1. Self-attention mechanism-- Lets any two words "talk" directly, saying goodbye to vanishing gradients.
    2. Full Parallelization-- A qualitative leap in training speed, making large-scale pretraining possible.
    3. 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