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

Transformer Architecture

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)

- 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)

- 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. - Function: Stabilize the training process and prevent values from becoming too large or too small (similar to "adjusting the volume" to an appropriate range). - 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)

- 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". - 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. - Similar to the encoder, it normalizes and deeply processes the decoder's representations.

4. Output (Top)

- 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 ]

Multi-Head Attention

Positional Encoding

Feed-Forward Network (FFN)

Residual Connection & Layer Norm

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:

  1. Masked multi-head attention: prevent the current position from attending to future information
  2. 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:

Characteristics of Positional Encoding

  1. Sensitive to Relative Position: Can learn relative positional relationships
  2. Length Extensible: Can handle sequences longer than those seen during training
  3. 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

  1. Excellent Performance: Achieve state-of-the-art on most NLP tasks
  2. Extensibility: The model scale can be easily scaled up (e.g. GPT-3)
  3. Multimodal Adaptability: Can be applied to various data such as text, images, and speech
  4. 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

  1. Visualize the positional encoding vectors at different positions
  2. 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:

  1. Powerful parallel computing capability
  2. Efficient long-term dependency modeling
  3. Flexible scalability
  4. 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.