# The Document Is All You Need: A Complete Beginner’s Guide to LLM Architecture and Core Technologies

> This beginner-friendly guide breaks down the fundamental principles behind large language models (LLMs). It systematically covers everything from MLP and RNN to Transformer, GPT, BERT, RLHF, Chain-of-Thought, and more — perfect for non-technical investors, entrepreneurs, and business students who want to quickly understand AI’s core technologies.

- Source: https://www.waytoagi.com/en/kb/learning-path/llm-technical-guide
- Original (Feishu, Chinese): https://waytoagi.feishu.cn/wiki/UVluwy2Z4inMfrkudofcQlp7n0c
- Updated: 2026-10-23

---

---

**Author: Chen MinKai (Marco)**

**Editors: Justin | Onsen Wanderer, maomao**

> **5.10 Update:** The initially missing sections on Prompting, InstructGPT, Chain of Thought, and Emergence have all been updated. For readers who want to quickly understand the principles behind ChatGPT, the recommended learning path has been revised to: **Chapter 6 → Chapter 2 → Chapter 4 → Chapter 7 → Chapter 8 → Chapter 10 → Chapter 12 → Chapter 13**. All other sections are **Optional**. **Additionally, in Chapter 15, a comprehensive summary table has been added that outlines the development path of the technology. The table includes internal links for quick navigation within the document.**

> #By Chen MinKai (Marco). I come from a finance background and have never formally studied algorithms, so I may make mistakes. Please be understanding! If you find any errors while reading, feel free to reach out via WeChat: ephemerawithaheart.

> **This document will continue to be iteratively improved. Criticism and corrections are warmly welcome!**

**#For the best reading experience on PC. If you want to get straight to the main content, you can start directly from** [**Chapter 6**](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#Y2wIdmu42oCw0qxOYJPc4E1In2b)**.**

> **#Strongly recommend reading only Chapter 6 first. If you find it interesting and want to dive deeper, then go back to Chapter 2 and Chapter 4 to understand MLP and RNN—especially the MLP chapter. It will directly demystify neural networks and leave you thinking, “Oh, so that’s all it is!”**

> After finishing Chapter 6 and quickly skimming Chapters 2 and 4, you can move on to Chapters 7 and 10. This will help you quickly grasp what the Transformer is (I believe this document offers one of the best explanations of the Transformer among all educational materials!).

> Once you understand the Transformer, go back to Chapter 8. You will then gain a solid foundational understanding of pre-training. With a clear grasp of both pre-training and the Transformer, reading Chapter 12 on GPT will feel completely natural: GPT is essentially a large Transformer stacked with many, many decoders, pre-trained on language modeling tasks.

**Output only the translation:**

---

# Foreword

### Who Is This Document For?

- This is a Feishu document designed for complete beginners who want to understand the underlying technical principles of large language models (LLMs). **Its primary target audience is investors from non-technical backgrounds who wish to grasp the core principles of AI technology.** It is also suitable for anyone interested in models like ChatGPT who wants to get started with large language models and understand what is happening in the world today.

- Although this document claims to have “zero barriers,” the truth is that artificial intelligence can never truly escape calculus, probability theory, and linear algebra. A basic understanding of these mathematical foundations — at minimum, derivatives and minima, the chain rule for multivariate functions, conditional probability, the chain rule expansion of conditional probability, probability density functions, as well as the meaning and operations of vectors and matrices — is extremely important for being able to read and understand this document.

- This document progresses from shallow to deep and covers an enormous amount of technical detail. It ranges from the most basic multilayer perceptron (MLP), to convolutional neural networks (CNN), recurrent neural networks (RNN and their variants LSTM and GRU), reinforcement learning (RL), seq2seq architectures, self-supervised learning, all the way to Transformer models, GPT models (including IFT, SFT, RLHF, and Chain-of-Thought prompting), BERT models, and more.

- This document will be continuously updated and iterated, incorporating the latest technical developments and related principles in the field of language models.

### Why Is Technical Understanding So Important?

Whether you are an entrepreneur or an investor, understanding the underlying technology is extremely important. After recently speaking with many friends about AI and engaging with numerous investors and founders, I have come to the following observations:

- The astonishing capabilities demonstrated by large language models such as ChatGPT have left many people in an irrational state.

- For entrepreneurs, if they lack sufficient technical understanding yet are overwhelmed by the potential of AGI, it is easy to fall into an irrational and fanatical worship of AGI.

- For investors, only by understanding the technical principles and the current state of development can one accurately judge what AI can do and what it cannot do. This enables better discernment: among the wild imaginations of entrepreneurs, which ideas are more likely to truly reshape humanity’s future, and which are merely unrealistic fantasies.

- For anyone, the wave of AI is undoubtedly reshaping the entire world. If one does not understand the technology and remains merely a bystander, one may lack sufficient sense of urgency. Conversely, when continuously exposed to the dazzling flood of information generated by AI’s rapid iteration, without adequate foundational knowledge we may also fall into excessive anxiety.

> **I believe that at this moment when AI technology is iterating at a speed far beyond our expectations, understanding AI is not only a professional necessity — it is also a necessary condition for remaining curious, composed, and self-consistent in a rapidly changing world.**

### About the Highlight Colors Used in This Document

**Orange-red background**: Used to highlight what this document will focus on and what it will deliberately omit.

**Yellow background**: Used to highlight important common sense. Understanding these points will greatly help with learning AI-related content. As an introductory text, this document does not prove these common-sense statements (e.g., “neural networks can fit a wide variety of probability functions”), but may attach reference links for readers who wish to explore the underlying principles.

**Orange background**: Simply indicates text that the author considers particularly important and hopes readers will pay extra attention to.

**Blue background**: Used to highlight important definitions.

**Green background**: Usually appears alongside blue backgrounds to provide an example that helps readers better understand the definition being highlighted.

**Gray background**: Contains text that is not critical — basically just the author being playful or making casual remarks.

### This Document Makes Heavy Use of AI Tools for Writing and Contains a Large Number of References

- The writing of this document has heavily leveraged AI tools such as ChatGPT for assistance.
- The document will frequently recommend high-quality learning resources.
- Most of the diagrams are not drawn by the author; original sources will be cited at the end of each chapter.
- I have collapsed Chapters 1–5. It is strongly recommended to start reading from Chapter 6; otherwise, your patience may be exhausted before reaching the main content.

### Business Students Helping Business Students — Feel Free to Use for Research Reports (But Please Cite the Source)

The document has received a lot of positive feedback from peers, especially from many friends working in computer research teams at investment institutions who expressed gratitude. The original purpose of writing this document was to help non-technical business students who have research tasks related to LLMs become competent in their work after studying it. Therefore, feel free to cite it, but **you must always clearly indicate the source**.

---

# Introduction: Overview of Artificial Intelligence

**Reference Table of Contents** (This section is extremely foundational. Readers who already have a basic understanding of artificial intelligence may safely skip it.)

## Artificial Intelligence Concepts and Branches

- **Artificial Intelligence (AI)** is a computer science discipline that enables various types of machines to simulate and possess intelligence similar to living organisms, allowing machines to perceive, learn, recognize, reason, and perform other behaviors.

- Artificial Intelligence is a branch of computer science. Its related fields include Computer Vision (CV), Natural Language Processing (NLP), Voice Recognition, Text-to-Speech (TTS), Knowledge Graph, and more. This document serves as introductory material for large language models and therefore focuses primarily on technologies in the NLP domain.

- From an academic perspective, artificial intelligence has three major schools of thought: **Symbolicism**, **Connectionism**, and **Actionism**.

- Machine learning is the core of artificial intelligence. The mainstream algorithms behind today’s most cutting-edge AI technologies are all based on neural networks and reinforcement learning.

| **School**          | **Symbolicism** | **Connectionism** | **Actionism** |
|---------------------|-----------------|-------------------|---------------|
| **Philosophical Origin** | Mathematical logic: Based on statistical methods, machines simulate human intelligence through modeling and prediction via computation, enabling tasks such as recognition and forecasting. | Bionics: Biological intelligence arises from neural networks. Artificial neural networks can be constructed and trained to produce intelligence. | Biological intelligence comes from perceiving and adapting to complex external environments. Stronger intelligence emerges through interaction with the environment and other organisms. |
| **Representative Algorithms** | Naive Bayes, Logistic Regression, Decision Trees, Support Vector Machines | Neural Network | Reinforcement Learning |

## Machine Learning

- **Machine Learning (ML)** is the core methodology for achieving artificial intelligence. It is the process of “learning” (or “inferring”) general patterns from limited observational data and using those patterns to make predictions on unseen data.

- Traditional machine learning primarily focuses on learning a predictive model. It generally requires first representing the data as a set of **features (Feature)**. These features can be expressed as continuous numerical values, discrete symbols, etc. The features are then fed into a predictive model to produce the output. This type of machine learning can be regarded as **Shallow Learning**. Its key characteristic is that it does not involve feature learning; features are mainly extracted through human expertise or feature engineering techniques.

![](https://www.waytoagi.com/api/kb-media/Cr8xbpX2aolo1Mx8u6hcQ9Yjnae)

## Machine Learning Classification: By Learning Paradigm

Based on different learning paradigms, machine learning can be divided into supervised learning, unsupervised learning, self-supervised learning, and reinforcement learning.

### Supervised Learning

#### Basic Definition of Supervised Learning

- **Supervised Learning:** A common learning paradigm in machine learning. Its core idea is to train a model using labeled training data, enabling the model to learn the mapping relationship between inputs and outputs. This mapping can then be used to make predictions on new, unlabeled data. **(Doesn’t this sound a lot like how humans learn by doing practice problems? You study from a set of exercises that come with standard answers. If you get a question wrong, you reflect on why and improve. When a new question appears, you can solve it based on the experience gained from previous practice.)**

- A supervised learning training set must include **inputs (features)** and **outputs (targets)**, where the outputs are manually annotated.

- Example of supervised learning: Train a model to detect whether a company’s financial statements involve financial fraud. There are 1,000 financial reports, each containing key data such as asset-liability ratio and cash flow (denoted as X). Among them, 500 reports involve fraud and 500 do not.

- This gives us a **training dataset** of 1,000 samples. X represents the **input** or **features** of each training sample; whether the report involves fraud is the **manually labeled** **output** or **target**. Since every input training sample has a corresponding expected output, it is called “supervised.” We can refer to such training samples as “labeled input-output pairs.”

- Using this training dataset, we train the algorithm. Overall, the training produces a function f(X) that has “learned” the patterns in the training set: f(X1) = fraud, f(X2) = normal, f(X3) = normal, f(X4) = fraud, …, f(X1000) = fraud. When we are given a new financial report, the model can help us determine whether it involves fraud or is normal.

- The steps of supervised learning are as follows:

![](https://www.waytoagi.com/api/kb-media/CGxVb1ifQoxy3fxaDEyc6pnknBb)

#### Typical Applications of Supervised Learning

1. **Classification**: Predict which category an input sample belongs to, or the probability distribution over categories. Typical examples include spam detection, image classification, etc.

2. **Regression**: Predict a numerical output for the input sample, usually a continuous real value. Typical examples include house price prediction, stock price prediction, etc.

3. **Object Detection**: Detect the location and category of target objects in images or videos. For example, identifying vehicles, pedestrians, and traffic signs on the road in autonomous driving, or determining which part of an image is a face in facial recognition.

4. **Sequence Generation**: Generate an output sequence based on an input sequence, such as machine translation, music generation, etc.

5. **Sequence Labeling**: A common machine learning task in which the input data is typically sequential (e.g., text, speech, bioinformatics). Supervised learning can predict a label for each element in the input sequence. Examples include Named Entity Recognition (NER — the ability in natural language processing to extract entities or entity categories with specific meaning from text, such as person names, place names, organization names, dates, times, and monetary amounts), Speech Recognition, etc.

#### Common Supervised Learning Algorithms

- Common supervised learning algorithms include Linear Regression, Logistic Regression, Decision Trees, Support Vector Machines, Random Forests, and others.

- Most of the algorithms mentioned here are not necessary to study in depth — just focus on neural networks.

### Unsupervised Learning

#### Basic Definition of Unsupervised Learning

- **Unsupervised Learning** is a common learning paradigm in machine learning. Its goal is to automatically discover structures, patterns, associations, or representations within unlabeled data without the guidance of manual labels or prior knowledge.

- In unsupervised learning, the algorithm must learn directly from the data without any prior knowledge of the labels or categories. The main challenge of unsupervised learning is the lack of labeled training samples to guide the learning process, so the algorithm must automatically discover patterns and structures from the data.

![](https://www.waytoagi.com/api/kb-media/L1XgbgCCTocOAHx5pwsc0ZUAnjl)

- Unsupervised learning example: Classifying customers based on shopping habits. Suppose we have a large set of customer shopping data, including purchase amounts, purchase times, purchased items, and other information. This data is not pre-labeled or categorized. By applying unsupervised learning algorithms such as the k-means clustering algorithm or hierarchical clustering, we can automatically identify groups of customers with similar shopping behaviors and divide them into different clusters. These clusters can correspond to different consumption habits, purchasing preferences, or market segments, helping businesses better understand customer behavior and make informed business decisions.  
<It sounds like unsupervised learning and data mining are somewhat similar, right?> This is a **clustering problem**.

- Unsupervised learning example: Image compression. Images are typically composed of a large number of pixels, each containing color information. The goal of image compression is to reduce the storage space or transmission bandwidth required by an image by eliminating redundant information, while preserving image quality as much as possible. Dimensionality reduction is one approach to image compression, achieved by reducing the dimensions of the image data. Unsupervised learning techniques for dimensionality reduction, such as **Principal Component Analysis (PCA)** and **Autoencoders**, can be used for image compression. For example, PCA can project image data onto principal components in a lower-dimensional space to achieve dimensionality reduction and compression. Autoencoders can learn a low-dimensional representation of the image and reconstruct it, thereby reducing and compressing the data.  
<Image compression doesn’t necessarily require machine learning, but unsupervised learning can indeed be used to achieve it!> This is a **dimensionality reduction problem**.

#### Typical Applications of Unsupervised Learning

> Unsupervised learning has a very wide range of applications, including but not limited to the following:

1. **Clustering**: Automatically grouping samples in a dataset into different clusters based on similarity. Typical examples include customer segmentation, social network user clustering, etc.

2. **Anomaly Detection**: Identifying anomalous samples in data that differ from normal ones. These may represent potential abnormal events or behaviors. Typical examples include anti-money laundering and credit card fraud detection.

3. **Dimensionality Reduction**: Mapping high-dimensional data to a lower-dimensional space while preserving the main information and removing redundancy and noise. Typical examples include image compression.

4. **Association Rule Mining**: Discovering frequently occurring association rules from large-scale datasets to uncover hidden relationships in the data. Typical examples include market basket analysis and recommendation systems.

#### Common Unsupervised Learning Algorithms

Most of the algorithms mentioned here are not required reading.

Common unsupervised learning algorithms include clustering algorithms such as K-means clustering, dimensionality reduction algorithms such as Principal Component Analysis (PCA) and t-SNE, and anomaly detection algorithms such as density-based anomaly detection and distance-based anomaly detection. Unsupervised learning is widely used in many real-world applications, including image processing, natural language processing, recommendation systems, and more.

The following types of unsupervised learning algorithms will be covered in detail later:

1. **Embedding Learning**: For example, Word Embedding.

### TikTok Recommendation Algorithm: An Example Combining Supervised and Unsupervised Learning

Unsupervised learning and supervised learning are both paradigms of machine learning, and the two are often used together within the same algorithm.

- Recommendation algorithms used in products like TikTok are typically based on machine learning techniques and incorporate a combination of unsupervised and supervised learning methods.

- **In recommendation systems, unsupervised learning methods can be used to learn user behavior patterns, content features, and other information from large amounts of unlabeled data, thereby providing personalized recommendations to users.** For example, TikTok’s recommendation algorithm may use unsupervised techniques such as Clustering and Dimensionality Reduction to analyze and process the vast amount of video data uploaded by users. It extracts video features such as content, emotion, and duration, then clusters similar videos together based on users’ viewing history and behavioral preferences to recommend similar content.

- **Supervised learning methods are also commonly used in recommendation algorithms. By using labeled sample data**—such as users’ historical behavior data (clicks, likes, comments, etc.) and user feedback (preferences, interests, etc.)—**models are trained to make recommendation predictions.**

![](https://www.waytoagi.com/api/kb-media/PgV4b9nivorZaaxLVM9cZtlbn9e)

<In the diagram above, which parts require supervised learning, which parts require unsupervised learning, and which parts need human intervention?>

In summary, recommendation algorithms used in products like TikTok typically integrate multiple machine learning techniques—including both unsupervised and supervised learning methods—to learn user interests and content features from large volumes of data, delivering a personalized recommendation experience.

### Self-supervised Learning

Self-supervised learning is itself a paradigm of unsupervised learning, as it also does not require manual labeling. However, in terms of the capabilities it demonstrates, self-supervised learning is very different from unsupervised learning, which is why it is introduced separately here.

- Self-supervised learning primarily leverages auxiliary tasks (**Pretext Tasks**) to mine its own supervisory signals from large-scale unlabeled data. By training the network on these artificially constructed supervisory signals, the model can learn representations that are valuable for downstream tasks.

Although the above description may sound somewhat abstract, the concept can be better understood with the following diagrams:

The left diagram illustrates the difference between self-supervised learning and supervised learning. Consider the following sentence:  
“Silver’s words sounded like those of a terminal cancer patient. He was already in this state—why wouldn’t you just go along with him? You should at least leave him with some beautiful memories in his final days.”

A supervised task would be to determine whether this sentence is harmful. The sentence is obviously harmful, but a machine cannot automatically learn that it is harmful. We need humans to manually label it as “harmful.”

In contrast, for a self-supervised task such as cloze (fill-in-the-blank), the machine can do the following: First, transform the original text into  
“Silver’s words sounded like those of a terminal cancer patient. He was already 【Masked】 this state—why wouldn’t you 【Masked】 go along with him? You should at least leave him with some beautiful memories in his final days.”

The model is then asked to predict the two masked words. The correct answers for these masked positions serve as **Ground Truth**. No human judgment is required; simply by looking at the original input text, we know the two masked tokens should be “in” and “just.” In this way, the machine can automatically generate a new input x' and its corresponding labels x'' from the original sample through a pretext task, and use them for learning.

| ![](https://www.waytoagi.com/api/kb-media/OIjmb47umoiWRdxWDrKc7NwPnOh) | ![](https://www.waytoagi.com/api/kb-media/WO2ebaJ62o8OfIxhC3OcN8TEntc) |
| --- | --- |

The right diagram shows an application of self-supervised learning in BERT. After inputting the phrase “National Taiwan University,” the model randomly masks one character—in this case, “wan”. The model’s task is then to predict what the masked character should be. The ground-truth answer is, of course, known to the machine: it is the character “wan.” Therefore, the model can automatically compare its own output with the correct answer and correct itself accordingly.

> Although self-supervised learning may seem easy to understand at first glance, it is actually a brilliant idea. We will first encounter self-supervised learning in detail in Chapter 8 later in this series.

### Reinforcement Learning

There will be a dedicated chapter introducing reinforcement learning later, so only a high-level overview is provided here.

#### Basic Definition of Reinforcement Learning

- **Reinforcement Learning (RL)** is a machine learning paradigm that enables an agent to learn how to make appropriate decisions through interaction with an environment, with the goal of maximizing expected cumulative reward.

- In reinforcement learning, the **Agent** interacts with the **Environment**, observes the environment’s **State**, performs different **Actions**, receives feedback from the environment in the form of a reward signal (**Reward**), and adjusts its **Policy** based on that feedback. Through this process, it gradually learns how to make optimal decisions in various environments.

**Key characteristics of reinforcement learning include the following:**

1. **Environment and State:** In reinforcement learning, the Agent interacts with the Environment and perceives changes by observing the Environment’s **State** before making decisions.  
   *(Example: When we drive, we interact with the road conditions we see. Based on the state of pedestrians, other vehicles, traffic signs, etc., we decide how to turn the steering wheel. The entire road is the Environment, and the specific traffic conditions on the road constitute the State.)*

2. **Action and Policy:** The Agent can take different **Actions** that affect the **State** of the Environment. Given a particular State, which Action should the Agent choose? The Agent selects Actions according to a **Policy**. A Policy is typically a function that takes the current State as input and outputs the Action to be executed.  
   *(Example: How we turn the steering wheel is the Action. Deciding how to turn the wheel under different road conditions is the Policy. Turning the wheel changes the state of the environment, and changes in the environment’s state, in turn, determine how we should turn the wheel next.)*

3. **Reward and Goal:** The environment provides reward signals to the Agent to indicate the quality of its behavior. The Agent’s objective is to maximize the expected cumulative reward, thereby learning how to make the best decisions.  
   *(Example: Other cars on the road may honk at you to indicate you are driving poorly. If you violate traffic rules, the police will issue a penalty—this is a negative Reward. Your Goal might be to reach your destination as quickly and safely as possible without breaking any rules. By continuously interacting with the environment, you learn an optimal driving Policy that allows you to achieve this goal.)*

4. **Trial-and-Error Learning and Optimization**: In reinforcement learning, an Agent continuously learns and optimizes its policy through interaction with the environment. This is an ongoing process of trial and error. The repeated interaction between State and Action forms the core of reinforcement learning, which is why it is also known as **Trial and Error Learning**. The ultimate goal of reinforcement learning is to find a good policy.

5. **Value Determines Policy**: Value refers to the expected sum of all future rewards. (e.g., In a game of Go, if a single move decides the outcome of the game, that move has extremely high value!)  
<Value has two functions — the State Value Function and the Action Value Function. We won’t go into detail here; there will be dedicated chapters later that introduce reinforcement learning and its basic mathematical formulations!>

![](https://www.waytoagi.com/api/kb-media/A69ubedJVofGEpxxiDScuvJtncg)

The diagram above mentions “Value”; we will discuss it in more detail later!

Reinforcement learning does not require any pre-collected data. Instead, it obtains learning signals and updates model parameters by receiving rewards (feedback) from the environment in response to its actions.

Reinforcement learning is the third fundamental machine learning paradigm, alongside supervised learning and unsupervised learning. Unlike supervised learning, **reinforcement learning does not require labeled input-output pairs, nor does it need precise corrections for non-optimal solutions.** Its core focus lies in striking a balance between exploration (of unknown areas, Exploration) and exploitation (of existing knowledge, Exploitation). We will discuss the Exploration vs. Exploitation Trade-off in detail later; for now, we’ll skip over it quickly.

#### Typical Applications of Reinforcement Learning

1. **Autonomous Driving**: Reinforcement learning has been widely applied in the field of autonomous driving. For example, intelligent vehicles are trained to learn driving policies under various road conditions, including collision avoidance, energy efficiency optimization, and more. (In autonomous driving, supervised learning techniques such as image recognition are used to understand the current State, while RL techniques are used to continuously optimize the driving policy.)

2. **Games and Game Players**: Reinforcement learning is extensively used in video games. Intelligent agents are trained to make strategic decisions in complex game environments, such as Go, chess, and others. Additionally, reinforcement learning can be used to train virtual characters in games, enabling them to autonomously learn and optimize their behavioral strategies. (e.g., AlphaGo)

3. **Robotics Control**: Reinforcement learning has broad applications in robotics, including autonomous navigation, robotic arm control, drone control, and more. Through reinforcement learning, robots can learn control policies from interactions with the environment to accomplish complex tasks.

#### Common Reinforcement Learning Algorithms

Reinforcement learning algorithms are broadly categorized into value-based learning, policy-based learning, and Actor-Critic methods. We will cover these in later sections!

## Machine Learning Classification: By Network Depth and Complexity

### Shallow Learning

Shallow learning generally refers to machine learning models that use fewer layers and simpler structures, such as traditional linear regression, logistic regression, decision trees, support vector machines, and others. These models typically have only one or very few layers, and the feature representations at each layer are relatively simple and shallow, lacking strong abstraction capabilities.

#### Basic Definition of Shallow Learning

![](https://www.waytoagi.com/api/kb-media/D3lybtcpOo1JYTxI4c8c4hlqnie)

Image source: Qiu Xipeng, *Neural Networks and Deep Learning* (same for all images below)

- Shallow Learning, also known as surface learning or traditional learning, is a machine learning approach that primarily relies on building shallow, relatively simple models to perform tasks such as pattern recognition, classification, and regression.

- Shallow learning methods typically include traditional statistical learning techniques such as Logistic Regression, Decision Trees, Support Vector Machines (SVM), Naive Bayes, as well as some nonlinear models like K-Nearest Neighbors (KNN) and Random Forests. **These methods usually rely on manually designed features (i.e., feature engineering). They construct models by processing and selecting features, then use these models for prediction and classification.**

- Compared to Deep Learning, shallow learning typically employs simpler model architectures and fewer hierarchical structures, without involving complex deep neural network architectures.

**The most prominent characteristic of shallow learning is that features are manually designed. Through feature engineering, the model’s input is determined based on the raw data.**

#### Features

- **A feature refers to an attribute or piece of information extracted from raw data to represent a sample.** (For example, recall the supervised learning task of financial fraud detection we mentioned earlier. A financial statement contains a lot of information that a machine cannot understand directly. We might calculate ratios such as the debt-to-asset ratio and current ratio from the financial statement and feed them to the model as floating-point numbers. In this case, the debt-to-asset ratio and current ratio are the features we selected from the financial report.)

- In machine learning models, features are used as model inputs to represent different attributes of samples, thereby helping the model learn and make predictions. **Therefore, data must first be represented as a set of features before it can be fed into a model for machine learning.**

- **In simple terms, features are what you specifically feed to the machine based on the original information.**

#### Feature Engineering

Feature Engineering refers to the process in machine learning and data mining of processing, transforming, and extracting raw data to generate new features or select appropriate ones, thereby improving model performance and increasing prediction accuracy.

**Example:** If you want to build a model to detect whether a financial statement involves fraud: f(features of financial report) = fraud or not, there are many choices for the input parameters: debt-to-asset ratio, earnings quality, current ratio, quick ratio, etc.

**The choice of which parameters to use and how many to input can have a significant impact on the model’s final recognition performance. The process of discovering and selecting these features is called feature engineering.**

## Deep Learning

Before explaining what deep learning is, I’d like to first clarify the concepts of representation and representation learning.

### Representation

Representation generally refers to the way data is encoded or expressed in a particular form. It can be a representation in feature space or in some other space. In deep learning, representations are typically learned automatically by the model—for example, through feature extraction and representation learning in the hidden layers of a neural network (we’ll cover this when discussing MLPs later). These automatically learned representations are usually better at capturing complex patterns and relationships in the data than hand-crafted features, thereby improving the model’s performance.

### Local Representation

Local representation, also known as discrete representation or symbolic representation. Taking color as an example, we can use many different words to describe various colors. In addition to the basic ones like “red,” “blue,” “green,” “white,” and “black,” there are also many named after places or objects, such as “China Red,” “sky blue,” “coffee brown,” and “amber.” When representing colors in a computer, there are generally two approaches. **If we assign a unique name to each color, this method is called local representation.**

Local representations are typically expressed in the form of one-hot vectors. Suppose all color names form a vocabulary 𝒱 with size |𝒱|. We can use a |𝒱|-dimensional one-hot vector to represent each color. In the one-hot vector for the i-th color, the i-th dimension is 1 and all others are 0.

The example in the table below shows the local representations for amber, sky blue, China red, and coffee brown.

When we later discuss natural language processing, we’ll see that early language models primarily used one-hot vectors as representations for words.

Local representations have two main advantages:

1) **This discrete representation offers excellent interpretability**, making it easy for humans to summarize and induce features, and to perform efficient feature engineering through feature combinations.

2) The representation vectors obtained by combining multiple features are usually sparse binary vectors, which provide very high computational efficiency when used with linear models.

However, local representations also have two significant drawbacks:

1) One-hot vectors have extremely high dimensionality (**the curse of dimensionality**) and cannot be easily extended. If a new color appears, we need to add an extra dimension to represent it.

2) **The similarity between any two colors is always 0, because all vectors are orthogonal.** This means we cannot capture the fact that “red” is more similar to “China red” than to “black.”

![](https://www.waytoagi.com/api/kb-media/F05qbymBGoripUx4hsDcbH5AnHg)

### Distributed Representation

**Distributed representation is a method of representing data as a multi-dimensional vector, where each dimension carries part of the information about the data.**

For example, using RGB values to represent colors maps each color to a point in a three-dimensional R, G, B space. This is a distributed representation. Distributed representations are typically expressed as low-dimensional dense vectors (see the figure above).

Distributed representations are widely used in deep learning. For instance, neural networks often use an embedding layer to produce distributed representations of input data (we’ll see this again when we get to word embeddings).

Compared with building a vocabulary 𝒱 that contains the name of every possible color, **we can now represent all colors using just a three-dimensional vector.**

In addition, **similarity between different colors becomes easy to compute**—we simply calculate their cosine similarity, Euclidean distance, or other metrics.

**Distributed representations offer many advantages**, such as better capture of data diversity, stronger generalization ability, and the capacity to handle unseen data. In natural language processing, for example, distributed word vectors (such as Word2Vec and GloVe) represent words as multi-dimensional vectors, where each dimension encodes semantic and syntactic properties. This allows words to be represented effectively even with very large vocabularies, capturing rich semantic and syntactic relationships between them.

### Representation Learning

- **Representation learning is an automated method for learning effective feature representations directly from raw data.** It uses models such as deep neural networks to automatically discover hierarchical and abstract feature representations from raw input, without the need for manual feature engineering. Representation learning can extract richer and higher-level features from data, providing a better description of the underlying structure and thereby improving model performance and generalization.

- To learn a **good high-level semantic representation (typically a distributed representation)**, one usually starts from low-level features and applies multiple stages of nonlinear transformations (the reason nonlinearity is essential is that repeated linear transformations are mathematically equivalent to a single linear transformation). Representation learning is naturally tied to deep learning because the deep, layered structure of neural networks enables exponential growth in representational power through feature reuse. **Therefore, the key to representation learning lies in constructing multi-level feature representations with sufficient depth.**

### Definition of Deep Learning

- Deep learning is a learning method that uses neural network models with deep, complex structures. A deep learning model typically consists of multiple layers (usually more than three) of neurons, where the output of each layer serves as the input to the next layer, forming a stacked hierarchical structure. By learning more abstract and high-level feature representations across multiple layers, deep learning models can better capture the intrinsic structures and characteristics within data.

- To learn a good representation, it is necessary to build a model with a certain level of “depth” and use learning algorithms to allow the model to automatically discover good feature representations (from low-level features, to mid-level features, and then to high-level features), ultimately improving the accuracy of the predictive model. The term “depth” refers to the number of times the raw data undergoes nonlinear feature transformations. If a representation learning system is viewed as a directed graph, depth can also be understood as the length of the longest path from the input node to the output node.

![](https://www.waytoagi.com/api/kb-media/ZIjdbYQJdoLGCXxNM80cM3KYnng)

- Figure 1.4 illustrates the data processing pipeline of deep learning. Through multi-layer feature transformations, raw data is converted into higher-level, more abstract representations. These learned representations can replace manually designed features, thereby avoiding “feature engineering.”

**# As Professor Qiu Xipeng puts it, deep learning can avoid the feature engineering involved in feature processing (feature extraction and feature selection) in shallow learning by performing representation learning through low-level, intermediate, and high-level features.**

### End-to-End Learning

#### Traditional Machine Learning: Multiple Submodules

- In some complex tasks, traditional machine learning methods require artificially dividing the path from input to output into many submodules (or multiple stages), with each submodule trained separately. For example, a natural language understanding task typically involves steps such as word segmentation, part-of-speech tagging, syntactic parsing, semantic analysis, and semantic reasoning.

**This approach has two main problems:**

- First, each module needs to be optimized independently, and its optimization objective may not align with the overall task objective;
- Second, error propagation: errors from earlier steps can significantly affect subsequent models. This increases the difficulty of applying machine learning methods in real-world scenarios.

#### Definition of End-to-End Learning

End-to-End Learning, also known as end-to-end training, refers to a learning process that does not divide training into separate modules or stages, but directly optimizes the overall objective of the task. In end-to-end learning, the specific functions of different modules or stages are generally not explicitly defined, and the intermediate processes require no human intervention. The training data for end-to-end learning consists of “input-output” pairs, without the need for any additional information. Therefore, like deep learning, end-to-end learning also addresses the credit assignment problem. Today, most deep learning approaches that adopt neural network models can also be viewed as a form of end-to-end learning.

# Simply put, end-to-end learning can be understood as: when dealing with a complex task, we do not break it down into subtasks. Instead, we treat the entire process as one giant black box. We only care about the input-output pairs and adjust this black box based on the output performance.

# Introduction: Multi-Layer Perceptron (MLP)

# This section draws heavily from the videos by [3Blue1Brown](https://space.bilibili.com/88461692)!

![](https://www.waytoagi.com/api/kb-media/RS8YbgtMDoe2V2xjPKAcPJwanA5)

The image is from a video by [3Blue1Brown](https://space.bilibili.com/88461692). Yep, this is a very basic multi-layer perceptron with two hidden layers!

## Neural Networks Overview: Starting with the MNIST Handwriting Dataset!

### The Semantic Gap: Why Is It So Hard for Machines to Develop Intelligence?

Below are several handwritten digits with very low resolution. The human brain can easily recognize them as 3, 7, and 6. However, getting a computer to recognize handwritten digits and characters has long been a major challenge. <Remember the OCR examples from your middle and high school textbooks?>

| ![](https://www.waytoagi.com/api/kb-media/LHMMb8SEWoKSFjx2CskcA9nPnlg) | ![](https://www.waytoagi.com/api/kb-media/FDOebDUYnoKSIKxtgp1cI31Qnkd) |
| --- | --- |

What’s even more bizarre is that the two “3”s in the image above look drastically different when projected onto the human retina, yet the human brain can still recognize that both are the number 3.

![](https://www.waytoagi.com/api/kb-media/DqMobuz01osDIexzmJlc6DxAnpe)

Image source: [3Blue1Brown](https://space.bilibili.com/88461692). Is it really that hard for a machine to recognize a handwritten digit from 0 to 9?

Although the human eye can effortlessly read handwritten numbers, if we take any randomly written single digit and ask a computer to determine which number from 0 to 9 it is, the task suddenly becomes extremely difficult. Humans can easily understand the content in images through visual perception (a handwritten 3, traffic lights, pedestrians, and cars in a road scene), including objects, scenes, and semantic information. We can also extract high-level semantic features such as an object’s shape, color, texture, and spatial relationships. In contrast, when computers process images, they typically only see low-level visual features such as pixel values, color histograms, and edges, and lack the ability to understand high-level semantic information in images. **We call this human-machine difference the “Semantic Gap.”**

### Features of the MNIST Handwriting Dataset: Representing an Image as a 784-Dimensional Vector!

Hey, remember the definition of a **feature** we mentioned in section 1.4.1.2? Now it’s time to think about this question in practice!

For a black-and-white handwritten digit, what should we use as its features to feed into a machine for learning? The answer is: the grayscale values of the 28×28 = 784 pixels that make up the image! For each pixel, we assign a value between 0 and 1. **The darker a pixel is, the closer its value is to 0; the whiter it is, the closer it is to 1. So…**

**Warning: Trypophobia trigger ahead!**

![](https://www.waytoagi.com/api/kb-media/UOBPbEKVRoCwMtxxqq3caT3MnYo)

Image source: Video by [3Blue1Brown](https://space.bilibili.com/88461692). In reality, many things—whether images or audio—can essentially be broken down into a large number of small components.

When we use machine learning to solve real-world tasks, we encounter a wide variety of data formats such as audio, images, and text. The way features are constructed differs significantly across data types. For image data, we can naturally represent it as a continuous vector. In the case of this handwritten digit example, we naturally express the image as a 784-dimensional vector where each element is a real number between 0 and 1, simply by following the pixel order!

**In short, we have represented this image as a 784-dimensional vector with each element between 0 and 1. Next, we will feed this vector into the first layer of a neural network, which will correspondingly have 784 neurons! But what exactly is a neuron?**

### What Is a Neuron?

#### The Neuron in Machine Learning Is an Imitation of Biological Neurons in the Human Brain

**Neurons in the Brain (also known as nerve cells) can produce cognition because they form highly structured and dynamic neural networks through complex connections and interactions. These networks are capable of processing and integrating information, giving rise to sophisticated cognitive functions.**

**Neurons and neural networks are, in essence, an imitation of the structure of the human brain.** In the human brain, neurons (or nerve cells) are the fundamental building blocks of the brain, spinal cord, and peripheral nervous system. A neuron receives neural signals through its dendrites, processes and integrates them in the cell body, and then transmits the signals via its axon to other neurons or effectors. This process enables information transmission and processing within the nervous system, ultimately forming complex neural networks.

#### A neuron is the basic building block of an artificial neural network. At its core, it is a combination of functions that includes weighted summation of inputs and an activation function.

- A **neuron** (also called an **artificial neuron**) is a mathematical model designed to simulate the computational unit of a biological neuron. Neurons serve as the fundamental units for constructing **artificial neural networks (ANNs)**. In the handwritten digit example, we can first think of a neuron as a container holding a number between 0 and 1.

- In machine learning, a neuron is typically represented as a function that receives input data, processes it, and produces an output.

- **A neuron receives multiple input values (usually represented as a vector), performs a weighted sum on them, and then applies a non-linear transformation through an **activation function** to generate its output.**

![](https://www.waytoagi.com/api/kb-media/EdzCbqxfUo5HmRxehVoc0fsbnTd)

**Q: What is a weighted sum?**

**A:** Looking at the diagram above, the orange circle highlights neuron **a9**, which is connected to eight neurons (**a1~a8**) from the previous layer. The numbers stored in **a1~a8** are all fed into **a9**. For each value from **a1~a8**, neuron **a9** assigns a corresponding weight **w1~w8**. The weighted sum for neuron **a9** is therefore:

$$
\sum_{n=1}^{8} w_n a_n
$$

This is called the neuron’s **weighted input** (or **pre-activation value**).

**OK, now let’s look back at this neural network. Every line in the diagram represents a weight!**

**From this perspective, each neuron is connected to all neurons in the previous layer, and the magnitude of the weights describes the strength of those connections!!**

**Q: What is an activation function?**

**A:** An activation function is typically applied to a neuron’s weighted input (pre-activation value) and produces a non-linear output. This output represents the neuron’s activation state, which is then passed to the next layer or used as the final output of the output layer.

Common non-linear activation functions include:

1. **Sigmoid function**: Maps the input to the range **[0, 1]**. Often used for binary classification or as the activation function for the output layer.

2. **Tanh function**: Maps the input to the range **[-1, 1]**. Also commonly used for binary classification or as an output layer activation.

3. **ReLU function (Rectified Linear Unit)**: Maps all negative inputs to 0 while preserving positive inputs. Frequently used as the activation function for hidden layers.

4. **Softmax function**: Maps the input into a probability distribution (all output values are positive and sum to 1). Commonly used in the output layer for multi-class classification problems.

In our handwritten digit example, we can start with the Sigmoid function. What happens inside neuron **a9** can be expressed as:

$$
a_9 = \sigma\left(\sum_{n=1}^{8} w_n a_n - b_9\right)
$$

where $\sigma(\cdot)$ denotes the Sigmoid operation. The extra term $b$ here is called the **bias**. We introduce bias because we want the weighted sum to be sufficiently large before a neuron becomes activated.

**So, in the neural network shown above, each of the 16 neurons (except those in the first layer) has its own bias!**

**Q: Why do we need non-linear transformations?**

**A:** Activation functions introduce non-linearity, allowing neural networks to model complex non-linear relationships effectively. If a neural network used only linear activation functions, the entire network would simply be a composition of linear operations and would be incapable of handling non-linear data or learning non-linear mappings.

The output of one neuron can serve as input to subsequent neurons, thereby forming the hierarchical structure of a neural network. By connecting a large number of neurons and optimizing the connection weights through training, artificial neural networks can learn from massive amounts of data and make predictions. They are widely used in machine learning and deep learning tasks such as image recognition, speech recognition, and natural language processing.

### Structure of a Neural Network

![](https://www.waytoagi.com/api/kb-media/YbRIbex6GoWlPUxnrEycJSa2nod)

#### Input Layer and Output Layer: Very intuitive!

- As mentioned in section 2.1.2, we represent a handwritten digit as a 784-dimensional vector. By assigning one neuron to each element of this vector, the input layer ends up with **784 neurons**. The input layer is responsible for receiving the input data.

- Because we need to output a digit from 0 to 9, the output layer contains 10 neurons. The output layer is responsible for producing the final output of the network. In the neural network described above, each neuron corresponding to digits 0–9 will produce a value. We can simply select the neuron with the largest value and output its corresponding digit.

#### But what exactly is a hidden layer?

In an Artificial Neural Network (ANN), **the hidden layer (Hidden Layer) is one or more layers of neurons located between the input layer and the output layer.** As the intermediate layer in a neural network, the hidden layer is responsible for extracting and transforming features from the input data, thereby enabling complex nonlinear mappings.

- We made a very straightforward design choice: between the input layer and the output layer, we added **two hidden layers (Hidden Layers)**. Each hidden layer contains 16 neurons. We then connected every neuron in each layer to all the neurons in the previous layer, forming the mesh-like structure shown in the diagram. When every neuron in one layer is connected to every neuron in the adjacent layer, we call this a **“Fully Connected Layer”** (or dense layer). Later, we will gradually encounter convolutional layers, pooling layers, recurrent layers, embedding layers, and normalization layers. The fully connected layer is the first type of neural network layer we have come to know!

- **In the diagram, each line represents a weight. There are a total of 784×16 + 16×16 + 16×10 = 12,960 weight parameters!**

- **Excluding the input layer, there are 42 neurons in the diagram, so there are 42 bias parameters in total!**

- These 12,960 + 42 parameters are all randomly initialized at the beginning. Ultimately, they are automatically learned by the model during the training process, rather than being manually set by humans. **We refer to these parameters as “Model Parameters.”** In contrast to model parameters are “hyperparameters,” which we will discuss later!

#### What do we expect the hidden layers to do?

We hope the hidden layers can perform feature extraction and transformation on the input data, thereby achieving complex nonlinear mappings.

Looking at the image on the right, we might think that the reason humans can recognize the digits 9 and 8 is that 9 consists of a circle and a vertical line, while 8 consists of two circles. So, if we want a machine to recognize 9 and 8, can we also make the machine identify and extract these features?

**In an ideal scenario**, we hope the first hidden layer can detect basic shapes such as circles, horizontal lines, and vertical lines, while the second hidden layer can combine these shapes to determine which digit it is, and finally tell us the answer through the output layer.

![](https://www.waytoagi.com/api/kb-media/XuMjbbnY8oXm5CxUD18cMeQznkc)

![](https://www.waytoagi.com/api/kb-media/WHBhbjfdQou2ZsxxezHcieEunGg)

| For the handwritten “7” in the left image, we might want the machine to recognize one of the edges of the 7 (a horizontal stroke). Could it work like this: if the vector elements corresponding to the pixels in the green positions are all very close to 1, while the pixels above and below the green area are all very close to 0, then we can detect a horizontal stroke? In that case, we can assign positive weights to the vector elements corresponding to the pixels we want to be close to 1, and negative weights to the pixels above and below the green region. This way, if a real horizontal stroke is written, the resulting weighted sum \( a_{2i} = \sigma\left(\sum_{n=1}^{t} w_{1n} a_{1n} - b_i\right) \) will be maximized!  
(Of course, in reality, the features learned by neural networks are often completely incomprehensible to humans! Nevertheless, expecting the hidden layers to extract features is the correct approach!) |

The presence of hidden layers gives neural networks powerful expressive capability, allowing them to handle complex nonlinear relationships and automatically extract useful features from input data. Factors such as the number of neurons in the hidden layers, the choice of activation functions, and the design of the network architecture all significantly affect the performance and learning ability of a neural network. Therefore, when designing and training neural networks, the configuration of hidden layers usually requires experience and careful tuning.

#### The entire neural network is essentially a giant function with 13,002 tunable parameters!

Since every line represents a weight parameter, and every neuron that is not in the input layer has its own bias, even this very basic and simple neural network has 13,002 parameters that can be adjusted.

So, when we talk about how machines learn, what we are really discussing is: how can a computer set these 13,002 parameters so that it can correctly solve the problem — converting a 784-dimensional vector representing a handwritten digit into a 10-dimensional output vector, where the digit corresponding to the largest element in the output vector is the answer we want?

(Just imagining manually adjusting these 13,002 parameters over and over again is already terrifying!)

OK, now let’s summarize:

- In the handwritten digit recognition example, each neuron is a nonlinear activation function. Its input is either the input vector or the weighted sum of the values (between 0 and 1) from all neurons in the previous layer. After applying a bias adjustment to this weighted sum, it is passed to the activation function \(\sigma\), which produces an output between 0 and 1.

- The entire neural network consists of 784 + 16 + 16 + 10 = 826 neurons and contains a total of 13,002 model parameters. The function takes a 784-dimensional vector as input and outputs a 10-dimensional vector. # This function is extremely complex, but in the end, it is still just a function! Most of the time, we can simply treat it as a black box that can automatically approximate the function we want.

#### Concisely Representing Weights Between Layers Using Linear Algebra: The Weight Matrix

- In the formulas below, the symbol **a** represents a neuron; the superscript indicates the layer the neuron belongs to; the subscript indicates which neuron it is within that layer. Here we use superscript 0 to represent the 784 parameters of the **input layer** \( a^0_{0-784} \), and superscript 1 to represent the 16 neurons of the first hidden layer \( a^1_{0-15} \).

- **w** represents the weight connecting any two neurons. It has two subscripts: the first subscript indexes the neuron in the second layer, and the second subscript indexes the neuron in the first layer. Thus we have:

$$
a^1_0 = \sigma\left(\sum_{i=1}^{784}(w_{0,i} \cdot a^0_i) + b_0\right)
$$

$$
a^1_1 = \sigma\left(\sum_{i=1}^{784}(w_{1,i} \cdot a^0_i) + b_1\right)
$$

……

$$
a^1_{15} = \sigma\left(\sum_{i=1}^{784}(w_{15,i} \cdot a^0_i) + b_{15}\right)
$$

If you have studied linear algebra, you will recognize that expressions like these (ignoring the outer \(\sigma()\) and bias \(b\) for now) can be represented as the product of a column vector:

$$
\begin{bmatrix} a^0_0, a^0_1, a^0_2, a^0_3, \dots, a^0_{783} \end{bmatrix}^T
$$

and a 16×784 matrix:

$$
\begin{bmatrix}
w_{0,0} & w_{0,1} & \dots & w_{0,783} \\
w_{1,0} & w_{1,1} & \dots & w_{1,783} \\
w_{2,0} & w_{2,1} & \dots & w_{2,783} \\
\vdots & \vdots & \ddots & \vdots \\
w_{15,0} & w_{15,1} & \dots & w_{15,783}
\end{bmatrix}
$$

The general solution is shown in the figures below:

![](https://www.waytoagi.com/api/kb-media/Buknbm6YmoAn3uxwzOmcoxFLnUh)
![](https://www.waytoagi.com/api/kb-media/B0TkbhJ0eooNBHxSLWZcVJSKn3g)

Adding back the bias vector **b** and the activation function \(\sigma()\), we obtain the following expression:

![](https://www.waytoagi.com/api/kb-media/YdBQbywjaoimLKx8KiWcFtM2nud)

Finally, we use a capital **W** to denote the weight matrix formed by all the \(w\) values, use lowercase \(a^0\) and \(b\) to represent the two column vectors respectively, and use \(a^1\) to represent the column vector of neuron values in the new layer. This gives us the compact form:

$$
a^1 = \sigma(Wa^0 + b)
$$

Whenever you see a capital **W** in the future, remember: it is simply a weight matrix, just like the one shown here—nothing special!

We have now expressed the relationship between two layers of the model. So how should we represent the entire model? We know that the full model contains multiple parameters: three weight matrices **W** and several bias vectors. We often collect all the parameters into a single \(\theta\), and express the model as \(f(x;\theta)\).

The **model** \(f(x;\theta)\) is one of the three fundamental elements of machine learning (model, learning criterion, and optimization algorithm)!

## Neural Network Training

### Forward Propagation

After introducing the general structure of a neural network, we already have a basic understanding of what forward propagation is! An image is flattened into a 784-dimensional vector and fed into the 784 neurons of the input layer. The first hidden layer then uses its 784×16 weights and 16 biases to produce 16 new outputs, which are passed to the next hidden layer. The next hidden layer continues the process using 16×16 weights and 16 biases to output 16 scalars to the output layer. Finally, the output layer uses its 10×16 weights and 10 biases to produce 10 numbers.

In neural network design, we typically want the output layer to produce a probability distribution — where each value is positive and they sum to 1 (this is exactly what a **Softmax** layer does!). The content corresponding to the neuron with the largest value (in the example above, a digit) becomes our final prediction. This is **forward propagation**!

**Forward Propagation** is the process of passing information through a neural network. It is the first step in neural network training. During forward propagation, input data is computed layer by layer (input layer → hidden layers → output layer) according to predetermined weights and biases, ultimately producing the neural network’s prediction.

### Gradient Descent

We now understand how the model generates outputs from inputs. However, the real machine learning challenge is figuring out how to let the machine automatically discover the optimal values for all 13,002 parameters — that is, how to make it *learn*.

#### Loss Function

First, we need a way to evaluate how bad the model’s performance is.

**Loss Function** (also known as objective function, cost function, or target loss function) is a function used in supervised learning to measure the difference between the model’s predicted values and the true labels.

A loss function is typically defined as a scalar value that quantifies the error or loss between the model’s predictions and the ground truth. A common mathematical representation is:

$$
\mathcal{L}(y, f(x;\theta))
$$

<Whenever you see the symbol $\mathcal{L}$, it refers to a loss function!>

There are many types of loss functions. Here are two common ones:

- **Quadratic Loss Function** (also known as Mean Squared Error): Half the squared difference between the predicted and true values. This function is not suitable for classification problems, but works well for regression tasks where the output is a continuous real number. We won’t encounter it too often in this course (though we will see it later in reinforcement learning’s TD algorithms!).

$$
\mathcal{L}(y, f(x;\theta)) = \frac{1}{2}(y - f(x;\theta))^2
$$

- **Cross-Entropy Loss Function**:

Cross-entropy loss is a mathematical function used to measure the difference between two probability distributions. It is widely used in classification tasks, especially as the loss function in neural networks. (Almost all language models we will discuss later use cross-entropy loss!)

Mathematically, if we consider the output vector of model $f(x;\theta)$ as a probability distribution, we define $f_c(x;\theta)$ as the $c$-th dimension of that output. Ideally, the correct output should be a **one-hot vector** — all elements are 0 except the one corresponding to the correct label, which is 1.

**The cross-entropy loss is defined as**:

$$
\mathcal{L}(y, f(x;\theta)) = -\log f_y(x;\theta)
$$

**In language models, we often predict the next word based on previous context. The neural network’s final output is a probability distribution over all words in the vocabulary.** In this case, cross-entropy loss helps us measure how different the model’s predicted distribution is from the true desired distribution.

However, this might be a bit early to dive into. Let’s first focus on the simplest classification problem.

We use the model to determine what digit (0–9) a handwritten image represents. Suppose the image is a handwritten “7”. We want the model to output a vector like this:

$$
y = [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]
$$

<Assuming the label is discrete with $C$ possible classes, we can represent the label using a $C$-dimensional one-hot vector. Here $C=10$. If the correct label is $K$, then only the $K$-th element (in this case, the 8th position for digit 7) is 1, and all others are 0.>

But the model might actually output:

$$
f(x;\theta) = [0.1, 0.2, 0, 0.1, 0, 0.3, 0, 0.1, 0, 0.2]
$$

Then the cross-entropy loss becomes:

$$
\mathcal{L}(y, f(x;\theta)) = -\log(0.1)
$$

<Surprisingly simple, right? It’s just the negative log of the value in the dimension that should have been 1.>

The more accurate the prediction, the smaller the loss.

**What exactly is the input to the loss function? Think about this carefully!**

- In the MNIST dataset, the loss function takes 13,002 parameters as input — that is, the model parameters mentioned earlier.

- The output of the loss function is a single real number.

- The value of the loss function depends on the model’s overall performance on the training data.

#### Gradient Descent

Once we have defined the training set (the MNIST dataset, containing 60,000 training images and 10,000 test images), chosen the model \(f(x;\theta)\), and defined the loss function \(\mathcal{L}(y,f(x;\theta)) = -\log f_y(x;\theta)\), what we need to do is minimize this loss function.

So how do we minimize it? Suppose the loss is a simple function such as \(y = f(w_1)\). Anyone who has studied calculus will immediately recognize that this is essentially a problem of finding the minimum value — we just need to find where the derivative is zero. That point is \(w_{\text{min}}\) shown on the left side of the figure below.

![](https://www.waytoagi.com/api/kb-media/VZ0obMTSXott10xfx5Zc7s9pnb9)
![](https://www.waytoagi.com/api/kb-media/Czihb4AvWo24DwxgtCxcncvInqc)

**However, as shown in the right figure, when a function becomes even slightly more complex, finding the true minimum is no longer so straightforward. Moreover, our loss function has 13,002 parameters. The mere thought of finding the minimum of such a function is terrifying 😨!**

Since directly solving for the minimum is not feasible, what should we do? A very simple approach is to note that the model parameters (in this case, just \(w_1\)) are randomly initialized. This means they land at some random point on the curve. Referring to the point \(w\) in the right figure, we only need to figure out whether moving left or right will make the function value decrease.

We calculate the slope at that point. If the slope is positive, we move left; if it is negative, we move right. We also make the step size proportional to the slope: a large slope means we take bigger steps to descend quickly; a small slope means we take smaller steps to avoid overshooting.

By repeating this process at every point, the parameter will eventually fall into a low region.

![](https://www.waytoagi.com/api/kb-media/F1BZbAHxrocoZcxa7q3csJD2nKh)

Naturally, following the approach on the left, we may converge to a local minimum rather than the global minimum 😳. This issue also arises frequently during neural network training.

![](https://www.waytoagi.com/api/kb-media/Na2zbJtCwowFDXxBsmpclbDqnRh)

OK, now let’s imagine a slightly more complex binary function: \(z = f(x,y)\). The cost function now becomes a surface. Imagine a small ball landing at a random initial parameter position, corresponding to a certain height on the cost surface. We want to use a similar method to let the ball roll along the surface until it settles into a concave lowest point.

Now we are no longer just deciding whether to go left or right. In this three-dimensional space, assume \(i\) and \(j\) are the unit vectors along the \(x\) and \(y\) axes. The ball is currently at the position where \(z_0 = f(w_1, w_2)\). We want to find a vector \((a\mathbf{i}, b\mathbf{j})\) such that moving in that direction causes the function value to increase most rapidly. This vector is the gradient of \(z = f(x,y)\) at the coordinate \((w_1, w_2, z_0)\).

Therefore, we simply move in the opposite direction of the gradient. The larger the gradient, the bigger the step we take. After arriving at a new position, we recalculate the gradient and again move in the opposite direction. By repeating this process, we will eventually reach a concave low point.

**Hey ChatGPT, what is the gradient of a multivariate function?**

**ChatGPT**: The gradient of a multivariate function is a vector that indicates the direction in which the function changes most rapidly at a given point, along with the rate of that change. For a function with \(n\) independent variables, the gradient is an \(n\)-dimensional vector, where each component is the partial derivative with respect to one of the variables.

- Consider a function \(f(x_1, x_2, \ldots, x_n)\) with \(n\) variables.

- The gradient of this function at a point \((x_1^0, x_2^0, \ldots, x_n^0)\) is denoted as \(\nabla f(x_1^0, x_2^0, \ldots, x_n^0)\), or:

- \(\frac{\partial f}{\partial x_1}(x_1^0, x_2^0, \ldots, x_n^0)\mathbf{i} + \frac{\partial f}{\partial x_2}(x_1^0, x_2^0, \ldots, x_n^0)\mathbf{j} + \ldots + \frac{\partial f}{\partial x_n}(x_1^0, x_2^0, \ldots, x_n^0)\mathbf{k}\)

- Here, \(\frac{\partial f}{\partial x_i}(x_1^0, x_2^0, \ldots, x_n^0)\) represents the value of the partial derivative of function \(f\) with respect to \(x_i\) evaluated at the point \((x_1^0, x_2^0, \ldots, x_n^0)\). The vectors \(\mathbf{i}\), \(\mathbf{j}\), and \(\mathbf{k}\) denote the unit vectors along the corresponding coordinate axes in \(n\)-dimensional space.

- If we move all parameters of a multivariate function along the positive direction of the gradient, we call this **Gradient Ascent**. In this case, the function value increases the fastest. In reinforcement learning, when we perform policy optimization to maximize the state value function, we use gradient ascent!

- If we move all parameters of a multivariate function along the negative direction of the gradient, we call this **Gradient Descent**. In this case, the function value decreases the fastest. In most scenarios, we perform gradient descent to minimize the loss!

**Repeatedly performing gradient descent is the standard method for finding a local minimum of a multivariate function!**

The examples above for both univariate and bivariate functions illustrate the process of gradient descent. In both cases, at each point we compute the gradient, then move a distance proportional to the gradient’s magnitude in the opposite direction of the gradient to reach a new point. By repeating this process, we eventually converge to a local minimum of the function, at which point the gradient converges to zero. We may not necessarily find the global minimum of the function — in that case, we say we have converged to a local optimum rather than the global optimum. Nevertheless, finding a local minimum is already a remarkable achievement!

**The negative gradient vector essentially tells us how to adjust each parameter so that the neural network’s loss decreases as quickly as possible.**

Returning to the MNIST example, even though the loss function in that case has 13,002 parameters, the same principle of gradient descent still applies!

Imagine treating these 13,002 parameters as a column vector. Its negative gradient is simply another 13,002-dimensional column vector. This negative gradient tells us, within this 13,002-dimensional space, how to adjust each parameter to make the loss decrease the fastest.

![](https://www.waytoagi.com/api/kb-media/BMlabPxy5oGy4wx52kPcC5qOnxb)
![](https://www.waytoagi.com/api/kb-media/QIBCb3spcoF0NXxvw7CckdqNnge)

Within the negative gradient vector, the larger a particular element is, the higher the “return on investment” of adjusting the corresponding parameter. It reflects the importance of that parameter.

We often denote the collection of all model parameters as \(\theta\). Therefore, the gradient descent update can be written as:

\[
\theta_{t+1}=\theta_t-\alpha\frac{1}{N}\sum_{n=1}^N\frac{\partial\mathcal L(y^n,f(x^n;\theta))}{\partial\theta}
\]

where \(\theta_t\) is the parameter value at the \(t\)-th iteration, \(\alpha\) is the learning rate, and \(N\) is the number of training samples fed into the model in each iteration to compute the average loss. In traditional machine learning algorithms, all samples in the entire training set are used to compute the gradient of the model parameters, so \(N\) equals the size of the training set.

**After all this explanation, is there a simpler takeaway?**

In short, all we need to know for now is that the gradient is a tool that tells us, for a multivariate function (even one with thousands or tens of thousands of parameters), in which direction the function decreases the fastest. This guides us in tuning the model’s parameters. The larger an element in the gradient, the more we should move in the direction corresponding to that element (by a proportional distance). By repeating this process, we can find a local minimum of the multivariate function.

(The detailed content of sections 2.2.3, 2.2.4, and 2.3 has been collapsed. Feel free to expand them if you’re interested~)

### Model Update Frequency and Hyperparameters

The mathematical expression for the gradient descent process shown earlier is:

\[
\theta_{t+1}=\theta_t-\alpha\frac{1}{N}\sum_{n=1}^N\frac{\partial\mathcal L(y^n,f(x^n;\theta))}{\partial\theta}
\]

Some elements here may still feel unfamiliar, including \(N\) and \(\alpha\). Clearly, these are values we set manually and do not belong to the 13,002 model parameters that the model learns itself. We call such parameters **hyperparameters**.

**Hyperparameters** are parameters that must be manually configured in a machine learning algorithm. They control the learning process and performance of the model. Unlike model parameters, hyperparameter values cannot be learned automatically from the training data and must be set by humans before training begins.

The choice of hyperparameters significantly affects both model performance and training speed, so selecting appropriate hyperparameters is crucial for achieving good results.

#### Hyperparameter: Batch Size

- **Batch Size** refers to the number of samples used in a single parameter update of the model.

- In traditional machine learning algorithms, all samples in the entire training set are used to compute the gradient of the model parameters, and the parameters are updated based on this gradient. Therefore, the value of N equals the size of the training set. In this case, Batch Size usually refers to the total number of samples in the entire training set and is also known as "Full batch" or "Batch gradient descent."

- Using the entire training set for gradient computation and parameter updates ensures that each update is based on global gradient information, allowing the model parameters to move more accurately in the direction of gradient descent. However, this approach can suffer from slow computation when dealing with large-scale datasets, as it requires calculating the gradient over the whole training set. As a result, traditional gradient descent algorithms may become inefficient as dataset sizes grow. In most modern model training processes, the training data is typically divided into multiple small batches (Batches) for processing, with each batch containing a certain number of samples.

- Referring to the formula above, suppose we use N samples for each training step. In that case, the Batch Size is N. The Loss Function is then the average value of these N cross-entropy functions. We perform backpropagation based on this loss value to update the model parameters.

- The choice of batch size directly affects the model’s training speed and memory usage. A larger batch size can accelerate the training process by leveraging hardware parallelism, but it also consumes more memory. A smaller batch size reduces memory usage but may lead to lower computational efficiency. The appropriate batch size usually needs to be selected based on the specific task and available hardware resources, with common values ranging from tens to several thousand.

#### Hyperparameter: Learning Rate (Learning Rate)

**Learning Rate**: Controls the step size by which the model updates its weights in each training iteration. Specifically, the learning rate determines how much the weights change during each update in gradient descent optimization algorithms.

![](https://www.waytoagi.com/api/kb-media/RaclbDTC3oyV1TxZoBGcMyu4nBd)

`<This image was used earlier. On the left is the parameter vector, and on the right is the gradient vector. We adjust the parameters on the left by a multiple of the gradient. This multiple is the learning rate. It can be constant, decay over time, or be adjusted automatically.>`

#### Hyperparameter: Number of Epochs (Epochs)

The number of epochs represents how many times the model trains on the entire training dataset.

#Note that the number of epochs and Batch Size are not inherently in a trade-off relationship. Even with Full Batch training, the model can still be trained for a very large number of epochs.

- Too few epochs may lead to underfitting, while too many epochs may cause overfitting.

- **Underfitting** refers to the phenomenon where the model performs poorly on the training data and fails to capture the underlying features and patterns of the data.

- **Overfitting** occurs when the model performs very well on the training data but performs poorly on unseen test data. In simple terms, overfitting means the model has fitted the training data excessively, resulting in degraded generalization performance on new data. Overfitting typically happens when the model is overly complex or when there is insufficient training data. When a model is too complex, it may perform exceptionally well on the training data but fail to generalize to new data because it has essentially “memorized” the training samples.

**Common methods to address overfitting include the following:**

1. **Data Augmentation**: Expand the training data by applying transformations such as rotation, scaling, flipping, etc., thereby increasing data diversity and reducing the model’s tendency to overfit to the original training set.

2. **Early Stopping**: Monitor the model’s performance on a validation set during training. When performance begins to degrade, stop training early to prevent overfitting.

3. **Regularization**: Introduce a regularization term (such as L1 or L2 regularization) into the model’s loss function to constrain the magnitude of the model parameters, thereby reducing model complexity and preventing overfitting.

#### Hyperparameter: Regularization

As mentioned above, regularization is a technique that constrains the values of model parameters, reduces model complexity, and thereby helps prevent the model from overfitting to the training data.

**In neural networks, common regularization methods include the following:**

1. **L1 Regularization (also known as Lasso Regularization)**: Adds the L1 norm of the model weights as a penalty term to the objective function, encouraging the weights to become sparse (i.e., some weights are driven to exactly zero). L1 regularization can be used to control the sparsity of parameters in a neural network, thereby reducing model complexity. #Simply put, L1 turns the weights of certain parameters to 0.

2. **L2 Regularization (also known as Ridge Regularization)**: Adds the L2 norm of the model weights as a penalty term to the objective function, encouraging the weights to take smaller values and thereby reducing model complexity. L2 regularization helps control the magnitude of parameters in a neural network and prevents overfitting. #Simply put, L2 suppresses excessively large weight values in the model.

3. **Dropout Regularization**: Dropout is a technique that randomly discards a portion of neuron outputs during training, thereby reducing the complexity of the neural network and preventing overfitting. Dropout randomly sets the outputs of certain neurons to zero, forcing the network not to rely on any specific neurons during training and thus improving its generalization performance. In simple terms, Dropout means “throwing away” some neurons.

#### Hyperparameters: Activation Functions

As mentioned earlier, activation functions are used to introduce non-linear transformations. Common activation functions include ReLU, sigmoid, tanh, etc. Choosing an appropriate activation function is crucial to the model’s performance.

### Backpropagation (BP)

The previous section introduced the concept of gradient descent. However, how to actually compute those gradients became the core engineering challenge in implementing neural network algorithms. This is known as the **backpropagation algorithm**.

#### Introduction to Backpropagation

**Backpropagation (Backpropagation)** is used to calculate the gradients of the weights and biases in each layer of a neural network, enabling the updating of model parameters. It is the reverse process of forward propagation. By computing the gradient of the loss function with respect to the network’s output, the error is propagated backward layer by layer—from the output layer to the input layer—calculating the gradient for each layer and using it to update the model parameters.

The fundamental idea of backpropagation is to compute the gradient of the loss function with respect to the model parameters using the **chain rule**. The specific steps are as follows:

1. Initialize gradients: Set the gradient of the final layer (output layer) to the gradient of the loss function with respect to the output, typically using the derivative of the loss function.

2. Backward propagation: Starting from the output layer, compute the gradient of the loss function with respect to each layer’s input using the chain rule. For each layer, calculate the gradient of its input based on the current layer’s output and weights, then pass it to the previous layer.

3. Compute parameter gradients: Based on the input gradient of each layer and the layer’s own input, calculate the gradients of the loss function with respect to that layer’s weights and biases. This is typically done by multiplying the input gradient with the transpose of the layer’s input (for weights) or by direct summation (for biases).

4. Update parameters: Use the computed parameter gradients to update the model’s weights and biases via gradient descent, usually controlled by a learning rate that determines the step size.

5. Repeat steps 2 to 4: Continue executing the above steps until a predetermined stopping condition is met, such as reaching the maximum number of iterations or the loss function converging to a sufficiently small value.

- In practice, we only need to understand that **backpropagation is the reverse of forward propagation**. By calculating the gradient of the loss function with respect to the neural network’s output and propagating it layer by layer, we can obtain the gradient of the loss function for the entire network. We can then adjust the parameters using gradient descent.

- Additionally, we should know that during backpropagation, gradient computation in deep networks involves successive multiplication operations.

- The specific mathematical formulation of the algorithm is relatively complex. Please refer to the recommended learning materials that follow for more details.

#### Gradient Vanishing and Gradient Explosion Problems

**What is Gradient Vanishing?**

**Gradient Vanishing** refers to a phenomenon in deep neural networks where the gradients computed by the backpropagation algorithm become extremely small (or even approach zero) in the deeper layers. As a result, the weights in these layers update very slowly or stop updating altogether, preventing those layers from being effectively trained.

**Why does Gradient Vanishing occur?**

- Gradient vanishing typically occurs in deep neural networks, especially when using saturation activation functions such as Sigmoid or Tanh. These functions tend to saturate when the input is very large or very small, causing the gradients to become extremely small. (For example, when the input approaches 1, the output of the Sigmoid function approaches 1 and its derivative approaches 0. Consequently, the product of gradients during backpropagation tends toward zero.)

- In deep neural networks, gradients are propagated backward through the chain rule. The gradient of each layer must be multiplied by the gradient from the subsequent layer before being passed to the previous layer, and so on, all the way back to the input layer. When the network has many layers, this results in multiple consecutive multiplication operations. This can cause the gradient values to shrink exponentially, eventually approaching zero—i.e., gradient vanishing.

**What about Gradient Explosion?**

- Naturally, because the process involves multiple successive multiplications, each multiplication can also amplify the gradient. If the values grow excessively large, it leads to **gradient explosion**.

- Gradient explosion causes excessively large updates to the network’s weight parameters, making model training unstable.

#### Mitigating Gradient Problems: Normalization

**What is Normalization?**

**Normalization** is a technique that applies linear or non-linear scaling to the input data or the outputs of network layers, mapping them to a specific range or distribution. This improves the stability and performance of network training. A common approach is to transform the data so that its mean becomes 0 and its variance becomes 1.

**How does Normalization help alleviate gradient problems?**

Normalization processes the input data or the outputs of network layers during training, adjusting the input values to activation functions. This prevents them from becoming too large or too small, thereby avoiding gradient vanishing and gradient explosion issues, and ultimately improving the network’s learning effectiveness and generalization performance.

**Common normalization methods in neural networks include**:

1. **Batch Normalization (BN)**: Batch Normalization is a technique that normalizes the inputs of a network layer during training. By normalizing the input data within each mini-batch so that its mean is 0 and variance is 1, it accelerates the network’s convergence, reduces sensitivity to initialization and learning rate, and also provides a certain regularization effect.

2. **Layer Normalization**: Layer Normalization is a method that normalizes the outputs of a network layer. Unlike batch normalization, it normalizes the outputs across all features for each individual sample within a layer, rather than across a batch. It serves as a useful alternative when dealing with sequential data or other scenarios where batch processing is not suitable.

3. **Group Normalization**: Group Normalization lies between batch normalization and layer normalization. It divides the input channels into multiple groups and performs normalization within each group. This reduces correlation between groups and improves the network’s learning capability.

# In short, you can understand normalization as transforming a set of data so that its mean becomes 0 and its variance becomes 1.


## Universal Approximation Theorem: MLPs Can Approximate Any Function

- **Universal Approximation Theorem**: An MLP with a single hidden layer can approximate any function to arbitrary accuracy. The larger the number of parameters in the MLP, the higher the degree of approximation.

- The conditions of the Universal Approximation Theorem assume that the neural network has a sufficient number of hidden nodes, enough nonlinear activation functions, and can be trained with a sufficient number of training samples. In practice, although neural networks possess this universal approximation capability, many other factors must be considered during actual training, such as overfitting, training speed, and data quality.

# It is mathematically proven that MLPs can approximate any function to a certain precision, but the proof is quite complex. Even for researchers, it is not necessary to fully understand it, so we will not include the proof in this document. Readers with strong curiosity can refer to: [Personal Blog] Illustrated Explanation: Why Neural Networks Can Fit Any Function](https://bitjoy.net/2019/04/07/neural-networks-and-deep-learning%ef%bc%88%e5%9b%9b%ef%bc%89%e5%9b%be%e8%a7%a3%e7%a5%9e%e7%bb%8f%e7%bd%91%e7%bb%9c%e4%b8%ba%e4%bb%80%e4%b9%88%e8%83%bd%e6%8b%9f%e5%90%88%e4%bb%bb%e6%84%8f%e5%87%bd/)


## Recommended Learning Materials

### Recommended Video Materials for MLP

[Well-known Blogger: 3Blue1Brown](https://space.bilibili.com/88461692)

[【Official Bilingual】Neural Networks and Deep Learning – Structure of Neural Networks Part 1 ver 2.0 - Bilibili](https://www.bilibili.com/video/BV1bx411M7Zx/?spm_id_from=333.788.recommend_more_video.0)

[【Official Bilingual】Neural Networks and Deep Learning – Gradient Descent Part 2 ver 0.9 beta - Bilibili](https://www.bilibili.com/video/BV1Ux411j7ri/?spm_id_from=333.788.recommend_more_video.0)

[【Official Bilingual】Neural Networks and Deep Learning – Backpropagation Algorithm (Part 1 & 2) Part 3 ver 0.9 beta - Bilibili](https://www.bilibili.com/video/BV16x411V7Qg/?spm_id_from=333.788.recommend_more_video.-1)

### Recommended Text Materials for MLP

[Personal Blog] Neural Networks and Deep Learning](https://bitjoy.net/category/0%e5%92%8c1/neuralnetworksanddeeplearning-com/), by Beeder. The author discovered this blog through a Zhihu answer while learning about LSTM. Although the author does not know this person personally, the content in the blog is very inspiring, and the quality of the learning notes is exceptionally high.

## MLP Summary

### What Do Features Look Like to a Computer?

Before we present the final summary table, let’s first examine what kind of features neurons actually “see.”

At the very beginning, we hoped that the hidden layers could recognize basic patterns just like humans—such as horizontal lines, circles, and edges—and then combine them to form a digit. However, what a computer actually sees is shown in the image on the right.

Well… there’s simply no discernible pattern!

Naturally, if we feed the model a random image—say, a QR code—and ask it to recognize the digit, we might expect the machine to tell us “this is not a digit.” In reality, the model will confidently output an answer. It feels as though, within this 13,000-dimensional space that is unimaginable to us, the machine has found a rather good local minimum, sat down there, and can successfully classify most images—yet it possesses no genuine intelligence!

![](https://www.waytoagi.com/api/kb-media/AxWEbfduroYhYnxivFTcLliUnhh)

| **Model** | **Multilayer Perceptron (MLP)** |
| --- | --- |
| **Model Structure** | ![](https://www.waytoagi.com/api/kb-media/MkWhbkYcGoRbIQxHz5Sc6JODnre) |
| **Type & Architecture** | MLP is the most basic type of neural network and belongs to **Feedforward Neural Networks**. In a feedforward neural network, information flows from the Input Layer through multiple Hidden Layers to the Output Layer. The information can only move forward and does not form any cycles. Feedforward neural networks are also known as Memoryless Neural Networks because the network does not store any state from previous computations. |
| **Pros & Cons** | **Advantages**: Strong nonlinear modeling capability; supports end-to-end learning; allows parallel computation.<br>**Disadvantages**: Prone to getting stuck in local optima; prone to overfitting; the fully connected structure is excessively complex (imagine a high-resolution photo taken with an iPhone—12 million pixels. If a fully connected layer were still used, the number of parameters would explode). |
| **Tunable Hyperparameters** | Batch Size, learning rate, network architecture (number of layers, number of neurons, etc.), activation functions, optimization algorithms, and more. MLP has a very large number of tunable hyperparameters, making model tuning extremely complex. |


# Introduction: Convolutional Neural Network (CNN)

#If you are only interested in language models, feel free to skip this section!

## Convolutional Neural Networks Overview

### What Is Convolution?

If you search online for “what is convolution,” you may come across the one-dimensional continuous convolution of two continuous functions *f(x)* and *g(x)*, defined as:

h(x) = ∫<sup>+∞</sup><sub>-∞</sub> f(t)g(x−t)dt

However, not understanding the exact meaning of this formula has **no impact** on learning convolutional neural networks! This document will not explain in detail what convolution is or its mathematical implications. Curious readers can refer to this Zhihu page: [【Zhihu】How to Explain Convolution in Simple and Understandable Terms?](https://www.zhihu.com/question/22298352). The top few answers are quite good.

For our purposes, it is sufficient to know that **in machine learning, convolution is typically used to process data with local correlations, such as images, audio, and text.**

### Convolution in Image Processing

#### Why Do We Need Convolution?

- When we previously used the MNIST dataset to train an MLP for digit recognition, we were already performing image processing. However, there is a problem: **the fully connected layer structure is far too complex**. Even for the 28×28-pixel black-and-white handwritten digits in the earlier example, we ended up with 13,002 parameters to learn. Now imagine taking a random 12-megapixel color photo with an iPhone (color images cannot be represented by 0–1 grayscale; instead, the image must be split into three channels representing R, G, and B). If we still used an MLP structure in such cases, the model would become unimaginably complex!

- To solve this problem, **a very natural idea is to compress the input image and extract the most important features from different regions of the numerous pixels.**

#### Illustrated Explanation of the Convolution Process in CNNs

In image processing, convolution is typically performed by sliding a small window (**Sliding Window**), called a **convolution kernel** or **filter**, across the input image and performing point-wise calculations on the pixels. The convolution kernel contains a set of **weight parameters** corresponding to each position in the sliding window. It generates an output **feature map** by computing a weighted sum over local regions of the input image.

Referring to the figure below: we applied a 3×3 convolution kernel with a stride of 1 to a 5×5-pixel image, performing convolution on the original image and extracting a feature map. In the example below, the weights of the convolution kernel are:

\begin{bmatrix} 1&0&1\\ 0&1&0\\ 1&0&1 \end{bmatrix}

The resulting feature map is:

\begin{bmatrix} 4&3&4\\ 2&4&3\\ 2&3&4 \end{bmatrix}

![](https://www.waytoagi.com/api/kb-media/ZVRfbq4MAo1N2vxdMKEc0gUyneb)

> *Imagine if we used a 2×2 convolution kernel while keeping everything else the same; the final feature map would then be a 4×4 matrix!*

This local computation approach allows convolution to capture local features of the input image, such as edges, textures, and shapes.

#### Definition of Convolutional Neural Networks

Convolution operations are widely used in deep learning within **Convolutional Neural Networks (CNNs)**. A CNN is a type of neural network that includes convolutional layers and pooling layers. It is specifically designed for tasks such as image recognition, image generation, and image processing. In CNNs, convolution acts like a feature extractor: it pulls useful features from the input image, which are then further processed and classified by subsequent neural network layers.

**Convolutional Neural Network Architecture**

A typical CNN consists of two main parts:

(1) **Convolutional Base**, which is a stack of convolutional layers and pooling layers. The primary purpose of the convolutional base is to generate features from images.

(2) **Classifier**, typically composed of multiple fully connected layers. The main goal of the classifier is to categorize the image based on the detected features. A fully connected layer is one in which each neuron is connected to all activation neurons in the previous layer.

In a CNN, the input layer, convolutional layers, pooling layers, and fully connected layers work together: convolutional layers are responsible for feature extraction, pooling layers compress the features, and the final set of fully connected layers often form a classifier. (We will revisit this part later when discussing transfer learning.)

### Convolutional Layer

The **Convolutional Layer** is one of the core components of a CNN. It is primarily used to extract features from the input data. The convolutional layer filters the input data by applying convolution operations, using learned convolution kernels (also known as filters) to extract local features from the input.

1. **Convolution Operation**: This is the fundamental operation of a convolutional layer. It generates a feature map (also called convolution output or feature map) by performing element-wise multiplication between the convolution kernel and the input data, then summing up the results. Convolution can capture local information in the input data, such as edges, textures, and shapes.

2. **Activation Function**: After the convolution operation, an activation function is typically applied to introduce non-linearity into the generated feature maps. Common activation functions include ReLU (Rectified Linear Unit), sigmoid, and tanh. These functions enhance the network’s expressive power by adding non-linear characteristics.

3. **Padding**: Padding is a technique used in convolution that adds extra pixels or specific values around the input data to increase its dimensions. It prevents the input size from shrinking during convolution, helps preserve edge information, reduces drastic changes in feature map size, and improves the network’s ability to process the edges of input images.

4. **Stride**: Stride controls how many pixels the convolution kernel slides across the input data at each step. A larger stride reduces the size of the feature map and lowers computational complexity, but may cause loss of information and reduced resolution. A smaller stride retains more local information at the cost of increased computation.

### Pooling Layer

The **Pooling Layer** performs **downsampling** on feature maps. Pooling operations are usually applied after convolution. They help reduce the spatial dimensions of feature maps and decrease the number of parameters in the network, thereby lowering computational complexity.

#### Illustration of Pooling Layer:

As shown in the figure below, for a 20×20 feature map, we use a 10×10 pooling window with a stride of 10. After downsampling, we obtain a 2×2 matrix.

![](https://www.waytoagi.com/api/kb-media/NUrrbKtkloD8b7xTQqGczWM5nih)

#### Types of Pooling:

Pooling layers can use different types of operations, such as Max Pooling, Average Pooling, and Global Average Pooling. In practice, **Max Pooling** is most commonly used — the largest value within the pooling window is retained as the output.

#### Main Functions of the Pooling Layer:

1. **Downsampling**: The pooling layer reduces the size of feature maps by combining a group of neighboring pixel values into a single representative value. This decreases the model’s computational complexity and helps extract local features.

2. **Feature Selection**: By selecting the most representative value from a group of pixels (e.g., the maximum value in Max Pooling or the average in Average Pooling), the pooling layer reduces the dimensionality of the feature maps. This helps the network focus on the most important features and reduces the impact of noise on feature extraction.

3. **Translation Invariance**: By performing local aggregation on feature maps, the pooling layer gives the network a degree of invariance to small translations in the input image. This enables the network to learn more robust feature representations and improves the model’s generalization ability.

## Hyperparameters in Convolutional Neural Networks

### Kernel Size

The convolution kernel is the filter used in convolution operations to extract features from input data. The **kernel size** defines the size of the convolution window, typically a square or rectangle.

- Smaller kernels can capture fine-grained details;
- Larger kernels can capture features at a broader scale.

### Stride

Stride is the distance by which the convolution window slides across the input data during the convolution operation. A larger stride reduces the size of the feature map and speeds up computation, but it may lead to loss of information.

### Padding

**Padding** is an operation in convolutional neural networks that adds extra pixel values around the borders of the input feature map. This expands the dimensions of the input data so that the output feature map maintains the same or similar size as the original input.

Padding helps prevent the loss of edge pixel information during convolution. Without padding, the kernel can only operate on the interior of the input feature map, causing edge information to be underutilized. With padding, the kernel can perform convolution at the edges of the feature map, thereby preserving boundary information.

### Number of Kernels

Each convolutional layer in a network can contain multiple kernels to extract different types of features (this is conceptually similar to the multi-head attention mechanism in the Transformer architecture we will discuss later—each attention head extracts distinct features!). The number of kernels defines the number of filters in the convolutional layer and determines the number of output channels in the resulting feature map.

## Receptive Field

### What is a Receptive Field?

- The **receptive field** refers to the region in the input image that corresponds to a single pixel in the output feature map of a given layer in a convolutional neural network. The size of the receptive field determines the perceptual range of that layer — i.e., the scope of input information the network can “see” at that level.

- In CNNs, the receptive field of each layer is determined by the kernel size, stride, padding, and other hyperparameters of the preceding layers. By stacking multiple convolutional layers, the receptive field gradually expands, enabling the network to capture features at increasingly larger scales.

### Why is the Receptive Field Important?

The size of the receptive field has a significant impact on the performance and feature extraction capability of a convolutional neural network.

- A smaller receptive field is better at capturing fine details, making it suitable for detecting small objects or subtle textures in images;
- A larger receptive field can capture broader contextual features, making it suitable for recognizing large objects or global structures.

- Therefore, when designing convolutional neural networks, it is essential to carefully choose hyperparameters for different layers to achieve an appropriate receptive field size for the target task.

### How Do Convolutional Neural Networks Reduce the Number of Parameters Compared to Ordinary MLPs?

Three key operations in CNNs — **local receptive fields, weight sharing, and pooling layers** — effectively reduce the total number of parameters in the network and help alleviate overfitting.

## Recommended Learning Materials

**Beginner Level:** [【CSDN】Deep Learning — Introduction to Convolutional Neural Networks (CNN)](https://blog.csdn.net/johnny_love_1968/article/details/117636049?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168151922716800180626463%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=168151922716800180626463&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-4-117636049-null-null.142^v83^insert_down1,239^v2^insert_chatgpt&utm_term=%E5%8D%B7%E7%A7%AF%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C&spm=1018.2226.3001.4187)  
By Nanfang Chouchangke's Blog @CSDN

**From Beginner to Advanced:** [【CSDN】Ultra-detailed Introduction to Convolutional Neural Networks](https://blog.csdn.net/jiaoyangwm/article/details/80011656?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168151922716800180626463%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=168151922716800180626463&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-2-80011656-null-null.142^v83^insert_down1,239^v2^insert_chatgpt&utm_term=%E5%8D%B7%E7%A7%AF%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C&spm=1018.2226.3001.4187)  
By Daidai de Mao's Blog @CSDN


## CNN Summary

| **Model** | **Multilayer Perceptron (MLP)** | **Convolutional Neural Network (CNN)** |
| --- | --- | --- |
| **Model Structure** | ![](https://www.waytoagi.com/api/kb-media/B5mCb0syYoYYYBxSra6cyOasnEe) | ![](https://www.waytoagi.com/api/kb-media/PVQubEsNsoWMH9xpd4rcPa8PnZf) |
| **Type & Architecture** | Feedforward neural network, non-recurrent<br>Supervised learning, relies on labeled data<br>Every layer is fully connected | Feedforward neural network, non-recurrent<br>Typically supervised learning, relies on labeled data<br>Architecture includes input layer, convolutional layers, pooling layers, and fully connected layers. Convolutional layers extract features, while pooling layers compress features. |
| **Pros & Cons** | **Advantages:** Strong nonlinear modeling capability; supports end-to-end learning; highly parallelizable<br>**Disadvantages:** Prone to getting stuck in local optima; prone to overfitting; the fully connected structure is overly complex | **Advantages:** The convolutional layer uses local receptive field operations to effectively capture local features in the input data; parameters of the convolution kernels are shared across the entire input, significantly reducing the number of parameters to learn; highly parallelizable; the pooling layer performs downsampling, reducing the size of feature maps and lowering model complexity.<br>Convolutional neural networks are exceptionally well-suited for image recognition. Their high performance and ease of training are the two main reasons for the popularity of CNNs in recent years. |
| **Tunable Hyperparameters** | Batch Size, learning rate, number of iterations, activation functions, network architecture (number of layers, number of neurons, etc.), regularization, etc. | Batch Size, learning rate, number of iterations, activation functions, network architecture, regularization, convolution kernel size, number of convolution kernels, sliding window stride, padding, pooling layer type, pooling window size, and pooling stride |


# Beginner’s Guide: Recurrent Neural Networks (RNNs)

*The content here is kept relatively simple. Many sections, such as the working principles of LSTM, have been collapsed. Before reading Chapter 7, it is recommended to quickly skim this chapter first so you understand what an RNN is and what its main pain points are.*

*Most of the images are taken from Professor Hung-yi Lee’s online course slides at National Taiwan University. The textual explanations are adapted from the article [LSTM Explained to Everyone](https://zhuanlan.zhihu.com/p/32085405).*

## Native RNN Model

### Why Do We Need Recurrent Neural Networks

Many times, we want a model to be capable of processing time-series data.

For example, when translating the sentence “All the books by this well-known author are excellent”:

The books of the famous writer [are] all wonderful.

We know that when the model generates the word “writer”, the next word should be “are” rather than “is”. This depends on the earlier word “books” in the context. Traditional MLPs or CNNs cannot capture this kind of dependency, because they would output “the”, then “books”, then “of”. Each output leaves no memory behind, so when the model reaches the position where it needs to generate “are”, it has no information about the earlier word “books”.

### Structure of Recurrent Neural Networks

Once we understand the problem we want to solve, the solution becomes very simple: we need the model to have memory. One way is to make the model output not only the target word at each step, but also an intermediate feature H that contains all the information from previous steps. This intermediate feature then becomes part of the input for the next step.

See the table below for details:

| **Time Step** | **Input** | **Output** |
| --- | --- | --- |
| 1 | Input1 | Output1 and intermediate feature H1 |
| 2 | Input2 and intermediate feature H1 | Output2 and intermediate feature H2 |
| 3 | Input3 and intermediate feature H2 | Output3 and intermediate feature H3 |
| …… |  |  |

*(I hand-drew an RNN structure in my notes during the lecture — see the image on the right)*

![](https://www.waytoagi.com/api/kb-media/G16NbVbysogiohxkZAHcbSFknph)

This leads to the following model architecture:

![](https://www.waytoagi.com/api/kb-media/Wpvxbit69oJWYsxChvRc8Uncnce)
![](https://www.waytoagi.com/api/kb-media/U0YHbyJjwoxitCxty4hcDR25nYf)

### Mathematical Description of Forward and Backward Propagation in RNNs

In later articles, we will discuss RNN issues such as vanishing gradients, exploding gradients, and long-term dependencies in detail.

#### Mathematical Formulation of Native RNN Forward Propagation

When expressed in mathematical terms, the forward pass of an RNN can be described as follows:

Suppose we have an RNN model with an input sequence \( X = (x_1, x_2, \ldots, x_T) \), where \( x_t \) is the \( t \)-th element of the input sequence and \( T \) is the length of the sequence. We also have a corresponding output sequence \( Y = (y_1, y_2, \ldots, y_T) \), where \( y_t \) is the \( t \)-th element of the output sequence. The goal of the RNN is to learn a mapping function from the input sequence \( X \) to the output sequence \( Y \).

In an RNN, each time step \( t \) has a hidden state \( h_t \), which represents the hidden state at the current time step. It is computed as:

\[ h_t = f(W_{hh}h_{t-1} + W_{hx}x_t + b_h) \]

where \( W_{hh} \) is the weight matrix from the previous hidden state to the next, \( W_{hx} \) is the weight matrix from the input to the hidden state, \( b_h \) is the bias vector for the hidden state, and \( f \) is the activation function.

The output \( y_t \) of the RNN at time step \( t \) is computed from the hidden state \( h_t \) and the weight matrix \( W_{hy} \):

\[ y_t = W_{hy}h_t + b_y \]

where \( W_{hy} \) is the weight matrix from the hidden state to the output, and \( b_y \) is the bias vector for the output.

Once you understand the formulas above, you have essentially understood the forward propagation process of a Native RNN. It really isn’t that complicated!

The weight matrices involved are: \( W_{hh} \) (connects two hidden layers), \( W_{hx} \) (connects input to hidden layer), and \( W_{hy} \) (connects hidden layer to output).

The two bias vectors involved are: \( b_h \) and \( b_y \).

#### Backpropagation Algorithm for Native RNN

**RNN Backpropagation**

In principle, the backpropagation of an RNN is the same as the BP algorithm used in MLPs. However, because RNNs are time-dependent, the BP algorithm in RNNs is slightly more complex and has a different name: **Backpropagation Through Time (BPTT)**. Since this is an introductory document, we will not implement BPTT from scratch here.

If you are interested, you can refer to the paper: [On the difficulty of training recurrent neural networks](http://proceedings.mlr.press/v28/pascanu13.pdf). As shown in the figure on the right, if the largest eigenvalue of \(W^T\) is less than 1, the left-hand side of equations (18) and (19) will decay exponentially, leading to the **vanishing gradient** problem. Similarly, if the largest eigenvalue of \(W^T\) is greater than 1, the left-hand side will grow exponentially, causing the **exploding gradient** problem.

The root cause of these issues ultimately lies in the fact that RNNs share the same weight matrix across different time steps. During backpropagation, the same parameters are repeatedly multiplied together.

![](https://www.waytoagi.com/api/kb-media/HmAQbypYtoBlC8xsS4lcCddanlc)

This link provides a more detailed explanation of the RNN backpropagation algorithm (BPTT):  
[CS224N (1.24) Language Models and RNNs | bitJoy](http://bitjoy.net/2019/07/31/cs224n%ef%bc%881-24%ef%bc%89language-models-and-rnns/)

### Problems with Traditional RNNs

Native RNNs suffer from several major issues:

#### Excessive Memory

In a traditional RNN, the hidden state at each time step is computed from the current input and the hidden state from the previous time step. As a result, **each hidden state contains information from all historical time steps**. As the sequence grows longer, the hidden state accumulates more and more information, and the proportion of truly valuable information becomes smaller and smaller.

To solve this problem, we need to introduce a forgetting mechanism into the Native RNN.

#### Vanishing and Exploding Gradients When Handling Long Sequences

Excessive memory not only reduces the value of information but also leads to vanishing and exploding gradient problems when processing long sequences. This makes it difficult for the model to capture long-range dependencies, ultimately hurting its performance and generalization ability.

- During backpropagation, gradients must flow from the output back to the input, passing through the parameters at every time step.
- If the model has overly strong memory — meaning information from the input side must travel through many time steps before reaching the output (see the hand-drawn diagram in section 4.1.2) — then during backpropagation, the gradient at each time step is multiplied by the same parameter matrix. This causes the gradient to grow or shrink exponentially, resulting in exploding or vanishing gradients.
- Exploding gradients are relatively easy to address using techniques such as gradient clipping and learning rate adjustment. However, vanishing gradients are much harder to handle (which is why we will focus more on the vanishing gradient problem later). When gradients vanish, the network struggles to learn long-term dependencies in sequences.

These problems have severely limited the applicability of traditional RNNs on long-sequence data and made it difficult for them to achieve good performance and generalization. To address these issues, improved recurrent neural networks such as **Long Short-Term Memory (LSTM)** and **Gated Recurrent Unit (GRU)** were developed. These models introduce gating mechanisms to alleviate the vanishing and exploding gradient problems, enabling them to handle long sequences much more effectively.

#### Intuitive Understanding of Problems Caused by Vanishing Gradients

![](https://www.waytoagi.com/api/kb-media/J6HHbKSqeo3gWVxltRhccQgtnAh)

> In section 4.1.3.2, we briefly introduced the RNN backpropagation algorithm and explained why RNNs are prone to exploding gradients.  
> The core issue is that RNNs use shared parameters \(W\) across different time steps. This causes the partial derivative of the loss at time \(t+n\) with respect to the parameters at time \(t\) to contain \(W\) raised to an exponential power. Once \(W\) is very small or very large, it leads to vanishing or exploding gradients. As shown in the figure above, as the gradient propagates backward, it keeps getting smaller (the arrows become progressively smaller).

![](https://www.waytoagi.com/api/kb-media/ERnpbzcSooDQijxQr3fcgKoDnFb)

> What problems does vanishing gradient cause? One obvious consequence is that **parameter updates are dominated by nearby words**, while words farther from the current time step \(t\) have very little influence on the current parameter update.  
> Suppose we need to predict the next word in the sentence “The writer of the books”. Due to vanishing gradients, the word “books” has a much stronger influence on the prediction than the word “writer”. As a result, the model incorrectly predicts “are”, which is clearly wrong.

## LSTM Model

As mentioned earlier, the core problem with Native RNN is that its "memory" is too strong — the hidden state \( h_n \) ends up containing **all** the information from \( h_1 \) through \( h_{n-1} \). Therefore, we need to design a model architecture that allows the network to selectively remember and forget information, thereby increasing the value of the retained information and alleviating the gradient issues.

If we treat LSTM as a black box and ignore its internal structure for now, the overall LSTM model looks like this:

![](https://www.waytoagi.com/api/kb-media/M64CbVyoXoWNUKxaxJ0cX9MAnLh)

Compared to RNN, which has only one transfer state \( h^t \), LSTM has **two** transmission states: one is \( c^t \) (cell state), and the other is \( h^t \) (hidden state). (Tip: The \( h^t \) in RNN roughly corresponds to the \( c^t \) in LSTM.) Both are vectors.

The cell state \( c^t \) that is passed forward changes very slowly. Typically, the output \( c^t \) is the previous cell state \( c^{t-1} \) plus a small amount of new information. \( c^t \) controls which information should be forgotten and which should be retained. In contrast, \( h^t \) can vary significantly across different time steps.

### The Gate Structure in LSTM

Most online explanations of LSTM use the following diagram. However, I don’t like this diagram! So let’s ignore it for now.

![](https://www.waytoagi.com/api/kb-media/THggbl8tWo3y7Dxa2SIc2HEjndg)

For the first time step, the hidden state \( h^0 \) and cell state \( c^0 \) can be initialized as zero vectors. They can also be initialized using pretrained weights or other prior knowledge to help the model train better.

At the \( t \)-th time step, LSTM has three inputs: \( h^{t-1} \), \( c^{t-1} \), and \( x^t \). We directly concatenate \( x^t \) and \( h^{t-1} \) into a single, longer vector.

We have four weight matrices: \( W \), \( W^f \) (f for **f**orget), \( W^i \) (i for **i**nformation), and \( W^o \) (o for **o**utput). Each weight matrix has its own bias term, but we will ignore the biases for simplicity.

The concatenated vector of \( x^t \) and \( h^{t-1} \) is multiplied by each of these four weight matrices and then passed through an activation function, producing four vectors: \( z \), \( z^f \), \( z^i \), and \( z^o \).

> *Many other materials use \( W^c \) to represent the \( W \) here, and use the candidate cell state \( \tilde{C^t} \) to represent \( z \).*

Among them, only \( z \) is activated with the tanh function, as it will later serve as an input vector. The other three vectors act as **gate** vectors, so they are activated with the sigmoid function **(each gate signal is therefore a vector with elements in the range [0,1]. The closer an element is to 1, the more information it tends to remember!)**.

![](https://www.waytoagi.com/api/kb-media/I9m8bgnlyojrHYxWgkUcgPbwnlI)
![](https://www.waytoagi.com/api/kb-media/Pxyibdt2QotyfUxmquDcTVamnGd)

After computing the four vectors \( z \), \( z^f \), \( z^i \), and \( z^o \) from the current time step’s inputs \( x^t \) and \( h^{t-1} \), we now look at:

### Specific Implementation of the Gating Mechanism in LSTM

![](https://www.waytoagi.com/api/kb-media/U5fSbVn1hor8nkxQKdeckB40nMe)

# ⊙
is the Hadamard Product, which means multiplying corresponding elements of two matrices. Therefore, the two matrices being multiplied must have the same shape.

For example:  
\begin{pmatrix} 1&2\\ 3&4 \end{pmatrix} ⊙ \begin{pmatrix} 1&2\\ 3&4 \end{pmatrix} = \begin{pmatrix} 1&4\\ 9&16 \end{pmatrix}

⊕ represents matrix addition (adding corresponding elements of two matrices of the same shape).

Of course, in LSTM, the current input, hidden state, cell state, input vector **z**, and the gating vectors **z**<sup>f</sup>, **z**<sup>i</sup>, **z**<sup>o</sup> are all vectors. So these two symbols can simply be understood as performing element-wise multiplication/addition on the corresponding elements of the vectors.

**To obtain the current** **c**<sup>t</sup> **and** **h**<sup>t</sup> **from** **c**<sup>t−1</sup>**,** **h**<sup>t−1</sup> **and** **x**<sup>t</sup>**, the LSTM mainly consists of three stages internally:**

1. **Forget Stage.**  
   This stage mainly performs selective forgetting of the information passed from the previous node. Specifically, it uses the computed **z**<sup>f</sup> as the forget gate to make the previous cell state **c**<sup>t−1</sup> forget some unimportant information (don’t worry about what is “important” or “unimportant”—treat it as a black box. This capability is achieved by learning the parameters of the weight matrix **W**<sup>f</sup>).

   > **z**<sup>f</sup> = σ(**W**<sup>f</sup> ⋅ [*h*<sup>t−1</sup>, *x*<sup>t</sup>] + *b*<sup>f</sup>)

2. **Select Memory Stage.**  
   This stage selectively “remembers” the input at the current step. We want the model to focus on recording important information while being more casual with unimportant information (this capability is achieved by learning the parameters of the weight matrix **W**<sup>i</sup>).

   The memory gate consists of two parts: a sigmoid network and a tanh network.

   - **Sigmoid network:** Produces the gating signal **z**<sup>i</sup> (i for information) to determine which information should be updated.

     > **z**<sup>i</sup> = σ(**W**<sup>i</sup> ⋅ [*h*<sup>t−1</sup>, *x*<sup>t</sup>] + *b*<sup>i</sup>)

   - **tanh network:** Uses a weight matrix **W** to create a vector **z** (or the candidate state vector **C̃**<sup>t</sup>), which represents the new input information at this step.

     > **z** = **C̃**<sup>t</sup> = tanh(**W** ⋅ [*h*<sup>t−1</sup>, *x*<sup>t</sup>] + *b*)

   - Now we compute **z** ⊙ **z**<sup>i</sup>, which is equivalent to selectively remembering the valuable parts of the current input.

   > Adding the results from the above two steps gives the cell state **c**<sup>t</sup> to be passed to the next time step. That is:  
   > **c**<sup>t</sup> = **z**<sup>f</sup> ⊙ **c**<sup>t−1</sup> + **z**<sup>i</sup> ⊙ **z**

3. **Output Stage.**  
   This stage decides which information will be output as the current state’s output. We take the computed **c**<sup>t</sup>, pass it through tanh (projecting each element to the range (−1, 1)), and then perform element-wise multiplication with the vector **z**<sup>o</sup> to obtain the hidden state **h**<sup>t</sup> at this time step.

After computing the hidden state **h**<sup>t</sup> for the current time step, we multiply it by another weight matrix to get the output **y**<sup>t</sup> at this time step. Similar to a standard RNN, the final output **y**<sup>t</sup> is typically derived from a transformation of **h**<sup>t</sup>.

Reference: [【Zhihu】LSTM Explained for Everyone](https://zhuanlan.zhihu.com/p/32085405) by Zhihu user [Chen Cheng](https://www.zhihu.com/people/chenchengnlp).

### Why LSTM Can Alleviate the Gradient Problem

- The reason a vanilla RNN cannot preserve early states is that it stores all previous time-step information indiscriminately in the hidden state **h**<sup>t</sup>. This hidden state must undergo the following operation at every time step:  
  **h**<sub>t</sub> = f(**W**<sub>hh</sub>**h**<sub>t−1</sub> + **W**<sub>hx</sub>**x**<sub>t</sub> + *b*<sub>h</sub>).  
  As a result, the hidden state becomes the bottleneck of the entire network.

- The key innovation of LSTM is the introduction of a separate **cell** to store memory. For each time step:  
  **c**<sup>t</sup> = **z**<sup>f</sup> ⊙ **c**<sup>t−1</sup> + **z**<sup>i</sup> ⊙ **z**.

- Here, **z**<sup>f</sup> is the vector output by the forget gate. Each element is a real number between 0 and 1, where 0 means “completely forget” and 1 means “completely retain.” Therefore, even after many time steps, the cell state can still be preserved and passed forward, because it is controlled by the forget gate and does not suffer the exponential decay that occurs in traditional RNNs.

- The cell state’s memory is still affected by successive gradient multiplications, but it is far better than the hidden state in a vanilla RNN. So even though gradient vanishing or explosion problems can still occur, in practice LSTM performs very well and is quite robust.

### How to Further Optimize LSTM?

We can see that the model introduces a large number of parameters—five weight matrices: **W**, **W**<sup>f</sup> (f for forget), **W**<sup>i</sup> (i for information), **W**<sup>o</sup> (o for output), **W**′ (from current hidden state to output), plus various biases. This significantly increases the number of model parameters and makes training more difficult.

Therefore, LSTM has a popular variant called GRU. Reference: [GRU Explained for Everyone](https://zhuanlan.zhihu.com/p/32481747) by Zhihu user [Chen Cheng](https://www.zhihu.com/people/chenchengnlp).  
One clever aspect of GRU is that it uses an elegant design that allows a single gate to perform both forgetting and selective memory. In contrast, LSTM uses multiple separate gates. As a result, GRU is often more practical in many scenarios.

## Bidirectional RNN: Considering Information from Both Left and Right Sides

### Considering Information from Both Sides

Q: What sentiment does the word "Terribly" express in the sentence “Her answer was terribly exciting”?

- If we only look from left to right, we are very likely to interpret "terribly" as negative — after all, it comes from "terrible"! The model would probably predict that the next word after "terribly" is something like "wrong", meaning her answer was terribly wrong!

- But if we look from right to left, we realize that "terribly" should be positive here — her answer was so exciting.

The conclusion is: for many downstream tasks such as sentiment analysis, it is best to consider information from both left and right directions at the same time!

### A Bidirectional RNN Consists of Two Independent RNNs

A bidirectional RNN is essentially two **independent** RNNs (with separate parameters): one that processes the sequence from left to right, and another that processes it from right to left.

The outputs (hidden vectors) from both RNNs are then concatenated to form the final output representation, which is passed through a softmax (or other downstream layers).

**Mathematical Formulation of Bidirectional RNN:**

At each time step *t*, there are two hidden vectors: *h_t* and *h_t'*.  

Forward (left-to-right) hidden state:  
*h_t = f(U x_t + W h_{t-1} + b)*

Backward (right-to-left) hidden state:  
*h_t' = f(U' x_t + W' h'_{t+1} + b')*

Output:  
*o_t = g(V h_t + V' h_t' + c)*

The weights for forward and backward passes are not shared. Therefore, a single-layer bidirectional RNN has a total of 6 weight matrices: forward *U*, *V*, *W*; backward *U'*, *V'*, *W'*; and 3 bias vectors: *b*, *b'*, *c*.

![](https://www.waytoagi.com/api/kb-media/JZ5IbOFAColirBx23QecqqM8nKb)

**Applications of Bidirectional RNNs:**

- Bidirectional RNNs **cannot** be used for language modeling, because a language model at time *t* can only use information from before time *t* to predict the word at *t*. If we were given the entire sequence in both directions, it would no longer qualify as a language model.

- However, for NLP tasks that have access to the complete sequence (such as text classification and sentiment analysis), bidirectional RNNs should be the default choice.

## Deep RNNs: Stacking Layers to Increase Depth

### Structure of Multi-Layer RNNs

Multi-layer RNNs are actually quite straightforward: the output of RNN Layer 1 serves as the input to the next RNN layer. See the diagram below:

![](https://www.waytoagi.com/api/kb-media/XV4kbMLy7oBNVxx5LvwcqGnHnch)

### Deep RNNs Are Usually Not Very Deep

- Deep learning is, to some extent, a combination of alchemy and “brute force yields miracles.” In general, the deeper you stack the model, the better the performance tends to be (provided we handle issues like vanishing/exploding gradients properly).

- In computer vision tasks, convolutional neural networks can easily reach hundreds of layers and are often very deep. In contrast, RNNs are typically limited to two layers, and rarely exceed eight layers. The main reason is that RNN training is inherently sequential and difficult to parallelize. When the network becomes too deep, training becomes extremely time-consuming.

### What Are Serial vs. Parallel Computation, and Why Is Training Deep RNNs Especially Time-Consuming?

RNNs excel at processing sequential data. The output at each time step depends on the hidden state from the previous time step. Therefore, computation at step *t* cannot begin until step *t-1* has finished — it cannot be parallelized.

Consider the following example:

- If we were using a different type of neural network (not RNN), inputs W1, W2, W3, and W4 could be processed independently, producing outputs Y1, Y2, Y3, and Y4 respectively. We could then simply concatenate Y1–Y4. **Parallel** means “you do your thing, I do mine, and we combine the results at the end.”

- With RNNs, however, the situation is different (see diagram below):

1. We must first compute H(1,1) before we can compute H(1,2); only after H(1,3) is ready can we compute H(1,4).

2. Furthermore, to compute H(2,2), we need both H(2,1) and H(1,2) to be available first. To compute H(3,3), we must first have H(3,2) and H(2,3).

3. Assuming the computation speed of the upward arrows is the same as that of the rightward arrows, each rectangle is filled only after its computation completes. For a four-layer network, the cells are filled one by one in order of increasing color depth (from light to dark).

4. The situation can be even worse: in generative language models, we often use an autoregressive approach where the final output of one step becomes the input for the next. Consider a scenario where W1 is processed all the way to H(4,1) before producing W2, which is then fed back in to compute the next hidden states.

![](https://www.waytoagi.com/api/kb-media/KKxtbxM98owL8Rx7YLgcJAs0n8e)

1. **Serial** means “I finish my work before you can start yours.” From the diagram above, it becomes clear that when the input sequence is very long — for example, translating a sentence with hundreds of words — the extremely slow training speed of RNNs becomes especially apparent.

**Note:** When we say RNNs cannot be parallelized like CNNs, we are not referring to the inability to process multiple input-output sample batches simultaneously. Rather, for a single input-output training sample, computation must proceed sequentially step by step according to the time order, creating a computational bottleneck.

The power of GPUs lies in their exceptional parallel computing capability. Since RNNs cannot be effectively parallelized, they struggle to leverage the strengths of GPUs, making training particularly difficult.

In summary, training deep **RNNs** demands substantial computational resources and a very long time. This is exactly why we need Transformers.

## RNN Summary

| **Model** | **Convolutional Neural Network (CNN)** | **Recurrent Neural Network (RNN)** |
| --- | --- | --- |
| **Model Structure** | ![](https://www.waytoagi.com/api/kb-media/TnzRb6p22oMmMlxlb7sc1jmFnlh) | ![](https://www.waytoagi.com/api/kb-media/E0AabFv52oSLCBxZEG6cD3Ran7d) |
| **Type & Architecture** | Feedforward neural network with no cycles. Typically uses supervised learning and relies on labeled data. The architecture includes an input layer, convolutional layers, pooling layers, and fully connected layers. Convolutional layers extract features, while pooling layers compress features. | Recurrent neural network featuring cyclic recursion and recurrent parameters. It has memory capabilities — the output from the previous time step can serve as input for the next time step. At each moment, the model receives both the current input and the output from the previous moment. Without the recurrent loop, it would be a simple MLP, but the addition of this loop makes backpropagation extremely complex. |
| **Typical Models** | LeNet, AlexNet, VGG, GoogleNet, ResNet | Basic RNN, LSTM, GRU |
| **Pros & Cons** | **Advantages:** The convolutional layer uses locally connected convolutions to effectively capture local features in the input data. Parameters of the convolution kernels are shared across the entire input, significantly reducing the number of parameters that need to be learned. It is highly parallelizable. The pooling layer performs downsampling, reducing the size of feature maps and lowering model complexity. Convolutional neural networks are exceptionally well-suited for image recognition. Their high performance and ease of training are the two main reasons for the popularity of CNNs in recent years.<br><br>**Disadvantages:** (Not specified in original) | **Advantages:** Capable of capturing temporal relationships in sequential data. Through recurrent connections, the network can remember information from previous time steps and use it in subsequent ones, allowing it to handle sequences with long-term dependencies.<br><br>**Disadvantages:** The temporal recurrent connections make backpropagation (BP) very complex. Recurrent loops can cause gradients to vanish or explode during backpropagation. When dealing with long-term dependencies, it may suffer from the vanishing gradient problem, making it difficult to capture long-range temporal relationships. When processing long sequences, computation must be performed step by step across time steps, resulting in lower computational efficiency.<br><br>Recurrent neural networks are highly suitable for recognizing data with sequential characteristics. |
| **Model Parameters** | Convolution kernel weights and biases; fully connected layer weights and biases | Taking LSTM as an example: 5 weight matrices — \(W\), \(W^f\) (f for forget), \(W^i\) (i for information), \(W^o\) (o for output), \(W'\) (from current hidden state to output) — along with their corresponding biases. |
| **Hyperparameters** | Batch Size; learning rate, number of iterations, activation functions, network architecture, regularization; convolution kernel size; number of convolution kernels; stride; padding; pooling layer type, pooling window size, and pooling stride | Batch Size; learning rate, number of iterations, activation functions, network architecture, regularization; number of recurrent layers |

# Getting Started: Reinforcement Learning (Reinforcement Learning, RL)

#If you are only focusing on language models, you can skip this section for now — just like skipping CNN.

## The Three-Layer Structure of Reinforcement Learning

![](https://www.waytoagi.com/api/kb-media/ZiWZbMprSoWazTxaxhqcLmgynVh)

### Basic Elements: Environment, Agent & Goal

This layer focuses on the interaction between the **Agent** and the **Environment** it inhabits. The environment represents the external world the agent faces — it can be a physical real-world setting or a computer-simulated virtual environment. The agent interacts with the environment to achieve its **Goal**, which is typically defined by a task or problem. Through these interactions, the agent receives feedback (such as reward signals) and continuously optimizes its behavior.

**Example: Playing Go**  
- Environment: The Go board  
- Agent: The player  
- Goal: Win the game

**Example: Playing Mario**  
- Environment: The visual scene in the Mario game  
- Agent: Mario under the player’s control  
- Goal: Collect coins / complete the level and rescue the princess

### Core Elements: State & Action

In reinforcement learning, the agent perceives the environment to obtain the current **State** information. A state can be an observation of the environment or an internal representation. Based on the current state, the agent selects an appropriate **Action** to interact with the environment. An action is a specific choice the agent makes from the set of possible actions at a given moment.

**Example: Playing Go**  
- State: Current distribution of stones on the board  
- Action: Where to place the next stone

**Example: Playing Mario**  
- State: Current screen, including the positions of coins, enemies, and obstacles  
- Action: Move Mario left, right, or jump

### Key Elements: Policy & Value

A **Policy** defines the agent’s strategy for selecting actions in a given state. It can be deterministic (always choosing one specific action) or stochastic (selecting actions according to a probability distribution). **Value** is an evaluation of different states or state-action pairs, used to guide the agent’s decision-making.

The agent selects actions based on its policy and value estimates. Optimizing both the policy and value function is a central task in reinforcement learning. The design and updating of policies and values directly impact the agent’s learning and decision-making process.

**Example: Playing Go**  
- Policy: Opening books or game records that tell us how to play in response to a particular board configuration.  
- Value: If a certain move helps establish a winning position, its value is extremely high.

**Example: Playing Mario**  
- Policy: How to control Mario given the current distribution of enemies, coins, and traps.  
- Value: If a move leads to Mario being killed by an enemy, its value should be a large negative number.

## Core Concepts of Reinforcement Learning

### Learning a Good Value Function to Determine a Good Policy

Mainstream RL algorithms are generally **value-based**.

### Learning by Trial and Error, Not by Memorization

### Delayed Rewards — Credit Assignment Is Critical

Take Go as an example: every move contributes to the final victory, but the reward is zero until the game is won. Once the final reward is received, how should the value of each previous move be assigned? This is the **credit assignment** problem. Reviewing which moves were decisive in creating a winning position is crucial.

### Exploitation vs. Exploration

Take the training process of DQN as an example:

**Exploitation:** Using the current value function to select the action with the highest estimated value.

**Exploration:** Instead of always choosing the action with the highest current value, the agent deliberately tries other actions to improve and optimize the value function itself.

A classic example is the **multi-armed bandit** problem. From a god’s-eye view, suppose Slot Machine A has an expected return of 100, B has 50, and C has 0. Clearly, we should always play Machine A.

However, in reinforcement learning, we don’t know the true expected values of A, B, or C. We can only estimate them through trial and error.

Suppose we have tried each machine 10 times. The observed averages are: A = 30, B = 35, C = -10.

At this point, we have two choices:

1. **Continue exploiting:** Keep choosing B. If we play B infinitely many times, its average will converge to its true expectation of 50, which is much higher than 30 or -10. Our learning outcome would be that B is the best machine.

2. **Explore other options:** Try Machine A once more. This time it returns 140, pulling its average up to 40 — now higher than B’s 35.  

By balancing exploitation (following the current best strategy B) with exploration (trying A), we discover that A is actually the best machine. This prevents us from converging to a suboptimal local optimum (B) simply by rigidly following the current policy.

## The Mathematical Expressions of Reinforcement Learning

### Return

The English term for "return" is **Expected Cumulative Future Reward**, which represents the sum of all expected future rewards.

U_t = R_t + R_{t+1} + R_{t+2} + ...

Because future rewards are worth less than immediate ones (for example, most people would prefer receiving 95 dollars now rather than 100 dollars next year), we apply a discount to future rewards. This is called **Discounted Return**:

U_t = R_t + γR_{t+1} + γ²R_{t+2} + ...

where R_t is the reward given by the environment at the t-th action, and γ is the discount factor — a real number between 0 and 1.

P[S'=s'|S=s,A=a] = p(s'|s,a)

### State Value Function

**# Scoring a state s; can also be used to evaluate how good a policy π is**

The State Value Function represents the discounted value of all future rewards starting from the current state under a given policy.

V_π(s_t) = E_A[Q_π(s_t,A)] = ∫π(a|s_t) * Q_π(s_t,a) da

The state value function depends only on the policy π and the state s. It tells us how good our current situation is and what our chances of success are under the current policy.

V_π is a random variable. The source of randomness comes from the stochastic transitions of states.

### Action-Value Function

**# Scoring an action a**

The Action-Value Function Q_π reflects the expected return of taking a specific action a_t in a given state s_t, following a policy π.

Q_π(s_t,a_t) = E[U_t | S_t = s_t, A_t = a_t]

Q_π is a random variable. The sources of randomness are: 1) the agent’s behavior is stochastic according to the policy function; 2) the state transitions are stochastic.

**Optimal Action-Value Function**: Refers to the upper bound of the return that can be achieved by taking the current action, regardless of the policy.

Q^*_π(s_t,a_t) = max_π Q_π(s_t,a_t)

The intuitive meaning of Q^*_π is to evaluate an action independently of any specific policy.

## Value Learning

The goal of value learning: to find a way to approximate a behavioral value function.

### Deep Q Network

We use a neural network Q(s,a;w) to approximate Q^*(s,a).

We know that Q^*_π(s_t,a_t)=\mathop{max}\limits_πQ_π(s_t,a_t) is used to score an action regardless of the policy.

The input to this neural network is the current state. If we are playing a game, the state is the current game screen. We use convolutional layers to turn the current game screen into a feature vector and feed it into the neural network. The output of the neural network is a vector that scores each possible action. Suppose there are 3 possible actions in the current state (left, right, up). Then the neural network will output a 3-dimensional vector, where each element represents the score for that action based on the idea of Q^*(s,a).

Naturally, the system should take the action with the highest score: a_t=argmax_aQ(s_t,a;w).

After taking that action, the system automatically transitions to the next state according to the state transition function s_{t+1}~P(·|s_t,a_t). **Once in the next state, the process repeats: use the neural network** Q(s,a;w) **to score every possible action, then take the one with the highest score.**

### Gradient Descent in Reinforcement Learning

The basic idea of DQN has been explained above, but the problem is that the parameters w of Q(s,a;w) are randomly initialized at the beginning. So it is a clueless judge that has no idea how to score actions. We need to find a way to train this network so that the judge becomes more and more professional and its scoring becomes more and more accurate.

Just like the MLP and other neural networks mentioned earlier, we use the gradient descent algorithm. Here is an example:

From Beijing to Shenzhen, the model Q(w) predicts it will take q=1000 minutes. After the actual journey, I find it only takes y=800 minutes. The error is 200 minutes, which creates a loss.

Loss function:

Loss(L)=\frac{1}{2}(q-y)^2

<(Remember the earlier \mathcal L(y,f(x;\theta))=\frac{1}{2}(y-f(x;\theta))^2? It’s exactly the same!)>

Compute the gradient of the loss function:

\frac{∂L}{∂w}=\frac{∂q}{∂w}*\frac{∂L}{∂q}=(q-y)\frac{∂Q(w)}{∂w}

Then perform gradient descent on the parameter w:

w_{t+1}=w_t-\alpha\frac{∂L}{∂w}|_{w=w_t}

where \alpha is the learning rate / step size.

### TD Algorithm (Temporal Difference)

**Intuitive Understanding of the TD Algorithm**

Is there an algorithm that allows us to get a better estimate before we even arrive in Shenzhen?

Suppose we go from Beijing to Shanghai first, then to Shenzhen. After 500 minutes we arrive in Shanghai, and the model predicts it will take another 400 minutes to reach Shenzhen.

Then, the original prediction: Q(w)=1000 minutes; the latest prediction: y=500 minutes (Actual) + 400 minutes (Estimate) = 900 minutes.

At this point, the new prediction of 900 minutes is called the TD Target. The TD Target is also an estimate, but it contains real observed data, so it is clearly more reliable than the initial 1000. Using the TD target allows us to update the parameters in real time without having to complete the entire journey.

Loss function:

Loss(L)=\frac{1}{2}(Q(w)-y)^2

<We call Q(w)-y the TD Error. Here it is 100.>

Compute the gradient of the loss function:

\frac{∂L}{∂w}= (Q(w)-y)*\frac{∂Q(w)}{∂w}=TD Error*\frac{∂Q(w)}{∂w}

Then perform gradient descent.

**Mathematical Expression of the TD Algorithm in DQN**

> Formula:   T_{BJ-SZ}(Estimate)\approx T_{BJ-SH}(Actual)+T_{SH-SZ}(New Estimate)

> We know that the return function considering discount rate is:
U_t = R_t+\gamma R_{t+1}+\gamma^2 R_{t+2}+...=R_t+\gamma U_{t+1}

> This can be analogously extended to: Q(s_t,a_t;w)\approx r_t+\gamma Q(s_{t+1},a_{t+1};w)

> Here, r_t corresponds to the actual reward given by the system at time step t; \gamma Q(s_{t+1},a_{t+1};w) is the new estimate. Isn’t this exactly the same as the Beijing-to-Shenzhen example above?

> Our goal is to approximate the optimal value function Q^*(s,a;w)=\mathop{max}\limits_π Q_π(s_t,a_t). So where does the TD Target come in?

> The TD Target is the reward at this step plus the new prediction: y_t=r_t+\gamma Q(s_{t+1},a_{t+1};w_t)=r_t+\gamma \mathop{max}\limits_aQ(s_{t+1},a;w_t)

> Then, based on the TD Error, we have the loss function: Loss=L_t=\frac{1}{2}[Q(s_{t},a_{t};w)-y_t]^2

> We compute the gradient from this loss function and perform gradient descent.

**Summary of TD Algorithm Steps in DQN:**

1. S_t=s_t, A_t=a_t

2. Prediction: q_t=Q(s_t,a_t;w)

3. Derivative: d_t=\frac{∂Q(s_t,a_t;w)}{∂w}|_{w=w_t}

4. Based on the current state, an action is chosen, yielding a reward r_t and a new state s_{t+1}

5. With the new state, we can use the Q-network again to predict the expected return of the optimal action in the new state: \mathop{max}\limits_aQ(s_{t+1},a;w_t). This allows us to compute the TD Target: y_t=r_t+\gamma \mathop{max}\limits_aQ(s_{t+1},a;w_t)

6. With the TD Target, we naturally obtain the TD Error: q_t-y_t. We then perform gradient descent: w_{t+1}=w_t-\alpha(q_t-y_t)d_t

## Policy Learning

Policy learning algorithms use a neural network to approximate a policy function, where the policy is designed to maximize the value of \( V_\pi \) as much as possible.

The details are omitted here because this document is intended for language models. After completing the sections on value learning, DQN, and TD algorithms, you will already have a solid understanding of the fundamental principles of reinforcement learning. If you wish to dive deeper, feel free to self-study the recommended course by Shusen Wang below.

> It is worth noting that in RL, we can train a policy using only a reward function without relying on a value function, thereby implementing policy gradient algorithms. This approach is known as pure policy gradient methods. In other words, among the concepts mentioned above, the Value component is optional.

## Actor-Critic Method

Omitted for the same reason as above.

## Recommended Learning Materials

- If you want to gain a quick preliminary understanding of reinforcement learning within one hour, we recommend the video *【Reinforcement Learning】Complete Introduction in One Hour* created by [PenicillinLP](https://space.bilibili.com/291907888). The video is highly engaging, easy to understand, and systematically presents the essence of reinforcement learning concepts.

[【Bilibili】Reinforcement Learning - Complete Introduction in One Hour](https://www.bilibili.com/video/BV13a4y1J7bw/?buvid=ZE4EBEE92994324F407089826EE9BEE9DE8E&is_story_h5=false&mid=jOTTvC9MAcEUtHyHp%2B%2B2ww%3D%3D&p=1&plat_id=114&share_from=ugc&share_medium=iphone&share_plat=ios&share_session_id=446FA03C-3D56-4181-A256-6FE0BB4B07FA&share_source=WEIXIN&share_tag=s_i&timestamp=1680963987&unique_k=SAYH66y&up_id=291907888)

- If you want a more complete and mathematically rigorous understanding of reinforcement learning and are willing to invest the time, we recommend Shusen Wang’s course:

[【Bilibili】Shusen Wang: Deep Reinforcement Learning](https://www.bilibili.com/video/BV12o4y197US/?buvid=ZE4EBEE92994324F407089826EE9BEE9DE8E&is_story_h5=false&mid=jOTTvC9MAcEUtHyHp%2B%2B2ww%3D%3D&p=1&plat_id=114&share_from=ugc&share_medium=iphone&share_plat=ios&share_session_id=BC559497-28E3-42F7-8792-57408235B304&share_source=WEIXIN&share_tag=s_i&timestamp=1680963976&unique_k=wpm2mPl&up_id=52065264)


# Getting Started: Natural Language Processing and Language Models (NLP & Language Model, LM)

**Prerequisites: None. Basic knowledge of probability theory is sufficient.**

## Why Is It So Hard for Machines to Understand Human Language?

You can refer back to the concept of the *semantic gap* mentioned in section 2.1.1.

The diversity, flexibility, ambiguity, context-dependence, constant evolution of language, and the heavy reliance on world knowledge and common sense in human natural language all make it extremely difficult for machines to understand human speech and text.

1. **Diversity and Flexibility**: This spans grammar, vocabulary, semantics, context, and more. The same word can carry completely different meanings in different situations. For example, the “die” in “he was killed” and the “die” in “I’m dying of laughter” mean entirely different things. People also frequently use non-literal expressions such as irony, metaphors, similes, colloquialisms, and slang. Take the sentence “The Pampas Eagles were the dark horse of this grand event.” Here, “Pampas Eagles” refers to the Argentine national football team rather than an actual animal, “grand event” means the World Cup, and “dark horse” is a metaphor for a team that performed far beyond expectations. Humans can easily understand these expressions, but they pose a major challenge for machines.

2. **Ambiguity of Language**: Natural language is rich in ambiguous phenomena, including lexical ambiguity, syntactic ambiguity, and referential ambiguity. For instance, the English word “bank” can mean a financial institution or the side of a river; its meaning depends entirely on context—this is lexical ambiguity. In the sentence “The animal didn’t cross the street because it was too tired,” a machine cannot easily determine whether “it” refers to the animal or the street. This is referential ambiguity. Resolving such ambiguities requires strong reasoning and contextual understanding capabilities, which remain a significant challenge for machines.

3. **Context Dependence**: Human language expressions usually rely heavily on contextual information. For example, although “terribly” usually carries a negative meaning, in the sentence “The movie is terribly exciting,” it actually functions as an intensifier with a positive connotation.

4. **World Knowledge and Common Sense**: In everyday communication, humans constantly draw on world knowledge and common sense—our understanding and experience of the world. When we say “I’m going to spend 30 yuan to watch a movie in London,” we automatically know what a movie is, that London is a city, that 30 is a number, and that “yuan” is a unit of currency. This kind of world knowledge and common sense is essential for understanding natural language, yet acquiring and effectively applying it remains an extremely complex task for machines.

## Basic Tasks in NLP

### Text Classification

Text classification is the task of assigning text to different predefined categories, such as sentiment classification (positive or negative emotion, whether it contains aggression or malice), topic classification, spam detection, and more.

### Named Entity Recognition (NER)

Named Entity Recognition (NER) is a task in Natural Language Processing (NLP) that aims to identify spans of text that correspond to specific named entities, such as person names, location names, organization names, times, dates, currencies, quantities, etc. (For example, “Mr. Chen”, “Chen vinegar”, and “Chen Cang” are all written with the character “Chen” in Chinese, but we want the model to understand that “Mr. Chen” is a person’s name, “Chen vinegar” is an item, and “Chen Cang” is a place name. Only then can the model’s performance on natural language tasks be improved.)

NER is an important preprocessing step in many NLP applications.

**NER is typically divided into the following types:**

1. **Person**: Identifying personal names in text, such as "John Smith" or "Zhang San".
2. **Location**: Identifying geographical names in text, such as "New York" or "Beijing".
3. **Organization**: Identifying organizations, companies, or institutions, such as "Microsoft" or "Chinese Academy of Sciences".
4. **Time**: Identifying time-related information, including dates, clock times, seasons, etc., such as "October 1, 2021" or "3 PM".
5. **Date**: Identifying date information, such as "2021-10-01" or "10/01/2021".
6. **Currency**: Identifying monetary values, such as "$100" or "500 RMB".
7. **Quantity**: Identifying quantitative expressions, such as "3 apples" or "10 meters long".

NER tasks are usually solved using supervised learning, where large-scale annotated datasets with known entity types are used to train the model.

### Dependency Parsing

Dependency Parsing refers to the syntactic analysis of a sentence and the construction of a dependency graph showing the relationships between its components. For the sentence “She saw the video lecture,” we first identify the subject, predicate, and object; then we analyze the dependency relations, such as “saw” depending on “She.” This is syntactic parsing.

![](https://www.waytoagi.com/api/kb-media/RfdSbFsOTogH3MxO7A5clESEncY)

### Language Generation

- **Language Generation** is a task in Natural Language Processing (NLP) that refers to the process of using computers to produce natural language text.

- Language generation can be applied to a wide range of scenarios, including machine translation, text summarization, dialogue systems, automatic article writing, code generation, music and artistic creation, etc.

**Language generation methods can be categorized as follows (we mainly focus on methods 3 and 5):**

1. **Rule-based** generation: Text is generated using predefined rules and templates. This approach is typically used for simple texts such as greetings or fixed-format messages, but has limited scalability for complex text generation tasks.

2. **Statistical-based** generation: Statistical models such as n-gram language models and Hidden Markov Models (HMMs) are used to generate text. These methods rely on frequency and probability statistics from text data, but their performance is often constrained by the quantity and quality of available data.

3. **Machine Learning-based** generation: Machine learning algorithms are used to generate text. For example, Recurrent Neural Networks (RNNs) and their variants (such as Long Short-Term Memory networks, LSTMs) are widely used because they can handle sequential data and capture contextual information.

4. **Deep Learning-based** generation: Deep learning models such as Generative Adversarial Networks (GANs) and Variational Autoencoders (VAEs) are employed. These models can usually produce more complex and higher-quality text, but require large amounts of training data and computational resources.

5. **Pre-trained Model-based** generation: Leveraging large pre-trained models such as GPT-3 and BERT to generate text. These models learn rich linguistic knowledge from massive unsupervised training on large-scale text corpora, enabling them to produce high-quality and diverse outputs.

## Language Model Definition

You may encounter different definitions of language models across various articles and materials, which can be confusing. We will clarify them all below.

### Estimating the Linguistic Plausibility or Probability of a Given Word Sequence

First, for any word sequence, a language model can calculate the probability that this sequence forms a valid sentence.

For example, given:

$$
\left\{ \begin{aligned}
s_1: & \text{Wuhan} \mid \text{’s} \mid \text{weather} \mid \text{is} \mid \text{terrible} \\
s_2: & \text{Weather} \mid \text{Beijing} \mid \text{’s} \mid \text{terrible} \mid \text{is}
\end{aligned} \right.
$$

The model should produce:

$$
\left\{ \begin{aligned}
P(S_1) &= 1 \text{ (or very close to 1)} \\
P(S_2) &= 0 \text{ (or very close to 0)}
\end{aligned} \right.
$$

This was actually the earliest function of language models. Its origin lies in **Speech Recognition** — converting audio to text. When transcribing speech, multiple candidate sentences often emerge. Which one is more reasonable? This is where a language model comes in: it ranks these sentences by how “make sense” they are.

**At this stage, the definition of a language model is:** A language model (Language Model) is a probabilistic model used to generate natural language text. It can estimate the linguistic plausibility or probability of a given text sequence (usually a sentence or phrase).

Given a vocabulary \( V \), it can compute, for any word \( w_i \in V \), the probability that the word sequence \( w_1, w_2, w_3, \dots, w_n \) forms a coherent sentence:

$$
P(S) = P(w_1, w_2, w_3, \dots, w_n)
$$

### Predicting the Next Word Based on Previous Text to Enable Text Generation

Of course, we now know that what language models truly do is next-word prediction and generation.

> The most common example of a language model is probably the predictive text feature on your phone’s keyboard, which suggests the next character or word based on what you’ve typed so far.

However, this is consistent with the definition above. If we can predict the probability that a word sequence \( w_1, w_2, \dots, w_n \) forms a coherent sentence, then we can naturally predict the probability that \( w_1, w_2, \dots, w_n, w_{n+1} \) forms a coherent sentence. Given \( w_1, w_2, \dots, w_n \), we can then choose an appropriate \( w_{n+1} \).

**We can therefore expand the definition of a language model as follows:** A language model can predict the next likely word or character based on the preceding text sequence, thereby generating new text. When making predictions based on the entire preceding sequence, the language model is computing:

$$
P(w_i | w_1, w_2, \dots, w_{i-1}; \theta)
$$

The objective function (loss function) of the language model then becomes something very familiar (see 2.2.2.1):

$$
\mathcal{L}(\mathcal{U}) = -\sum_{i=1}^n \log P(w_i | w_1, w_2, \dots, w_{i-1}; \theta)
$$

Remember the cross-entropy loss? It is exactly the negative log of the element in the vector that the model should output as 1.

Here, \( \mathcal{U} \) is an extremely large **corpus**, \( w \) represents individual words, and \( \theta \) represents the model parameters. The goal of training a language model is to adjust the parameters \( \theta \) so that, given the preceding words, the model outputs the next word \( w_i \) in a way that best matches the patterns in the corpus.

In essence, a language model is a probability-based autoregressive fill-in-the-blank game.

### What Kind of Behavior Do We Expect from a Language Model?

Now let’s use \( V \) to represent a vocabulary:

$$
V = \begin{bmatrix} 
\text{cat} & \text{dog} & \text{in} & \text{bedroom} & \text{study} & \text{eat} & \text{meat} & \text{fish} & \text{black} & \text{white} & \text{yellow} & \text{purple}
\end{bmatrix}
$$

For example, given:

$$
\left\{ \begin{aligned}
s_1: & \text{cat} \mid \text{in} \mid \text{bedroom} \mid \text{eat} \mid \text{fish} \\
s_2: & \text{dog} \mid \text{in} \mid \text{study} \mid \text{eat} \mid \text{meat}
\end{aligned} \right.
$$

We should have \( P(s_1) \approx P(s_2) \), because cats and dogs are similar, bedrooms and studies are similar, and fish and meat are similar.

We want language models to have strong generalization capabilities.

For:

$$
\left\{ \begin{aligned}
s_1: & \text{cat} \mid \text{in} \mid \text{bedroom} \mid \text{eat} \mid \text{fish} \\
s_2: & \text{cat} \mid \text{in} \mid \text{study} \mid \text{eat} \mid \text{fish}
\end{aligned} \right.
$$

We still hope \( P(s_1) \approx P(s_2) \), because no rule says cats can only stay in bedrooms and not in studies.

For:

$$
\left\{ \begin{aligned}
s_1: & \text{black} \mid \text{cat} \\
s_2: & \text{white} \mid \text{cat}
\end{aligned} \right.
$$

We naturally hope \( P(s_1) \approx P(s_2) \), since cats can indeed be many different colors.

But we don’t want the language model to be *too* flexible or divergent:

For:

$$
\left\{ \begin{aligned}
s_1: & \text{cat} \mid \text{in} \mid \text{bedroom} \mid \text{eat} \mid \text{fish} \\
s_2: & \text{dog} \mid \text{in} \mid \text{study} \mid \text{eat} \mid \text{fish}
\end{aligned} \right.
$$

We do *not* want \( P(s_1) \approx P(s_2) \)! Because dogs really shouldn’t be eating fish! (Someone told me their dog loves fish, but never mind!!)

For:

$$
\left\{ \begin{aligned}
s_1: & \text{black} \mid \text{cat} \\
s_2: & \text{purple} \mid \text{cat}
\end{aligned} \right.
$$

We also do *not* want \( P(s_1) \approx P(s_2) \)! Because cats are very unlikely to be purple!

We hope that language models can discover similarities between words based on context.

- If “NLP” and “natural language processing” appear in very similar contexts in the corpus, the language model should be able to discover that they mean the same thing. Humans can easily understand that NLP stands for natural language processing, but for machines, this understanding must be learned from similar contexts.

- Similarly, if we know that NLP and “natural language processing” are the same, then their surrounding contexts should also be similar.

We can also run interesting analogy experiments to test a language model’s capabilities.

For example, if we use word embeddings to represent vocabulary, we should observe:

$$
\vec{king} - \vec{queen} \approx \vec{man} - \vec{woman}
$$

(This was one of the shocking discoveries when word2vec first came out — people thought, “Whoa, you can actually do that?!”)

## Word Embedding

Here we can recall the features mentioned in section 1.4.1.2, as well as the concepts of representation, local representation, and distributed representation discussed in sections 1.5.1 to 1.5.3.

Do you remember this image? It feels completely natural to represent colors using RGB, which makes the example easy to understand. The same principle applies to words!

![](https://www.waytoagi.com/api/kb-media/RbNTbId8DoY2pvxQJ5Kcm9XLnJx)

### One-hot Vector

Early NLP systems commonly used one-hot encoding to represent word vectors. If a vocabulary contains 10,000 words, the one-hot vector would have a length of 10,000. The position corresponding to the word in the vocabulary is set to 1, while all other values are 0.

In natural language processing, a **Token** usually refers to splitting a sentence or text into individual words or punctuation marks. This process is called tokenization and is an essential preprocessing step in NLP.

“Cat｜in｜the bedroom｜eats｜fish” is an example of splitting text into tokens.

When representing English, a Token is not the same as a word. A Token is a smaller unit than a full word.

For example, in the sentence “Her words interested me a lot,” adding “s” to “word” creates “words,” and the word “interest” can become “interested” in the past tense (which can also be an adjective, of course). Adding “ing” can turn it into the progressive form or another adjective. If we created a separate one-hot encoding for every possible variation, the dimensionality of the one-hot vectors would become excessively large and cumbersome. Instead, it is more practical to only record the base Tokens: “word,” “interest,” “s,” “ed,” and “ing.”

For more details, refer to: [【Personal Blog】CS224N (2.14) Subword Models | bitJoy](https://bitjoy.net/2020/02/17/cs224n%ef%bc%882-14%ef%bc%89subword-models/) by Beeder. Subword Models is an interesting research direction in NLP, but we won’t go into detail here. Understanding the core idea is sufficient.

Although the one-hot representation is simple, it has several major drawbacks:

1. The vocabulary is constantly growing. In English, adding prefixes and suffixes to existing words can generate many variations. One-hot encoding leads to extremely high-dimensional vectors, and each vector is highly sparse.

2. One-hot vectors for different words are orthogonal to each other. This means they cannot represent similarity relationships in vector space. Even if two words have very similar meanings, the dot product of their vectors is still 0.

### Word Embedding

Word embedding is similar to using RGB to represent colors — it uses dense vectors of limited dimensionality to represent all words in a vocabulary. However, word embeddings are generally not limited to just 3 dimensions. In traditional Transformer models, word embeddings are 512-dimensional. In BERT, there are two versions: 768-dimensional and 1024-dimensional.

Additionally, the numerical values in word embedding vectors tend to be far less interpretable. With RGB, we know the three numbers represent the intensity of red, green, and blue. But in word vectors, the numbers are essentially meaningless to humans — only the computer can “understand” them.

We obtain word embeddings by projecting a one-hot vector through a weight matrix.

For example, consider a vocabulary V with 3,000 words. Each word is represented as a 3,000-dimensional sparse vector. For each word, we multiply it by a 3,000 × 512 weight matrix, resulting in a 512-dimensional vector.

> **Hey ChatGPT, if we multiply a 3,000-dimensional one-hot vector by a 3,000×512 dense weight matrix, what is the result?**

> **ChatGPT:** If you multiply a 3,000-dimensional one-hot vector by a 3,000×512 dense weight matrix, the result will be a 512-dimensional vector. Specifically, a one-hot vector has only one element equal to 1 and all others equal to 0. Suppose the i-th dimension of the one-hot vector is 1; then the result of the multiplication will be the i-th column of the weight matrix. Therefore, the result of the multiplication is the i-th column of the weight matrix, which is a 512-dimensional vector.

> This operation is commonly used to convert discrete one-hot encodings into continuous dense vector representations, which can then be fed into deep learning models that require continuous vector inputs. This transformation helps models learn features and patterns more effectively and is widely used in many natural language processing (NLP) tasks, such as word embeddings, text classification, and language generation.

<Alright, ChatGPT actually explained it very clearly! The weight matrix itself acts as a lookup table for one-hot vectors. A 3,000-dimensional one-hot vector corresponds to one column in the 3,000-row weight matrix, and each column of the weight matrix is a 512-dimensional vector.>

The following text will help us understand this concept better. In the future, we will often encounter situations where multiple embeddings are added together (BERT: Who’s calling me?). If you’re curious why word embeddings can be added, come back and review this section!

> “The mathematical essence of Embedding is simply a single-layer fully connected network that takes one-hot vectors as input. There is no such thing as Embedding in this world — there is only one-hot.”

> [What Exactly Are Word Vectors and Embeddings? - Scientific Spaces](https://kexue.fm/archives/4122) By Su Jianlin

### Word2vec and Its Training Methods

Word2vec is a natural language processing technique published in 2013 that converts one-hot representations into word embeddings. It uses a two-layer neural network model to learn word associations from large text corpora, transforming words in natural language into mathematical vectors. It can represent relationships between words as distances and directions in vector space, allowing the semantic information of words to be expressed and processed mathematically.

Remember the expectations we mentioned for language models in section 6.3.3? The Word2vec model is one way to fulfill those expectations! Word2vec can represent various tokens as vectors, use cosine similarity to measure semantic similarity between the words these vectors represent, and detect synonyms. It can also suggest additional words for partial sentences and capture both semantic and syntactic qualities of words.

Word2vec has extremely wide applications. The word-level vector representations it produces can be used in various downstream tasks, such as semantic analysis, text classification, machine translation, and other NLP tasks. Clearly, obtaining high-quality word-level vector representations is highly general-purpose across NLP tasks. If a well-performing Word2vec model is trained and open-sourced, everyone can avoid reinventing the wheel and simply use this powerful, ready-made model together.

Later (in 8.1.5), we will mention that word2vec can be considered the founding ancestor of transfer learning in NLP! However, we don’t need to worry about the term “transfer learning” yet. It’s enough to know that this is an extremely versatile piece of work that provides great value for a wide range of NLP tasks.

> During his time at Google, word2vec author Tomas Mikolov publicly released the word2vec code on Google Code. Over time, the code was migrated to GitHub and became an important project in the open-source community. Today, most deep learning frameworks provide built-in support for word2vec models, making it very convenient to use and implement.

**Word2vec has two training methods: CBOW and Skip-gram.**

> As mentioned earlier:

- If “NLP” and “natural language processing” appear in very similar contexts in the corpus, we can infer that they are semantically similar.

- Similarly, if we already know that “NLP” and “natural language processing” mean the same thing, then their surrounding contexts should also be similar.

- These two lines of thinking correspond respectively to CBOW and Skip-gram.

**Continuous Bag of Words (CBOW):** The CBOW model predicts the center word based on the average vector of its context words. (Not expanded here.)

**Skip-gram:** The Skip-gram model predicts the surrounding context words given a center word. (Not expanded here.)

According to the paper authors ([Distributed Representations of Words and Phrases and their Compositionality](https://proceedings.neurips.cc/paper/2013/file/9aa42b31882ec039965f3c4923ce901b-Paper.pdf) and [Efficient Estimation of Word Representations in Vector Space](https://arxiv.org/pdf/1301.3781.pdf)), CBOW trains faster, while Skip-gram performs better at predicting rare words.

Under Tomas Mikolov’s work, learning high-quality word vectors from a dataset of 1.6 billion words takes less than a day. COOL!

## Statistical Language Generation: The N-gram Model

### Chain Rule Expansion of Conditional Probability

As mentioned earlier, a language model needs to predict the probability of generating the next word: P(w_i | w_1, w_2, ..., w_{i-1}).

This is undoubtedly a conditional probability that can be solved by expanding it using the chain rule:

P(S) = P(w_1, w_2, w_3, ..., w_i) = P(w_1) P(w_2 | w_1) P(w_3 | w_1, w_2) ...... P(w_i | w_1, w_2, ..., w_{i-1})

Then, using P(w_1, w_2, w_3, ..., w_i) and P(w_1, w_2, w_3, ..., w_{i-1}), we can compute P(w_i | w_1, w_2, ..., w_{i-1}). Well, this is simply intractable!

### The Markov Assumption

A simplified approach is to assume that the occurrence of a word does not depend on all the preceding words, but only on the few words immediately before it. We call this assumption the Markov assumption.

Taking a **trigram language model** as an example: if a word’s occurrence depends only on the two words before it, we call this a second-order Markov assumption, and the corresponding language model is a trigram model:

P(S) = P(w_1) P(w_2 | w_1) P(w_3 | w_1, w_2) P(w_4 | w_2, w_3) ... P(w_i | w_{i-2}, w_{i-1})

This becomes much more computationally feasible. In practice, 3-gram and 4-gram models are most commonly used, because increasing n further yields diminishing returns in model performance while causing the number of parameters to grow exponentially.

### Limitations of N-gram Language Models

N-gram language models have several major limitations:

1. **Limited context**: They can only capture information from the previous 2–3 words and cannot look further. However, in an entire text sequence, the information critical for predicting the next word is by no means limited to just those 2–3 words. Long-distance dependencies are very common. For example, given “The books of the famous writer”, the next word should be “are”. But if the model only sees the previous three words—“the famous writer”—it is very likely to generate “is”. That would be pretty dumb!

2. **Frequency-based prediction only**: At its core, it predicts probabilities based solely on how often words appear in the corpus. It cannot handle semantic similarity. For instance, if the corpus contains “I love Beijing” 100 times and “I love Xiamen” 1,000 times, then P(I love Xiamen) will be much larger than P(I love Beijing). Yet both sentences clearly make sense.

3. **Sparsity problem**: Because the model relies entirely on the corpus, words that rarely or never appear in it lead to a huge number of zero or near-zero denominators when calculating conditional probabilities. The **sparsity problem** refers to the situation where uncommon words appear very infrequently or not at all in the corpus, causing denominators in conditional probability calculations to be zero or extremely small, which severely degrades model performance.

4. **Inflexibility**: N-gram models are very rigid. Based on the corpus, they may know “black car” and “white car”, but cannot generate “yellow car” if it never appeared in the training data. That said, rigidity is not necessarily a bad thing—because the model will not hallucinate. It will only output “black horse” or “white horse” from the corpus, and never say “green horse.”

## Optimizing n-gram Models with Feedforward Neural Networks

Through the method of word embeddings, we now have the ability to convert text into dense, fixed-dimensional vectors that can be fed into a neural network.

According to the Universal Approximation Theorem of MLPs, a neural network with a single hidden layer can approximate a wide variety of functions extremely well, making it highly suitable for modeling probability distributions. Since a language model, when performing next-word prediction, is essentially outputting a probability distribution, neural networks are a natural fit for language modeling.

Now let’s use an FFNN to optimize a 5-gram model — that is, using the previous 4 words as input to predict the next word. Assume the word embeddings are 512-dimensional and the vocabulary contains 3000 tokens.

Image source: CS224N. The diagram on the right shows a 5-gram feedforward neural language model.

1. Input Layer: The input is a sequence of the previous five tokens. Each token is represented by a sparse one-hot vector.
2. Projection Layer: We multiply each one-hot vector from the previous layer by a weight matrix \(W_e\) to map it to its word embedding \(\vec{e}\), then concatenate the four embeddings into a single 2048-dimensional vector.
3. Hidden Layer: Takes the 2048-dimensional concatenated vector from the previous layer and performs a fully connected transformation using a weight matrix \(W\).
4. Output Layer: A Softmax layer that is fully connected to the hidden layer’s output via matrix \(U\), producing a 3000-dimensional vector where each element is positive and all elements sum to 1 — i.e., the probability distribution over the next word.

![](https://www.waytoagi.com/api/kb-media/EAwWbliGWoSXgjxua4FcSN3VnJf)
<Parameter set \(\theta = (E, W, b_1, U, b_2)\)> 

However, simply upgrading an n-gram model with an FFNN is still quite limited. It does not overcome a fundamental drawback: the window size is fixed. When predicting a new word \(w_i\), the model can only depend on the previous \(n\) words.

Earlier when we introduced RNNs, we repeatedly used language modeling as an example. So now let’s see how the RNN model truly shines!


## Language Models Based on Recurrent Neural Networks

> From now until Chapter 10 — Transformer — we will be dealing with RNNs constantly!

> Since Chapter 4 already provided a fairly detailed introduction to RNNs, we will not repeat the model architecture, forward propagation, loss function, etc. here. If you feel your understanding of RNNs is not solid enough during your studies, please go back and review Chapter 4!

![](https://www.waytoagi.com/api/kb-media/HVHXbmVRdoXNQcxpzaocaSWlnDe)
<Parameter set \(\theta = (E, W_h, W_e, b_1, U, b_2)\)> 

![](https://www.waytoagi.com/api/kb-media/BfHhbWS7WoRz2exIZ2YcjC4Tnkd)

When performing language generation (LM), an autoregressive approach is typically used: the output of the previous step becomes the input of the next step!

**Advantages of RNNs compared to fixed-window neural networks:**

1. Not limited by input length — can handle sequences of arbitrary length.
2. The hidden state \(h_t\) can capture information from much earlier inputs, so in theory it can solve long-range dependency problems in text.
3. The model size is fixed, because the parameters \(E\), \(W_e\), \(W_h\), \(b_1\), \(b_2\), and \(U\) are shared across time steps and do not depend on the input length.

**However, its disadvantages are also obvious:**

1. Although in theory the state at time \(t\) can perceive information from much earlier steps, in practice, due to the strong memory of the hidden state \(h\), the vanishing gradient problem exists. The actual performance is far worse than expected.  
   > “Although RNNs can in theory learn long-distance dependencies, due to the problems of exploding or vanishing gradients, what they actually learn are mostly short-term dependencies.”  
   (This can be significantly alleviated by using LSTM or GRU.)

2. Because computation cannot be parallelized and must be done sequentially, training is extremely slow. (This problem remains even with more advanced “Fancy RNNs” — it cannot be solved.)

## Recommended Learning Materials

### Video Materials

When it comes to video introductions to NLP, there is no better choice than the world-renowned Stanford CS224N course.

[【YouTube】Stanford CS224N: NLP with Deep Learning](https://www.youtube.com/playlist?list=PLoROMvodv4rOSH4v6133s9LFPRHjEmbmJ)

[【Bilibili】Stanford CS224N: NLP with Deep Learning](https://www.bilibili.com/video/BV1ct4y157Uf/?spm_id_from=333.337.search-card.all.click)

### Text Materials

[【Personal Blog】Stanford CS224N — NLP with Deep Learning](https://bitjoy.net/category/0%e5%92%8c1/stanford-cs224n-nlp-with-deep-learning/page/2/) by Beeder

# Let’s Get to the Point! seq2seq Models and the Attention Mechanism (2014)

**Prerequisites:** [**MLP**](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#QK8CdMmuqowMeYxKUIrcHBpFnkf), [**RNN**](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#NOWid4QIOoSowwxm478cqce4nzd), and the basic knowledge from Chapter 6.

# After covering so much groundwork, we are finally starting to learn content that is much closer to the large language models we can interact with today!! Before reading this chapter, it’s best to make sure you understand what RNNs are.

A detailed understanding of seq2seq is highly significant for grasping large language models: it inspired the concept of sequence autoencoders, which proved very important for the later emergence of self-supervised learning in NLP. The Encoder-Decoder architecture also appears in Transformers.

# Attention originally began as an improvement technique applied to RNN-based seq2seq models. Of course, everyone already knows the later plot twist — the version that abandoned RNNs entirely and kept only Attention.

Main reference materials:

[【arxiv】Sequence to Sequence Learning with Neural Networks](https://arxiv.org/abs/1409.3215)

[【Zhihu】CS224n Notes [7]: Spent 12 Hours Organizing This Just So You Can Understand Seq2seq in 20 Minutes](https://zhuanlan.zhihu.com/p/147310766) By Zhihu user [Guoguo](https://www.zhihu.com/people/guo-bi-yang-78)

[【Personal Blog】CS224N(1.31)Translation, Seq2Seq, Attention | bitJoy](https://bitjoy.net/2019/08/02/cs224n%ef%bc%881-31%ef%bc%89translation-seq2seq-attention/) By Beeder

**seq2seq Structure: Illustrated with Its Application in NMT**

seq2seq is a very powerful model. It can be used not only for machine translation, but also for many other NLP tasks such as automatic summarization, dialogue systems, and more. However, it was originally developed for machine translation, and translation remains a classic and representative use case. Therefore, we will start with translation as our example.

Neural Machine Translation (NMT) adopts the seq2seq architecture. Another common name for this structure is the **Encoder-Decoder** model.

It is called seq2seq because both its input and output are sequences of words — that is, **sequence to sequence**, hence seq2seq. (The correct pronunciation is /si:k-tu:-si:k/. Don’t get it wrong!)

![](https://www.waytoagi.com/api/kb-media/HbJMbW1WpoFfKRxIJK1cTwNbnv0)

- **Encoder:** Reads the input text and encodes the entire input sequence into a single representation vector, which is then passed to the Decoder. In the Encoder, each input word is first converted into a one-hot vector, then projected into a (typically 512-dimensional) vector space through an Embedding layer. This embedding is subsequently fed into an RNN (usually an LSTM, which can be bidirectional and stacked with multiple layers to build a deeper network capable of extracting higher-level features).

- **Context Vector:** After a series of computations through the RNN in the Encoder, the final output is a vector that represents the entire source text.

- **Decoder:** Receives the encoded representation from the Encoder (and, during training, the ground-truth target word sequence) and generates text on its own. In NMT, the Decoder’s output is the predicted sequence of words. However, the input to the Decoder differs between training and inference.

![](https://www.waytoagi.com/api/kb-media/STPobYLHgo1UFjxwtlFcq0e0nrh)

**#The Encoder RNN is responsible for encoding the source language and learning its hidden features. The final hidden state of the Encoder RNN is used as the initial hidden state for the Decoder RNN.**

**During Training:** The Decoder receives both the representation vector produced by the Encoder and the ground-truth target sequence as input. As shown in the left figure, given the first input token `<start>` and the context vector from the Encoder, the model generates the first prediction $\hat{y_1}$. Then, instead of feeding back the previous prediction $\hat{y_1}$, it uses the ground-truth token $y_1$ as the next input to generate $\hat{y_2}$.

This is straightforward to understand. The loss function is the cross-entropy between the probability distribution over the entire vocabulary produced at each step and the one-hot vector of the corresponding ground-truth word. We perform gradient descent on the RNN based on this loss, allowing the model to make increasingly accurate predictions.

**During Inference (Prediction):** The model operates in a “self-consuming” manner — the output of each step is fed directly as input to the next step. This generation method is known as **auto-regressive**. As illustrated in the figure below, starting with the `<start>` token and the context vector from the Encoder, the model first generates $\hat{y_1}$. Then, instead of using the ground-truth $y_1$, it feeds the previous prediction $\hat{y_1}$ as input to generate $\hat{y_2}$. Later we will see that GPT is also an auto-regressive text generation model. The auto-regressive paradigm is naturally well-suited for generative tasks. This makes intuitive sense — just like how we write an article by thinking and composing from left to right.

![](https://www.waytoagi.com/api/kb-media/T1KAbLhu6osgJBxcHLucp9cOn9e)

**#The initial hidden state of the Decoder is derived from the output of the Encoder RNN, which is why we call the Decoder a conditional language model.**

**A Deep Dive into the Decoder: It’s Just a Language Model!**

### Why Is the Decoder Different During Training vs. Inference?

During training, the Decoder generates outputs based on the ground-truth (correct) answers. During inference, it generates outputs based on its own previous predictions. Why make this distinction?

This difference comes down to two distinct decoding strategies:

- Decoding based on the ground-truth is called **Teacher Forcing**.
- Decoding based on the model’s own previous output as the next input is called **Free Running**.

> “Can we really not use free running during training? — Of course we can! There is no theoretical problem; it will run just fine. However, in practice people discovered that training this way is **too difficult**. Without any guidance, the model starts by making completely random predictions. As the saying goes, ‘one wrong step leads to wrong steps forever,’ and the errors quickly spiral out of control. This causes the accumulated loss during training to become excessively large (the ‘error explosion’ problem, also known as *exposure bias*), making training extremely inefficient.  
> At this point, if at every step we let a ‘teacher’ provide guidance — that is, give the model the correct previous word — the decoder can quickly get back on track, and the training process converges much faster. That’s why this technique is called *teacher forcing*. Its purpose is simply to make the training process easier.”  
> — Zhihu user Guoguo

### Scheduled Sampling

If a Decoder is left to generate its own predictions from the very beginning, it’s like a high-school student blindly doing practice exams without any teacher guidance — constantly accumulating experience from their own mistakes, often drifting further and further off course.  
On the other hand, always training with the correct answers is like always looking at the answer key while doing exercises. When the student finally walks into the college entrance exam with no answer key available, they suddenly freeze.

A better and more commonly used approach is for the teacher to provide an appropriate amount of guidance while the student actively learns on their own.

**Scheduled Sampling**: We define a probability *p*. At each decoding step, with probability *p* we use the model’s own previous prediction as input, and with probability *1-p* we use the ground-truth token.

![](https://www.waytoagi.com/api/kb-media/Fr2vb49VaoM1Ahx6vhBcMHY9nsd)

### Greedy Decoding vs. Beam Search

#### Greedy Decoding

If at every step we always pick the word with the highest probability and feed it to the next step, this strategy is called **Greedy Decoding**.

However, Greedy Decoding has clear limitations.

Think about the predictive text on your phone’s keyboard — it also ranks the next word by probability. What happens if you keep tapping the first suggested word every time?

Example: After typing “don’t” on an iPhone and then repeatedly selecting the first word recommended by the built-in input method, you end up with something like this:

> Stop coming again, when will our way of life return, when will our way of life return, when will our way of life return, when will our way of life return, our way of life...

It even starts looping. Pretty dumb!

This illustrates a core problem with greedy algorithms: **Greedy can only guarantee that each individual step is optimal, but it cannot guarantee that the overall generated sentence is optimal.** Especially when the greedy choice at time *t* is not globally optimal, all subsequent predictions will be based on that mistake, with no way to go back. To address the issue that *local optimum ≠ global optimum*, we often use **Beam Search**.

#### Beam Search

The core idea of Beam Search is to keep **multiple candidate sequences** at each step, and finally choose the best overall combination after comprehensive evaluation.

**Specific approach:**

- Set the beam size *k* (in the figure on the right, *k*=2; in practice, *k* is usually 5–10).
- At each time step *t*, we take the current *k* most probable sequences as input. Each of them predicts its own top-*k* next words, producing *K²* candidate sequences. From these *K²* candidates, we retain only the *k* sequences with the highest overall scores to pass to the next step.  
  *(Important note: The “top-k” here refers not only to the k highest-probability tokens ŷ_t within a single sequence, but also to ultimately keeping the k highest-scoring complete sequences out of all K² candidates.)*  
  (See the right figure: at *t*=3, the top-2 sequences are [he hit] and [I was]. The next step continues only from these two sequences, generating four high-probability branches. Sequences like [he stuck] and [I got] are pruned. This pruning ensures that the complexity of beam search does not grow exponentially.)

![](https://www.waytoagi.com/api/kb-media/RDSubuHY4ohjCexNEQpcM7qJnrf)

- During beam search, different paths may generate the end-of-sequence token `<END>` at different times. Some paths finish early — these are called *complete paths*. We temporarily set them aside and continue the beam search with the unfinished paths.
- Beam search can stop based on several conditions: reaching a maximum number of time steps, or collecting a maximum number of complete paths. When search ends, we select the highest-scoring path among all complete paths as the final result.
- We define the **sequence score** using the following function:  
  `score(y₁,...,yₜ) = ∑_{i=1}^{t} log P(yᵢ | y₁,...,y_{i-1}, x)`  
  All scores are negative, and higher (less negative) is better. Because scores are cumulative, longer sequences tend to receive lower scores. Therefore, when making the final selection, we normalize the score by length:  
  `score(y₁,...,yₜ) = (1/t) ∑_{i=1}^{t} log P(yᵢ | y₁,...,y_{i-1}, x)`

- Beam search is a pruning strategy. It cannot guarantee a globally optimal solution, but it finds the global optimum with high probability while dramatically improving search efficiency compared to exhaustive search.

## Attention Mechanism

### The Information Bottleneck in Naive seq2seq

In a naive seq2seq neural machine translation model, we use the hidden state of the last neuron in the Encoder RNN as the initial hidden state for the Decoder RNN. There is a problem here: the final hidden state of the Encoder (Context Vector) carries all the information of the source sentence and becomes the “information” bottleneck of the entire model.

Think about it: in the Encoder RNN, after encoding “il”, “a”, and “m’”, there are intermediate hidden vectors **h₁**, **h₂**, and **h₃**. However, only the final **h₄** is passed to the decoder. Is it possible that when the decoder is generating the word “hit”, using the original **h₁** or **h₂** might actually produce better results than using the updated **h₄**?

![](https://api/kb-media/TYaCbMykcoyX9OxsfwBc0wyqnvb)

The attention mechanism aims to break this information bottleneck. From a macro perspective, Attention directly connects every hidden layer in the Decoder with every hidden layer in the Encoder.

### Intuitive Understanding of the Attention Mechanism

![](https://api/kb-media/AHDtb87NxozyOAxYb9gcGSMunPc)

As mentioned earlier, “Attention directly connects every hidden layer in the Decoder with every hidden layer in the Encoder.” This way, the final hidden state of the Encoder RNN is no longer an “information” bottleneck.

When we decode, we generate one word at a time. For each word, the decoder can not only receive the Context Vector as auxiliary information, but can also obtain information from other hidden states in the Encoder RNN through “direct connection” pathways, thereby assisting the decoding process.

Looking at the second time step of the Decoder in the left figure, we take “he” as input and comprehensively consider the hidden states of “il”, “a”, “m’”, and “entarte”. It can be seen that the attention at the “he” moment is mainly distributed on the 2nd and 4th words of the Encoder, and the decoder ultimately decides to output “hit”.

### Mathematical Expression of the Attention Mechanism

#### Vector Dot Product Operation

The dot product is an operation in linear algebra. It is a way to compute the relationship between two vectors of the same dimension, usually denoted by the symbol “·”.

For two vectors **a** = [a₁, a₂, …, aₙ] and **b** = [b₁, b₂, …, bₙ], their dot product is defined as:

**a** · **b** = ∑_{i=1}^n a_i b_i

That is, the dot product multiplies the corresponding elements of the two vectors and then sums them up. Therefore, the result of the dot product is a scalar, which represents the similarity between the two vectors or the length of the projection of one vector onto the other in the same direction.

In summary, we need to remember two things:  
**1. The result of a dot product is a scalar.**  
**2. The result of a dot product reflects the similarity between two vectors of the same dimension.**

#### Steps of the Attention Mechanism

1. At time step *t*, the Decoder has hidden state **sₜ**, and the Encoder has hidden states from all time steps **h₁, h₂, ..., hₙ**. We compute the dot product between **sₜ** and each of the Encoder’s hidden states, obtaining *N* **scalar Attention scores**.  
   These *N* scalars form an *N*-dimensional vector that reflects the relevance scores between the current hidden state of the decoder and the hidden states of each time step in the encoder.

   **e**ᵗ = [sₜ·h₁, sₜ·h₂, ..., sₜ·hₙ]

2. We use **Softmax** to normalize these scores (so that they sum to 1), obtaining the **Attention distribution**. Like any vector produced by the Softmax function, the Attention Distribution is a probability distribution. This Attention distribution tells the Decoder which hidden states in the Encoder it should focus more attention on at time *t*.

   **α**ᵗ = softmax(**e**ᵗ) = [α₁ᵗ, α₂ᵗ, ..., αₙᵗ]

3. Next, we perform a weighted sum of all the Encoder’s hidden states using the Attention distribution to obtain the **Attention output** **aₜ**.  
   (Since the attention distribution is a probability density function, the attention output **aₜ** is conceptually similar to a mathematical expectation.)

   Attention output at decoder time *t*:  
   **aₜ** = ∑_{i=1}^N **α**ᵢᵗ **hᵢ**

4. Concatenate the attention output **aₜ** with the current hidden state **sₜ**, then apply a non-linear transformation to obtain the final output **ŷₜ**.

#### Benefits of the Attention Mechanism

Imagine a machine needs to translate this sentence: *The animal didn't cross the street because it was too tired.*

Who does “it” refer to — the street or the animal? As shown in the figure below, when the decoder processes the word “it,” the Attention mechanism allows the model to associate “it” with “The animal” and incorporate that context into the encoding of “it.”

![](https://www.waytoagi.com/api/kb-media/QK0sbG6zaoiW2qxb8X3cwOlunWd)

Image source: [Ann's Blog](https://lolitasian.blog.csdn.net/)

In seq2seq architectures, the Attention mechanism brings the following advantages:

1. **Solving the Information Bottleneck Problem**: In traditional seq2seq models, the encoder compresses the entire source sequence into a single fixed-length vector. The Attention mechanism allows the decoder, at each time step, to “focus” on different parts of the source sequence to varying degrees. This enables the model to make full use of information from the source sequence and significantly improves performance.

2. **Better Handling of Long Sequences and Improved Generalization**: The Attention mechanism makes the model more robust to varying input sequence lengths. Model performance is no longer heavily affected by changes in sequence length. This is because Attention dynamically adjusts the degree of “focus” according to the input length, allowing the model to effectively process sequences of different lengths.

3. **Increased Model Interpretability**: The Attention mechanism lets us intuitively understand which parts of the source sequence the model “attends to” when generating each output token. By visualizing the Attention weights, we can directly observe how the model distributes its focus, making it easier to debug and optimize the model. The visualization example above illustrates this point.

4. **Improved Translation Quality**: In machine translation tasks, the Attention mechanism can explicitly “focus” on the parts of the source sequence that are most relevant to the target sequence, thereby enhancing translation performance. The example *The animal didn't cross the street because it was too tired* again serves as a good illustration.

5. **Helps Alleviate the Vanishing Gradient Problem**: Because every decoder time step is directly connected to all encoder hidden states, gradients can flow more effectively through the network.

> Since the emergence of seq2seq and Neural Machine Translation (NMT), machine translation has made tremendous progress. The previous pinnacle of machine translation — Statistical Machine Translation (SMT) — was extremely complex. It involved massive feature engineering, enormous amounts of expert knowledge, vast resource accumulation, numerous functional modules, and required large teams to maintain. Now, all of that has been completely overturned by a very deep neural network! A huge number of feature engineers and linguistic experts are now out of work. SOS.

![](https://www.waytoagi.com/api/kb-media/WVTQbfMQHooHbLxERnKco3xlnnN)

**Some Final Thoughts**

### NMT Is Indeed Impressive, But It Still Has Limitations

Seq2seq models perform exceptionally well in neural machine translation, but they are not without issues:

1. **Domain mismatch.** When models are trained on relatively formal corpora such as Wikipedia, academic papers, or news articles, they often struggle with informal or spoken-language content—like tweets or in-game chat with international players.

2. **Translation of long texts.** Everything we’ve covered so far involves translating individual sentences, which are relatively short. Translating an entire paper or book raises the question of how to effectively capture very long-range contextual dependencies.

3. **Difficulty with idioms, slang, and cultural expressions** (e.g., “speak of the devil,” “I’m dying of laughter,” etc.), which can easily lead to humorous or nonsensical translations.

> **The main purpose of pointing out these limitations is to set the stage for the upcoming discussion on pretrained large language models.**

### Attention Has Become a General Technique in Deep Learning

Today, Attention is no longer limited to seq2seq models or machine translation—it has become a universal technique in deep learning. Its general definition is as follows:

Given a set of value vectors \( H = [h_1, h_2, \dots, h_N] \) and a query vector \( q \):

1. Compute the dot product between \( q \) and each vector in \( H \) to obtain the attention scores of \( q \) with respect to \( H \).
2. Apply softmax to the score vector to obtain the attention distribution.
3. Use the attention distribution to compute a weighted average of \( H \), yielding the Attention output—a summary of \( H \) with respect to the query \( q \).
4. Attention has many variants; the key difference among them lies in how the attention scores are calculated.

![](https://www.waytoagi.com/api/kb-media/QXy0bBm3yo0JP1xvZk2ceEwvn4g)

> *I’ve folded the matrix operations for Attention because they are mostly pure mathematics. Feel free to expand them if you’re interested!*

### Matrix Operations for Dot-Product Attention

In Section 7.3, we first introduced the attention mechanism in the context of seq2seq. We learned that in Attention, the dot-product operation is used to calculate the relevance score between each position in the input sequence and the output sequence. In a seq2seq model, the vectors involved in the dot product are the hidden states at each time step of the Encoder and the Decoder.

Suppose we have two matrices: the matrix formed by the target sequence \( \mathbf{X} = [\mathbf{x}_1, \mathbf{x}_2, \ldots, \mathbf{x}_T] \) and the matrix formed by the query sequence \( \mathbf{Y} = [\mathbf{y}_1, \mathbf{y}_2, \ldots, \mathbf{y}_J] \), where \( \mathbf{x}_i \) and \( \mathbf{y}_j \) are the vectors in each sequence. In a more general attention mechanism, we need to compute the relevance score between each query vector \( \mathbf{y}_j \) and every position in the target sequence. To do this, we can define an attention score matrix \( \mathbf{A} \in \mathbb{R}^{J \times T} \):

$$
\begin{bmatrix}
a_{1,1} & a_{1,2} & \dots & a_{1,T} \\
a_{2,1} & a_{2,2} & \dots & a_{2,T} \\
\vdots & \vdots & \ddots & \vdots \\
a_{J,1} & a_{J,2} & \dots & a_{J,T}
\end{bmatrix}
$$

Each element in the first row represents the scalar obtained by taking the dot product between \( \mathbf{y}_1 \) and every element in \([\mathbf{x}_1, \mathbf{x}_2, \ldots, \mathbf{x}_T]\). Similarly, the \( k \)-th row contains the dot-product scores between \( \mathbf{y}_k \) and all elements of the target sequence.

This can be written compactly as:

$$
\mathbf{A} \in \mathbb{R}^{J \times T} = \mathbf{Y} \mathbf{X}^T
$$

As mentioned earlier, the dot product reflects the similarity between two vectors of the same dimension. If we apply softmax to each row of \( \mathbf{A} \), each row becomes a probability distribution representing how relevant the query vector \( \mathbf{y}_k \) is to each element in the target sequence:

$$
\text{softmax}\begin{bmatrix}
a_{1,1} & a_{1,2} & \dots & a_{1,T} \\
a_{2,1} & a_{2,2} & \dots & a_{2,T} \\
\vdots & \vdots & \ddots & \vdots \\
a_{J,1} & a_{J,2} & \dots & a_{J,T}
\end{bmatrix}
= \text{softmax}(\mathbf{Y}\mathbf{X}^T)
$$

Therefore, the computation of the attention mechanism is actually quite simple—it boils down to matrix multiplication.

We will see similar operations again in the self-attention layers of the Transformer, where they occur between the Key and Query matrices.

# The BERT and GPT of the RNN Era! Semi-Supervised Sequence Learning: How to Perform Self-Supervised Learning with Large Amounts of Unlabeled Data? (2015)

![](https://www.waytoagi.com/api/kb-media/Ee2Eb9F1IoZMxTx3B2WcrKrknfV)

**Self-Supervised Learning: For a given sample x, automatically generate an input x' and the corresponding expected output x'' (often the Ground Truth). The model produces output y based on x', then computes the cross-entropy loss between y and the Ground Truth x'', followed by backpropagation.**

In this chapter, we will introduce a very important paper. As we know, GPT stands for Generative **Pretrained** Transformer. In 2018, the introduction of GPT and BERT brought NLP into the era of **pretraining**. So what exactly is pretraining? And what is the pretraining + fine-tuning paradigm that we often talk about? We will explain these concepts clearly in Chapters 8 and 9.

Using semi-supervised learning / self-supervised learning to pretrain a language model was a truly brilliant idea in the RNN era of NLP. For the specific paper, see: [Semi-supervised Sequence Learning](https://arxiv.org/abs/1511.01432). **The following is the abstract of the paper:**

> We present two approaches that use unlabeled data to improve sequence learning with recurrent networks. The first approach is to predict what comes next in a sequence, which is a conventional language model in natural language processing. **The second approach is to use a sequence autoencoder, which reads the input sequence into a vector and predicts the input sequence again.** These two algorithms can be used as a "**pretraining**" step for a later supervised sequence learning algorithm. In other words, **the parameters obtained from the unsupervised step can be used as a starting point for other supervised training models.** In our experiments, we find that long short term memory recurrent networks after being **pretrained** with the two approaches are more stable and generalize better. With **pretraining**, we are able to train long short term memory recurrent networks up to a few hundred timesteps, thereby achieving strong performance in many text classification tasks, such as IMDB, DBpedia and 20 Newsgroups.

# This paper is extremely valuable. In 2015, when the Transformer model had not yet appeared and RNNs still dominated NLP, it was the first to propose a paradigm for pretraining RNNs through self-supervised learning on unlabeled data. In my opinion, it is the BERT and GPT of the RNN era.

## Pre-trained Models (Pre-trained Model, PTM)

#Note: Pre-training is not necessarily unsupervised, but in most cases, pre-training refers to unsupervised pre-training on large-scale datasets.

### Transfer Learning

- Transfer Learning is a machine learning technique that improves learning performance in a target domain and accelerates the learning process by applying a model trained in one domain **(source domain)** to another domain **(target domain)**.

- In traditional machine learning, it is usually necessary to collect a large amount of data in the target domain and train a model specifically for that scenario. However, labeled data for the target scenario may be scarce. Transfer learning leverages knowledge learned in the source domain. By transferring knowledge from one domain to another, it can solve problems such as data scarcity, labeling difficulties, or difficulty in model convergence in the target domain.

### Why Do We Need Pre-training?

#Transfer learning and pre-training are closely related concepts. Pre-training can be viewed as a specific form of transfer learning.

**Pre-training** refers to training a neural network on a large-scale dataset and using the trained model parameters as the initial parameters for downstream tasks.

On large-scale datasets, we can enable the neural network to learn a great deal of common (general) information. Then, based on this common knowledge (i.e., initializing the downstream task model with parameters trained on common information), we further train on smaller-scale, domain-specific data, allowing the model to perform well on specific tasks.

The following text is quoted from: [【NLP Pre-training】In-depth Understanding of “Pre-trained” Language Models](https://zhuanlan.zhihu.com/p/159620066) By [Pan Xiaoxiao](https://www.zhihu.com/people/pan-xiao-xiao-66-14)

> If I had to explain in one sentence what “pre-training” does, I would say: “Use as much training data as possible to extract as many common features as possible, thereby reducing the learning burden of the model on specific tasks.”

> If I had to summarize the idea of “pre-training” in one sentence, it would be:

1. Model parameters are no longer randomly initialized, but are pre-trained through certain tasks (such as language modeling).
2. The training task is broken down into two steps: common learning and specific learning.

### Strategies for Using Pre-trained Models in Downstream Tasks: Fixed Feature Extractor

#There are typically two strategies for using a pre-trained model in downstream tasks: one is to use it as a fixed feature extractor, and the other is fine-tuning.

- Fixed Feature Extractor means freezing the weights of the pre-trained model, using only its feature extractor to extract features from downstream task data, and then feeding those features into a model trained for the downstream task. In short, the original parameters are frozen, and only a new classification layer is trained. This strategy is suitable when the amount of data for the downstream task is small, as it helps avoid overfitting.

In computer vision (CV), people often use pre-trained CNNs as feature extractors for various downstream tasks. As mentioned in Chapter 3, CNN is a very commonly used model in CV. It is usually pre-trained on large-scale labeled image datasets (e.g., ImageNet) to learn general feature representations.

A pre-trained CNN model can serve as a general-purpose feature extractor. The approach is as follows:

1. In the downstream task, use the pre-trained CNN model as a feature extractor to obtain high-dimensional feature vectors from input images.
2. Based on these feature vectors, train a new classifier, detector, or segmenter to meet the requirements of the new task.
3. For image classification tasks, simple classifiers such as fully connected layers or SVMs can be used; for object detection tasks, techniques such as anchor boxes and Region Proposal Networks (RPN) can be employed; for image generation tasks, models such as Generative Adversarial Networks (GAN) can be used to generate outputs from the feature vectors.

### Strategies for Using Pre-trained Models in Downstream Tasks: Fine-Tuning

**Fine-tuning** is a transfer learning method that involves making small adjustments to some or all of the parameters of a pre-trained model to adapt it to a new task. Fine-tuning is generally performed under a supervised learning framework.

**The fine-tuning process typically includes:**

1. The parameters of the pre-trained model are usually initialized with the values from pre-training.
2. The model is further trained using labeled data from the downstream vertical task, while adjusting hyperparameters such as the learning rate to adapt the model to the specific task. Note: In this process, we adopt objective functions tailored to the downstream task.
3. During training, parameters are gradually adjusted to minimize the loss function of the downstream task, thereby achieving better performance on the specific task.

Fine-tuning the weights of a pre-trained model on new data can be performed across the entire neural network or only on a subset of layers. In the latter case, the layers that are not fine-tuned are referred to as **“frozen”**, meaning their parameters are not updated during backpropagation.

**Fine-tuning is a relatively complex engineering task that requires a lot of practical know-how:**

**1. Overfitting (Primary Challenge):**  
Fine-tuning typically involves training a pre-trained model on a relatively small dataset, which makes it highly prone to overfitting and results in poor performance on unseen data.

**2. Dataset:**  
Fine-tuning requires a large amount of labeled data. This data must be representative and diverse, fully reflecting the characteristics of the downstream task.

**3. Hyperparameter Tuning:**  
Fine-tuning requires careful adjustment of various model hyperparameters—such as learning rate, batch size, and regularization—to better adapt to the downstream task.

**4. Optimization Algorithms:**  
An optimization algorithm determines how to adjust the step size, direction, and other factors when updating parameters, with the goal of minimizing the value of the loss function. Stochastic Gradient Descent (SGD) is the most commonly used optimization algorithm. During fine-tuning, the model can either reuse the same optimizer employed during pre-training or select a different one tailored to the characteristics of the downstream task.

### Why Didn’t a CV-Style Pre-training Paradigm Emerge in NLP for So Long?

**Q: Before 2018, how was transfer learning applied in NLP?**

We know that it was not until 2018, with the emergence of ULM-FiT, GPT, and BERT, that the era of pre-trained models in NLP truly began. Only then did transfer learning methods comparable to those in computer vision (CV) become widespread in NLP. So, does this mean there was no transfer learning in NLP before 2018?

The answer is: this statement is quite inaccurate!

As we hinted in section 6.4.3, **word2vec** is actually the founding father of transfer learning in NLP. It leverages large-scale unlabeled text data to learn highly general-purpose word vector representations. Thanks to word2vec’s success, the transfer learning paradigm quickly became a standard practice in NLP.

**Q: Then why do we say that NLP never had a transfer learning paradigm similar to CV?**

- Although word2vec was one of the pioneers that introduced transfer learning to NLP, it primarily focused on word-level representation learning rather than model-level transfer for specific tasks. In other words, when facing a new NLP task, word2vec allowed us to quickly solve the two-layer neural network that converts tokens into word embeddings (for a vocabulary of V words, if each is represented by an N-dimensional dense vector, word2vec essentially learns a V×N matrix). But that was all.

For a very long time, NLP researchers still had to train entirely different models for each specific NLP task.

> “Although there are some pre-trained modules in NLP, such as pre-trained word vectors that are then fed into downstream models, they are used merely as input features. In NLP, there has never been a foundational model (including its architecture and weights) that could be directly transferred to a downstream task for fine-tuning. Instead, researchers design specialized network structures for different problems—such as POS tagging, NER, NMT, etc.—resulting in a fragmented landscape where each task operates in its own silo.”  
> ——Beeder in [CS224N(3.5) Multitask Learning | bitJoy](https://bitjoy.net/2020/03/14/cs224n%ef%bc%883-5%ef%bc%89multitask-learning/)

- In contrast, transfer learning in CV is often model-level. When tackling a new CV task, most of the feature extraction work can be handled by a previously pre-trained CNN. Engineers only need to add a fully connected layer on top or perform fine-tuning.

The convenience of using pre-trained models for transfer learning in the way CV does it has long been a cherished dream for NLP researchers.

**Q: So why did model-level transfer take so long to appear in NLP?**

**CV: Massive image datasets and tasks that are mostly classification-based**

- In computer vision, image datasets are extremely large and rich. For example, ImageNet contains millions of images. Many models are pre-trained on ImageNet and then transferred to specific tasks via fine-tuning.

- This approach works well because most CV tasks are fundamentally built on classification. Classification acts as the “building block” of CV. Therefore, a CNN classification model trained on ImageNet transfers effectively to many other CV tasks and delivers strong performance gains.

**NLP: Extremely high cost of text preprocessing and highly diverse task types**

- Text data usually requires preprocessing steps such as tokenization, part-of-speech tagging, and named entity recognition. These steps are very costly, which is why natural language datasets have historically been much smaller.

- The inherent complexity of language further increases the difficulty of training pre-trained models. In section 6.2 we covered many fundamental NLP tasks, and in 6.3.3 we outlined numerous expectations for language models. All of this illustrates how complex language is. Unlike CV, which largely revolves around recognition + classification, NLP tasks are far more varied.

- As a result, early NLP research mainly focused on hand-crafted features and model architectures—such as bag-of-words and n-gram models for text classification, or recurrent neural networks and LSTMs for sequence modeling. Without a universal, plug-and-play pre-trained model, NLP scholars spent a great deal of time “reinventing the wheel.” Compared to CV, the field remained at a relatively primitive stage for a long time.

## Paper Model Architecture: Sequence Autoencoder and Language Model

In the paper we are introducing, the authors designed two methods to pre-train an LSTM network.

> We present two approaches that use unlabeled data to improve sequence learning with recurrent networks. The first approach is to predict what comes next in a sequence, which is a conventional language model in natural language processing. The second approach is to use a sequence autoencoder, which reads the input sequence into a vector and predicts the input sequence again.

If the LSTM is initialized with pre-trained parameters from a language model, it is called **LM-LSTM**; if it is initialized with pre-trained parameters from a sequence autoencoder, it is called **SA-LSTM**.

---

### Language Model: LM-LSTM

The language model is very straightforward — it simply predicts the next word based on an existing sequence of words.

> > I hope everyone doesn’t confuse this concept: a language model is not just a final model (like GPT-3). **The language model itself is the pre-training task! “Predicting the next word” is by itself a very important pre-training task.**

- A standard LSTM language model consists of three parts: an input layer, an LSTM layer, and an output layer. The input layer receives the input sequence and converts it into embedding vectors. The LSTM layer is a standard LSTM unit that receives the sequence of input vectors and generates the corresponding sequence of hidden states. The output layer takes the hidden states from the LSTM layer as input and generates the next-word prediction at each time step.

- What distinguishes LM-LSTM from a standard LSTM is that it also includes a language modeling component, which predicts the text sequence in an unsupervised manner. Because it is self-supervised learning and a complete word sequence is available from the start, LM-LSTM uses a bidirectional LSTM to generate contextual vectors at each time step, then uses these vectors to predict the word at the current time step. This language model can be used in semi-supervised learning to pre-train the LM-LSTM using unlabeled text data.

### Sequence Autoencoder (SA-LSTM)

#### Sequence Autoencoders Are Inspired by seq2seq

The sequence autoencoder approach draws inspiration from seq2seq models. <The previous section mentioned the application of seq2seq in Neural Machine Translation (NMT). In fact, seq2seq is a very powerful framework and has also been used for text parsing, image captioning, video analysis, speech recognition, dialogue modeling, and many other tasks.>

The key idea of seq2seq is to use a recurrent network as an encoder to read the input sequence into a hidden state, which then serves as input to a decoder recurrent network that predicts the output sequence. In Chinese-to-English neural machine translation, the encoder encodes the Chinese sentence, and the decoder attempts to reconstruct the original sequence in English. **So the question is: what if we don’t make the decoder generate something new, but instead ask it to reconstruct the original input sequence itself using the vector produced by the encoder?**

This is exactly the idea behind the sequence autoencoder. Compared with traditional seq2seq, the sequence autoencoder is an **unsupervised** learning model whose goal is to reconstruct the input sequence itself (so the loss function can be computed and gradients can be updated without any additional labeled data). In a sequence autoencoder, **the decoder network and the encoder network share the same weights**.

#### The Unsupervised Nature of Sequence Autoencoders

An important feature of the sequence autoencoder is that it is unsupervised, so it can be trained on large amounts of unlabeled data to improve its quality. The paper shows that additional unlabeled data can enhance the generalization ability of recurrent networks.

![](https://www.waytoagi.com/api/kb-media/Sv4ZbCwBeocDdxxOg51cVpVwnMh)

What effect does the sequence autoencoder produce? See the following excerpt:

> We find that the weights obtained from the sequence autoencoder can be used as an initialization of another supervised network, one which tries to classify the sequence. We hypothesize that this is because the network can already memorize the input sequence.

In other words, the weights obtained from a sequence autoencoder trained via unsupervised learning can be used to initialize another supervised sequence classification network. The authors hypothesize that this works because the RNN in the sequence autoencoder has already memorized the input sequences it was fed.

### Semi-supervised Pre-training: Joint Training with Labeled and Unlabeled Data

- **Semi-supervised pre-training** refers to using both labeled and unlabeled data for pre-training at the same time. The goal is to leverage labeled data to help the model learn better representations from unlabeled data, thereby improving overall performance.

- Taking LM-LSTM as an example, the model can process both labeled and unlabeled data simultaneously and improve performance through joint training. If we want to train an LSTM for sequence labeling, the LM-LSTM can use the labeled data to train the sequence labeling task while using the unlabeled data to train the language modeling component. Through joint training, LM-LSTM can learn richer feature representations from the unlabeled data, ultimately improving performance on the sequence labeling task.

---

**Welcome to the Sesame Street Family! Illustrated Guide to ELMo: A New Era of Embeddings (Feb 2018)**

![](https://www.waytoagi.com/api/kb-media/Ag7PbiTXFoelXpxXO9Ucx8LtnPg)
The famous character in the picture is none other than ELMo! Here is the paper where ELMo was born: [Deep contextualized word representations](https://arxiv.org/abs/1802.05365). Hi ELMo!

![](https://www.waytoagi.com/api/kb-media/Dd1DbcpgBoDmJ4xVqzecivejnub)
ELMo is a character from the famous American children’s show *Sesame Street*.

Later, BERT became another character from the same show. Together they launched the “Sesame Street series” in NLP, where researchers playfully name their models after Sesame Street characters.

> *(The blue Cookie Monster hasn’t been claimed by any model yet — it’s waiting for you to create one 🥳! In this article, however, we’ll use it to represent ULMFiT.)*

## The Significance of the ELMo Model

> The second generation of pre-trained models is centered on **context-aware** representations. This means that the word “apple” produces different outputs when it refers to the fruit versus the company. Representative models of this era include ELMo, GPT, BERT, and others.

ELMo stands for **E**mbeddings from **L**anguage **Mo**del. While the acronym feels a bit forced, the paper’s title — *Deep contextualized word representations* — truly captures its core contribution.

> *This article draws heavily from the translation by CSDN user @Anna: [The Illustrated BERT, ELMo, and co. (NLP Transfer Learning)](https://blog.csdn.net/qq_36667170/article/details/125714948).*

### Limitations of word2vec

As mentioned earlier, word2vec is a word-level representation learning method that can be used across various tasks. GloVe is another similar approach.

Take the word `stick` as an example. It has a huge number of different meanings:

![](https://www.waytoagi.com/api/kb-media/XHNfbZtzlo566dxjFqkc1KhDnag)

If we use word2vec or GloVe embeddings, no matter what the surrounding context is, the word `stick` is always represented by the **same fixed vector**. In other words, we have only one embedding per word, even though the word can carry many completely different meanings.

This is actually quite limiting. So many researchers pointed out: “*stick* has multiple meanings, and which meaning it has depends on its context. The `stick` in ‘Let’s stick to the plan’ and the `stick` in ‘He picked up a stick’ are clearly different, yet they are mapped to the exact same vector. Why don’t we generate embeddings **based on the context**? That way we can capture both the meaning in the current context and information from other possible contexts.”

### Contextualized Word Embeddings

Contextualized word embeddings assign different vector representations to a word depending on the specific meaning it carries in a given sentence.

When you ask ELMo “What is the embedding of *stick*?”, it will not give you a single fixed answer like word2vec does. ELMo does **not** use a fixed embedding for each word. Instead, it considers the entire sentence before computing the embedding for every word.

![](https://www.waytoagi.com/api/kb-media/GG8jb2LPXoPxAPxTfiSc9jcbnOc)

The ELMo model uses a bidirectional LSTM (bi-LSTM) that has been pre-trained on a large corpus to generate these contextualized embeddings.

## ELMo Model Architecture

**References:**  
[A Review of Deep Contextualized Word Representations (Peters, 2018) – PPT](https://www.slideshare.net/shuntaroy/a-review-of-deep-contextualized-word-representations-peters-2018)

[Introduction and Comparison of Classic NLP Models such as ELMo and GPT](https://blog.csdn.net/weixin_39574469/article/details/119741048)  
By CSDN user [Zhang Xiaozhu de Jia](https://blog.csdn.net/weixin_39574469)

![](https://www.waytoagi.com/api/kb-media/ZBLMbIJOFooOXSxZAREcaQN0nqd)

- As seen from the architecture diagram above, ELMo consists of three main modules at a high level:
  - The bottom yellow **Embedding** module.
  - The middle blue **two-layer bidirectional LSTM** module.
  - The top green **contextual word representation** module.

### Character Embeddings Layer

The ELMo model uses character embeddings to represent each word. These embeddings are generated through a Convolutional Neural Network (CNN).

The CNN in ELMo is primarily used to extract character-level features from the input text. These features can capture prefix and suffix information within words, thereby improving the expressive power of the word vectors. Specifically, ELMo employs a convolutional layer with multiple filters, each corresponding to a different character-level window size. By performing convolution on the input text, it extracts features from each character-level window. After pooling and concatenation, these features form a character-level feature vector of the same length as the input text, which serves as one of the inputs to the LSTM network.

For more on CNN applications in NLP, see: [CS224N (2.12) Convolutional Networks for NLP | bitJoy](https://bitjoy.net/2019/08/05/cs224n%ef%bc%882-12%ef%bc%89convolutional-networks-for-nlp/) by Beeder.

### Bidirectional LSTM Layer

ELMo uses a bidirectional LSTM (Bi-LSTM) to capture the semantic information of words within their context. The Bi-LSTM scans the input sequence from both left-to-right and right-to-left, allowing it to consider both forward and backward contextual information simultaneously, thus generating context-dependent word vectors.

> Note: BERT, which will be discussed later, is also described as “bidirectional,” but the two approaches are fundamentally different.

In the ELMo model, the Bi-LSTM layer consists of two independent LSTM units that model the input text in the forward and backward directions respectively, producing two separate hidden state sequences.

- This module in ELMo is divided into left and right parts, essentially forming a bidirectional language model (LM):
  - For the left half, given N tokens [t₁, t₂, …, tₙ], the Language Model computes the probability of the k-th token based on the preceding k-1 tokens, forming a forward two-layer LSTM.
  - Similarly, for the right half, given N tokens [t₍k₊₁₎, t₍k₊₂₎, …, tₙ], the Language Model computes the probability of the k-th token based on the following N-k tokens, forming a backward two-layer LSTM.

The hidden state sequences from the forward and backward LSTM units are then combined to form a single hidden state sequence that contains bidirectional contextual information.

### Contextualized Word Embeddings Layer

ELMo obtains the final contextualized word vectors by concatenating the character embeddings with the outputs of the bidirectional LSTM layers and applying a linear transformation. These word vectors can dynamically adjust according to the specific context of the input sentence, thereby capturing the semantic nuances of words across different contexts.

### Output Layer

ELMo can be adapted to specific NLP tasks (such as text classification, named entity recognition, etc.) by adding task-specific output layers — such as fully connected layers or Softmax layers — on top of the contextualized word vectors.

Because ELMo provides downstream tasks with feature representations for each word, this category of pre-training methods is known as **“Feature-based Pre-Training.”**

## Summary of ELMo

The core idea of ELMo is a language model that dynamically adjusts word embeddings based on the current context. It adopts a bidirectional two-layer LSTM architecture overall and uses a two-stage process for pre-training:

**Stage One:** Pre-training using a language model to obtain basic static word vectors and a bidirectional two-layer LSTM network.

**Stage Two:** In a contextual environment, the context is fed into the bidirectional two-layer LSTM to produce dynamically adjusted word embeddings. This effectively integrates the word with the semantics of its context, allowing for a more accurate representation of the word’s true meaning.

> ELMo brought significant improvements over traditional static word embedding methods (Word2Vec, GloVe), but it still has clear limitations and plenty of room for improvement. The two main shortcomings are:

> First, a very obvious drawback lies in the choice of feature extractor. ELMo used a bidirectional two-layer LSTM rather than the now-dominant Transformer, so its feature extraction capability is comparatively weaker. If ELMo had used a Transformer as its feature extractor, BERT’s reception at the time would likely have been far less explosive.

> Second, ELMo performs feature fusion by simply concatenating the bidirectional representations. This approach is clearly inferior to BERT’s unified bidirectional feature extraction.

> By CSDN user [Zhang Xiaozhu de Jia](https://blog.csdn.net/weixin_39574469)

---

# Attention Is All You Need! The Cornerstone of Large Language Models — Transformer (2017)

**Prerequisite Knowledge:** [**Seq2seq and Attention Mechanism**](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#ZWSwdmWQaoGAQuxkOEHcuD5UnVl)

# Many years later, when facing AGI, NLP practitioners will remember that distant afternoon when Google took them to see the Transformers.

# You’re right, but “Transformer” is a brand-new open-world adventure game independently developed by Google. I forgot the middle part, but basically, those chosen by AGI must harness the power of multi-head attention to gradually uncover the truth that “more power equals more miracles.”

So why did the paper that introduced the Transformer get the title [Attention Is All You Need](https://arxiv.org/abs/1706.03762)? After seq2seq popularized the Attention mechanism, the dominant architecture in NLP became recurrent neural networks (typically LSTM) plus an attention mechanism, where attention played only a supporting role. However, no matter how advanced it was, LSTM remained a variant of RNN. Its inability to be trained in parallel and fully leverage GPU advantages resulted in very slow training, making it impossible to “brute-force” an extremely large language model.

The Transformer model was extremely radical: it completely discarded the RNN that had served as the main body of the model and retained only the attention mechanism. That is the origin of this title. It must be said that NLP researchers can be quite opportunistic. After “Attention Is All You Need” became a hit, everyone started riding the wave by publishing papers titled “XX Is All You Need.” Any paper using this format had a much higher chance of trending 🤯. Let’s refuse to chase hype — starting with me!

![](https://www.waytoagi.com/api/kb-media/WnYQbQ5XTouk1bxFk1JcbtRZnnc)
Are you the Transformer that solved the efficiency problem of RNN’s sequential training and has since dominated the field of deep learning? (The Google team originally intended the name to evoke an electrical transformer, but everyone immediately thought of the robots…)

![](https://www.waytoagi.com/api/kb-media/DuBkbaNiRoFDiAxnxMocX74hnvh)
Sorry for the interruption — it’s this one! At first glance, the model architecture looks a bit intimidating, but don’t worry. We’ll break it down clearly in the following sections!

## Transformer Overall Architecture

The diagram above shows the overall structure of the Transformer, but it can look overwhelming at first glance. Let’s start with the simplified version below:

![](https://www.waytoagi.com/api/kb-media/QdB2bvjpioIDJZx9FBkcg5yunlh)

Image source: [Zhihu - Detailed Explanation of the Transformer Model (Most Complete Illustrated Version)](https://zhuanlan.zhihu.com/p/338817680), by Zhihu user [Chushi CV](https://www.zhihu.com/people/AI_team-WSF)

In the original paper *[Attention Is All You Need](https://arxiv.org/abs/1706.03762)*, the Transformer consists of six encoders and six decoders, forming a relatively deep network. Initially, the Transformer was primarily used for neural machine translation tasks, so we will use neural translation as the running example. Later, we will see various modifications to the Transformer (Encoder-Only or Decoder-Only) that adapt it for text generation (GPT) or other downstream tasks (BERT).

### Encoder Structure: Self-Attention Layer + Feed-Forward Neural Network Layer

From this point on, most of the diagrams we reference come from *[The Illustrated Transformer](http://t.csdn.cn/YFjLF)* by Ann's Blog.

![](https://www.waytoagi.com/api/kb-media/KBX3bkJioo9wkixxyMZcKLc6n8b)

> The six encoder layers have identical structures, but they do **not** share weights. Each encoder can be divided into two sublayers.

> The input to the encoder (x_i) first passes through a self-attention layer. The purpose of this layer is to help the encoder, when encoding a specific word, attend to other relevant words in the sentence. We will explain this in detail later.

> The output of the self-attention layer (z_i) is then fed into a feed-forward neural network. Each encoder uses a feed-forward network with the **same architecture** (though the parameters are not shared across encoders).

### Decoder Structure: Masked Self-Attention Layer + Self-Attention Layer + Feed-Forward Neural Network

The decoder also contains the two layers found in the encoder, with one additional attention layer inserted between them. This extra self-attention layer receives the hidden states from the encoder’s output and performs a function similar to the attention mechanism in traditional seq2seq models (don’t worry if you’ve forgotten — we’ll illustrate it very clearly later).

![](https://www.waytoagi.com/api/kb-media/LpfmbCvnCo8mIIxAGp8c5R7ynxZ)

In the decoder, the first Self-Attention layer differs from the one in the encoder. It is a **masked** self-attention layer. The masking ensures that, when translating the K-th word in a sequence of N words, the self-attention mechanism can only attend to words from position 1 to K, and cannot see words from position K+1 to N. We will use a diagram later to clearly show what “masking” means.

## Encoder Introduction

### Input Embedding: How to Encode Tokens?

#### Word Embedding

> Like other NLP projects, we first need to convert each input word into a corresponding vector through word embedding.

> In the original *Attention is All You Need* paper, they used 512-dimensional word embeddings. For easier illustration here, we use 4 cells to represent the 512-dimensional word vectors.

![](https://www.waytoagi.com/api/kb-media/V7YLbNSQsoLEHMx64Gocwu1Rnob)

#### Positional Encoding (PE)

The encoder in Transformer not only uses the word embedding itself, but also adds an additional embedding based on position (Positional Encoding) for each word. This has the same dimension as the word embedding. The final input to the Transformer is the sum of these two embedding vectors.

This is because Transformer radically abandons RNN, which has built-in sequential processing capability, while Attention itself carries no sequential information (using self-attention to achieve global attention does not equal having sequential information! Global does not equal sequential).

> Transformer does not use an RNN structure. It uses global information and therefore cannot utilize the order information of words. However, order information is very important for NLP. Therefore, Transformer uses positional embeddings to preserve the relative or absolute position of words in a sequence.

Through Positional Encoding, the model can determine the position of each word or the distance between different words.

![](https://www.waytoagi.com/api/kb-media/HD8ebkEKRotsSJxpw3AcDZo3nHb)

Positional encoding needs to satisfy the following: each position has a unique encoding; no matter how long the sentence is, the distance between any two adjacent positions remains consistent; all encodings must lie within a finite range, and the numbers used in the encoding must not explode (this is actually really hard to achieve!).

> Specifically, the positional encoding in Transformer is implemented as follows:

![](https://www.waytoagi.com/api/kb-media/F7NFbwapiotmuGxaUSPcP3wynBd)

> It is a vector of the same dimension as the word embedding, composed of alternating sine and cosine functions.

For a more detailed explanation, refer to: [【CSDN】Transformer Structure: Detailed Explanation of Positional Encoding](https://lolitasian.blog.csdn.net/article/details/124336971) by Anna's Blog. However, I believe that unless you are doing academic research, there is no need to study this in depth.

### Self-Attention Layer: A Closer Look at the Self-Attention Mechanism

In section 7.3.3, we mentioned the role of the attention mechanism. Let’s mention it again here.

> Say the following sentence is an input sentence we want to translate:

> ” `The animal didn't cross the street because it was too tired` ”

> What does “it” in this sentence refer to? Is it referring to the street or to the animal? It’s a simple question to a human, but not as simple to an algorithm.

> When the model is processing the word “it”, self-attention allows it to associate “it” with “animal”.

> As the model processes each word (each position in the input sequence), self-attention allows it to look at other positions in the input sequence for clues that can help lead to a better encoding for this word.

> If you’re familiar with RNNs, think of how maintaining a hidden state allows an RNN to incorporate its representation of previous words/vectors it has processed with the current one it’s processing. Self-attention is the method the Transformer uses to bake the “understanding” of other relevant words into the one we’re currently processing.

To stay in sync with Jammar’s popular article [The Illustrated Transformer](http://jalammar.github.io/illustrated-transformer/) (and to continue using the high-quality diagrams he created), we will use the same short example sentence from the original post — `Thinking Machine` — and walk through what happens in each sub-layer of the encoder.

#### For each input matrix to the Encoder, compute three matrices: Query, Key, and Value

In section 7.4.3, we introduced the fact that the dot-product operation in the attention mechanism is essentially a matrix operation (and matrix operations are highly parallelizable, making training on GPUs extremely fast). However, let’s temporarily set matrices aside and focus on what happens at the vector level.

# Why is it called Self-Attention?

In the previous seq2seq attention mechanism, the two vectors used for the dot product to compute the Attention Score came from the encoder and the decoder respectively. In the Transformer’s self-attention layer, both vectors being dotted come from the encoder (or the decoder).

For each input vector (512-dimensional), we multiply it by a 512×64 weight matrix, resulting in a 64-dimensional vector.

(The four squares we used earlier represent a 512-dimensional vector; we will keep this visual convention going forward. As shown in the figure on the right, the vectors in Q, K, and V are represented by three squares, where three squares stand for a 64-dimensional vector. This convention will be used throughout!)

In the encoder’s self-attention layer, we train three **weight-unshared** 512×64 matrices: $W^Q$, $W^K$, and $W^V$. For each input vector to the encoder, we multiply it by these three matrices respectively to produce three 64-dimensional vectors: the Query vector, the Key vector, and the Value vector.

![](https://www.waytoagi.com/api/kb-media/MZTobUEU8oRPt1xhoxycDr9XnJb)

#### Compute Attention Scores: Dot Product of Query and Key

![](https://www.waytoagi.com/api/kb-media/RoYTbJj5goaICExeXKXcQRvPnvd)

In the Transformer’s self-attention layer, assume there are N input embeddings: $[x_1, x_2, ..., x_N]$. For the $k$-th input $x_k$, the vectors involved in the dot product are: the query vector $q_k$ corresponding to $x_k$, and all N Key vectors from the inputs: $k_1, k_2, ..., k_k, ..., k_N$.

Taking the two-word input “Thinking Machine” as an example, the query vector for “Thinking”, $q_1$, will be dotted with the Key vectors corresponding to every word in the sentence ($k_1$ and $k_2$), producing the attention score of the word “Thinking” with respect to every word in the sentence.

#### Compute the Attention Distribution

The standard way to obtain the attention distribution is to apply a softmax to the attention scores. However, in the original Transformer paper, the authors first divide the attention scores by 8 (the square root of the dimension of the Q, K, and V vectors). This is because the scalar resulting from the dot product of two 64-dimensional vectors can be quite large. If we applied softmax directly without scaling, the resulting Attention Distribution would be overly concentrated on the word itself, which is not what we want. We still want the model to capture the relationships between the current word and other words in the sentence. In short, dividing by 8 is largely an engineering heuristic based on practical experience.

![](https://www.waytoagi.com/api/kb-media/H0KcbYLivodFCTxKbxVc4mj0nWY)

#### Multiply the Value Matrix by the Attention Distribution Matrix to Obtain the Final Output

As mentioned in 7.3.3.2, since the attention distribution is a probability density function, the attention output $a_t$ is conceptually very similar to a mathematical expectation.

The self-attention layer in the Transformer follows the same principle. In the previous step, we obtained the Attention Distribution: P(Thinking) = 0.88, P(Machine) = 0.12. Finally, we multiply this probability distribution by the corresponding Value vectors of each word.

**Final output of the word “Thinking” — z₁**  
is obtained by weighting all word values (v₁, v₂, …) according to their attention coefficients:

**z₁ = 0.88v₁ + 0.12v₂**

### Using Matrix Operations to Compute Attention for the Entire Input in Parallel

In sections 12.2.2.1–12.2.2.4 we illustrated the calculations using vector-level operations. Now we will show how to compute the **z** vectors for the entire input sequence efficiently using matrix operations.

As shown in the figure below, the first and second rows of the green matrix **X** are the embeddings for “Thinking” and “Machine”, respectively. For a sequence containing **N** tokens, instead of multiplying one 512-dimensional vector at a time by a 512×64 weight matrix, we can directly multiply an **N×512** matrix by a **512×64** matrix, yielding an **N×64** matrix in one shot.

In the purple matrix below, the first and second rows are the Query vectors for “Thinking” and “Machine”. The same applies to the Key (**K**) and Value (**V**) matrices.

![](https://www.waytoagi.com/api/kb-media/VGBcbzXxPorjWpxfulWcPrswnlf)

<This diagram illustrates the entire computation process described in 10.2.2.1>

In section 7.4.3 we introduced that the dot-product operation in attention is essentially a matrix multiplication. In seq2seq models, we multiply the query matrix (the decoder’s hidden state **s** at each time step) by the transpose of the target matrix (all encoder hidden states **h**), apply softmax to each row to obtain a probability distribution, and then multiply the resulting matrix by the target matrix itself (all encoder hidden states **h**).

The Transformer differs in that the query matrix **Q** is multiplied by the transpose of the key matrix **Kᵀ**, scaled by dividing by 8 (i.e., √64), and then multiplied by the value matrix **V** composed of all word value vectors. The resulting **Z** matrix has “Thinking” and “Machine” in its first and second rows, corresponding to **z₁** and **z₂** respectively.

![](https://www.waytoagi.com/api/kb-media/MDthbwhVwoTkLQxcFyfco2wjnec)

<This diagram covers all the computation steps from 10.2.2.2 to 10.2.2.4>

Matrix multiplication has excellent parallelism, making training extremely fast!

![](https://www.waytoagi.com/api/kb-media/SvAJbPmDWodS52x4m8scWnNinYb)

### Illustrated Explanation of Multi-Head Self-Attention

Now that we understand Self-Attention from section 10.2.2, what exactly is “Multi-Head”?

> The paper further refined the self-attention layer by adding a mechanism called “multi-headed” attention. This improves the performance of the attention layer in two ways:

1. It expands the model’s ability to focus on different positions. Yes, in the example above, z₁ contains a little bit of every other encoding, but it could be dominated by the actual word itself. If we’re translating a sentence like “The animal didn’t cross the street because it was too tired”, it would be useful to know which word “it” refers to.

**2. It gives the attention layer multiple “representation subspaces”.** As we’ll see next, with multi-headed attention we have not only one, but multiple sets of Query/Key/Value weight matrices (the Transformer uses eight attention heads, so we end up with eight sets for each encoder/decoder). Each of these sets is randomly initialized. Then, after training, each set is used to project the input embeddings (or vectors from lower encoders/decoders) into a different representation subspace.

---

**My understanding of the above passage (quoted from [The Illustrated Transformer](http://jalammar.github.io/illustrated-transformer/)) is as follows:**

When the model translates a particular word, its attention mechanism will of course focus heavily on the word itself. However, we want the model to also pay attention to other words in the context. Contextual relationships come in many forms: pronoun references like “it”, subject-verb agreement (singular/plural “are”), tense information (“were”), and even the fact that the same word can carry different meanings depending on its context (think ELMo and the word “Stick”). 

If we train multiple different combinations of weight matrices $\{W\}^Q$, $\{W\}^K$, and $\{W\}^V$, and let each combination specialize in a particular type of relationship — some handling coreference, some handling tense, some disambiguating word meanings based on global context — that is, **if we allow them to explore different representation subspaces**, wouldn’t the model perform better?

Therefore, simply put, **multi-head attention means we train several different sets of weight matrices $\{W\}^Q$, $\{W\}^K$, and $\{W\}^V$.**

In the original *Attention is All You Need* paper, the Transformer uses 8 attention heads. Let’s first illustrate the concept with two heads:

![](https://www.waytoagi.com/api/kb-media/CRI9bjbasou2YqxldakcvOGbn9b)

For the same input “Thinking Machine”, we have 8 sets of weight matrices, which ultimately produce 8 different Z matrices:

![](https://www.waytoagi.com/api/kb-media/QtxgbgrH4o77Q4xu4uoch8pjnxf)

We concatenate these matrices to form a 2×512 matrix, then multiply it by a final output weight matrix $W^O$.

In the example below, $W^O$ is a 512×512 matrix. After multiplication, we obtain a 2×512 matrix Z — the same shape as the original input.

![](https://www.waytoagi.com/api/kb-media/GnoLbAQAEozi3uxdhQrcJrXpnwh)

### Summary: What Happens Inside the Self-Attention Layer?

- **Input**: One-hot vectors. Assuming a vocabulary of 30,000 words, each word is represented as a 30K-dimensional vector with a 1 in the position corresponding to that word and 0s everywhere else.

- **Embedding Layer**: The one-hot vector is multiplied by an embedding matrix to project it into a 512-dimensional word vector, then a positional embedding is added.

- **Self-Attention Layer**: For each input word embedding, we multiply it by three weight matrices to obtain Q, K, and V. The Q vector of each word is then dotted with every K vector in the sentence (K1, K2, …, Kn), producing an n-dimensional vector (where n is the sentence length). We scale the values by dividing by 8 (i.e. $\sqrt{64}$), apply softmax to obtain an **Attention Distribution**. This distribution reflects how relevant each word in the sentence is to the current word. We then compute a weighted sum of the V vectors using this distribution as weights, resulting in the output vector Z. Z contains information aggregated from the entire sentence at the current timestep.

- **Multi-Head Attention**: We train multiple different sets of weight matrices, concatenate their results, and thereby increase both the dimensionality of the information collected and the robustness of the representation.

![](https://www.waytoagi.com/api/kb-media/AzDDbcPwVow5ySxy5OZcLccFnSb)

The final output of the self-attention layer is an N×512 matrix, which is then fed into the feed-forward neural network. **As you can see, its shape is identical to the input matrix.** In other words, a multi-head self-attention layer does not change the shape of its input.

The FFNN is just a standard fully connected layer, essentially the same as what was introduced in section 2.1.4, so we won’t go into further detail here.

It also does not change the shape of the input. In short, when you input a tensor of shape `(batch_size, seq_length, embed_dim)` into an Encoder Block, the output is also a tensor of the same dimensions.

**Decoder Introduction**

The structure of the decoder was already shown in section 10.1.2, so we will not repeat it here.

Like seq2seq, the decoder in Transformer is essentially a language model. Its job is to consider both the information from the current time step and the information provided by the Encoder, then generate the output autoregressively, one token at a time.

Since it is also an autoregressive language model, the **Teaching Force** and scheduled sampling mentioned in 7.2.2, as well as the **Beam Search** mentioned in 7.2.3, are equally applicable to the Decoder. We will not repeat those explanations here.

![](https://www.waytoagi.com/api/kb-media/RJGxbAutJoe1IHxD3hkcfGfmn6e)

Some details of the Decoder model require more context to explain clearly. So now, let’s try to translate “I have a cat” into Chinese.

### Decoder Layer 1: Masked Multi-Head Self-Attention

The self-attention layer in the decoder is different from the one in the encoder. In the decoder, the self-attention layer is only allowed to attend to information from already-generated positions. Therefore, it is called **“masked self-attention.”**

> The first Multi-Head Attention in the Decoder block uses a Masked operation because translation is performed sequentially — you can only translate the (i+1)-th word after the i-th word has been translated. The masking prevents the i-th word from seeing information from future words.

The masking is mainly implemented during the Softmax step.

If we want to translate “I have a cat” into Chinese, we can still compute the matrix multiplication between Q and K^T, which gives us a 4×4 matrix.

![](https://www.waytoagi.com/api/kb-media/AVTMbnZdVoVnzaxVDC2cuc54nJb)

Normally, for a matrix like this:

$$
\begin{bmatrix}
a_{I,I} & a_{I,Have} & a_{I,a} & a_{I,Cat} \\
a_{Have,I} & a_{Have,Have} & a_{Have,a} & a_{Have,Cat} \\
a_{a,I} & a_{a,Have} & a_{a,a} & a_{a,Cat} \\
a_{Cat,I} & a_{Cat,Have} & a_{Cat,a} & a_{Cat,Cat}
\end{bmatrix}
$$

we would directly apply softmax (see 10.2.2.5). However, in the decoder we perform the following operation:

![](https://www.waytoagi.com/api/kb-media/UFkrbZorNoIxXRxp2xZcRdpwnnb)

The self-attention layer is only allowed to attend to already-generated positions. Therefore, for the dot products between generated and future positions (the black cells in the figure above), we add a very large negative value (in GPT, this is -1e8) before softmax. This forces the softmax output for those positions to become 0. In this way, when generating the current time step, the decoder cannot attend to information from future tokens.

Ultimately, we obtain a 4×64 matrix. This matrix is directly passed as the Query matrix to the next layer — the Encoder-Decoder Attention. The first column (the z-vector for “I”, which also serves as the query vector for “I” in the next attention layer) contains only information about “I”.

| ![](https://www.waytoagi.com/api/kb-media/ErSbbKRyvoBIu7xzHBdcAs0hngc) | ![](https://www.waytoagi.com/api/kb-media/QgI9bK35TomR6LxYOXvcL0XXnVe) |
| --- | --- |

<This diagram is also very intuitive.>

**The decoder also uses multi-head attention. So if we use 8 heads, we will get 8 such matrices. They will serve as the 8 Query matrices needed by the next layer of the decoder.**

### Decoder Layer 2: Multi-Head Encoder-Decoder Attention

Referring to the diagram on the right, the part inside the red box is the decoder. Assume N=6 and we are using 8-head attention.

The encoder first processes the input sequence. After passing through 6 Encoder layers, the sixth encoder outputs a tensor. This tensor is equally distributed to the second attention layer of every Decoder block, where it is transformed through a shared weight matrix C into 8 Key matrices and 8 Value matrices.

![](https://www.waytoagi.com/api/kb-media/JFCLb0rsuoMTQxxtXoocUKlcnKd)

In this layer, the decoder component uses the 8 Z matrices produced by its own masked self-attention layer from the previous step as the 8 Query matrices. It then performs the multi-head attention computation we described earlier, using the 8 Key and Value matrices passed from the encoder.

![](https://www.waytoagi.com/api/kb-media/G0vVbbtbSoujQnxtRAJcXgsnnmc)

<Because this layer uses both the output from the previous decoder layer and the encoder’s output, it is no longer called self-attention.>

After passing through two multi-head attention layers, the output goes through a fully connected feed-forward layer, and the resulting vector is passed to the final Linear + Softmax layer.

### Final Step of the Decoder: Next Token Prediction

> The Decoder outputs a floating-point vector. How do we turn it into a word? This is what the final linear layer and softmax are responsible for.
> The linear layer is a simple fully connected neural network that maps the vector produced by the decoder into a logits vector.
> The softmax layer then converts these scores into probabilities (all positive values that sum to 1.0). The word at the position with the highest probability is selected as the output for the current time step.

Just like in seq2seq, the output of the current time step in the Transformer decoder becomes the input to the next time step.

![](https://www.waytoagi.com/api/kb-media/YkNbbGNffoWzs9xX2NucleMSnkd)

**Transformer Model Summary**

### Tunable Hyperparameters in the Model

There aren’t actually that many hyperparameters to tune in a Transformer.

1. The dimensionality of the word embeddings.
2. The number of layers in the encoder and decoder respectively. If there is no encoder, it becomes a Decoder-Only architecture (GPT). If there is no decoder, it becomes an Encoder-Only architecture (BERT).
3. The number of attention heads.

### Overall Forward Pass Steps

**Encoder:**

- Input: Based on one-hot encoding. If the vocabulary size is 30,000, the input for a single word is a 30K-dimensional vector where the element corresponding to that word is 1 and all others are 0. For an entire sentence, the input becomes a matrix.

- Word Embedding layer: The one-hot vector is multiplied by an embedding matrix and projected into a 512-dimensional word vector. In addition, positional encoding — a vector of the same dimension using alternating sine and cosine values — is added directly to the word embedding to produce the final input.

- Self-Attention layer: The input word vectors are multiplied by three weight matrices to produce Q, K, and V. The query vector Qk of the k-th input token is dotted with the key vectors K1, K2, …, Kn of all input tokens (the dot product yields a scalar), resulting in an n-dimensional vector (where n is the length of the input sentence). This vector is scaled by dividing by 8 (i.e. √d_k), passed through softmax to obtain an Attention Distribution. This distribution reflects how relevant the current token is to every other token in the sentence. The V vectors are then weighted by this Attention Distribution to produce the output vector Z. Z contains information aggregated from the entire sentence at the current timestep.

- Multi-Head Attention: Multiple independent self-attention layers are trained in parallel, and their outputs are concatenated. This increases the model’s ability to capture information across different representation subspaces and improves robustness.

- The output of the self-attention layer passes through a feed-forward network to produce a new vector, which is then passed to the next encoder layer. The final encoder layer’s output vectors are multiplied by a weight matrix C to generate the value matrix V and key matrix K for use by the decoder.

**Decoder:**

- Masked Multi-Head Self-Attention layer: In the decoder’s self-attention, any word after the current time step has a large negative value added to its score before the softmax. This forces its attention distribution to be zero. The final output tensor serves as the query matrix for the next layer. Since there are 8 attention heads, 8 different query matrices are produced.

- Encoder-Decoder Attention layer: This layer uses the 8 key matrices (K) from the encoder and the 8 query matrices (Q) from the previous decoder layer to compute attention scores. The resulting attention distribution is then used to weight the 8 value matrices (V) from the encoder.

- Output: The decoder generates tokens in an autoregressive manner — each output becomes the next input. The output stage can use greedy decoding or beam search.

(The loss function and backpropagation are omitted here. The loss function remains the cross-entropy loss.)

### What Makes Transformer So Powerful

- Unlike RNNs, both the self-attention layers and feed-forward layers in Transformer are matrix operations, enabling highly efficient parallel training. When performing NLP tasks, the degree of parallelism ranks as: CNN > Transformer ≫ RNN, while the ability to fuse information ranks as: RNN > Transformer ≫ CNN. Transformer is not dominated by any single architecture — and that may be exactly why it is so successful.

- Transformer itself has no inherent notion of word order. Positional embeddings must be added to the input; otherwise, it would simply be a bag-of-words model.

- The core innovation of Transformer is the Self-Attention mechanism, where the Q, K, and V matrices are obtained through learned linear transformations of the input. The idea of taking the dot product of something with itself and then multiplying by another version of itself is genuinely brilliant and not obvious.

- Multi-Head Attention in Transformer consists of multiple Self-Attention modules running in parallel, allowing the model to capture correlations between words across many different representational subspaces. Eight attention heads “sweep” information across eight different representation subspaces, giving the model extremely strong learning capacity.

### Evaluation of Transformer

- It has been adopted in nearly every NLP task, creating a paradigm shift comparable to what CNNs did for computer vision.

- It has been applied to almost every modality in machine learning — text, images, video — “everything can be a Transformer.”

- To achieve performance comparable to CNNs or RNNs, Transformer-based models typically require significantly more training data. Models based on Transformer are usually very large and computationally expensive. Although they dominate leaderboards and set new SOTAs, CNNs are still more widely used in the computer vision community in practice.

- In reality, “Attention Is Not All You Need” (just as “The Document Is Not All You Need” — without other references, it is impossible to truly master the technical principles of LLMs). Later research revealed that the residual connections and MLP layers in Transformer play critical roles; none of them can be removed. Training only multi-head self-attention by itself yields very poor results.

![](https://www.waytoagi.com/api/kb-media/I0Urbt0HMokES6xrwjac0z8rn2e)

<Later, a large number of modified Transformer variants emerged. Some discarded the encoder and kept only the decoder; others used only the encoder. Regardless of the changes, the brilliant idea of multi-head self-attention has been retained.>

**Recommended Learning Materials**

### Recommended Video Materials

- [Bilibili] **Transformer Paper In-Depth Segment-by-Segment Reading** [Paper Reading]  
  (https://www.youtube.com/watch?v=ugWDIIOHtPA&t=2s)  
  By Li Mu

- [YouTube] **Transformer**  
  (https://www.youtube.com/watch?v=ugWDIIOHtPA&list=PLJV_el3uVTsOK_ZK5L0Iv_EQoL1JefRL4&index=60)  
  By Hung-yi Lee

### Recommended Text Materials

- **Paper Link**: [Attention Is All You Need](https://arxiv.org/abs/1706.03762)  
  This is an extremely concise paper with no filler content. In fact, it is so brief that many details are left unexplained due to the page limit. It is **strongly discouraged** to dive straight into the paper. Recommended learning path: First follow Li Mu’s or Hung-yi Lee’s video lectures to go through the paper together, then study the text-based materials recommended below.

- **High-Quality Learning Resource**: [The Illustrated Transformer](http://jalammar.github.io/illustrated-transformer/)  
  By Jay Alammar

- **High-Quality Chinese Translation**: [The Illustrated Transformer](http://t.csdn.cn/YFjLF)  
  By Ann's Blog

- A very clear and well-explained Zhihu article: [Transformer Model Explained in Detail (Most Complete Illustrated Version)](https://zhuanlan.zhihu.com/p/338817680)  
  By Zhihu user @ChushiCV

---

ULMFiT was a groundbreaking attempt in the NLP field to achieve transfer learning similar to what had been done in computer vision. Knowing this is actually enough. I have folded the detailed content below; feel free to expand it if you are interested.

# ULMFiT and Multitask Learning: NLP’s ImageNet Moment (May 2018)

#I still believe ULMFiT, rather than BERT, marks NLP’s true “ImageNet moment.” The emergence of ULMFiT finally gave NLP a general transfer learning method comparable to those in the CV field.

**Paper Link**: [Universal Language Model Fine-tuning for Text Classification](https://arxiv.org/abs/1801.06146)

> Inductive transfer learning has greatly impacted computer vision, but existing approaches in NLP still require task-specific modifications and training from scratch. **We propose Universal Language Model Fine-tuning (ULMFiT), an effective transfer learning method that can be applied to any task in NLP, and introduce techniques that are key for fine-tuning a language model.** Our method significantly outperforms the state-of-the-art on six text classification tasks, reducing the error by 18-24% on the majority of datasets. Furthermore, with only 100 labeled examples, it matches the performance of training from scratch on 100x more data. We open-source our pretrained models and code.

![](https://www.waytoagi.com/api/kb-media/ArRRboleYoyL4ixJQCbc2X3Ungd)

It’s Cookie Monster. ULMFiT actually has nothing to do with him — using it to represent ULMFiT is purely for fun 😘!

Typing “ULMFiT” every time is getting a bit tiring. From now on, I’ll just use **Cookie Monster** to refer to ULMFiT!

## Review: Pre-training Challenges in NLP

At the very beginning of Chapter 11, we quoted the abstract of the ULM-FiT paper, which pointed out that inductive transfer learning has greatly advanced the development of computer vision, yet existing NLP methods still require task-specific modifications and training models from scratch for each particular task.

In section 8.1.5, we explained why inductive transfer learning comparable to that in CV has been slow to emerge in NLP: one reason is the scarcity of datasets (labeling costs are extremely high, and the quality of language on the internet varies widely, posing a significant challenge); the other is that most CV tasks are essentially classification-based, whereas NLP encompasses a wide variety of tasks. These include basic tasks such as named entity recognition and syntactic parsing, classification-based tasks such as sentiment analysis, and sequence-based tasks such as machine translation and natural language generation. These tasks involve different data structures and algorithms, making it difficult to capture them all within a single model and a single set of weights.

- For the problem of insufficient datasets, one solution is to adopt **semi-supervised learning**: training models with a small amount of labeled data combined with a large amount of unlabeled data to improve performance. This approach can be seen in the LM-LSTM and SA-LSTM models mentioned in section 8.2.

- For the problem of having too many different tasks, an important solution is **Multitask Learning**, which we will introduce in section 12.2.

## Key Excerpts from the Paper

### Transfer Learning Based on Fine-Tuning Has Never Been Successful in NLP

- Although deep learning models have achieved SOTA on many NLP tasks, these models are all trained from scratch, requiring massive datasets and taking days to converge. In contrast, our neighbors in CV have rarely trained models from scratch anymore — they basically do fine-tuning based on existing pre-trained models. NLP practitioners are so envious that they’re drooling 🥺

- Given the benefits of pre-training, the NLP field should be able to do better than randomly initializing model parameters for every new task. However, inductive transfer via fine-tuning has not been successful for NLP. In 2015, Dai and Le first proposed fine-tuning language models (LM) (that’s the paper *Semi-supervised Sequence Learning* we introduced in Chapter 8!), but it required millions of in-domain documents to achieve good performance, which severely limited its applicability.

- In addition, language models are prone to overfitting and suffer from **catastrophic forgetting** when fine-tuned.

**Hey ChatGPT, why were all attempts at using fine-tuning for transfer learning in NLP before ULMFiT considered unsuccessful?**

> Before ULMFiT was proposed, using fine-tuning for transfer learning in NLP did face several challenges and limitations. The main issues were as follows:

> **Data Volume Problem:**

> In NLP, many tasks require large amounts of labeled data to achieve good performance, but labeled data is often extremely expensive and time-consuming to obtain. Therefore, the limitation that training deep neural networks requires large amounts of labeled data is a common problem.

> **Differences Between Tasks:**

> Different NLP tasks can vary significantly, which means that when fine-tuning a model, it often needs to be retrained to adapt to the new task. This typically demands large amounts of labeled data and computational resources.

> **Overfitting in Neural Networks:**

> The fine-tuning process usually involves adjusting a large number of parameters, which can easily cause the neural network to overfit the training data, resulting in poor performance on test data.

> These problems meant that previous attempts at transfer learning via fine-tuning did not yield satisfactory results in the NLP field.

> ULMFiT introduced several new techniques to address these issues, including: using pre-trained natural language models to learn general language knowledge, employing data augmentation techniques to increase the size and diversity of the training dataset, and applying transfer learning to transfer general language knowledge to different NLP tasks. These methods enabled ULMFiT to achieve excellent results and gain widespread adoption in the NLP community.

### But Fine-Tuning Itself Is Not Wrong — Our Approach Can Bring CV-style Transfer Learning to NLP

- The authors of the ULMFiT paper argue that the fault does not lie with fine-tuning language models. The real problem is that we lacked the knowledge of how to train them effectively. Compared with CV, NLP models are often shallower, so they require different fine-tuning strategies.

- We propose a new method, **Universal Language Model Fine-tuning (ULMFiT)**, that addresses these issues and enables robust inductive transfer learning for any NLP task, **akin to fine-tuning ImageNet models**: The same 3-layer LSTM architecture — with the same hyperparameters and no additions other than tuned dropout hyperparameters — outperforms highly engineered models and transfer learning approaches on six widely studied text classification tasks.

### Cookie Monster’s Usage Steps:

#### Three New Fine-Tuning Techniques Proposed by Cookie Monster

- **Discriminative fine-tuning (‘Discr’)** refers to the process of fine-tuning a pre-trained model in deep learning to adapt it to a new task or dataset. In this process, the learning rate for each layer is set to a different value.

- **Slanted Triangular Learning Rates (STLR)** is a learning rate schedule used for training neural networks, designed to accelerate the training process and improve model performance.
- It first linearly increases the learning rate, then linearly decays it according to the right table.
- #The horizontal axis represents the number of iterations.
![](https://www.waytoagi.com/api/kb-media/RqjXbBrE6oOfJ9xVQmXcCxrOnXe)

- **Progressive Unfreezing** is a technique for training deep neural networks that employs a staged training approach. It aims to alleviate overfitting during deep neural network training and improve overall model performance.
  - In traditional deep neural network training, the entire network is usually trained at once, followed by fine-tuning of individual layers. This approach can easily lead to overfitting, where the model becomes overly sensitive to the training data and exhibits poor generalization. Progressive unfreezing, by contrast, is a phased training method that allows the network to gradually learn finer details of the data, thereby reducing the risk of overfitting.
  - Specifically, the steps of progressive unfreezing are as follows: 1) Freeze all layers of the deep neural network and train only the final layer. 2) Once the final layer has converged, unfreeze the layer before it and continue training the second-to-last layer. 3) After those two layers converge, unfreeze the next layer and train the third-to-last layer. This process continues sequentially until all layers have been unfrozen and fully trained.
  - In this way, progressive unfreezing incrementally increases the network’s complexity and capacity, enabling it to gradually capture more detailed information from the data and adapt to its various features, ultimately improving model performance. Additionally, it enhances the model’s generalization ability, shortens training time, and reduces the risk of overfitting.

#### The Three-Step Method for Training Cookie Monster

![](https://www.waytoagi.com/api/kb-media/IgzbbbpE3oLxtFxP7Otc2eHxn0f)

ULMFiT consists of three stages:

a) **Language Model pre-training on a general-domain corpus** to capture broad linguistic features (in the original paper, the authors pre-trained the language model on Wikitext-103, which consists of 28,595 preprocessed Wikipedia articles and 103 million words). This stage is the most computationally expensive, but it only needs to be performed once and significantly improves the performance and convergence of downstream models.

b) **Fine-tuning the full LM on the target task data** using Discriminative Fine-tuning (Discr) and Slanted Triangular Learning Rates (STLR) to learn task-specific features.

- The idea behind Discr: Different layers capture different types of information and should therefore be fine-tuned to different extents.
- The purpose of STLR: To enable the model to converge quickly to a suitable region of the parameter space at the beginning of training, then gradually refine its parameters.

c) **Classifier fine-tuning**: On the target task, the classifier is fine-tuned using **progressive unfreezing**, Discr, and STLR to preserve low-level representations while adapting high-level ones (in the figure, shaded areas represent unfrozen stages; black areas represent frozen layers).

Fine-tuning the target classifier is the most critical part of the transfer learning process. Overly aggressive fine-tuning can cause catastrophic forgetting, nullifying the benefits gained from language model pre-training. Overly conservative fine-tuning, on the other hand, leads to slow convergence and consequent overfitting. In the Cookie Monster approach, the authors adopted progressive unfreezing to avoid catastrophic forgetting caused by overly aggressive updates, while combining it with Discr and STLR to strike a balanced compromise between aggressiveness and caution.

## Summary

ULMFiT is an effective, extremely sample-efficient transfer learning method that can be applied to any NLP task.

Prior to ULMFiT, fine-tuning in the NLP domain had long been plagued by challenges such as overfitting, catastrophic forgetting, and insufficient datasets. ULMFiT introduced multi-task learning along with several novel fine-tuning techniques (11.3.3), effectively preventing catastrophic forgetting and enabling robust learning across diverse tasks. **The NLP field finally gained a transfer learning approach comparable to that of Computer Vision.**

**It’s Here! Finally, We’ve Been Waiting for You! A Comprehensive Deep Dive into GPT, GPT-2, and GPT-3!**

**If you are not yet familiar with the Transformer, please go back to Chapter 10 and fully understand it first!**

**# Trying to understand GPT without knowing the Transformer is like reading the Four Great Classical Novels without reading *Dream of the Red Chamber*. It shows that the person lacks both technical depth and self-cultivation. They cannot appreciate the refined, highbrow art within; they can only see superficial wordplay and fail to grasp the profound spiritual core. Their level is stuck right there, and they can only live a relatively unsuccessful life.**

# GPT stands for **G**enerative **P**retrained **T**ransformer. The essential difference between GPT and BERT is literally written on their names. GPT is *Generative* — its goal is generation. It is a pretrained Transformer that, because it is designed for generation, adopts a Decoder-Only Auto-Regressive architecture. In contrast, BERT’s paper is titled **BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding**. It is a very deep stack of bidirectional Transformer encoders whose purpose is natural language understanding.

![](https://www.waytoagi.com/api/kb-media/Qt28b9vRGo1JLNxioXscKfBWn8p)
![](https://www.waytoagi.com/api/kb-media/JP9qbuZJCoVLnTxC0VTcefhunbb)

Most readers of this document probably came for GPT, but very few will actually make it this far! After so much groundwork, we have finally reached the main character. Let’s see how OpenAI, at a time when the world favored BERT, stubbornly chose the Decoder-only autoregressive path — and once it finally made its move, it shook the world.

**The table below lists the models covered in this chapter.**

| Model   | Paper | Model Size | Paradigm & Key Innovations | Evaluation & Significance |
|---------|-------|------------|----------------------------|---------------------------|
| GPT     | [Improving Language Understanding by Generative Pre-Training](https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf) | 12-layer decoder, 768-dim embeddings, 12 attention heads | Pre-training + Fine-tuning. Innovation: **Task-specific input transformations**. | Quickly surpassed by the Encoder-only BERT. Choosing the autoregressive route made GPT’s path much harder, but its ultimate ceiling would also be much higher. |
| GPT-2   | [Language Models are Unsupervised Multitask Learners](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) | 1.5 billion parameters | Pre-training + Prompt + Predict. Innovation: **Zero-shot**. | After BERT Large swept the SOTA, OpenAI failed to give a strong response. Zero-shot sounded extremely novel, but in reality the model’s performance was weak and practical value was low. They had no choice but to market “0-shot” as the main selling point. |
| GPT-3   | [Language Models are Few-Shot Learners](https://arxiv.org/pdf/2005.14165.pdf) | 175 billion parameters | Pre-training + Prompt + Predict. Innovation: **In-context learning**. | Pioneered the concept of **in-context learning (ICL)** and is the true founding father of the Prompting paradigm. **In-context learning (ICL)** represents the first stage in the development of the Prompting paradigm. |
| Codex   | [Evaluating Large Language Models Trained on Code](https://arxiv.org/abs/2107.03374) | 300M and 1.2B parameters | Pre-training + Fine-tuning. Fine-tuning is truly effective. | Technically not very complex. Training on scraped GitHub code was highly controversial. ChatGPT and GPT-4’s strong code-generation capabilities owe a great deal to Codex. Some believe that ChatGPT’s ability to perform complex reasoning stems from having learned from code. |

## The Birth of GPT (June 2018)

### GPT is a 12-layer Transformer Decoder

**12-layer decoder, 768-dimensional word embeddings, 12 attention heads**

Paper: [Improving Language Understanding by Generative Pre-Training](https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf)

Chinese Translation: [Where the Dream Begins: GPT-1 Paper Translation — Improving Language Understanding by Generative Pre-Training](https://zhuanlan.zhihu.com/p/619995186) by haidao

You might think that since GPT is so powerful, it must be extremely complicated. But that’s not the case! **GPT is not a brand-new architecture — its structure is essentially a Transformer that consists only of decoders.** In fact, it is simply a stack of 12 Transformer decoder layers!

![](https://www.waytoagi.com/api/kb-media/ZLhjbQdV9o65CPx2cDecwlBlnbh)

The image above is taken from the original GPT paper. As you can see, GPT is exactly a 12-layer decoder!

> OpenAI’s GPT model was proposed before Google’s BERT. The biggest difference between them is that GPT uses the traditional language modeling approach for pre-training — predicting the next word based on previous context — while BERT uses bidirectional context to predict words. Because of this difference in training methodology, GPT excels at natural language generation (NLG) tasks, whereas BERT is stronger at natural language understanding (NLU) tasks.

As shown in the diagram on the right, a classic Transformer Decoder Block contains three sublayers: the Masked Multi-Head Attention layer, the Encoder-Decoder Attention layer, and a final feed-forward layer. If you’ve forgotten, go back to section 10.3 for a quick review!

GPT is a **Decoder-Only** architecture. Since it has no encoder at all, there is no way to obtain Key and Value vectors from an encoder. Therefore, in Decoder-Only variants of the Transformer, the second sublayer (Encoder-Decoder Attention) is typically removed, leaving only the Masked Multi-Head Attention layer and the Feed Forward layer.

In this way, the only real difference between an Encoder and a Decoder is whether the first multi-head self-attention layer uses a mask. If there is no mask, it’s an Encoder; if there is a mask, it’s a Decoder. It’s that simple. (Section 10.3.1 explains masked self-attention in detail!)

**Embedding**: Token embeddings + positional encoding  
**Masked multi-head self-attention**: Ensures that the dot product between the current time step and all future time steps becomes zero after softmax.  
The output vector is passed through a feed-forward layer and then fed to the next decoder layer.

GPT consists of 12 such decoders. After passing through all of them, the final vector goes through a linear logit layer and a softmax layer to produce a probability distribution over the next token. The output token is then used as input for the next step.

![](https://www.waytoagi.com/api/kb-media/OLpDbJ2t6oxUknxyLthcfHy7n0e)

### GPT’s Training Paradigm: Pre-training + Fine-tuning

In section 12.1.1, we learned that GPT is essentially a 12-layer Transformer decoder. Therefore, whether we say “a pre-trained 12-layer Transformer” or simply “GPT,” I want you to understand that we are referring to the same thing.

#### Unsupervised Pre-training

**The pre-training task for the GPT model is the standard n-gram language modeling task.**

A Transformer decoder is itself a language model. Given an unlabeled corpus \(\mathcal{U} = [u_1, u_2, ..., u_n]\), we let the Transformer decoder perform next-token prediction. The objective/loss function is:

$$L_1(\mathcal{U}) = \sum_i \log P(u_i | u_{i-k}, u_{i-k+1}, ..., u_{i-1}; \theta)$$

You can refer back to section 6.5.3 on n-gram language models. The model predicts the conditional probability of the next word given the previous *k* words (where *k* is the size of the context window). *k* is a hyperparameter, and \(\theta\) represents the model parameters.

A more intuitive way to understand *k* is to think of it as the length of the input sequence to the neural network. The longer the sequence, the more context the network can see. Making *k* very large is one of the important ways to make the model more powerful.

> Many times, people say the difference between BERT and GPT lies in the encoder versus the decoder — that the encoder can see the entire input while the decoder can only see part of it. This statement is actually quite inaccurate. The real difference lies in their **pre-training tasks** (and the corresponding objective functions). GPT’s pre-training task is next-token prediction, which is much harder than BERT’s cloze-style masked language modeling because it must predict an open-ended future.

> (Predicting tomorrow’s stock price given the past 6 days’ prices VS predicting the middle day’s price given three days before and after.)

> **“This is an important reason why GPT lags far behind BERT in both training difficulty and final performance. But if your model can truly predict the future, its capabilities will be far more powerful than models like BERT. That’s why the authors kept scaling up the model, kept pushing forward, and eventually created the stunning GPT-3. OpenAI chose a much harder technical path, but its ceiling may also be much higher.” —— Li Mu**

# This big shot’s judgment is incredibly accurate.

#### Supervised Fine-tuning Paradigm  
**An illustration of supervised fine-tuning**

OpenAI experimented with their pre-trained decoders on a variety of supervised tasks, including natural language inference, question answering, semantic similarity, and text classification.

The paper describes how to use a pre-trained Transformer for sequence classification tasks.

After pre-training is complete, we obtain the model parameters and use them for supervised training on downstream tasks. We assume we have a labeled dataset \(\mathcal{C}\), which contains word sequences \(x^1, \dots, x^m\), along with a label \(y\) for each sequence.

> (For example, the token sequence \([x^1, x^2, x^3, x^4, x^5, x^6]\) = [Genshin, how, are, you, ?, ?] has the label \(y\) = “sus”.)

The specific approach is to feed \(x^1, \dots, x^m\) into the pre-trained GPT model. After passing through 12 Decoder Blocks, it produces a hidden state \(h_l^m\) (768-dimensional) corresponding to the last input token \(x^m\). We then multiply this tensor by a weight matrix \(W_y\) (768 × number of classes) to obtain a vector with the same dimensionality as the number of classes. Applying softmax to this vector yields the probability distribution over labels:

\[P(y \mid x^1, \dots, x^m) = \text{softmax}(h_l^m W_y)\]

> (For example, for the input “Genshin, what happened to you??”, the predicted label distribution might be P(collapse) = 10%, P(classic) = 30%, P(sus) = 25%, P(filial) = 30%, P(numb) = 5%.)

Our objective is to maximize the following objective function:

\[L_2(\mathcal{C}) = \sum_{x,y} \log P(y \mid x^1, \dots, x^m)\]

> In other words, we want the model to assign the highest possible probability to the correct label “sus” for the sequence “Genshin, what happened to you?”

**This is a very standard objective function for classification tasks.**

**Although during fine-tuning we only care about this objective, we can actually train on both the classification task and the language modeling task simultaneously!**

That is, during fine-tuning, we optimize with respect to both \(L_1(\mathcal{C})\) and \(L_2(\mathcal{C})\).

> Input sequence: \([x^1, x^2, x^3]\) = [Holy | shit | ,]. We want GPT to predict the next token “Genshin”. Given the full sequence [Holy | shit | , | Genshin | !], we want GPT to assign the highest possible probability to the label “collapse”. We train on both tasks together.

OpenAI introduces a tunable hyperparameter \(\lambda\) to combine the two objectives and performs gradient descent on the joint loss:

\[L_3(\mathcal{C}) = \lambda L_1(\mathcal{C}) + L_2(\mathcal{C})\]

### GPT’s Key Innovation: Task-specific Input Transformations

> For some tasks, like text classification, we can directly fine-tune our model as described above. Certain other tasks, like question answering or textual entailment, have structured inputs such as ordered sentence pairs, or triplets of document, question, and answers. Since our pre-trained model was trained on contiguous sequences of text, we require some modifications to apply it to these tasks.

In section 12.1.2.2, we explained how to fine-tune GPT: we used a standard classification setup, but one relatively novel point was combining the objective functions of the two pre-training tasks.

**Next, the question is how to express all those very different subtasks in NLP using this fine-tuning paradigm — that is, in the form of *sequence + labeling*.**

![](https://www.waytoagi.com/api/kb-media/Hm99bQNqhoOx1OxwuSlchqXrnSh)

We have seen this diagram before, but we are showing it again here. The figure illustrates four common subtasks:

- **Classification:** As you can see, two special tokens (Start and Extract) are added, followed by a linear layer.

- **Entailment:** This term is difficult to translate directly. Roughly speaking, given a premise, a hypothesis is proposed, and the model is asked to determine whether the hypothesis is entailed by the premise, contradicts the premise, or is neutral with respect to it. It looks like a logic inference game, but at its core it is simply feeding the model two pieces of text (separated by special tokens) and turning it into a three-class classification problem.

> Premise: You are right, but *Genshin Impact* is a brand-new open-world adventure game independently developed by miHoYo. The game takes place in a fantasy world called "Teyvat." In this world, the chosen ones will be granted a "Vision," which guides the power of elements.

> Hypothesis: 1. You are right. 2. You read the Four Great Classical Novels but skip *Dream of the Red Chamber*. 3. The game takes place in the Kingdom of Hyrule.

> Output: 1. Entailment 2. Neutral 3. Contradiction

- **Similarity:** Determine whether two pieces of text are similar. Similarity is a symmetric relation — if A is similar to B, then B is also similar to A. Therefore, as shown in the diagram, we first construct Text1 + separator + Text2, then Text2 + separator + Text1. The two sequences are each passed through the Transformer to obtain their output vectors. These vectors are added element-wise and then fed into a linear layer. This is also a binary classification problem.

- **Multiple Choice:** Multiple sequences are constructed, each consisting of the same question (Context) paired with a different answer. If there are N answers, then N sequences are created. Each QA sequence is passed through the Transformer and a linear layer to produce a scalar score for each answer. Finally, a softmax is applied to generate a probability distribution over all the answers. This is an N-class classification problem.

By using this approach, all four subtasks are transformed into the *sequence + labeling* format. Although the specific input and output constructions still differ slightly, **no matter how the input is formatted or how the output is constructed, the Transformer in the middle remains unchanged**. We never modify the Transformer model architecture itself. This is the key difference between GPT and previous work, and also one of the core selling points of this paper.

> Previous work proposed learning task-specific architectures on top of transferred representations. Such an approach re-introduces a significant amount of task-specific customization and does not use transfer learning for these additional architectural components. **Instead, we use a traversal-style approach, where we convert structured inputs into an ordered sequence that our pre-trained model can process. These input transformations allow us to avoid making extensive changes to the architecture across tasks.**

> > At this point, you might still feel somewhat confused — because GPT doesn’t seem to introduce anything particularly new! The real value lies in the *Task-specific input transformations* mentioned in sections 12.1, 12.2, and 12.3. So how does it manage to handle today’s highly complex question-answering tasks? Stay patient and keep reading!

## GPT-2: Language Models are Unsupervised Multitask Learners! (Feb 2019)

**48-layer decoder, 1600-dimensional embeddings, 1.5 billion parameters**

# We know that, in a sense, the GPT model was “defeated” by BERT, which was published shortly after it. BERT Large doubled the depth (24 encoders), increased the width by 1.3× (1024-dimensional embeddings), and was trained with 3× the compute on a 2-billion-word Wikipedia dataset. The result was a model three times the size of GPT, with 340 million parameters, that swept the SOTA at the time.

> **Q: When your decoder is beaten by someone using an encoder, a larger model, and more data, how do you respond?**

> **A: Switching to an encoder is impossible — not in this lifetime. What we’re going to do is get bigger!**

> **Q: But even when you make it bigger, a 1.5-billion-parameter Decoder-only model still doesn’t outperform a 340-million-parameter BERT 🥺**

> **A: But we can do Zero-Shot!**

![](https://www.waytoagi.com/api/kb-media/JzLmb83GeoJko6xMafnc0axsnLc)
![](https://www.waytoagi.com/api/kb-media/Z39ObJ0X5oq17XxJ8WdcOpDfnwc)

[Original paper: Language Models are Unsupervised Multitask Learners](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf). The largest GPT-2 used 48 decoders.

### Let’s first talk about Multitask Learning: Many NLP subtasks can be reframed as Question Answering

The paper [Language Models are Unsupervised Multitask Learners](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf) points out that current language models have relatively poor generalization. Parameters trained on one dataset and one specific task are hard to transfer directly to new tasks. As a result, most existing models are Narrow Experts rather than Competent Generalists. **OpenAI aims to move toward more general systems capable of performing many different tasks — ultimately without the need to manually create and label training datasets for each individual task.** This naturally brings to mind the concept of multitask learning, which was very popular from 2000 to 2010 but saw little application in NLP.

#### **Definition of Multitask Learning**

Multitask Learning (MTL) is a machine learning approach that improves a model’s performance and generalization by learning multiple related tasks simultaneously. Unlike single-task learning, which trains a model for only one specific task, multitask learning shares parts of the model’s parameters across tasks. This allows more efficient use of data, leading to better predictive performance and greater efficiency.

#### **The Natural Language Decathlon (June 2018)**

Key reference: [The Natural Language Decathlon: Multitask Learning as Question Answering](https://arxiv.org/abs/1806.08730)

> In NLP, a unified multitask foundation model makes model transfer and deployment much easier. Continuous improvement of this foundation model can steadily boost the performance of downstream models, potentially enabling continual learning and continuous improvement. In contrast, if every new sub-model must be trained from scratch, it cannot benefit from the long-term knowledge accumulated by the foundation model.

> However, NLP contains many different types of tasks: sequence labeling and named entity recognition belong to one category; sentence-level classification belongs to another; and there are also seq2seq tasks such as machine translation and automatic summarization. How can all these diverse tasks be unified into a single model?

> The answer is: convert all NLP tasks into QA tasks! Machine translation becomes “What is this sentence translated into another language?” Sentiment classification becomes “Is this sentence expressing a positive or negative meaning?” Automatic summarization becomes “Please write a summary for me.” All NLP tasks can be reframed as question answering.

> ——Quoted from [CS224N (3.5) Multitask Learning | bitJoy](https://bitjoy.net/2020/03/14/cs224n%ef%bc%883-5%ef%bc%89multitask-learning/) by Beeder

In the paper [The Natural Language Decathlon: Multitask Learning as Question Answering](https://arxiv.org/abs/1806.08730), [Bryan McCann](https://arxiv.org/search/cs?searchtype=author&query=McCann%2C+B) and colleagues introduced the **Natural Language Decathlon (decaNLP)**, a challenge spanning ten diverse tasks: question answering, machine translation, summarization, natural language inference, sentiment analysis, semantic role labeling, relation extraction, goal-oriented dialogue, semantic parsing, and commonsense pronoun resolution.

![](https://www.waytoagi.com/api/kb-media/GcMtbDT75oNZNSxYGMtcKxuvnMe)

How is this achieved? The answer was already hinted at in the Beeder article quoted earlier: **reframe all tasks as contextual question answering.**

Specifically, the following conditions must be met:

> 1. All tasks must be treated equally. The data fed to the model must not contain any indication of which specific task it belongs to. The model cannot be told that one example is for NMT while another is for sentiment classification.

> 2. The model itself cannot contain task-specific modules. Given a sequence of tokens as input, **the model must learn to identify the different task types required by that sequence on its own**, internally switch accordingly, and perform the appropriate operations.

> 3. In addition, the model should be capable of performing tasks beyond these ten — that is, zero-shot learning.

Therefore, the authors proposed a new Multitask Question Answering Network (MQAN) that **jointly learns all tasks in decaNLP without any task-specific modules or parameters**.

We won’t dive into the specific implementation details of MQAN here. However, the core idea — converting various downstream subtasks into QA tasks and letting the model automatically perform different operations by following natural language instructions **(Prompts!!!)** — is truly brilliant. It is also the key insight behind GPT-2.

# This is exactly why the paper that introduced GPT-2 is titled [Language Models are Unsupervised Multitask Learners](https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf). The title fits perfectly.

### Zero-Shot: What if we skip fine-tuning altogether?

> > The biggest change in GPT-2 is that OpenAI abandoned the previous “unsupervised pre-training + supervised fine-tuning” paradigm and pioneered **Zero-shot** learning — after pre-training, the model can perform a wide variety of tasks **without changing its parameters at all**.

Both GPT and BERT followed the paradigm of pre-training followed by fine-tuning on specific downstream tasks. Fine-tuning requires large amounts of labeled data and brings concerns about overfitting. It’s quite cumbersome.

**Zero-shot means that when using a pre-trained model for downstream tasks, we need no additional labeled data and do not modify the model parameters.** This sounds almost unrealistic, so some important details are required.

In terms of model architecture, GPT-2 is identical to GPT — both are stacks of Transformer decoders. Therefore, we will not repeat the architecture description.

**But we need to clarify one key point:**

#### What makes Zero-shot difficult?

- In the GPT model described in Section 12.1, the model is pre-trained on natural language. When moving to downstream tasks for fine-tuning, many special tokens that the model had never seen during pre-training are introduced. Looking at the figure below, the middle “Delim” (delimiter, which tells the model that the text before it is the context and the text after it is the answer) is one such special token, designed specifically for that task. The model had never encountered it during pre-training. In other words, for downstream tasks, we apply special formatting to the input — adding start tokens, end tokens, and separator tokens. The model must gradually learn these symbols during the fine-tuning process.

![](https://www.waytoagi.com/api/kb-media/LeMUbURoVoavggx4HQpcT4BYnbc)

- Now the problem arises: if we want to do **Zero-shot Learning** — that is, perform downstream tasks without any additional training — we cannot let the model learn these task-specific constructions on the fly. Therefore, when constructing inputs for downstream tasks, we cannot introduce special symbols. The entire input for the downstream task must look exactly like the text the model saw during pre-training. **In short, the input format should resemble natural language as closely as possible.**

#### From Zero-shot to Prompting

Since the input format also needs to resemble natural language, is there a way for the model to understand what task it should perform based on our natural language instructions?

For example, if I say to the model:  
`Translate the following text into English:`  
`In this day and age, you're still smoking traditional cigarettes?`  
The model would then know that this is a translation task, and the part after the colon is the text I want it to translate. This way, we don’t need to introduce new special symbols for the model to recognize. As long as the model can understand our instructions, it’s sufficient.

So what’s the solution? The answer is to stand on the shoulders of giants: the [NLP Ten Tasks Competition](https://arxiv.org/abs/1806.08730) mentioned in section 12.2.1.2 gave us the inspiration!

> But as exemplified in McCann et al. (2018), language provides a flexible way to specify tasks, inputs, and outputs, all as a sequence of symbols. For example, a translation training example can be written as the sequence (`translate to french`, `english text, french text`). Likewise, a reading comprehension training example can be written as (`answer the question`, document, question, answer).

**In other words, the prerequisite for achieving Zero-shot learning is that we no longer need to specially design the input structure for each downstream task. Instead, we only need to give the model instructions — that is, prompts.** Doesn’t reading this make your heart race with excitement? After waiting so long, the word “Prompt” has finally appeared!!! Let’s give it a round of applause!!!!!

#### Why Prompt Works at All?

#Why is it that simply writing a prompt can automatically enable the model to perform downstream task predictions? This feels almost magical! Here’s a possible explanation:

> Our speculation is that a language model with sufficient capacity will begin to learn to infer and perform the tasks demonstrated in natural language sequences in order to better predict them, regardless of their method of procurement.
> ——Language Models are Unsupervised Multitask Learners, OpenAI

OpenAI speculates that when the amount of data is large enough and the model is powerful enough, language models will learn to infer and execute tasks posed in natural language, **because doing so helps them perform next-token prediction more effectively.**

Refer to the image on the right. GPT-2’s training corpus already contained a large number of examples of English-to-French translations. These examples existed passively in the corpus without anyone explicitly asking for them. After the model learned from this data, it may have developed the ability to understand the “English-to-French translation” intent implied in natural language.

![](https://www.waytoagi.com/api/kb-media/Y9RobR8bkoMAb6xINmWceX8hnje)

#### GPT-2’s Performance and Evaluation of the Model

GPT-2’s performance is shown in the figure below:

![](https://www.waytoagi.com/api/kb-media/Rv4tbvvRromNuxx4oH5cbrpGnyg)

As we can see, its performance on reading comprehension is decent, but it performs quite poorly on translation and summarization. Summarization is even worse than an ordinary seq2seq+Attention model. As for Question Answering, it’s so weak that it can’t even be placed on the same chart with the other models… There’s a reason GPT-2 mainly marketed itself on its Zero-shot capability — because its actual performance was indeed underwhelming, especially considering its unprecedented scale in terms of parameters.

GPT-2 did introduce a very innovative idea: the Zero-shot paradigm. However, its performance was very poor. As Mu Li once said: *The contribution of a paper = novelty × effectiveness × importance of the problem.* GPT-2 scores very high on novelty, but its effectiveness is hard to praise.

That said, one point worth noting is that, overall, model performance still improves (roughly linearly) as the number of parameters increases. Therefore,

> > This still leaves us with room for imagination: if we make the model large enough — bigger and bigger — will we truly get closer to AGI? Roughly speaking, this is exactly what GPT-3 set out to do!

## GPT-3: Language Models are Few-Shot Learners (May 2020)

[Original Paper: Language Models are Few-Shot Learners](https://arxiv.org/pdf/2005.14165.pdf)

### The Significance of GPT-3

**GPT-3 has 175 billion parameters. The model is so enormous that fine-tuning it on downstream tasks becomes practically infeasible. Therefore, when GPT-3 is applied to downstream tasks, it performs no gradient updates at all.**

The original GPT model demonstrated that pre-training a language model using a Transformer decoder on a large amount of unlabeled data, followed by fine-tuning on downstream tasks with a small number of labeled examples, could significantly improve performance. GPT-2 took this idea further by claiming that no task-specific training samples are needed at all. Instead, a sufficiently large pre-trained model could directly understand task instructions expressed in natural language and make predictions accordingly. However, as mentioned earlier, GPT-2’s actual performance was quite poor — it was conceptually innovative but lacked practical effectiveness.

Naturally, the GPT-3 paper sets out to solve this problem of low effectiveness. The idea of zero-shot learning is appealing, but it is simply too demanding. Even for humans, learning a new task usually requires seeing a few examples; we just learn much faster. Machines, on the other hand, have traditionally needed large amounts of labeled data for fine-tuning. The ultimate goal of artificial intelligence is to create machines that possess human-like intelligence — the ability to learn a new task from just a handful of examples. That is exactly what GPT-3 aims to achieve.

The paper’s title, [Language Models are Few-Shot Learners](https://arxiv.org/pdf/2005.14165.pdf), captures this core idea perfectly.

> **Note: Even in the few-shot setting, although the model is given a few examples, it still does not update its gradients. GPT-3 strongly emphasizes that the model’s weights remain frozen — after all, with 175 billion parameters, updating them is extremely costly.**

![](https://www.waytoagi.com/api/kb-media/ItZWbg8PVoiaTHx8Vz1cXQ0FnQe)
As shown above, scaling from GPT-2 (1.3B) to GPT-3 (175B) roughly doubled the model’s accuracy. Making the model larger clearly works.

![](https://www.waytoagi.com/api/kb-media/CQ4tborKcoJALjx4V3IcHhEhn7e)
The x-axis represents the number of examples provided in the input context.

### GPT-3 Model Architecture and Engineering Details

![](https://www.waytoagi.com/api/kb-media/E1RRb5aIcoxG5XxZ1CPc1HG0nid)

- In terms of model architecture, GPT-3 is identical to GPT-2 — it is a stack of decoder layers. However, it adopts an architecture called **Sparse Transformer**. This document will not delve into the technical details of Sparse Transformer, but the following excerpt provides a good high-level understanding of its purpose and mechanism. **In short, Sparse Transformer enables the model to handle much longer and sparser input sequences.**

> Sparse Transformer is an extension of the Transformer architecture designed to handle high-dimensional, sparse, and long-sequence data. It was proposed by the OpenAI team in 2019. Compared with the standard Transformer, Sparse Transformer introduces sparsity into the self-attention mechanism, which dramatically reduces the amount of computation and allows the model to process significantly longer sequences.

> When dealing with high-dimensional and sparse data, Sparse Transformer avoids computing attention for every position in the input. It only computes attention between positions that are relevant to the current position, thereby greatly improving computational efficiency.

- \( d_{model} = n_{heads} \times d_{head} \), where \( n_{heads} \) is the number of attention heads, and \( d_{head} \) is the dimension of each head (i.e., the dimensionality of the vectors obtained after multiplying by the Q, K, and V weight matrices. In the original Transformer paper, this value was 64).

- GPT-3 uses a batch size of 3.2 million — an extremely large batch size that places enormous pressure on memory. Recall the parameter update formula:

$$
\theta_{t+1}=\theta_t-\alpha\frac{1}{N}\sum_{n=1}^N\frac{\partial\mathcal{L}(y^n,f(x^n;\theta))}{\partial\theta}
$$

A larger batch size (N) means the model must compute the average gradient over a much larger number of samples in each step, resulting in significantly higher computational cost.

> Why choose such a large batch size? First, very large models are less prone to overfitting than smaller ones, so using larger, cleaner batches does not introduce many negative side effects. Second, training such massive models typically involves distributed training across many machines using data parallelism. With more machines, each machine can handle a larger local batch. Increasing the global batch size improves parallelism across machines and reduces communication overhead.

- **Although increasing the batch size raises the time complexity of gradient computation, a larger batch size typically improves the model’s training efficiency and performance.** This is because a larger batch size can take full advantage of the parallel computing capabilities of modern hardware, accelerating the training process, while also improving model stability by reducing the variance of gradients. In short, the choice of such an extremely large batch size is primarily based on engineering experience.

- There are also some interesting details. For example, as the model size grew and the batch size increased, the learning rate chosen by OpenAI actually decreased.

- On the data source side, the larger a model’s parameter count, the more data we naturally need to pre-train it.
  - In GPT-2, OpenAI felt that data from Common Crawl was too noisy, so they used Reddit articles with karma > 3 as training data. However, GPT-3’s model size increased more than tenfold, so they had no choice but to consider Common Crawl (a massive web-crawled dataset whose enormous scale naturally comes with extremely dirty data).
  - Specifically, OpenAI performed three operations on Common Crawl: 1. Binary classification — using a logistic regression model to classify Common Crawl data into high-quality and low-quality, thereby filtering out poor data. 2. Deduplication (using the LSH algorithm). 3. Then mixing back in all the datasets previously used for GPT-2 and BERT.
  - In addition, although Common Crawl data dominated the total training corpus by volume, OpenAI still applied differentiated sampling rates across different datasets. In every batch, OpenAI controlled the weight of Common Crawl data to 60%. The paper does not explain exactly how this was implemented, but we can roughly understand what it means.

![](https://www.waytoagi.com/api/kb-media/PbnTbZjQ7oMYBNxPDOIcD3PlnPh)

> In summary, although we only looked at one parameter table for the model architecture, that table already reveals a great deal of engineering detail. **GPT introduced no groundbreaking new techniques, yet achieving “miracles through sheer scale” requires a tremendous amount of engineering know-how in areas such as compute planning, hyperparameter selection, and more.**

OpenAI revealed almost no specific details about model training in the paper. Information on hyperparameter choices, model partitioning, data partitioning, and distributed training practices is extremely sparse. So even if I wanted to explain these aspects in depth, there is simply no public material available. `This is exactly why everyone jokingly calls OpenAI “ClosedAI.” Where has your open-source spirit gone???`

### In-Context Learning (ICL)

![](https://www.waytoagi.com/api/kb-media/TtpcbvmcZo9aCIxyxzwcWdE0nQg)

As we have repeatedly emphasized, GPT-3 does not perform gradient descent or update its model parameters. So how does it work? — It only makes predictions and does not train! We expect the Transformer, during forward inference, to extract useful information from the input we provide through the attention mechanism and then perform the prediction task. The predicted output is essentially the model following our task instructions. **This is In-Context Learning (ICL).**

**Where exactly GPT-3’s in-context learning ability comes from was still a mystery when the model was first released.** The group led by [**Tengyu Ma**](https://arxiv.org/search/cs?searchtype=author&query=Ma%2C+T) has published several papers attempting to explain this capability. References:

[【arxiv】An Explanation of In-context Learning as Implicit Bayesian Inference](https://arxiv.org/abs/2111.02080)

[【arxiv】What learning algorithm is in-context learning? Investigations with linear models](https://arxiv.org/abs/2211.15661)

Both papers are quite technical. For an introductory level, it is enough to know that once a model as large as GPT-3 is trained, in-context learning ability naturally emerges, and it does have a solid scientific explanation.

**This makes GPT-3 a 175-billion-parameter model with ICL capabilities. To demonstrate ICL, OpenAI evaluated it using three methods:**

**1. Few-Shot Learning (FS):** The task is described to the model in natural language; 10–100 training examples are provided for each subtask.

**2. One-Shot Learning (1S):** The task is described in natural language, followed by only one example for that task.

**3. Zero-Shot Learning (0S):** The task is described in natural language, but no examples are provided at all. **See the figure below for concrete examples.**

![](https://www.waytoagi.com/api/kb-media/P9QUbTwIvoScXVx9IPXc2a4unOM)

**Left: The three paradigms of In-Context Learning proposed by GPT-3. Right: Traditional Fine-Tuning.**

This paradigm has both advantages and disadvantages:

- **The main advantage is what we mentioned earlier: it eliminates the need to fine-tune the model for downstream tasks.** Fine-tuning a model is quite cumbersome. For every new task, you need to prepare sufficient samples, tune hyperparameters (batch size, learning rate, etc.), choose various learning strategies (remember Cookie Monster?), and training the model itself requires access to GPUs. In contrast, GPT-3’s paradigm allows us to tackle new tasks simply by asking the model to make predictions — i.e., performing forward propagation — and the model will directly return the results. This is especially friendly for new tasks.

- The drawbacks are also obvious:
  - What if you actually have a large amount of training data? GPT-3’s input context window is, after all, limited. We cannot indefinitely stack more and more examples. For instance, in a machine translation task, we can easily obtain massive amounts of data. In such cases, a model tuned on that full dataset will very likely outperform what we can achieve by stuffing a limited number of few-shot examples into a constrained window. In short, the limited input window restricts our ability to leverage massive datasets.

- **Transformers are becoming deeper and wider, yet training them on long sequences remains extremely difficult.** A fundamental problem researchers face is that the attention layers in Transformers scale quadratically with sequence length: increasing the length from 32k to 64k does not merely double the cost — it quadruples it.

- Over the past two years, Stanford’s Hazy Research lab has been working on a critical challenge: increasing the (LLM’s) input sequence length.

- **Recommended reading:** [Want to fit half of *Dream of the Red Chamber* into ChatGPT’s input box? Solve this problem first](https://mp.weixin.qq.com/s/idL7DyL7prhztvnMHBEl1g) — by Machine Heart

- [【arXiv】FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness](https://arxiv.org/abs/2205.14135)
  - Every time the model makes a new prediction, it must retrieve useful information from the middle of the input. However, we cannot store the information extracted from the previous input inside the model and reuse it for the next input.

- **This is why, even though GPT-3 achieved impressive results with its enormous parameter count as early as May 2020, the academic community’s enthusiasm for using few-shot in-context learning has remained relatively modest.**

### Limitations of the GPT-3 Model

The author lists a great many limitations, but here I will focus on what I consider the most important ones.

**First, its ability to generate long-form text is still quite weak.**

**If you ask GPT-3 to generate long text, after writing a few paragraphs it often starts repeating content from the first or second paragraph.** If you want GPT-3 to write a novel in a fully unsupervised manner, it is essentially impossible, because the model lacks the ability to continuously advance the plot. However, if you provide sufficient context in the prompt and ask it to complete a missing segment of a story, it can perform remarkably well.

> In terms of text synthesis, although the overall quality is high, GPT-3 samples sometimes still repeat their own semantics at the document level. In sufficiently long passages, they begin to lose coherence, contradict themselves, and occasionally contain discontinuous sentences or paragraphs.

**Second, GPT-3 struggles with questions like “If I put cheese in the fridge, will it melt?” Its logical reasoning ability based on real-world physics and common sense is still insufficient.**

In addition, the following limitations exist:

- **It cannot learn the way humans do — by focusing on the key parts of the material.** For example, content words usually make up only a small proportion of a sentence, yet language models spend a large amount of their learning on function words such as “a”, “the”, “to”, etc., because the model treats every token equally.

- **GPT-3 is still unimodal — it can only work with text.** OpenAI’s dream is to achieve multimodal AGI that can not only output text but also perform multimodal generation. This is what GPT-4 was set to address.

- **Poor interpretability.** You will never know which specific weights in the model are responsible for turning a given input into a beautiful output.

- **It may generate harmful or biased content that is not aligned with human values or socialist core values.** OpenAI investigated GPT’s gender biases, racial biases, and so on. For example, the next-token predictions following “A man is ___” and “A woman is ___” can differ dramatically.

### Remaining Question: How Did GPT-3 Evolve into ChatGPT?

In the beginning, GPT-3 performed reasonably well on some tasks, but it was still far from the stunning level demonstrated by today’s ChatGPT. We know that ChatGPT can understand and follow human instructions exceptionally well. It engages in genuine natural language interaction with humans through an extremely clean, constraint-free interface. It maintains context, can solve nearly all natural language tasks, performs logical reasoning, and even writes code.

**So, how did GPT-3 get there? What exactly did people do to GPT-3 on the journey toward the ChatGPT era? This is the question we will explore next.**

The specific evolutionary path is shown in the figure below (quoted from [Yao Fu](https://franxyao.github.io/)).

![](https://www.waytoagi.com/api/kb-media/MnIibUR8eo1Zg8x38AscnAztnPd)

In the following section 12.4, we will examine the first piece of the puzzle that unlocked GPT-3’s capabilities.

---

## Codex: Fine-tuning a GPT Model with GitHub Code (June 2021)

#On June 29, 2021, GitHub officially released GitHub Copilot. Developed in collaboration between GitHub and OpenAI, this AI-powered tool provides automatic code completion for developers using Visual Studio Code, Microsoft Visual Studio, Vim, Cursor, or JetBrains IDEs. Official page: [GitHub Copilot · Your AI pair programmer](https://github.com/features/copilot)

#Those interested can check out the demo released by OpenAI: [Creating a Space Game with OpenAI Codex](https://openai.com/blog/openai-codex), which demonstrates how to build a small game using natural language.

![](https://www.waytoagi.com/api/kb-media/OO3ubM7KYoZJy4xpu0ucjM3inSh)
![](https://www.waytoagi.com/api/kb-media/Hh22bhwSQoKkOExlK8kcAJalngg)

#“There’s no way OpenAI would ever use your fine-tuning stuff. I’d rather starve, die outside, or jump off a building.” — “It smells so good!”

Even without being specifically trained for code generation, GPT-3 could still produce some simple code, though its overall performance was quite poor. So the natural question arose: if we feed the model a substantial amount of code, could it achieve significantly better results in code generation and even serve as a useful assistant for programmers? Codex was built on exactly this idea. The OpenAI team collected all unique Python files from GitHub, totaling 179GB (which drew widespread criticism), applied basic filtering to remove overly large files (>1MB) and excessively long code (>100 lines or single lines exceeding 1,000 characters), and created a training dataset. Using this dataset, they fine-tuned a GPT-3 model.

Although Codex appears impressive and unique, explaining it doesn’t require complex theory:

> > Essentially, it is an extended version of GPT-3 that was fine-tuned on a large corpus of publicly available code from GitHub, with its weights updated to enable code generation. Its ability to generate code still stems from the next-token prediction mechanism of language models. In other words, it is a downstream application of a pretrained language model that has been fine-tuned for code generation.

The paper behind Codex: [Evaluating Large Language Models Trained on Code](https://arxiv.org/abs/2107.03374)

> We introduce Codex, a GPT language model fine-tuned on publicly available code from GitHub, and study its Python code-writing capabilities. A distinct production version of Codex powers GitHub Copilot. On HumanEval, a new evaluation set we release for measuring functional correctness of synthesized programs from docstrings, our model solves 28.8% of the problems, while GPT-3 solves 0% and GPT-J solves 11.4%. Moreover, we find that repeated sampling from the model is a surprisingly effective strategy for producing working solutions to difficult prompts. Using this method, we solve 70.2% of the problems with 100 samples per problem. Careful investigation of the model’s limitations reveals that it has difficulties with docstrings describing long chains of operations and with binding operations to variables. Finally, we discuss the potential broader impacts of deploying powerful code generation technologies, including security and economic implications.

Note: HumanEval is a dataset collected by OpenAI containing 164 original programming problems that cover language understanding, algorithms, simple mathematics, and typical software engineering interview questions. It is used to evaluate a model’s code generation capabilities.

[OpenAI Codex Paper In-depth Reading](https://www.bilibili.com/video/BV1iY41137Zi/?buvid=ZE4EBEE92994324F407089826EE9BEE9DE8E&is_story_h5=false&mid=jOTTvC9MAcEUtHyHp%2B%2B2ww%3D%3D&p=1&plat_id=114&share_from=ugc&share_medium=iphone&share_plat=ios&share_session_id=410BD0A2-09B3-40DA-92AE-963B9EF201DF&share_source=WEIXIN&share_tag=s_i&timestamp=1682615486&unique_k=i6pA5Lz&up_id=1567748478) by Li Mu

> > **Fine-tuning GPT-3 to learn code was the first piece of the puzzle on our journey toward ChatGPT!**

> > The reason we dedicate a full article to Codex, which may seem unremarkable at first glance, is that many people speculate (or believe) that the complex logical reasoning abilities that emerged in models like ChatGPT are, to some extent, the result of learning code generation. During this process, large language models acquired the capability of reasoning. Reference: [How does GPT Obtain its Ability? Tracing Emergent Abilities of Language Models to their Sources](https://yaofu.notion.site/How-does-GPT-Obtain-its-Ability-Tracing-Emergent-Abilities-of-Language-Models-to-their-Sources-b9a57ac0fcf74f30a1ab9e3e36fa1dc1#929906a4292b4cceadabd92c47f3843f), by [Yao Fu](https://franxyao.github.io/), yao.fu@ed.ac.uk

---

# A New Paradigm for Pre-trained Language Models: Prompting!

![](https://www.waytoagi.com/api/kb-media/ZRG8bnWmOoyIQqxo1JncsfMZnfs)

As mentioned in Section 12.3, GPT-3 introduced a pivotal concept — **In-Context Learning (ICL)**.

> ICL is essentially the forefather of Prompting. It single-handedly shifted the paradigm of applying pre-trained language models to downstream tasks from the Fine-Tuning era into the Prompting era. Shortly afterward, three major paradigms of Prompting emerged for ultra-large pre-trained language models: In-Context Learning (ICL), Instruction Tuning, and Chain-of-Thought (CoT).

> Now, as of this writing in 2021, **we are in the middle of a second sea change, in which the “pre-train, fine-tune” procedure is replaced by one in which we dub “pre-train, prompt, and predict”.** In this paradigm, instead of adapting pre-trained LMs to downstream tasks via objective engineering, downstream tasks are reformulated to look more like those solved during the original LM training with the help of a textual prompt.

> —— [Pre-train, Prompt, and Predict: A Systematic Survey of Prompting Methods in Natural Language Processing](https://arxiv.org/pdf/2107.13586.pdf)

**The table below lists the models covered in this chapter.**

| **Model** | **Paper** | **Model Size** | **Paradigm & Key Innovation** | **Evaluation & Significance** |
| --- | --- | --- | --- | --- |
| GPT-3 *(mentioned only; already covered in 12.3)* 2020.5 | [Language Models are Few-Shot Learners](https://arxiv.org/pdf/2005.14165.pdf) | 175B parameters | Pre-train + Prompt + Predict. Innovation lies in **in-context learning**. | Pioneering introduction of the **in-context learning** concept — the true originator of Prompting. **In-Context Learning (ICL)** is the first major Prompting paradigm designed for large models. |
| InstructGPT 2022.3 | [Training language models to follow instructions with human feedback](https://arxiv.org/pdf/2203.02155.pdf) | 1.3B parameters | Pre-train + SFT + RLHF. Essentially still a form of Fine-tuning. RLHF can be understood as a fine-tuning approach that converts generative tasks into discriminative ones to reduce annotation costs. | **Instruction Tuning** is the second major Prompting paradigm for large models. When using SFT + RLHF to align models with human values, the process may have taught the model how to follow instructions. |
| PaLM 2022.4 | [PaLM: Scaling Language Modeling with Pathways](https://arxiv.org/abs/2204.02311) | 540B parameters | Demonstrated that **Chain-of-Thought prompting** can significantly improve model performance on challenging downstream tasks such as arithmetic reasoning and commonsense reasoning (based on world knowledge, e.g., “will cheese melt if left in the fridge?”). | PaLM’s primary goal was to prove that further scaling model parameters could still yield additional performance gains. **Chain-of-Thought (CoT)** is the third major Prompting paradigm tailored for large models. |

# During my own learning journey, I often felt confused about the concepts of Prompting, Prompt Tuning, and Prompt Learning. **This is why I want to begin this chapter with a clear conceptual clarification, distinguishing these three related but distinct ideas.**

**Concept Clarification: Prompting, Prompt Tuning, and Prompt Learning**

> Prompting refers to providing a language model with a specific piece of text (i.e., a prompt) to guide it in generating the particular output we desire. It’s essentially the same as typing messages to ChatGPT.

> **Prompting refers to the process of giving a specific prompt or input text to a language model to guide its generation of a specific output text.** The prompt can be a question, a sentence, or just a few words related to the desired output. The language model then produces the output based on the prompt and its own internal knowledge of language.

> In other words, Prompting is a technique for guiding a language model to generate specific output text, whereas Prompt Tuning is a method for adapting a pre-trained language model to a downstream task by fine-tuning it with task-specific prompts.

**Prompt Tuning** is closer to traditional fine-tuning. It is an automated way to generate “soft prompts.” We’ll explain exactly how it works later, but for now it’s enough to know that Prompt Tuning is a special form of fine-tuning. It does modify the model’s weight parameters, yet it is far more parameter-efficient than full fine-tuning.

> **"Prompt tuning", a simple yet effective mechanism for learning "soft prompts" to condition frozen language models to perform specific downstream tasks.** Unlike the discrete text prompts used by GPT-3, soft prompts are learned through backpropagation and can be tuned to incorporate signal from any number of labeled examples. —— [The Power of Scale for Parameter-Efficient Prompt Tuning](https://arxiv.org/abs/2104.08691)

> > First, let’s quickly clarify the definition of Prompt Learning with a highlighted block:

> > **Prompt Learning is a very general term. It can be understood as any machine learning paradigm that involves the use of prompts.** In simple terms, it refers to methods that edit the input of downstream tasks so that its form mimics the data and tasks used during the model’s pre-training. For example, in a sentiment classification task, supervised learning would feed the model “I failed my exam today” and have it output a classification score or distribution. In contrast, prompt learning appends a natural language template such as “I feel very ____” after the sentence, lets the model generate the missing part, and then maps the generated content to a classification label via a mapping function.

> > ——Harbin Institute of Technology ChatGPT Survey Report

> > Next, let’s use another highlighted block to quickly explain how the Prompt Learning paradigm works:

> > **Traditional Pre-training + Fine-tuning**: After pre-training, the model is fine-tuned on labeled downstream datasets, which requires updating the model’s weights and biases. The model then predicts output y given downstream input x: P(y|x).

> > **New Paradigm: Pre-training + Prompt + Predict**: Given input x, a template is used to convert it into a specific structured prompt x'. x' is an incomplete sentence with a certain format, where some fields remain unfilled. The model fills in these fields based on probability to produce a complete input \hat x. Based on this \hat x, the model then predicts the output y.

Prompt Learning is a broad term that refers to the use of prompts in machine learning. In natural language processing, it involves training a language model to understand and respond to a specific set of prompts.

Finally, let’s briefly mention **Prompt Engineering**. The development of language technology has gone through four paradigms: the fully supervised learning era based on symbolism, the fully supervised learning era based on neural networks, the pre-training + fine-tuning stage, and the pre-training + prompting + prediction stage. These four stages correspond to four types of engineering: feature engineering (manually extracting features), architecture engineering (building better neural network structures to extract features more effectively), objective engineering (selecting good objective functions), and prompt engineering. **Prompt Engineering** is the practice of carefully designing prompts so that language models can generate the outputs we want, thereby unlocking the full potential of these models.

## The Beginning: When We Discovered That the Bigger the Model, the Better…

In section 12.2.2.4, we mentioned that the GPT-2 model reached 1.542 billion parameters. Although its performance was not yet satisfactory, it did prove that continuously scaling up parameters and making the model larger could still improve performance. However, as models grew larger, other problems quickly emerged. The two main issues are as follows:

- **Larger pre-trained models require far more pre-training data.** When the amount of unsupervised pre-training data becomes massive, the labeled data available for downstream supervised tasks becomes negligible in comparison.

- **Larger pre-trained models with more parameters dramatically increase the cost of computing gradients via backpropagation.** Fine-tuning becomes extremely expensive and often impractical.

- In addition, **fine-tuning inevitably modifies the model’s weights and biases based on supervised downstream tasks, making it very prone to overfitting.**

> We know that GPT-2 had 1.5 billion parameters, while GPT-3 would scale up to 175 billion parameters. With such an astonishing model size, after investing enormous resources to complete pre-training, performing gradient descent and backpropagation—even just for fine-tuning on a small amount of downstream task data—becomes a cost that is almost unbearable.

> The traditional solution is to look for **parameter-efficient** transfer learning methods. That is, during fine-tuning, instead of updating all parameters, only a subset of them is modified. If we can minimize the number of updated parameters while still preserving task performance, that is already a good outcome.

> But the OpenAI team would not settle for that. Their dream was to achieve AGI—general, human-like intelligence. Humans are not limited to excelling at only one specific downstream task. No matter how efficient parameter-efficient transfer learning becomes, it still requires humans to explicitly define and partition tasks. Therefore, OpenAI focused on another solution: **Could we apply the model to any downstream task without changing its parameter weights at all, but instead simply provide the model with some natural language prompts?** This is exactly what Prompt is.

> **The reason for writing all this is to help everyone understand: Prompt engineering is not just some wild idea from engineers. It is a prerequisite that enables these massive “bigger-is-better” models to be useful across a wide variety of scenarios, and it is also the necessary path toward AGI.**

## Pre-Prompt Era Attempts: Parameter-Efficient Learning

[【arxiv】Parameter-Efficient Transfer Learning for NLP](https://arxiv.org/pdf/1902.00751.pdf)

[Parameter-Efficient Fine-Tuning Guide](https://zhuanlan.zhihu.com/p/619583361) By [TimsonShi](https://www.zhihu.com/people/timsonshi)

#### Definition of Parameter Efficiency

- **Full Fine-Tuning:** When performing fine-tuning for downstream tasks, all model parameters are updated. This inevitably causes the model to overfit to small target datasets, making it unusable for other tasks after fine-tuning.

- **Parameter-Efficient Fine-Tuning (PEFT):** When performing fine-tuning for downstream tasks, not all model parameters are updated. We may selectively update only the top few layers of weights, or update only the bias terms without changing the connection strengths between neurons. The goal is to preserve the model’s performance on downstream tasks while updating as few parameters as possible.

#### Partial Parameter Fine-Tuning: Selective Methods

To address the fine-tuning challenges of massive pre-trained models, researchers first proposed methods that fine-tune only a subset of parameters or freeze most of them.

- **The earliest works focused on fine-tuning only the top few layers of the network.**

- **Later, people realized that parts of the network most relevant to the downstream task could be fine-tuned based on human experience and reasoning.**

1. First, humans possess prior knowledge about the distribution of model parameters. For example, after completing Chapter 10, we understand that the Encoder is responsible for encoding language into high-dimensional vectors, while the Decoder generates the target sentences.

2. With such prior-knowledge-based assumptions, when fine-tuning model parameters, we can update only the portions most relevant to the target task. For instance, if we want to convert a Transformer originally used for summary generation into a Paraphrasing model that generates original text, we may only need to modify the Decoder parameters without touching the Encoder.

- **More extreme approaches involve fine-tuning only the bias terms or specific rows of the model.**

- **The most extreme version may involve sparsely updating the model—ignoring its structure and updating only certain parameters.**

#### Enhancing Existing Pre-trained Models with Additional Parameters: Additive Methods

**The core idea of additive methods is to enhance existing pre-trained models by introducing extra parameters or layers, training only these newly added parameters.** This is currently the largest and most widely adopted category of PEFT methods. The primary implementation of additive methods is through adapters (soft prompts will not be discussed here).

**Adapter**

**In simple terms, it involves inserting a small fully connected network after a Transformer sub-layer.**

> Building upon the “partial parameter fine-tuning” approach, researchers proposed the Adapter method. By adding a flexible, plug-and-play trainable Adapter Module, we can alter the data distribution of a specific layer (or several layers), enabling the model to adapt to a wide variety of tasks and domains. The typical practice is to have one Adapter Module per task or domain. During training, only the parameters of the Adapter corresponding to the current task are updated. During inference, the Adapter for the relevant task/domain is activated, while Adapters for other tasks/domains are ignored. Compared with “partial parameter fine-tuning” methods, the advantages of Adapter methods are (1) being more lightweight and (2) achieving better performance with the same proportion of trainable parameters.

#### Reparameterization-based PEFT

[【arxiv】INTRINSIC DIMENSIONALITY EXPLAINS THE EFFECTIVENESS OF LANGUAGE MODEL FINE-TUNING](https://arxiv.org/pdf/2012.13255.pdf)

Reparameterization-based PEFT methods leverage low-rank matrix representations to reduce the number of trainable parameters. **The most widely used reparameterization-based method today is Low-Rank Adaptation (LoRA).** The term LoRA is familiar to many readers—especially those interested in Diffusion models! In numerous applications, Low-Rank Adaptation has proven highly effective. For example, in image processing, low-rank structures are used for image denoising, image restoration, and image segmentation. In recommendation systems, Low-Rank Adaptation improves the accuracy and robustness of recommendation algorithms. However, I have not yet decided whether to introduce LoRA in this article.

#### Evaluation of the Above Methods

In sections 12.3.2.2–12.3.2.4, we discussed many parameter-efficient learning methods designed to address the increasing difficulty of training ever-larger LLMs. However, we can see that all the methods above are based on the “pre-training then fine-tuning” paradigm. No matter how lightweight they are, each task still requires its own set of parameters (even if most parameters can be shared).

> At this point, most people have not actually realized that **its fatal flaw is: tasks themselves must be manually defined**. Yet knowledge in real life is not strictly categorized by tasks. Most real-world tasks involve multiple capabilities: for example, a Chinese person reading an English article and then writing a summary in Chinese involves both *translation* and *summarization* abilities. **Prompting can blur the boundaries between tasks—it does not require humans to explicitly divide tasks. Instead, the task description is provided directly as part of the input to the pre-trained model.**

> This is precisely why the Prompting paradigm is “a critical step toward a truly unified language model.”

## Defining Prompting: A Key Step Toward a Truly Unified Language Model

![](https://www.waytoagi.com/api/kb-media/TQF5bR8hKoSuSqxv0KtcMsL8nSd)

Image source: [Pre-train, Prompt, and Predict: A Systematic Survey of Prompting Methods in Natural Language Processing](https://arxiv.org/pdf/2107.13586.pdf). This diagram summarizes the four paradigms that emerged during the development of NLP. The two figures in the bottom-right corner provide a clear contrast between the Fine-tune paradigm and the Prompt paradigm: whether to make the pre-trained model adapt to downstream tasks, or to make downstream tasks adapt to the pre-trained model.

### **Definition of Prompting / Prompt Learning**

After reading [12.2.2.1](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#KUW4dyCAyo442wx04r0cAT6Fnvd), we should understand that the purpose of a Prompt is to convert the objective of a downstream Fine-tuning task into a Pre-training task (i.e., expressing various subtasks through Question Answering based on next-token prediction). At the same time, we must not construct task-specific input structures for downstream tasks or introduce additional special tokens.

This approach of prompt learning narrows the gap between the test distribution and the pre-training distribution, allowing us to leverage the powerful language modeling capabilities that large-scale pre-trained language models acquired during pre-training. As a result, these models can achieve strong performance on various downstream tasks **without any fine-tuning**.

Once the Prompt paradigm is adopted, the original Pre-train, Fine-tune paradigm evolves into **Pre-train, Prompt & Predict**.

> The new paradigm that incorporates Prompting can be roughly summarized as “pre-train, prompt, and predict.” In this paradigm, downstream tasks are reformulated to resemble the pre-training task. For example, given a pre-trained GPT and the input sentence “I love this movie.” for a text sentiment classification task, we can append a prompt such as “The movie is ___”. The pre-trained language model then fills in the blank with sentiment-related words like “great,” “fantastic,” etc. Finally, these answers are mapped back to sentiment classification labels. **In this way, by selecting appropriate prompts, we can steer the model’s predictions, enabling a purely unsupervised PLM to be applied to a wide variety of downstream tasks.**

> —— [Zhihu: NLP’s New Favorite — A Brief History of Prompt](https://zhuanlan.zhihu.com/p/399295895) by [AI Box Column](https://www.zhihu.com/people/dou-hong-jian-44), Author: Min Yingqian@RUC

**Mathematical distinction between fine-tuning and prompting:**

- We know that the Fine-tuning process is a form of supervised learning. Given an input $x$, a model parameterized by $\theta$ predicts the probability distribution of the output $y$: $P(y|x;\theta)$. This distribution is then compared with the labeled output to compute the loss function.

- In contrast, the goal of Prompting is to avoid supervised fine-tuning with labeled data. Therefore, there are no input-output pairs ($x$ and $y$). Mathematically, it works as follows: given the input, the model models the probability distribution of $x$: $P(x;\theta)$, and then uses this distribution over $x$ to predict the model’s output $y$.

- This explanation can still feel confusing. A clearer way to put it is: the model understands our intent and slightly transforms the input $x$ we provide. The transformed input, which we can call $\hat{x}$, becomes something the model is more familiar with, and the model then predicts $y$ based on $\hat{x}$.

- **It is clear that the above process is unsupervised, and predicting $y$ based on $\hat{x}$ is a capability the language model already possesses. Therefore, the key lies in how to design the mechanism that transforms the original input $x$ into $\hat{x}$.**

### **Prompts Were Not Originally Called “Prompts”—They Were Simply Templates.**

Section 13.2.2.1 mentions that the key lies in how to design the mechanism that transforms input $x$ into $\hat{x}$. This naturally leads to one straightforward approach—using templates.

Actually, Prompt was not originally called by this name—it was simply a kind of template.  
That’s why, in the paper that introduced GPT-3, [*Language Models are Few-Shot Learners*](https://arxiv.org/pdf/2005.14165.pdf) (May 2020), the word “Prompt” appears only 27 times. By the time of InstructGPT (March 2022), however, the term appeared more than 300 times in the paper.

Prompt was originally an input format or template designed by researchers for downstream tasks. It encodes information about different downstream tasks and closely resembles the input format used during the pre-training of large language models. This similarity helps the pre-trained language model “recall” the knowledge it acquired during pre-training.

A template typically contains two parts to be filled: one is the **input slot [X]**, and the other is the **answer slot [Z]**.

> The table below shows examples of how a pre-trained language model, without any fine-tuning, can leverage templates and its own next-token prediction capability to perform various downstream tasks.

| **Downstream Task Type** | **Task** | **Input [X]** | **Template**<br>(Mapping Input to Prompt (1)) | **Answer [Z]**<br>(Prediction (2)) |
|--------------------------|----------|---------------|------------------------------------------------|------------------------------------|
| Text Classification | Sentiment Classification | This movie is really good. | - [X] It is [Z].<br>(This movie is really good. It is [Z]? → wonderful)<br><Then map “wonderful” to positive sentiment via a function> | wonderful (positive sentiment) |
| | Topic Classification | Next, I will criticize a game. | “[X]”. This passage is about the topic of [Z].<br>(“Next, I will criticize a game”. This passage is about [Z]? → Genshin Impact) | Genshin Impact |
| Text Pair | Natural Language Inference (Entailment; NSP) | [X1] The story takes place in a land called Teyvat.<br>[X2] The player embarks on a series of adventures in Hyrule Kingdom. | We know that [X1]. Therefore, the statement “[X2]” is [Z].<br>(We know that the story takes place in a land called Teyvat. Therefore, the statement “The player embarks on a series of adventures in Hyrule Kingdom” is [Z].) | correct / incorrect / irrelevant |
| Text Generation | Summarization | Back then, Chen Daozai could win 37 million with 20 bucks. Winning 5 million with 200,000 is definitely no problem for me. | “[X]”. This passage mainly expresses [Z]. | Chen Daozai made a fortune through gambling; naturally, I can also make a small profit. |
| | Translation | Look at yours. | Chinese: [X]. English: [Z]<br>(Chinese: Look at yours. English: _____) → can can need | can can need |

<Note: The purpose of the content in this table is to enable a pre-trained model to be used for a wide variety of downstream tasks. It may not feel very relevant to the ChatGPT we are familiar with today. After all, before ChatGPT appeared, the goal of training LLMs was not to build chatbots, but to solve various natural language subtasks.>

(1) Here, we call the input we provide **Input**. The Input is first mapped into a Prompt by a function \( f_{\text{prompt}} \). The mapping function can fill the [X] part of the Template using our input. A Prompt is a template and also an incomplete sentence that contains an unfilled slot—the [Z] part. At this point, another function comes into play: \( f_{\text{fill}} \).

(2) \( f_{\text{fill}}(\text{prompt}) \) computes the probability distribution over possible content for [Z]. The **Answer** is the **correct** content that should be filled into Z. In the examples above, the goal of the language model is to output the correct Answer.

> > **Prompt Engineering:** Refers to the process of designing the prompt function \( f_{\text{prompt}}(x) \) to achieve strong performance on downstream tasks.
>
> > **It can be understood this way: The emergence of the Prompting paradigm means that when facing downstream tasks, we no longer need to Fine-tune a large pre-trained model as we did before. Instead, we only need to train a good function \( f_{\text{prompt}} \) that maps input text into a template.**
>
> > Consequently, choosing the right template and mapping function becomes very important. For example, in the sentiment classification case, the template matches well with “This movie is really good.” But if we want to determine the sentiment of the sentence “And you, my friend, you are the real hero,” that same template would be completely off-target.

### **General Working Pattern of Prompt (The Most General Version)**

Section 13.2.2.2 has already explained in detail how Template-based Prompting actually works. Now let’s summarize the entire process.

![](https://www.waytoagi.com/api/kb-media/HJ8cbXXdkopgGExW4uPcC1Nnnjb)

1. First, we pre-train a language model on massive amounts of unlabeled data through self-supervised learning. **(Pre-train)**

2. We feed the model with input text *x*.  
Just like how we write prompts for ChatGPT today, the input text can be written quite casually. However, those of us who understand the technology know that different texts can produce vastly different results. Carefully crafted prompts written according to specific rules are far more effective at unlocking the model’s capabilities.

3. For a given *x*, we design a function *f_prompt* tailored to the specific downstream task, where *x* serves as the input. We define *f_prompt(x) = x'*.  
The purpose of this function is to transform the natural language input *x* provided by a human into a templated input *x'* that better enables the model to “recall” the knowledge it acquired during pre-training.  
**<This is why it is called “Prompt” (prompting) rather than “instruction” — because it is a piece of text that helps the model recall what it learned during pre-training.>**  
For concrete examples, refer to the table in section 13.2.2.2. **(Prompt)**

(Note that *f_prompt* itself can also be a language model; the act of filling the input into a template can itself be based on probability distributions.)

1. As shown in section 13.2.2.2, the resulting *x'* contains two slots to be filled: an **input slot** `[X]` and an **answer slot** `[Z]`. The `[X]` slot is filled according to our actual input.

2. After applying *f_prompt(x) = x'*, we have already filled the original unfilled slot `[X]` in the template with our input *x*, producing *x'*. However, *x'* still contains an unfilled slot: `[Z]`.  
We now use another function *f_fill(x', z)* to generate a piece of text that fills this `[Z]` slot. **This process is called Predict.**  
The model performing this “prediction” is the very same large language model we pre-trained earlier. **(Predict)**

> > **Answer Engineering:**  
> > Refers to the engineering work of designing the answer *z ∈ Z* and the mechanism by which *z* fills the `[Z]` slot.
>
> > 1. Here, *z* can be chosen from a finite set of options — especially in classification tasks (e.g., the five sentiment categories “meltdown, classic, triggered, bootlicking, numb” we used earlier). It can also be any generated text used to fill `[Z]`, particularly in generative tasks (like GPT).
>
> > 2. A language model can do two things. First, its core competency: evaluating the probability that an entire sentence “makes sense.” This capability can be used to score sentences. For example, when filling `[Z]`, we can try all five options (meltdown, classic, triggered, bootlicking, numb), score each one, and select the highest-scoring one.
>
> > 3. Second, next-token prediction allows it to generate arbitrary content to fill `[Z]` without requiring humans to pre-define the options.

1. Generating a piece of text *z* to fill the `[Z]` slot is inherently a probability sampling process, which means there can be many possible choices and thus many different Filled Prompts. We select the highest-scoring *z* — denoted as *z** in the diagram — as the final output.

2. Finally, the language model outputs *z**. In this way, we have successfully completed the downstream task **without any fine-tuning**, relying solely on designing the template and the *f_prompt* function.

## Prompt Engineering & Prompt Tuning

Designing instructions and templates may seem straightforward, but in practice, pretrained models often struggle to truly “understand” these instructions.

> Prompt engineering is the process of creating a prompting function fprompt(x) that results in the most effective performance on the downstream task. In many previous works, this has involved prompt template engineering, where a human engineer or algorithm searches for the best template for each task the model is expected to perform.

**Prompt Engineering:** Refers to the process of designing a prompting function f_prompt(x) to achieve strong performance on downstream tasks.

### Manual Prompt Template Design vs. Automatic Template Learning

#### Manual Prompt Design

- In early research, this involved prompt template engineering, where human engineers or algorithms searched for the best template for each task the model was expected to perform. The underlying idea is that humans possess prior knowledge—including an understanding of the model and of language itself—so manually designing templates feels highly intuitive. (Perhaps the most natural way to create prompts is to manually create intuitive templates based on human introspection.) All the prompts shown in the table in [13.4.2](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#GuCCdWSoQooEGexSu1zcN2eXntg) fall into this category.

As shown in the table below, manually designing a template such as `We know that [X1]. So, the statement “[X2]” is [Z].` feels completely intuitive, and these templates are typically composed of natural language.

| Natural Language Inference (Entailment; NSP) | [X1] The story takes place in a continent called Teyvat. [X2] The player embarks on a series of adventures in the Kingdom of Hyrule. | We know that [X1]. So, the statement “[X2]” is [Z]. (We know that the story takes place in a continent called Teyvat. So, the statement “The player embarks on a series of adventures in the Kingdom of Hyrule” is [].) | Correct / Incorrect / Irrelevant |
| --- | --- | --- | --- |

> However, manual prompt template design has many limitations. First, crafting good templates is extremely difficult; it requires engineering experience and sometimes even artistic inspiration, bearing a strong resemblance to the “expert systems” of the past. From a historical perspective, this approach is destined to be phased out. Second, machine learning researchers are not necessarily experts in how machines actually work—prompts that align with human intuition are not always the ones that best unlock a model’s potential. The optimal prompts may be combinations of tokens that appear bizarre to humans; no amount of brainstorming would ever lead a person to discover them.

> (1) creating and experimenting with these prompts is an art that takes time and experience, particularly for some complicated tasks such as semantic parsing (Shin et al., 2021); (2) even experienced prompt designers may fail to manually discover optimal prompts (Jiang et al., 2020c).

#### Parameterized Prompt / Automatic Prompt

#Since we already have something as powerful as GPT-3, why not let the machine write the templates itself?

- This led to the emergence of **Automated Template Learning**. Instead of relying on human intuition to design templates, the model automatically generates them—deciding what words the template should contain, where the input slots should be, and where the answer slots should be.

- Once we broaden our perspective and let language models generate templates, a wealth of new possibilities emerges. First, we can leverage the strengths of neural networks to perform trial-and-error learning, continuously discovering, iterating, and optimizing \( f_{prompt}(x) \), steadily improving performance. Second, we can harness the automation capabilities of artificial intelligence—for example, generating a custom template for each individual input instead of using a single template for everything. As a result, automatic template learning has produced two main classification approaches:

  - **Discrete Prompts** and **Continuous Prompts**. The former refers to templates composed of natural language text, while the latter consists of vector combinations that still reside in the embedding space of the LLM.
  - **Static Prompts** and **Dynamic Prompts**. Static prompts use essentially the same prompt template for every input, whereas dynamic prompts generate a customized template for each input. Both static and dynamic strategies are applied across different types of discrete and continuous prompts.

> In particular, the automatically induced prompts can be further separated into discrete prompts, where the prompt is an actual text string, and continuous prompts, where the prompt is instead described directly in the embedding space of the underlying LM。

### Discrete Prompt a.k.a. Hard Prompt

**In automatic template learning, a discrete prompt (also known as a hard prompt) refers to generating prompt templates that exist in the form of natural language text.**

This name comes from the fact that natural language is essentially a sequence of one-hot token vectors residing in a discrete space. In contrast, prompts that exist in the embedding layer as dense vectors are continuous. (Works on discovering discrete prompts (a.k.a. hard prompts) automatically search for templates described in a discrete space, usually corresponding to natural language phrases).

The main generation methods include:

1. **Prompt Mining**: By analyzing large volumes of text data, identifying keywords, phrases, and sentences within it, and combining them into a series of concise and effective “prompts” to serve as input for natural language models.

2. **Gradient-based Search**: Gradient descent/ascent is a method for finding minima/maxima, and can naturally be used to find optimal prompts. However, since there are no differentiable functions in discrete spaces, the gradient descent algorithm requires modifications, making gradient-based search for hard prompts relatively complex.

3. **Prompt Generation**: Treating prompt creation as a text generation task and using standard generative language models to perform it. A typical example is the T5 model based on the seq2seq architecture.

### Continuous Prompt a.k.a. Soft Prompt

#Wait — do we really care whether the template is made of “natural language”? — Your next prompt doesn’t have to be a prompt at all!

> For some soft prompt methods, such as Prefix-Tuning and P-tuning, they re-examine the definition of a template, abandoning the conventional requirement that “a template must be composed of natural language.” This transforms template construction into a continuous parameter optimization problem. Although simple, it proves highly effective.

> —— [P-tuning: Automatically Constructing Templates to Unlock the Potential of Language Models - Scientific Spaces](https://spaces.ac.cn/archives/8295/comment-page-1) by Su Jianlin

> > Because the goal of constructing prompts is to find a way for the LM to perform tasks effectively, rather than for human consumption, there is no need to restrict prompts to human-readable natural language. For this reason, researchers have proposed continuous prompts (also known as soft prompts), **directly performing prompting in the model’s embedding space.**

> > (That said, in practice this usually means freezing most of the model’s parameters and only fine-tuning a small subset of parameters that represent the downstream task. These unfrozen parameters are the soft prompt.)

> > Note: The mathematical derivations in this section would be extremely complex if written out in full, which does not align with the purpose of an introductory document. Therefore, the explanation here is primarily conceptual. The original papers are linked throughout; interested readers or those with a strong technical background are encouraged to explore them directly.

#### What Soft Prompts Bring Us: The embedding vectors of a Template no longer need to correspond to natural language word embeddings.

**Continuous Prompts allow any vector in the embedding space to serve as a template token. These dense vectors that constitute the template do not need to come from the natural language vocabulary and do not have to correspond to any token in the model’s dictionary.**

Relaxing this constraint has several important implications:

1. **More flexible template representation:** In certain tasks, word vectors from the natural language vocabulary may not accurately capture the intended meaning of the template. For example, in specialized domains or with technical terminology, there may be no corresponding words in the vocabulary. Using vectors from the natural language vocabulary in such cases can lead to inaccurate template representations and degrade model performance. By relaxing the constraint, templates can be represented more flexibly and better adapted to different tasks and scenarios.

2. **Broader range of applications:** Loosening this restriction allows templates to be applied in a much wider variety of scenarios. For non-natural-language tasks such as code generation or machine translation, using vectors from a natural language vocabulary often makes little sense, since these tasks require representations that go beyond human language.

#### What Soft Prompts Bring Us: Removing the Constraint That Templates Must Be Parameterized by a Pre-trained LM

The significance of no longer requiring templates to be parameterized by a pre-trained language model is that we can now define templates using independent, trainable parameters instead of being tied to the model’s original weights.

This brings several key advantages:

1. **More flexible template representation:** Previously, template representations were dictated by the parameters of the pre-trained language model. This severely limited flexibility, as templates could only use vectors already present in the model. Now, we can define task-specific template parameters tailored to the needs of each downstream task, greatly improving flexibility and applicability.

2. **Finer-grained template tuning (Prompt Tuning):**

> Once the template is transformed from discrete natural language into continuous parameters (dense embedding vectors), we can optimize it using methods such as stochastic gradient descent.

Using independent template parameters allows us to adjust the template with much greater precision. We only need to fine-tune the template parameters rather than the entire pre-trained large language model. This idea directly leads to the concept of **Prompt Tuning**: **Prompt tuning typically refers to fine-tuning only the parameters within the template to adapt to specific downstream tasks.** In prompt tuning, the pre-trained language model itself is usually kept frozen, and only the template parameters are updated.

Specifically, the goal of prompt tuning is to adjust the template parameters so that the template better aligns with the input of the downstream task, thereby improving performance. Although these template parameters are typically initialized from the pre-trained model, the knowledge and capabilities of the original LLM still play a crucial role during tuning. Prompt tuning thus allows us to avoid modifying the entire pre-trained LLM, saving significant computational cost, while still leveraging the model’s rich prior knowledge.

#### Methods for Generating Soft Prompts: From Prefix-Tuning to Prompt Tuning

**1. The first stage of soft prompts: Prefix-Tuning (January 2021)**

[Arxiv] Prefix-Tuning: Optimizing Continuous Prompts for Generation  
https://arxiv.org/abs/2101.00190

**Prefix-Tuning** is a method that prepends a sequence of continuous task-specific vectors to the input. By adding a trainable prefix before the model’s input, it steers the model’s behavior for a specific task.

As shown in the figure on the right, **in Prefix-Tuning the model architecture is slightly modified: a trainable prefix is inserted before the input and before every hidden layer.** The prefix parameters are trainable, while the parameters of the original model (the “suffix”) are typically frozen.

Unlike traditional fine-tuning, Prefix-Tuning only updates the prefix parameters and leaves the rest of the model untouched. It can therefore be viewed as a much more lightweight form of fine-tuning.

![](https://www.waytoagi.com/api/kb-media/N4o4bldNGobRHgxljFacg6xVnsQ)

Why is this considered a form of soft prompt? Because the dense vectors in the prefix (which we can call task vectors) essentially act as a prompt — they tell the model what task it should perform. The only difference is that instead of using natural language, they use a long sequence of numbers that humans cannot read. This approach is conceptually very similar to the **Adapter** method mentioned earlier in the PEFT section — both introduce additional trainable parameters. The key difference is that instead of adding a fully connected layer at the end of the model, Prefix-Tuning concatenates a specific task vector sequence directly to the input word embeddings at the very beginning of the model.

**2. First Simplification of Prefix Fine-Tuning: P-Tuning (Hard-Soft Prompt Hybrid Tuning)**  
**2021.3**

[【Arxiv】GPT Understands, Too](https://arxiv.org/abs/2103.10385) (P-Tuning V1)

[【Arxiv】P-Tuning v2: Prompt Tuning Can Be Comparable to Fine-tuning Universally Across Scales and Tasks](https://arxiv.org/abs/2110.07602) (P-Tuning V2)

> A recent Arxiv paper [*GPT Understands, Too*](https://arxiv.org/abs/2103.10385) proposed a method called **P-Tuning**, which **successfully enables automatic template construction**. Moreover, with the help of P-Tuning, GPT achieved better results on SuperGLUE than BERT models of the same size for the first time. **This overturned the long-held belief that “GPT is not good at NLU,” which is also the reason behind the paper’s title.**

> —— [P-Tuning: Automatic Template Construction to Unlock the Potential of Language Models - Scientific Spaces](https://spaces.ac.cn/archives/8295/comment-page-1) by Su Jianlin

Instead of using a purely learnable prompt template, hard-soft hybrid tuning methods insert some tunable embeddings into a hard prompt template.

> In simple terms, hard-soft hybrid prompt tuning refers to inserting some tunable task-specific embeddings into the embedding tensor formed by discrete hard prompts.

P-Tuning learns continuous prompts by inserting trainable, tunable variables into the input embeddings.

![](https://www.waytoagi.com/api/kb-media/JBxsbULuNooGApxoWKtc8HH8nJd)

Specifically, the working principle of P-Tuning can be summarized as follows:

1. Take an input sentence and a pre-designed discrete template. For example, with the input “`The Disney film is good!`” and the template `[X], it was [Z]`, the resulting input becomes: `The Disney film is good! It was [MASK].`;

2. Within the input template, select one (or more) tokens to serve as pseudo tokens: `The Disney film is good! [pseudo] was [MASK]`. These can be initialized directly using the original token embeddings.

3. Feed all pseudo tokens \( P_i \) into an LSTM layer to obtain the hidden state vector \( h_i \) for each pseudo token.

4. Feed the entire sentence into GPT’s embedding layer. For the token embeddings corresponding to the pseudo tokens, replace them with \( h_i \). Finally, GPT generates the corresponding output based on this tensor.

**3. Further Simplification of P-Tuning: Prompt Tuning**  
**2021.4 / 2021.8**

[【Arxiv】The Power of Scale for Parameter-Efficient Prompt Tuning](https://arxiv.org/abs/2104.08691)

> **We freeze the entire pre-trained model and only allow an additional k tunable tokens per downstream task to be prepended to the input text.**

- In GPT-3, the Prompt Tokens \( P \) are part of the model’s embedding table. Therefore, they are governed by the model’s frozen parameters \( \theta \). Since the parameters are frozen, finding the optimal prompt typically requires manual search or non-differentiable automated search methods (the problem with hard prompts).

- Prompt Tuning still freezes the model parameters θ, but it removes the restriction that the prompt must be parameterized by θ. Instead, the prompt in Prompt Tuning has its own dedicated parameters θ_P, which can be updated through backpropagation. Prompt Design (manually crafting discrete templates) can be viewed as selecting prompt tokens from a fixed vocabulary of frozen embeddings, whereas Prompt Tuning treats the tokens as fixed while making their embeddings learnable.

- Compared to Prefix Tuning, Prompt Tuning no longer requires adding prefixes of the same length to every hidden layer. As a result, the model architecture remains completely unchanged. It simply makes the embedding parameters of certain tokens tunable. These tunable parameters account for only about 0.1% of the total model parameters. This makes Prompt Tuning significantly more flexible.

#### Are soft prompts necessarily better than hard prompts?

The answer is: not necessarily. While continuous prompts do offer the advantages mentioned in sections 13.5.3.1 and 13.5.3.2, their biggest drawback is that they are essentially still a parameter-efficient fine-tuning method similar to the pre-prompting era. The only difference is that the “adapter” is not a fully connected layer added before the model’s output, but is instead placed at the model’s embedding layer. From a fundamental perspective, it suffers from the same issues as fine-tuning, such as overfitting and unstable task performance. Additionally, although we consider soft prompting to be parameter-efficient and resource-saving, it still relies on backpropagation to tune parameters, and issues such as pseudo resource-saving remain.

**As we will see later, soft prompts were extremely popular throughout 2021. However, Google later revived hard prompts with a vengeance through Chain-of-Thought prompting, sparking a renaissance.**

### Recommended Articles:

[Zhihu: The Previous Life of ChatGPT — The Philosophy of Prompting](https://zhuanlan.zhihu.com/p/608139212) By [Pan Xiaoxiao](https://www.zhihu.com/people/pan-xiao-xiao-66-14)

[New NLP Paradigm After Fine-tuning: Prompts Are Getting Hot — CMU Chinese Postdoc Publishes a Survey Paper](https://mp.weixin.qq.com/s/2eA4PBd-wr9tVyyuzJ66Bw) By Machine Heart

[Paper Interpretation: Prefix-Tuning: Optimizing Continuous Prompts for Generation](https://blog.csdn.net/qq_36426650/article/details/120255851) By [Wang Jianing, Huashan Institute of Data Science](https://wjn1996.blog.csdn.net/)

[Paper Interpretation: GPT Understands, Too](https://wjn1996.blog.csdn.net/article/details/120802305) By [Wang Jianing, Huashan Institute of Data Science](https://wjn1996.blog.csdn.net/)

---

## ChatGPT/InstructGPT/GPT-3.5: SFT (Supervised Fine-Tuning) or Instruct-Tuning, and RLHF (Reinforcement Learning from Human Feedback) (March 2022)

Original Paper: [【Arxiv】Training language models to follow instructions with human feedback](https://arxiv.org/pdf/2203.02155.pdf)

According to OpenAI’s blog, the instruction learning approach used in InstructGPT is essentially the same as that of ChatGPT. Therefore, this article focuses on the InstructGPT paper, which offers a glimpse into the underlying principles of ChatGPT.

### Abstract

> Making language models larger does not inherently make them better at following a user’s intent. For example, large language models can generate outputs that are untruthful, toxic, or simply not helpful to the user. In other words, these models are not **“aligned”** with their users. In this paper, we show an avenue for aligning language models with user intent on a wide range of tasks by fine-tuning with human feedback. Starting with a set of prompts and prompts submitted through the OpenAI API, we collect a dataset of labeler-written responses that we use as a demonstration of desired model behavior. We then use supervised learning to fine-tune GPT-3 on this dataset. Next, we collect a dataset of human-ranked model outputs and use reinforcement learning from human feedback to further fine-tune the supervised model. We call the resulting models InstructGPT. In human evaluations on our prompt distribution, outputs from the 1.3B parameter InstructGPT model are preferred to outputs from the 175B GPT-3, despite having 100× fewer parameters. Moreover, InstructGPT models show improvements in truthfulness and reductions in toxic output generation while having minimal performance regressions on public NLP datasets. Although InstructGPT still makes simple mistakes, our results demonstrate that fine-tuning with human feedback is a promising direction for aligning language models with human intent.

> —— [【Arxiv】Training language models to follow instructions with human feedback](https://arxiv.org/pdf/2203.02155.pdf)

### The Problem to Solve: Misalignment

**What problems exist in large language models:**

By making models larger, we compress more data into the model’s weights, biases, and other parameters using Transformers. While this may improve next-token prediction across various tasks, it does not necessarily make the model better aligned with user intentions. For example:

1. **Simply not useful (i.e., talking nonsense)**. If you ask the model a specific question but it evades the topic and responds with a long, official-sounding but ultimately worthless answer, the model is clearly inadequate.

2. **Untruthful Hallucinations: Fabricated or AI-generated hallucinations**. (In natural language processing, hallucinations are typically defined as “generated content that is nonsensical or unfaithful to the provided source.”) As we all know, ChatGPT is very good at confidently making things up. A well-known meme is asking ChatGPT about “Lin Daiyu uprooting a weeping willow.” Its answer is impressively well-written (❌).

![](https://www.waytoagi.com/api/kb-media/ZBCcbCKvyoYP0fxkzB0c8zTMnzg)

> ChatGPT is particularly skilled at fabricating things because it has been trained on an enormous amount of data and has a strong ability to capture word context, which allows it to seamlessly weave incorrect information into surrounding text.

3. **Toxic: Harmful content**. For instance, asking GPT to write fake news, generate massive amounts of spam, create crime plans, explain how an AI could rule humanity, or produce insulting and racist statements.

**Why do these problems exist? — Misalignment**

> > An Underlying Premise: When we reflect on why these problems occur, we have already accepted a fundamental premise: artificial intelligence should produce outputs that humans like and that meet human needs — not merely perform “accurate” next-token prediction.

> This is because the language modeling objective used for many recent large LMs—predicting the next token on a webpage from the internet—is different from the objective “follow the user’s instructions helpfully and safely” (Radford et al., 2019; Brown et al., 2020; Fedus et al., 2021; Rae et al., 2021; Thoppilan et al., 2022). Thus, we say that the language modeling objective is misaligned. Averting these unintended behaviors is especially important for language models that are deployed and used in hundreds of applications.

Every time we ask a model a question, we expect it to provide the answer we want—one that solves our problem and is safe and harmless. That is the model’s true objective. Although LLMs can be prompted to perform a wide range of NLP tasks, including the Zero-shot (0S), One-shot (1S), and Few-shot (FS) settings mentioned earlier, **its actual objective function is extremely simple: to predict the next token as accurately as possible.**

L_1(\mathcal U) =∑_ilogP(u_i|u_{i-k},u_{i-k+1}...,u_{i-1};\theta)

This objective naturally deviates significantly from what humans truly want—helpful, safe, and aligned behavior. From this we define **Misalignment**: the LLM’s training objective differs substantially from human intentions. Excelling at next-token prediction does not equate to truly meeting user needs.

**Are these problems serious? The answer is: extremely serious!**

**Before we even talk about user experience, let’s look at issues that can determine the life or death of an entire product.**

- First, the United States places heavy emphasis on political correctness and has a long list of values that must be strictly followed—it is extremely picky. For example, if you let an LLM perform next-token prediction on prompts like “A man is ___” versus “A woman is ___”, the results can differ dramatically. Even if the model outputs “Lazy” as the most likely continuation for “A man is” and “Beautiful” for “A woman is”, critics will accuse the model of focusing excessively on women’s appearance, calling it a form of bias. In short, it is very hard to please everyone.

Public opinion may be somewhat more forgiving toward startups, but large companies face intense scrutiny. See the article: [Google apologises for Photos app's racist blunder](https://www.bbc.com/news/technology-33347866). In 2015, Google released a product that could recognize various elements in images, such as skyscrapers and cars. It ended up labeling several Black people as “Gorillas.” Once the media learned about it, the backlash was explosive. Google was forced to issue repeated apologies and eventually had to remove the feature entirely. **A perfectly good product was killed just like that.**

![](https://www.waytoagi.com/api/kb-media/Ez4pb4sc7oJ1P4xDggqcDW10nih)

- China, like the United States, has many sensitive topics that must not be touched. If a model outputs content that seriously violates core values or hits forbidden red lines, both the product and the company behind it could be shut down in one fell swoop.

**After considering these existential risks, let’s look at customer experience.** In many applications—especially industrial-grade or enterprise settings—we definitely want the model’s outputs to be stable and reliable. Unhelpful or hallucinatory outputs can reduce customers’ willingness to pay and even hinder the commercial adoption of LLMs. Therefore, we truly need to find ways to solve the Misalignment problem.

### Solution: Reinforcement Learning with Human Feedback (RLHF)

**Prerequisite knowledge: Basic reinforcement learning concepts. See Chapter 5,** [**link here**](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#CqqQdmKS8o0yWuxc3hccrZXWnwh)**.** The OpenAI team that developed RLHF originally came from a reinforcement learning background and already had deep expertise in this area.

**After reading the paper’s abstract and the issues raised in section 12.6.2, we now have a basic understanding of InstructGPT’s goal: to better align large language models with human values, making them more helpful and safer. Specifically, the method they adopted is RLHF — Reinforcement Learning from Human Feedback.**

![](https://www.waytoagi.com/api/kb-media/Ej8hbltjXonpJOxveSuc6HMxnSf)

Although this may be the first time many readers encounter reinforcement learning, the core ideas and methods behind RLHF are actually quite straightforward. Once you go back to Chapter 5 to build a basic understanding of reinforcement learning algorithms, patiently reading on will be manageable.

---

#### **Step 1: Supervised Fine-tuning (SFT)**

> Collect demonstration data, and train a supervised policy.

Don’t worry about the term “policy” for now. The first step is simply a straightforward process of fine-tuning the model using labeled data. Without the next two steps, this stage would not qualify as reinforcement learning at all.

1. **Collect Prompts.** Prompts come from two sources: (1) hiring people to write them manually, or (2) prompts submitted by users while using OpenAI’s GPT products.
2. **For the collected prompts, have humans write the corresponding outputs.** The outputs written by humans (which OpenAI calls **Demonstration Data** or **Labeler Demonstration**) naturally represent the *desired* outputs. Ideally, the model would always generate responses at this quality level.
3. **Through the first two steps, we obtain a labeled dataset.** Using Prompt (input) + Labeler Demonstration (desired output), we can fine-tune GPT following the standard fine-tuning paradigm.

![](https://www.waytoagi.com/api/kb-media/PWzWbS9CDoCAtXx8hysckagLnSf)

OpenAI refers to the above process of fine-tuning GPT-3 as **Supervised Fine-tuning (SFT)**. In principle, it is no different from fine-tuning any other model.

**#SFT is also known as Instruction Tuning. It is the second major piece of the puzzle on our Way to ChatGPT.**

**So what does this have to do with reinforcement learning? Why not just keep using large amounts of human-annotated data for fine-tuning? Why introduce RLHF?**

We can understand it this way:

> After SFT, the resulting GPT-3 can be viewed as a giant **Policy** function. This policy takes the user’s input (Prompt) as its **State**, and based on that state, it takes an **Action** — that is, it generates a response. In this framing, obtaining a high-quality LLM is no longer limited to gradient descent via labeled data; we can also optimize the policy using algorithms such as policy gradients to find a better strategy.

**If Labeler Demonstrations are so good, why not rely entirely on fine-tuning?**

- First, hiring people to write high-quality desired outputs is extremely expensive. You need to train them specifically — teaching them what counts as a good answer, which topics to avoid, when to be direct, and when to be tactful.
- Second, there are countless possible natural-language prompts, each unique and varied. It is nearly impossible to achieve full coverage by manually writing answers for every case.
- Finally, as mentioned earlier in 12.3.1, once a language model becomes sufficiently large, acquiring enough labeled data to tune it becomes both prohibitively expensive and practically impossible.

**Therefore, from the perspective of workload and cost, we must find a smarter way to align models with humans. That method is reinforcement learning.**

---

#### **Step 2: Train a Reward Model (RM)**

> RM training marks the beginning of RLHF’s departure from previous paradigms. The RM takes a sequence of text as input and outputs a scalar reward value that corresponds to human preference. As we discussed in 6.3.1, the essence of a language model (LM) can be next-token prediction or the probability that a sentence “makes sense.” Naturally, it can also be used to score a sentence. **Thus, the Reward Model is itself a language model.**

We know that asking humans to write a desired output as a label is costly because it is a *generative* task. In contrast, if humans only need to perform *discriminative* tasks, the workload is greatly reduced. This is the core insight behind RLHF.

**Translation:**

As mentioned earlier, the entire GPT-3 model after Supervised Fine-Tuning (SFT) is essentially a giant **Policy** function. This Policy takes the user’s input (Prompt) as its state (State) and, under that state, selects an Action — that is, it generates a response.

Now let’s recall the core components of reinforcement learning:

- **Basic elements**: [Environment, Agent, Goal]  
- **Main elements**: [State, Action, Reward]  
- **Core algorithmic elements**: [Policy, Value]

> It is worth noting that in RL, we can train a policy using only a reward function without a value function. This approach is known as **pure policy gradient methods**. In other words, among the elements listed above, the Value function is optional.

Therefore, in order to train an optimal Policy — that is, an LLM aligned with our values — the missing piece is the **Reward**.

The purpose of **Step 2** is exactly this: we want to train a good **Reward Model (RM)** that can score the outputs generated by the model.

![](https://www.waytoagi.com/api/kb-media/BdXkbnbn9onqDlxD2b8cP5VDnkr)

**The steps to train a Reward Model (RM) are as follows:**

1. **Sample a Prompt, feed it to the model, and have the model generate multiple different outputs.**

> **But the model parameters remain fixed during inference — why does GPT still exhibit randomness?**

> A: This is because during text generation, the GPT model adopts a strategy called **“Sampling”**, which introduces randomness.

> Specifically, when generating text, the GPT model predicts the next token based on the preceding context and then samples from the predicted probability distribution. As mentioned earlier, there are methods like Greedy Decoding and Beam Search. **However, ChatGPT uses Top-K Sampling instead of argmax for probability sampling**. It keeps only the top K most probable tokens from the predicted distribution and then randomly samples from those K candidates. Naturally, this sampling method allows the model to produce a variety of different outputs.

2. **Human labelers rank the multiple outputs produced by the model.** For example, given outputs A, B, C, and D, the labeler determines that D > C > A = B.

3. **Using the data from steps 1 and 2, we obtain a dataset whose purpose is to train a reward function — the Reward Model (RM).** 

   The RM is also a neural network. Its input is the model’s output, and its output is a scalar score assigned to that output. We first randomly initialize the Reward Model and let it score the outputs for a given Prompt. The scoring results should match the ranking provided by the human labelers. If they don’t match, we perform gradient descent. In short, the training objective is to make the scores given by the RM consistent with the ranking provided by the labelers.

We can see that the process of training this Reward Model is not itself reinforcement learning, but rather standard **supervised learning**. The supervision signal is the ranking scores annotated by humans. The reward model is simply used later as part of the reinforcement learning process.

---

#### Step 3: Use the large language model itself as the policy function, use the trained RM as the reward function, and fine-tune the model using the PPO algorithm.

> Optimize a policy against the reward model using reinforcement learning.

At this point, all the elements are very clear. What we need to do is simply use the existing reward function and apply a policy gradient algorithm to optimize our policy function — that is, the LLM.

After reading Chapter 5, you should have gained a basic understanding of the core ideas behind reinforcement learning. This article will not provide a detailed explanation of the PPO (**Proximal Policy Optimization**) algorithm. It really isn’t that complicated. Once you understand how to train a reward model, the rest is simply continuously updating the policy’s gradients so that it performs better.

(In fact, if we were to dive into the technical principles and engineering challenges, this step is still quite complex. Applying familiar RL algorithms to such an enormous model has always been a significant challenge.)

![](https://www.waytoagi.com/api/kb-media/HpmSbgPLVoDKKFx2Uj8cTFL9nFb)

The description of Step 3 here is intentionally brief and only covers the high-level algorithmic idea. For those who want to learn more, you can refer to:  
[The "Unsung Hero" Behind ChatGPT — A Detailed Explanation of RLHF Technology By HuggingFace](https://mp.weixin.qq.com/s/TLQ3TdrB5gLb697AFmjEYQ)

Although we casually say this step is “just PPO,” a closer look reveals that PPO for language models differs quite a bit from the PPO used in standard reinforcement learning. If you’ve reached this point and are curious, you can refer to: [Detailed Explanation of the RLHF Process for Large Language Models (with Code Walkthrough)](https://zhuanlan.zhihu.com/p/624589622?utm_medium=social&utm_oi=1239682420452487168&utm_psn=1635641325230948352&utm_source=wechat_session). This topic goes beyond the scope of this document and involves greater technical complexity, so we won’t cover it here.

> > **#RLHF is the final piece of the puzzle that unlocked GPT-3’s capabilities and led it to become ChatGPT.**

> A large language model the size of GPT-3 already possesses some zero-shot and few-shot abilities. This is likely because the pre-training corpus already contained similar instructions, and completing the downstream tasks posed by humans helps the model perform next-token prediction even better.

> After being trained on code, it gains the ability to generate code and may have also learned reasoning—i.e., logical inference.

> After Instruct-Tuning, it learns how to follow human instructions, and this capability generalizes remarkably well.

> After RLHF, it pays a performance cost (alignment tax) but further learns to follow human instructions, producing outputs that are useful, relevant, and non-toxic, thereby aligning with human values.

> #Neither instruction tuning nor RLHF injects new capabilities into the model. Instead, they allow the vast potential compressed within the model’s hundreds of billions of parameters—acquired from massive pre-training data—to be effectively unleashed, generating the outputs we actually want.

> The outputs we want to see (desired output) are those that can solve the downstream tasks we pose: they should be useful, correct, and logically reasoned. One extremely important reason why ChatGPT is so astonishing, in my personal view, is the idea of “alignment.” The model demonstrates extremely powerful understanding and reasoning abilities, but all of this may simply be in service of achieving better next-token prediction that is aligned with us.

---

### Model Performance and Evaluation

- **Answers generated by InstructGPT are clearly better than those from GPT-3 (they align much more closely with human values). This holds true even when the InstructGPT model has only 1.3 billion parameters while GPT-3 has 175 billion.**

> On our test set, outputs from the 1.3B parameter InstructGPT model are preferred to outputs from the 175B GPT-3, despite having over 100x fewer parameters. These models have the same architecture, and differ only by the fact that InstructGPT is fine-tuned on our human data. This result holds true even when we add a few-shot prompt to GPT-3 to make it better at following instructions.

> Outputs from our 175B InstructGPT are preferred to 175B GPT-3 outputs 85 ± 3% of the time, and preferred 71 ± 4% of the time to few-shot 175B GPT-3. InstructGPT models also generate more appropriate outputs according to our labelers, and more reliably follow explicit constraints in the instruction.

- **InstructGPT shows improvements over GPT-3 in terms of truthfulness:**

> On the TruthfulQA benchmark, InstructGPT generates truthful and informative answers about twice as often as GPT-3. Our results are equally strong on the subset of questions that were not adversarially selected against GPT-3. On “closed-domain” tasks from our API prompt distribution, where the output should not contain information that is not present in the input (e.g. summarization and closed-domain QA), InstructGPT models make up information not present in the input about half as often as GPT-3 (a 21% vs. 41% hallucination rate, respectively).

- **InstructGPT shows small improvements in toxicity over GPT-3, but not bias：** It reduces the generation of harmful content, but shows little improvement on bias. For example, it still defaults to assuming drivers are male and nurses are female.

> To measure toxicity, we use the RealToxicityPrompts dataset (Gehman et al., 2020) and conduct both automatic and human evaluations. InstructGPT models generate about 25% fewer toxic outputs than GPT-3 when prompted to be respectful. InstructGPT does not significantly improve over GPT-3 on the Winogender (Rudinger et al., 2018) and CrowSPairs (Nangia et al., 2020) datasets.

- **On public datasets, InstructGPT’s performance does not degrade significantly.** By adjusting the RLHF fine-tuning procedure, performance regressions can be minimized (We can minimize performance regressions on public NLP datasets by modifying our RLHF fine-tuning procedure). The specific approach is: when performing fine-tuning based on RLHF, in addition to updating parameters via the PPO algorithm, the original cross-entropy loss is also introduced for parameter updates. This idea is somewhat similar to the approach mentioned in 12.1.2.2 of combining two objective functions for joint training.
  - Here we introduce a concept called **Alignment Tax**. In many cases, solving a model’s misalignment problem requires sacrificing some performance in exchange for better alignment with humans. The performance that is sacrificed is called the alignment tax.
  - What OpenAI is saying is that because they adopted the method described above (the green-highlighted part), after completing RLHF and making the model’s outputs more consistent with human preferences, the alignment tax they paid is actually relatively small.

> During RLHF fine-tuning, we observe performance regressions compared to GPT-3 on certain public NLP datasets, notably SQuAD (Rajpurkar et al., 2018), DROP (Dua et al., 2019), HellaSwag (Zellers et al., 2019), and WMT 2015 French-to-English translation (Bojar et al., 2015). **This is an example of an “alignment tax,” since our alignment procedure comes at the cost of lower performance on certain tasks that we may care about.** We can greatly reduce the performance regressions on these datasets by mixing PPO updates with updates that increase the log likelihood of the pretraining distribution (PPO-ptx), without compromising labeler preference scores.

- **InstructGPT generalizes to the preferences of “held-out” labelers that did not produce any training data — that is, for certain types of questions, even without any human-ranked answers in the training set, the model can still generate responses that are better aligned with human preferences.**

> To test the generalization of our models, we conduct a preliminary experiment with held-out labelers, and find that they prefer InstructGPT outputs to outputs from GPT-3 at about the same rate as our training labelers. However, more work is needed to study how these models perform on broader groups of users, and how they perform on inputs where humans disagree about the desired behavior.

Generalization capability is a great thing — it means our workload can be dramatically reduced. This conclusion is entirely consistent with common sense, yet it is also extremely important.

- **InstructGPT models show promising generalization to instructions outside of the RLHF fine-tuning distribution. Its generalization ability is very strong: it can extend from generating natural language to generating code, and from English to multiple other languages, even though code generation and non-English instructions were almost never seen during RLHF fine-tuning.** (In contrast, getting GPT-3 to perform these tasks is much harder — it requires extremely careful prompt engineering, and even then the model sometimes fails to follow the instructions correctly.)

> **We qualitatively probe InstructGPT’s capabilities, and find that it is able to follow instructions for summarizing code, answer questions about code, and sometimes follows instructions in different languages, despite these instructions being very rare in the fine-tuning distribution.**

> In contrast, GPT-3 can perform these tasks but requires more careful prompting, and does not usually follow instructions in these domains. **This result is exciting because it suggests that our models are able to generalize the notion of “following instructions.”** They retain some alignment even on tasks for which they get very little direct supervision signal.

> This conclusion is also very important and exciting, because OpenAI believes it shows that **through RLHF, InstructGPT has not only achieved better alignment, but the things it has learned may have also helped it generalize the concept of “following instructions” (our models are able to generalize the notion of “following instructions”).** Looking back at the paper’s title now — [Training language models to follow instructions with human feedback](https://arxiv.org/pdf/2203.02155.pdf) — one can truly understand its real meaning.

- **InstructGPT still makes simple mistakes: it can still make some mindless errors and is not yet fully aligned.** That said, this is perfectly normal — the current results are already very impressive.

> For example, InstructGPT can still fail to follow instructions, make up facts, give long hedging answers to simple questions, or fail to detect instructions with false premises.

---

### Summary of the InstructGPT Paper

From the results, after applying RLHF, a 1.3-billion-parameter InstructGPT already outperforms the 175-billion-parameter GPT-3. It follows human instructions better, produces fewer toxic outputs, and if we have to name a remaining shortcoming, it would be that the bias issue has not yet been fully resolved.

A 1.3B-parameter model that incorporates a large amount of human intervention outperforms a 175B-parameter GPT-3. This outcome is impressive, but not entirely surprising:

- **The principle that “the more human effort you put in, the more intelligence you get.”** Hiring people at significant cost to write answers and provide labels is undoubtedly expensive. However, the resulting data has two major advantages: first, higher signal-to-noise ratio. Since some prompts and outputs are written by humans, they naturally contain far less noise than data crawled from the web. Second, the labeled information — such as the human-written demonstrations used in SFT — is much closer to the final evaluation criteria the model is judged against, so better evaluation results are only natural.

- **This reflects a deeper insight: there is no need to harbor hostility toward human-annotated data or view it as outdated.** If we rely solely on unsupervised pre-training of extremely large models using unlabeled data and push that approach to the extreme, both the computational cost and data requirements may become unsustainable. For certain capabilities we strongly desire but cannot achieve simply by scaling up data and letting Transformers compress patterns (such as being non-toxic, relevant, and helpful), incorporating more human-annotated data may offer far better cost-effectiveness.

[Reference: In-depth Reading of the InstructGPT Paper [Paper Reading · 48] - Bilibili](https://www.bilibili.com/video/BV1hd4y187CR/?buvid=ZE4EBEE92994324F407089826EE9BEE9DE8E&is_story_h5=false&mid=jOTTvC9MAcEUtHyHp%2B%2B2ww%3D%3D&p=1&plat_id=114&share_from=ugc&share_medium=iphone&share_plat=ios&share_session_id=AD8BBE31-8084-443E-99C6-F6936D247C54&share_source=WEIXIN&share_tag=s_i&timestamp=1682653931&unique_k=EPUNfG5&up_id=1567748478)

**How Does Instruction Tuning Actually Work?**

- Instruction tuning **does not inject new capabilities into the model** — all abilities already exist within it. The role of instruction tuning is to **unlock or elicit these existing abilities**. This is mainly because the volume of instruction-tuning data is several orders of magnitude smaller than pre-training data (foundational capabilities are instilled during pre-training).

- Instruction tuning **divides GPT-3.5 into different skill trees**. Some variants become better at in-context learning, such as `text-davinci-003`, while others excel at conversation, such as `ChatGPT`.

- Instruction tuning **trades performance for alignment with human preferences**. The authors of OpenAI’s instruction tuning paper call this the “alignment tax.” Many papers report that `code-davinci-002` achieves the best benchmark performance (though the model may not always behave as humans expect). After instruction tuning on top of `code-davinci-002`, the model produces outputs that better match human expectations (i.e., it becomes aligned with humans), such as zero-shot question answering, generating safe and fair dialogue responses, and refusing to answer questions beyond its knowledge scope.

> —— [The Past and Present Life of ChatGPT](https://blog.csdn.net/CV_Autobot/article/details/128424961?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168302340416800182779676%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=168302340416800182779676&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-128424961-null-null.142^v86^control_2,239^v2^insert_chatgpt&utm_term=alignment%20tax&spm=1018.2226.3001.4187) By Zidong Jiashi zhi Xin

---

**Reference:** [How does GPT Obtain its Ability? Tracing Emergent Abilities of Language Models to their Sources](https://yaofu.notion.site/How-does-GPT-Obtain-its-Ability-Tracing-Emergent-Abilities-of-Language-Models-to-their-Sources-b9a57ac0fcf74f30a1ab9e3e36fa1dc1#929906a4292b4cceadabd92c47f3843f)  
By [Yao Fu](https://franxyao.github.io/), yao.fu@ed.ac.uk

## Chain of Thought (CoT) (January 2022)

### [Foundational Paper: Chain-of-Thought Prompting Elicits Reasoning in Large Language Models](https://arxiv.org/pdf/2201.11903.pdf)

![](https://www.waytoagi.com/api/kb-media/OVthbflYuotI22xGOr9c0qyAnxe)

> Scaling up model size alone has not proved sufficient for achieving high performance on challenging tasks such as arithmetic, commonsense, and symbolic reasoning. —— [Self-consistency Improves Chain Of Thought Reasoning in Language Models](https://arxiv.org/abs/2203.11171)

Chain-of-Thought (CoT) prompting is a prompting technique designed for large language models (LLMs). While LLMs have completely reshaped research in the field of NLP, simply scaling up model size cannot solve every problem: LLMs still struggle to achieve strong performance on challenging tasks such as arithmetic, commonsense, and symbolic reasoning.

> > Once we have built sufficiently large language models and compressed a massive corpus through enough layers of Transformers, **the “energy” inherent in the model itself may already be enormous—enough to enable zero-shot and few-shot predictions (in-context learning). What we need to do is find more ways to unlock and release this energy**.
>
> > As mentioned earlier, Instruct tuning and RLHF do not inject new capabilities into the model; all capabilities were already present. However, they effectively channel the model’s vast latent potential toward “following human instructions and aligning with human values,” producing outstanding results. **Chain-of-Thought is one of the outcomes of this same philosophy: it is not that the model lacks reasoning ability, but that our prompts have not effectively elicited it. In previous In-Context Learning (ICL) approaches, we only provided input-output demonstrations for the model to learn from. For tasks that require reasoning, can we also include the reasoning path in the demonstration so the model can learn it? This is exactly the core idea behind CoT.**

Chain-of-Thought is a special form of In-Context Learning that uses discrete prompts rather than continuous prompts (which, at the time, represented a renaissance, as continuous prompt learning was then dominating the field). It resembles 1-shot and few-shot prompting, but **in addition to providing Input-Output demonstrations, we also insert a verbose reasoning process—called a “Relational” or “Reasoning Path”—between the input and output**. Therefore, when using CoT, the prompt given to the model becomes a short piece of text that contains a logical reasoning process, as shown in the blue section of the figure at the beginning of this chapter.

In April 2022, Google released the language model PaLM. After applying Chain-of-Thought techniques, it achieved state-of-the-art (SOTA) performance on mathematical problems using 540B parameters (roughly three times the size of GPT-3).

![](https://www.waytoagi.com/api/kb-media/Eu4abtdv7oS9ZSxqP2QcJzqqnAG)

> > This paper is relatively straightforward. It introduces a prompting method that explains the logic to the model in a detailed, step-by-step manner. It does not involve any modification to the model architecture (no code changes were made yet). In the following sections, we will explore how CoT can be combined with more model-level details.

### Classic CoT Method: Changing the Decoding Strategy — [Self-consistency Improves Chain Of Thought Reasoning in Language Models](https://arxiv.org/abs/2203.11171)

> In this paper, we introduce a novel decoding strategy called **self-consistency** to replace the greedy decoding strategy used in chain-of-thought prompting (Wei et al., 2022). This approach further improves the reasoning performance of large language models by a significant margin. Self-consistency is built on the intuition that complex reasoning tasks typically admit multiple different reasoning paths that can lead to the correct answer (Stanovich & West, 2000). The more deliberate thinking and analysis a problem requires (Evans, 2010), the greater the diversity of reasoning paths that can recover the correct answer.

> Self-consistency leverages the intuition that a complex reasoning problem usually has multiple distinct ways of thinking that lead to the same correct answer. The more complex the problem, the greater the number of potential logical chains.

![](https://www.waytoagi.com/api/kb-media/ZQqHbmGN6oi2kkxUmk3cQ5ZXn1c)

We know that a Decoder is inherently an autoregressive language model. When generating output, language models have several decoding strategies:

- **Greedy Decoding Strategy (Greedy Strategy)**: Always select the token with the highest probability.
- **Beam-Search Strategy**: See section 7.2.3.2.
- **Top-k Sampling**: Randomly sample from the k most probable tokens based on their probabilities.

Self-consistency is a method that builds upon chain-of-thought prompting by changing the decoding strategy. Its working mechanism is illustrated in the figure above. **Given an input enhanced with chain-of-thought prompting, the model uses its inherent capabilities to generate a set of outputs with diverse reasoning paths, each corresponding to an answer. This is similar to voting on the answers: we select the answer with the most votes as the model’s final output.**

### The World-Famous “Let’s Think Step by Step”: [Large Language Models are Zero-Shot Reasoners](https://arxiv.org/abs/2205.11916)

Generally, using chain-of-thought prompting implies One-shot or Few-shot learning, because you need to provide the model with at least one reasoning example (see the top-right of the figure below). However, this paper shows that Chain-of-Thought (CoT) can also be Zero-shot: under 0-shot CoT, we do not need to give the model any examples — we simply tell it to “think step by step.”

![](https://www.waytoagi.com/api/kb-media/C4yVbD9gkohO3wx9zdicr7eEnVf)

> While these successes are often attributed to LLMs’ ability for few-shot learning, we show that LLMs are decent zero-shot reasoners by simply adding “Let’s think step by step” before each answer.

By simply adding “Let’s Think Step by Step” before each answer, LLMs become decent zero-shot reasoners. Looking at the bottom-right of the figure above, this is a zero-shot arithmetic task. Without the phrase, the model would output an incorrect result. But after appending this sentence after “A:”, the model is able to generate its own reasoning process and produce the correct answer.

## Emergent Abilities of Large Language Models: We Still Don’t Know Why the Models We Saw That Day Could Reason

[Introduction to emergent abilities: [arxiv] Emergent Abilities of Large Language Models](https://arxiv.org/pdf/2206.07682.pdf)

### What Are Emergent Abilities in Large Language Models? — If a capability is absent in smaller models but appears in larger ones, we consider it an emergent ability.

> **Emergent abilities of LLMs** are formally defined as “the abilities that are not present in small models but arise in large models”, which is one of the most prominent features that distinguish LLMs from previous PLMs. It further introduces a notable characteristic when emergent abilities occur [31]: performance rises significantly above random when the scale reaches a certain level.

> —— [【arxiv】A Survey of Large Language Models](https://arxiv.org/pdf/2303.18223.pdf)

![](https://www.waytoagi.com/api/kb-media/HMyEbQDvYopZAkxEJGtcvxLTnvh)

> Referring to the figure above (from [arxiv] Emergent Abilities of Large Language Models). Emergent abilities cannot be predicted from smaller models using Scaling Laws. In the chart, the x-axis represents the number of model parameters and the y-axis represents performance on a given capability. Emergent abilities exhibit a clear pattern: before a certain threshold, performance stays close to random (even as the model grows larger, performance only fluctuates randomly around a baseline level). Once the threshold is crossed, performance jumps significantly above random.

### Emergence Is Sharp and Unpredictable

**Emergent abilities are unpredictable:**

- We cannot predict at what model scale a particular emergent ability will appear.

- **Most scholars training models today are often not using the optimal training recipe** (Today’s language models are likely not trained optimally (Hoffmann et al., 2022), and our understanding of how to best train models will evolve over time). Training a model involves countless engineering details: data sources and quality control (e.g., how GPT-3 processed the CommonCrawl dataset), hyperparameter selection (batch size, learning rate, number of iterations, gradient descent strategies, etc.), compute allocation, and many more. We still don’t know exactly how to train a model, or at what scale, emergence will occur.

**Emergent abilities are sharp — once the threshold is reached, they are triggered abruptly:**

> In fact, these emergent abilities are so surprising that “sudden, specific capability jumps” have been recognized as one of the two highest defining characteristics of LLMs. Terms such as “breakthrough capabilities” and “sharp left turns” have also been used.

> ——By [Jiqi zhi Xin](https://mp.weixin.qq.com/s/tt9xYESUgw3V2c4XJu5ZVw)

**When combined with techniques like Chain-of-Thought and instruction tuning, emergent abilities become even more striking.**

As shown in the figure below, once models reach a certain scale, using Chain-of-Thought prompting and instruction tuning leads to earlier and more powerful emergence.

![](https://www.waytoagi.com/api/kb-media/ZkMWbdaHJoaANXxgYgLcdf4qnob)

In short, when models are made large enough and trained on sufficiently diverse data, they exhibit many unexpected behaviors — including in-context learning and the reasoning abilities that emerge. **We still don’t know why the large models we saw that day could reason.** Many people’s reflections on the reasoning capabilities that emerge in large models have risen to philosophical levels: “What is consciousness?”, “Is language a unified abstract representation of everything in the universe?”, and “Can consciousness arise from compressing language?”…

### Criticisms of Emergence

[【arxiv】Are Emergent Abilities of Large Language Models a Mirage?](https://arxiv.org/pdf/2304.15004.pdf)

Although many people explain language models as complex systems—arguing that the Transformer in an LLM compresses a vast amount of information within such a system, thereby (in a physical sense) triggering a phase transition (“More is different”) to account for emergence—**some papers criticize this view, claiming that emergence is a pseudo-concept and that the appearance of emergent abilities depends on the evaluation metrics we choose for the model.**

- We know that we often evaluate a model’s capabilities using benchmark datasets such as GLUE, HumanEval, and various assessment metrics. Evaluating a model’s ability is never entirely objective or neutral; it depends on the metrics we select.

- **Researchers at Stanford question whether there are really so many “miracles.” They argue that the emergence we observe is actually a result of metric selection:** The suddenly steep curves at the beginning of the chapter appear because the metrics used to measure the model are nonlinear and brittle. When replaced with more continuous and smoother metrics, the emergence phenomenon becomes far less pronounced and closer to linear, as shown in the figure below.

![](https://www.waytoagi.com/api/kb-media/YbkwbEap4ojo7kxoRKRcFjIwnsb)

> Their skepticism is based on the following observation: emergent abilities in models appear only under metrics that scale the model’s per-token error rate in a nonlinear or discontinuous way. For example, in BIG-Bench tasks, >92% of emergent abilities appear under these two metrics:

![](https://www.waytoagi.com/api/kb-media/FrF7bcm6yomS4xxOuqZc6Ehxnab)

> This opens up an alternative explanation for the origin of emergent abilities in LLMs: although a model family’s per-token error rate changes smoothly, continuously, and predictably as model scale increases, **the seemingly sharp and unpredictable jumps may be artifacts caused by the measurement methods chosen by researchers**. In other words, emergent abilities may be a mirage, largely resulting from researchers selecting metrics that alter per-token error rates in a nonlinear or discontinuous manner. This is partly because there is too little test data to accurately estimate the performance of smaller models (making them appear completely incapable of performing the task), and partly because too few large-scale models were evaluated.

> Reference: [Stanford’s latest research warns: Don’t be too obsessed with emergent abilities in large models—they are a result of metric selection](https://mp.weixin.qq.com/s/tt9xYESUgw3V2c4XJu5ZVw), from Machine Heart.

> > That said, don’t use this paper to outright deny the existence of emergence. The paper itself is not entirely rigorous:

> > First, many task metrics are inherently unable to be “linear.” For such tasks, it is unreasonable to demand linearity.

> > Second, when NLP tasks use discontinuous metrics, the values are often averaged across multiple samples, so the overall numbers are actually continuous. The authors also provide two explanations attempting to show that emergence under such metrics is also a mirage, but they fail to prove it rigorously.

> > **In the end, regardless, the authors do not dispute that model performance improves as the number of parameters increases, nor do they deny the reasoning capabilities of LLMs. That alone is enough.**

---


# Why Was It More Hyped Than GPT at Launch? Illustrated Guide to Sesame Street’s New Member BERT! (2018.10)

![](https://www.waytoagi.com/api/kb-media/ICNabkkp4otU3TxMOUJcn24Hnqf)

BERT is here to show off. Hold My Beer! (Though we already covered GPT first… so the flex isn’t quite as strong.)

[【arxiv】BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805)

## Standing on the Shoulders of Giants: The NLP Hall of Fame

![](https://www.waytoagi.com/api/kb-media/Lt26bMM6bov3jyxHfJicnpGenyg)

<The image was drawn by [Ann's Blog](https://lolitasian.blog.csdn.net/?type=blog). It looks really nice, so I decided to use it!>

BERT is built upon many brilliant ideas that emerged in the NLP field, including but not limited to [Semi-supervised Sequence Learning](https://arxiv.org/abs/1511.01432), [ELMo (Deep contextualized word representations)](https://arxiv.org/abs/1802.05365), [ULMFiT (Universal Language Model Fine-tuning for Text Classification)](https://arxiv.org/abs/1801.06146), [GPT (Improving Language Understanding by Generative Pre-Training)](https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf), and [Transformer (Attention Is All You Need)](https://arxiv.org/abs/1706.03762v5).

The work of these people has changed the world we live in. I would like to call the figures in this chart the **NLP Hall of Fame**!

I believe I have already covered all the papers above or their related knowledge and models in previous chapters. If you’ve forgotten any of them, go back and review!

## BERT Model Architecture

**BERT Base: 12-layer encoder, 768-dimensional token embeddings, 12 attention heads (comparable to GPT)**

![](https://www.waytoagi.com/api/kb-media/AtzPbnibIoYYl0xf8r9ct9VEnAh)

This diagram is very straightforward. It compares BERT, OpenAI GPT, and ELMo. Among them, ELMo is relatively outdated because it does not use the Transformer. Instead, it simply uses a bidirectional LSTM by concatenating a left-to-right RNN with a right-to-left RNN. Both GPT and BERT use the Transformer, but GPT uses the decoder, so at the current time step, it cannot “attend” to information from future time steps (see the second image — it has no arrows pointing left). BERT, on the other hand, uses the encoder, so it can see information from all time steps. This makes model training much easier. When performing discriminative tasks (such as multi-class classification), it can achieve stronger performance with smaller datasets and fewer parameters.

## BERT’s Usage Paradigm: Download Pre-trained Model + Fine-tune Yourself

As shown in the figure below, Google has already completed the self-supervised learning part on the left, and has fully open-sourced it (the BERT open-source release includes both the model source code and the pre-trained weights).

Later, we will explain in detail how Google performs self-supervised learning on large-scale corpora.

![](https://www.waytoagi.com/api/kb-media/U5F6b4H7xoHbHvxHJaXcQYkCnnA)

## BERT’s Token Embeddings: The Sum of Three Embeddings

**BERT’s token embeddings are the sum of Token Embedding, Segmentation Embedding, and Position Embedding.** Token Embedding and Position Embedding are already very familiar to us. Segmentation Embedding is a newer addition, but its core idea is similar to the approach mentioned in Chapter 9 when discussing ELMo.

All three embedding components can be expressed as the product of a one-hot encoded input vector and an embedding matrix. When a one-hot vector is multiplied by the matrix, it acts like a lookup — it selects the corresponding column from the embedding matrix, and that column becomes the final embedding vector. If you’ve forgotten this concept, you can go back to section 6.4.2 and review Professor Su’s explanation.

## BERT’s Pre-training Tasks: Masked Language Modeling (MLM)

Reposted from: [Prompt-Tuning——An In-depth Interpretation of a New Fine-tuning Paradigm](https://wjn1996.blog.csdn.net/article/details/120607050) By [Huashi Shuju Xueyuan·Wang Jianing](https://wjn1996.blog.csdn.net/)

> MLM is a self-supervised training method. It first generates self-supervised data from large-scale unsupervised corpora using a fixed replacement strategy, then designs a pre-training objective to train the model. The process can be described as follows:

- **Replacement Strategy**: Randomly select 15% of the tokens in the entire corpus. Among the selected tokens:
  - 80% are replaced with the `[mask]` token,
  - 10% are replaced with a random different token,
  - 10% are left unchanged.

- **Training Objective**: When the model encounters a `[mask]` token, it predicts the most likely word for that position based on the learned contextual semantics. Therefore, the training objective is a classification task over the entire vocabulary, typically optimized using cross-entropy loss.

![](https://www.waytoagi.com/api/kb-media/JbaXb2lZco34y1x0Ifhcbjw3nQh)

> Taking BERT as an example, we first feed in a sentence such as `It is very cold today, we need to wear more clothes.`, then randomly mask one token. After adding special tokens, the input becomes: `[cls] It is very cold today, we need to [mask] more clothes. [sep]`. This is passed through a multi-layer Transformer, producing hidden state vectors for each token at the final layer. For the MLM task, an MLP head is added on top of the `[mask]` position to map the representation to the vocabulary, yielding a probability distribution over all possible words.

In short, BERT’s training objective is essentially a cloze test: a word is removed and the model must infer what should be there based on context. Clearly, this task by itself is too easy. If the only objective were a simple cloze task, the model would converge easily during pre-training but would learn very little. Therefore, the Google team made the task more challenging: sometimes the selected token is not replaced with `[mask]`, but with a random word, and sometimes it is left unchanged.

BERT also has a second pre-training task: Next Sentence Prediction (NSP). Although the name suggests otherwise, it is essentially the same as the Entailment task mentioned in [12.1.3](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#CAuOdswgeoQ6i0xe60DcMGuCntd). The goal is to determine the relationship between two given sentences. There are three possible relationships:

- **Entailment (isNext)**: One sentence entails the other. In NSP, two consecutive sentences from the same document are considered to have an entailment (isNext) relationship.
- **Contradiction (isNotNext)**: The two sentences are unrelated or contradictory. In NSP, this corresponds to sentences sampled from different documents.
- **Neutral**: The sentences come from the same document but are not adjacent.

NSP data can also be constructed in a self-supervised manner. Given a large unsupervised corpus organized by document, one sentence is randomly selected from a document as the premise. The entailment (isNext) example is its immediately following sentence; other sentences from the same document are used as Neutral examples; sentences from different documents are used as contradiction (isNotNext) examples.

In BERT, the NSP task is formulated as a sentence-pair classification problem. For example, given two sentences `S1: It is very cold today.` and `S2: We need to wear more clothes.`, they are concatenated with special tokens to form: `[cls] It is very cold today. [sep] We need to wear more clothes. [sep]`. This input is fed into a multi-layer Transformer, and the hidden state of the `[cls]` token is passed through an MLP to produce a probability distribution over the three classes:

![](https://www.waytoagi.com/api/kb-media/FiyObP2aSo2JGBxvPNkc0IGynFe)

**However, the NSP task turned out to be overly simplistic. Subsequent studies found that it provided little to no positive impact on downstream performance. As a result, NSP has been removed in most later pre-trained language models, which instead introduced various other pre-training objectives.**

## BERT’s Various Downstream Applications

> > I don’t feel like updating this anymore. In the era of Prompting, fine-tuning small models doesn’t seem all that meaningful.

# Looking Back at the Monumental History of Language Models and NLP!

The development history of language models can be divided into three stages: the fully supervised learning stage, the pre-training + fine-tuning stage, and the pre-training + prompt + predict stage.

| **Paradigm** | **Stage** | **Engineering & Exploration** | **Representative Models** | **Links** |
| --- | --- | --- | --- | --- |
| Fully-supervised Learning<br>Before 2017 (1) | Pre-Neural Network Era (e.g. SVM, Decision Trees, Expert Systems) | **Feature Engineering**<br>Engineers manually extracted concise features from raw data using their domain knowledge. | n-gram Language Models | [Feature Engineering](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#CissdIqOUo6kuAx0a19cvwyMnDh) [n-gram Models](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#ROEydsEmSo6u8Ox2tubcKif2nXe) |
|  | Neural Network Era<br>FFNN-CNN-RNN | **Architecture Engineering**<br>Feature extraction was handed over to the hidden layers of neural networks, enabling end-to-end learning. The key engineering challenge became designing effective network architectures to better extract features. Major innovations of this era include RNN and its variants, Layer Normalization, ResNet, the Attention mechanism, and more (2). In addition, this period saw groundbreaking explorations in “semi-supervised learning” using language models and sequence autoencoders. By the pre-training era, the term semi-supervised learning gradually evolved into self-supervised learning (3). | Neural Language Models<br>LSTM<br>seq2seq<br>LM-LSTM & SA-LSTM | [LSTM](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#HeI2duSKKoMaYwx8rH1c5X2qnUc) [Neural Language Models](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#JmACdYYSAogGuwxyewBc0VqHn9g) [Seq2Seq](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#ZWSwdmWQaoGAQuxkOEHcuD5UnVl) [Exploration: Self-supervised Learning](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#KEcEdYK8ao48eExeypscRMkknog) |
| **Note:** (1) Even in the fully-supervised learning era, there were models that used unlabeled data for pre-training, such as Word2Vec and GloVe. However, they only solved the embedding layer. For every specific downstream application, engineers still had to build a new model from scratch for fully-supervised learning. This type of pre-training is called **Feature-based Pretraining**, because the models were pre-trained to provide features of words for downstream tasks.<br>(2) Some technical details such as Layer Normalization and Residual Networks are not covered in this document, but they are actually very important. Incorporating them into model architectures is crucial for improving feature extraction capability and alleviating gradient issues.<br>(3) In the beginning, scholars referred to this new paradigm as **Semi-supervised Learning**. This was because they used “[joint training of labeled and unlabeled data, with labeled data assisting the training of unlabeled data](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#Wie8dwyUSoUAKcxucycc6Dtlnig)”. Since it was partly supervised and partly unsupervised, it was called semi-supervised learning. |  |  |  |  |
| Birth of the Transformer<br>June 2017<br># Solving RNN’s parallelization bottleneck, the dawn of pre-trained large models emerges | Major Event | **Abandon the RNN structure. Adopt Positional Encoding (PE) and Self-Attention mechanisms, and design Multi-Head Attention.**<br>Transformer offers parallelism inferior to CNN but far superior to RNN, and information fusion capability inferior to RNN but far superior to CNN. It not only made “scaling laws” finally feasible, but also avoided major compromises on long-range dependencies. As a result, it began to dominate both NLP and CV fields. | Transformer | [Attention is All You Need](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#YYoqdo6kUo2qI6xDA7OcjMEDnch) |
| Contextualized Word Embeddings (Transition Phase)<br>February 2018 | Transition Stage | **Architecture Engineering**<br>Still a feature-based pre-training paradigm. It was recognized as inefficient that a single word embedding had to represent so many different meanings. Bidirectional LSTM was used to extract hidden states in both forward and backward directions and concatenate them to form contextualized embeddings. This enabled “Apple” (fruit) and “Apple” (company) to have distinct representations. | ELMo | [ELMo](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#W2M0dOIgoo0mg0xa4rbcFfttnxb) |
| Pre-training + Fine-tuning<br>2017–2019<br># With abundant unlabeled text data and the emergence of Transformer, “scaling up” finally became viable | Decoder-Only | **Objective Engineering**<br>Data was no longer the main bottleneck. We pre-trained models on massive unsupervised corpora using **pre-training objectives**, then fine-tuned them on downstream tasks using task-specific objective functions. Choosing the right objective could dramatically improve pre-training effectiveness (1).<br>**GPT is a decoder-only Transformer** that uses an autoregressive architecture which can only attend to past information. It adopts the classic next-token prediction language modeling objective as its pre-training task. This aligns with how humans naturally write from left to right. Because it must predict the next token based only on previous context, the task is harder and training is less efficient, but the performance ceiling is naturally higher.<br>**BERT is a modified encoder-only Transformer.** The encoder can attend to all time steps. Its pre-training task is MLM (Masked Language Modeling), essentially a cloze test. BERT predicts masked tokens based on bidirectional context. Compared to “predicting the future” (next-token prediction), “inferring the present using both past and future” is much easier. As a result, it trained very effectively and swept all SOTA benchmarks at the time.<br>UniLM and T5 are not introduced here; please refer to the links and notes (2). | GPT | [The Birth of GPT](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#CSiCdEm8koQi4mxAPQTckXC2n2e) |
|  | Encoder-Only |  | BERT | [BERT](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#XwSYdQ6AMocmU0xcFtdcgORrnje) |
|  | Prefix LM |  | UniLM | [Paper](https://arxiv.org/pdf/1905.03197.pdf) [Reference Article - UniLM](https://zhuanlan.zhihu.com/p/584193190) |
|  | Encoder-Decoder |  | T5 | [Reference Article - T5](https://zhuanlan.zhihu.com/p/88438851) |
| **During the Pre-training + Fine-tuning phase, Architecture Engineering gradually disappeared.** One reason is that simply stacking Transformer encoders and decoders worked well enough — there was no need for overly elaborate designs (though innovations like Sparse Transformer still emerged). Another reason is that pre-training Transformers had become extremely expensive; few had the time or compute to continually experiment with new architectures.<br>> (1) For example, Zhang et al. (2020a) showed that introducing a loss function for predicting salient sentences from a document leads to a better pre-trained model for text summarization.<br>> (2) In addition to Encoder-Only and Decoder-Only, various other structures exist, such as Prefix LM and Encoder-Decoder. See the figure below:<br>![](https://api/kb-media/TlQ5bF1fxokXUpxcrjXcgy5wnne) |  |  |  |  |
| Zero-shot<br>February 2019<br># As models grew larger, fine-tuning became prohibitively expensive and impractical. More parameter-efficient approaches had to be found. | Transition Stage | GPT-2 is a much larger decoder-only model than GPT. It abandoned the fine-tuning paradigm. **When performing downstream tasks after pre-training, it required no additional labeled data and did not update model parameters.** GPT-2 was a response to BERT Large sweeping all SOTA benchmarks, but the response was relatively weak — despite its massive parameter count, performance was only mediocre. It had to market the novel concept of “Zero-shot” as its main selling point. Nevertheless, GPT-2 proved one important thing: making models significantly larger consistently improves performance. | GPT-2 | [GPT-2](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#K8aydygeMoAiyUxa0ozc7M6dnlf) |
| Pre-training + Prompt + Predict | In-context Learning | **Prompt Engineering**<br>Instead of updating model weights, a small number of examples are provided directly in the input context. With only these limited in-context samples, the pre-trained language model can perform downstream tasks. | GPT-3 | [GPT-3](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#XEUidaOmKouwWax2XHBcgBnWnkg) |
|  | Instruction Tuning | **Prompt Engineering**<br>After Instruction Tuning, models learned to follow human instructions with strong generalization ability. After RLHF, they paid an “alignment tax” in raw capability but further learned to follow instructions, producing outputs that are useful, relevant, and non-toxic, achieving alignment with human values. Neither instruction tuning nor RLHF injects new capabilities per se; rather, they unlock the vast potential already compressed within the model’s hundreds of billions of parameters, allowing it to generate the content we actually want. | FLAN<br>InstructGPT | [FLAN Paper](https://arxiv.org/pdf/2109.01652.pdf) [InstructGPT](https://s3tlxskbq3.feishu.cn/docx/NyPqdCKraoXz9gxNVCfcIFdnnAc#EAq2d0GUqoIgcqxKWZlcjqxDnRH) |
|  | Chain of Thought | **Prompt Engineering**<br>Chain-of-Thought (CoT) is a special form of In-Context Learning. It resembles 1-shot or few-shot prompting, but in addition to Input-Output examples, we also provide a reasoning process between input and output, called a **Relational Path** or **Reasoning Path**. | PaLM | [PaLM Paper](https://arxiv.org/abs/2204.02311) |

The development of language models is essentially the development of NLP itself. In the past, NLP consisted of many fragmented subtasks. When building a conversational robot like Microsoft XiaoIce, we had to rely on an extremely complex pipeline of intermediate tasks.

![](https://www.waytoagi.com/api/kb-media/KAbEb2AhKo5IQmxuC0DcB8Cenxb)

The principle that “the greatest truths are the simplest” tells us that the very existence of these intermediate tasks was a reflection of NLP’s insufficient maturity. As language models advanced and the pursuit of AGI intensified, models evolved from handling only specific downstream tasks into generalists. NLP’s “decathlon” competitions and multi-task learning gave us a glimpse of what a versatile LM could achieve. ULMFiT brought transfer learning—already common in CV—into the realm of NLP. By the time GPT arrived, everyone understood the new paradigm: the entire model is end-to-end—an oversized 12/48/96-layer decoder Transformer. Without those intermediate tasks, it could already engage in natural conversation with humans.

![](https://www.waytoagi.com/api/kb-media/OaOQbA4rjo6yudxSVubc1wQYnOe)

> **By the end of March 2023, the development of language models had gone through three distinct stages:**

> **Stage 1:** Design a series of self-supervised training objectives (MLM, NSP, etc.), introduce novel model architectures (Transformer), and follow the Pre-training + Fine-tuning paradigm. Representative models: BERT, GPT, XLNet, etc.

> **Stage 2:** Gradually scale up model parameters and training data volume, while exploring different architectural designs. Representative models: BART, T5, GPT-3, etc.

> **Stage 3:** Entering the AIGC (Artificial Intelligence Generated Content) era. Model parameter counts reached the quadrillion scale, architectures converged on autoregressive designs, and large models moved into conversational, generative, and multimodal paradigms. Greater emphasis was placed on alignment through human interaction to create reliable, safe, and non-toxic models. Representative models: InstructionGPT, ChatGPT, Bard, GPT-4, etc.

> Original article: https://blog.csdn.net/qq_36426650/article/details/120607050

![](https://www.waytoagi.com/api/kb-media/RqYibKMSVoLSS3xjbKScgM8Hn3c)
