Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

How Are ChatBots Built? From Codex and AlphaCode to RLHF

This article explores the journey of building ChatBots on top of large language models. Starting from the GPT development roadmap, it dives deep into the foundational work of Codex and AlphaCode, covering key technologies like the HumanEval benchmark, pass@k metric, top-p sampling, and Supervised Fine-Tuning (SFT) that paved the way for advanced techniques like RLHF.

ChatBot developmentRLHFCodexAlphaCodeHumanEval

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

Author: Xiao A, aaronxic, Zhihu Profile

Publication Date: July 8, 2023

Original Article: https://zhuanlan.zhihu.com/p/642282717

Introduction

Hello everyone, I’m Xiao A. In the previous article, we introduced the three different transformer architectures used in LLM base models. Today, in the third installment of this series, we will explore how the most popular downstream application of LLM base models — the ChatBot — is built.

Starting with LLM-Assisted Programming

Rome wasn’t built in a day, and neither was ChatGPT, the breakout star of AGI. It too went through a long period of exploration and development. Many of you will still remember the GPT development roadmap shown below. As you can see, before the groundbreaking text-davinci-002 appeared, the OpenAI team had already conducted extensive research into programming assistance. I believe this work had two major significances:

  • It significantly enhanced the LLM’s capability in logical reasoning.

  • It validated that Supervised Fine-Tuning (SFT) is effective for the downstream application of LLM-assisted programming, laying a solid foundation for the later emergence of more advanced techniques such as RLHF in ChatBots.

GPT Development Roadmap

Therefore, before diving into the more complex technologies required to train a functional ChatBot, let’s first examine what kinds of data and training methods are needed for LLM-assisted programming applications. In the following sections, we will take a detailed look at two foundational works in this field: Codex and AlphaCode.

These two systems adopted different transformer architectures: decoder-only and encoder-decoder, respectively.

markdown
## Codex

Codex is another major release from OpenAI. From the moment of its birth, it showed a strong inclination toward productization. The Copilot plugin inside VSCode actually uses a product-specialized version of Codex. In my view, Codex’s main contributions are as follows:

- It introduced the HumanEval programming benchmark dataset and proposed the **pass@k** metric to evaluate the performance of code-generation models.
- It proposed a two-stage training approach: the first stage performs unsupervised pre-training on a massive corpus of GitHub source code; the second stage performs supervised fine-tuning (SFT) on additional data consisting of docstrings paired with their corresponding function implementations.

It is worth noting that Codex primarily focuses on the Python language, which is a significant difference from the later AlphaCode.

The following sections introduce Codex from five aspects:

- Definition of the code completion problem
- Definition of the pass@k metric
- Introduction to the sampling algorithm
- Four optimization methods and experimental results
- Limitations of Codex

### Definition of the Code Completion Problem

Let’s first get a sense of the programming problems we aim to solve. Each data record contains:

- Function name and parameters
- A docstring enclosed in triple quotes that describes the function’s purpose in natural language, along with several Input/Output examples
- The actual function implementation

```python
def incr_list(l: list):
    """
    Return list with elements incremented by 1.
    >>> incr_list([1, 2, 3])
    [2, 3, 4]
    >>> incr_list([5, 3, 5, 2, 3, 3, 9, 0, 123])
    [6, 4, 6, 3, 4, 4, 10, 1, 124]
    """
    return [(e + 1) for e in l]

The authors collected 164 such problems at an intermediate-to-easy difficulty level, with relatively short overall character lengths. Each problem also includes several test cases to verify the correctness of the function. Passing all test cases counts as a correct solution. For detailed information about the dataset, please refer to this link.

The goal of a code completion system is to see the first two parts (function signature + docstring) and generate the final part (the function body), thereby completing the code.

The pass@k Metric

Before competing on the leaderboard, it is essential to clearly understand how the metric is calculated.

pass@k, as the name suggests, means: sample k solutions; as long as any one of them passes all test cases, the entire submission is considered correct.

It is easy to see that this metric can be unstable when k is small. To address this, the authors expanded the sampling process into two stages:

  1. Stage 1: First, sample and generate a sufficiently large number n of candidate solutions.
  2. Stage 2: From these n samples, select k of them using a sampling strategy (e.g., random sampling) as the final submission.

Then, use the test cases to check the correctness of these k samples. If at least one is correct, the submission is counted as correct.

Codex fixes n = 200. Suppose c out of the n samples are correct, where k ≤ 100 and c ≤ n. The value of pass@k can then be computed from a combinatorial probability perspective using the following formula:

$$ \text{pass@k} = \mathbb{E}_{\text{problem}}\left[1 - \frac{\binom{n-c}{k}}{\binom{n}{k}}\right] $$

where:

  • $\binom{n-c}{k}$ represents the number of ways to choose k samples that are all incorrect;
  • $1 - \binom{n-c}{k}$ represents the number of ways to choose k samples that contain at least one correct solution;
  • $\binom{n}{k}$ is the total number of ways to choose any k samples from n.

Directly computing pass@k can easily cause integer overflow due to large factorials. The authors therefore simplified the expression as follows:

$$ \begin{align} 1 - \frac{\binom{n-c}{k}}{\binom{n}{k}} &= 1 - \frac{\frac{(n-c)!}{k!(n-c-k)!}}{\frac{n!}{k!(n-k)!}} \end{align}

(The translation continues with the remaining mathematical simplification in the original text, preserving all LaTeX and structure exactly as in the source.)

= 1 - \frac{(n-c)!\cdot(n-k)!}{n! \cdot (n-c-k)!} \\
&= 1 - (\prod_{i=n-c+1}^n \frac{1}{i}) \cdot (\prod_{i=n-c-k+1}^{n-k} i) \\
&= 1 - (\prod_{i=n-c+1}^n \frac{1}{i}) \cdot (\prod_{i=n-c+1}^{n} (i-k)) \\
&= 1 - \prod_{i=n-c+1}^n \frac{i-k}{i} \\
&= 1 - \prod_{i=n-c+1}^n (1-\frac{k}{i})
\end{align}

In this way, we obtain a simpler and more numerically stable `pass@k` formula.

```python
def pass_at_k(n, c, k):
    """
    :param n: total number of samples
    :param c: number of correct samples
    :param k: k in pass@k
    """
    if n - c < k:
        return 1.0
    return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1))

Sampling Algorithms

Codex uses top-p sampling, also known as nucleus sampling. While we’re at it, let’s briefly introduce the common sampling strategies used in LLMs. This will help with later comparisons and understanding.

Sampling algorithms mainly fall into two categories: deterministic sampling and stochastic sampling.

  • Greedy search

    • Deterministic sampling with a greedy strategy.
    • At each step, it selects the token with the highest probability according to the next-token probability distribution.
  • Beam search

    • Deterministic sampling; greedy search can be viewed as a special case where beam width n = 1.
    • Step 1: Maintain a priority queue with maximum size n. Insert the initial sequence; the queue size is now 1.
    • Step 2: Pop a sequence from the queue, obtain the probability distribution for the next token, form new sequences, and push the top-n highest-probability ones back into the queue (now size n).
    • Step 3: Pop all sequences from the queue and repeat Step 2. Note that P(new sequence) = P(new token) × P(old sequence). This increases the sequence length by 1 and updates the queue.
    • Step 4: Repeat Step 3 until the preset length is reached or all sequences have ended.
  • Naive random sampling

    • The simplest stochastic sampling strategy.
    • Samples the next token directly from the probability distribution.
  • Top-k

    • Stochastic sampling that avoids extremely low-probability tokens; the number of candidates is fixed.
    • Sorts the next-token probability distribution in descending order, keeps the top k tokens, renormalizes their probabilities, and samples from this new distribution.
  • Top-p (nucleus sampling)

    • Stochastic sampling that avoids extremely low-probability tokens; the number of candidates is dynamic.
    • Sorts the next-token probability distribution in descending order, selects the smallest set of tokens whose cumulative probability exceeds p, renormalizes their probabilities, and samples from this new distribution.

It is worth noting that the probability distribution comes from softmax, which is commonly modulated by a temperature parameter:

$$ p(x_i)=\text{softmax}(x_i)=\frac{e^{x_i/T}}{\sum_{j=1}^N e^{x_j/T}} $$

  • When $T \rightarrow 0$, the “rich get richer”: the maximum value’s probability approaches 1 while all others approach 0.
  • When $T \rightarrow \infty$, the distribution becomes almost uniform.

Codex uses temperature coefficients where $T \le 1$.

Attempt 1: Naive Approach

With the metric and sampling method defined, we can start trying to climb the leaderboard. The most straightforward idea is to take GPT-3 as-is and see how it performs. Unfortunately, GPT-3 achieves essentially 0% pass rate.

This is easy to understand. As shown below, although GPT-3 was trained on 450TB of text (roughly 300B tokens), it contains almost no dedicated code data.

GPT-3 training data composition

Attempt 2: Code Pre-training

A natural improvement is to ensure the LLM has seen a large amount of programming code—especially Python code—during training.

To achieve this, Codex did the following:

  • Collected all Python files under 1MB from GitHub up to May 2020, totaling 179GB. After simple filtering and cleaning, 159GB of data remained.

  • The token distribution in this 159GB corpus differs significantly from the original GPT-3, especially regarding multiple spaces. The authors therefore added dedicated tokens for whitespace of varying lengths, which reduced the total vocabulary size by 30%.

  • The authors also found that initializing with GPT-3 weights had little impact on final accuracy, but it did accelerate convergence.

After applying the above techniques, the accuracy of Codex-12B jumped to 28.8%.

Attempt 3: SFT Approach

This was still not enough for leaderboard chasing. Further analysis revealed that although LLMs had seen Python code, they had not encountered a large volume of programming problems formatted like those in HumanEval.

Codex therefore collected an additional SFT dataset that closely resembled the HumanEval format. The data came from two sources:

  • Programming competition websites such as Codeforces
  • Function code snippets that could pass CI unit tests

PS: The supervised fine-tuning (SFT) here is actually unsupervised training, just like the code pre-training stage. Don’t be misled by the word “Supervised.”

After this SFT process, the resulting model, Codex-12B-S, further improved performance to 37.7%.

Attempt 4: Optimizing the Ranking Strategy

Previously, when calculating \text{pass}@k, the method was to first sample a fixed n=200 candidates and then randomly select k samples from those 200 to compute the metric in a probabilistic sense. If the model could rank the quality of these 200 samples, it could simply submit the single most reliable answer. In that case, \text{pass}@k returns to its original definition: the success rate when sampling k times and submitting only one.

Codex experimented with several ranking strategies:

  • Oracle strategy: ranking sampled solutions using test cases (the oracle has perfect hindsight and is used only as a reference)
  • Baseline strategy: randomly ranking the sampled solutions
  • \text{sum } \text{logp} strategy: summing the \log p probability of every token in a sampled sequence
  • \text{mean } \text{logp} strategy: averaging the \log p probability of every token in a sampled sequence

The \text{mean } \text{logp} strategy ultimately performed best, pushing \text{pass}@100 above 40%.

Experimental Results

The table below summarizes the four optimization strategies. The four successive improvements raised performance from 0% to over 40%. For reference, the oracle sampling strategy achieved approximately 80%.

Limitations

As an early pioneering work, Codex inevitably has some immature aspects. Looking back today, the main limitations are:

  • Training efficiency is not high enough. Even after training on 150B tokens, the model can only solve relatively simple problems, with pass rates still below 50%.
  • Performance is highly sensitive to the length of the input docstring; overly long docstrings cause a sharp decline in model performance.
  • It struggles with math-related problems and frequently makes mistakes on simple addition, subtraction, multiplication, and division.

AlphaCode

Unlike OpenAI’s strong focus on productization, DeepMind is committed to proving that AI can outperform humans across various domains. This time, they turned their attention to the field of programming assistance. The problems they chose were also significantly more difficult — they went straight to the Codeforces programming platform to compete directly against human participants.

In my opinion, AlphaCode’s key contributions are:

  • In the SFT stage, they introduced a cleaner 13k programming dataset called CodeContests. The number of test cases for each problem was greatly expanded, which significantly reduced the probability of false positives and slow solutions.

  • In the inference sampling stage, they increased the number of candidates to 1 million, and applied filtering and clustering methods to rank the results. This allowed them to outperform 54.3% of human participants on average across 10 programming competitions.

Compared with Codex, AlphaCode has several notable differences:

  • It supports multi-language programming, whereas Codex only supported Python.

  • It made a comprehensive trade-off between inference speed and accuracy, ultimately choosing an encoder-decoder architecture, unlike Codex which used a decoder-only architecture.

  • The number of samples reached up to 1 million, which is several orders of magnitude larger than Codex’s 100 samples.

The overall training approach of AlphaCode is similar to that of Codex, consisting of two stages: Code Pre-training and SFT. The following sections introduce AlphaCode from four aspects, with a focus on the differences from Codex:

  • The n@k metric
  • Code Pre-training data preparation and training
  • SFT data preparation and training
  • Large-scale sampling and ranking

AlphaCode workflow diagram

n@k Metric

Recall that Codex used the pass@k metric, which has two definitions:

  • One-stage definition: Directly submit k samples; if any one of them passes, it is considered correct.

  • Two-stage definition: First sample n=200 candidates, then select k samples from these n to submit. If at least one passes, it is considered correct.

AlphaCode adopts the two-stage definition and renames it n@k. Note that the symbols n and k are used in the opposite way compared to Codex. In practice, they typically use the 10@k metric — that is, from a set of k samples, 10 are selected for submission. If any one of them passes, it is considered correct.

Code Pre-training Data Preparation

AlphaCode collected GitHub data up to July 14, 2021 — one year more recent than Codex. In addition, it included both Python and other languages, resulting in a total of 715GB of data, which is five times larger than Codex’s 150GB dataset.

Code Pre-training Training

The training process is relatively standard. It uses the AdamW optimizer, with the learning rate linearly warming up to 1e-4 over the first 1000 steps, then decaying to 1e-5 following a cosine schedule.

The transformer adopts an encoder-decoder architecture based on the Multi-Query Attention (MQA) variant.

  • Encoder-decoder selection: Because the problem descriptions are very long, adding an encoder helps the model better understand the problem statement.

  • Multi-Query Attention (MQA) selection: It accelerates inference with minimal loss in accuracy. The MQA approach shares a single key head across multiple heads for K, and does the same for V, while keeping Query unchanged. This reduces both the parameter count and computation in the input projection layers.

The authors also conducted experiments comparing the accuracy and speed of two other architectural choices:

  • Decoder-only structure: Slightly higher accuracy, but requires much longer input tokens, resulting in lower inference efficiency (unclear whether KV cache was used).

  • Standard MHA encoder-decoder structure: Comparable accuracy, but even lower inference efficiency.

SFT Data Preparation

As we learned from Codex, SFT is a critical stage for transferring a base LLM to downstream applications, and it requires a high-quality dataset. To address this, AlphaCode created the CodeContests dataset.

The problems in this dataset come from multiple programming websites, including Codeforces, Description2Code, and CodeNet.

Here’s an example of a problem:

AlphaCode data sample

The solutions for these problems come from user submissions. In addition to correct solutions, incorrect ones were also collected. This provides two types of data: (problem, correct_solution) and (problem, wrong_solution) as positive and negative examples.

To prevent training data from leaking into the test set, the authors split all data based on time, as shown below:

AlphaCode data split (by time)

AlphaCode data partitioning

In building CodeContests, the team gave very careful consideration to one important question: whether the test cases for each problem provide sufficient coverage.

LLM-Assisted Programming Summary

To answer this question, the team sampled 50 problems each from the APSS, HumanEval, and CodeContests Raw datasets. They used a 1B model to generate solutions and manually inspected those that passed the existing test cases. The inspection revealed a very high false-positive (FP) rate, along with a high proportion of solutions that timed out (Slow Rate).

The solution was to augment the test cases. The heuristic augmentation methods used were:

  • For binary inputs: flip bits
  • For integer inputs: randomly increase or decrease the values
  • For string inputs: randomly swap or modify characters

The resulting dataset is CodeContests. Compared with the Raw version, the false-positive rate dropped significantly, although the slow-rate probability remained relatively high.

SFT Training

Compared with Codex, AlphaCode introduced several improvements:

  • Value Conditioning: In an unsupervised manner, binary correctness labels are used by prepending the keywords “correct” or “wrong” to the prompt template. The model is then trained on (problem, correct_solution) and (problem, wrong_solution) pairs in an unsupervised fashion.

  • Value Prediction: In a supervised manner, binary labels are used. Given a (problem, solution) pair, the network is trained to perform binary classification.

  • GOLD Method: This mainly addresses the problem of the model’s learning objective oscillating when a single problem has multiple valid solutions. Each (problem, solution) pair is assigned a coefficient. If one solution for a given problem is sufficiently good, the weights of other solutions for the same problem are slightly reduced. This allows the model to focus on learning one high-quality solution. GOLD is an offline RL algorithm introduced in this paper.

Inference Sampling Process

Following the two-stage definition of the 10@k metric, the inference sampling process is also divided into an “addition” phase followed by a “subtraction” phase.

  • Addition Phase: Generate millions of samples — far more generous than Codex’s 100 samples. No top-k or top-p sampling is used; samples are drawn directly from the model’s probability distribution. The generation methods include:

    • Generating solutions in multiple languages (e.g., both C++ and Java)
    • Randomly perturbing metadata tags (such as rating and tags present in the original samples)
    • Increasing the sampling temperature to enlarge variance
  • Subtraction Phase: Unlike Codex, which ranks solutions by mean log probability, AlphaCode uses a filtering + clustering approach:

    • Filtering: Use sampled test cases to filter out incorrect solutions; any solution that fails on any test case is discarded.
    • Clustering: An additional test-case generator is trained. Given a problem, it produces a large number of test cases. These test cases are fed into the remaining candidate solutions. Solutions are then clustered based on their behavior on these test cases, and one representative solution from each cluster is selected for submission.

Experimental Results

By incrementally stacking all the techniques, the system ultimately achieved a 34% solve rate, placing it at the 54th percentile.

PS: Some technical details are omitted here. For full information, please refer to the original paper.

Summary of LLM-Assisted Programming

Codex and AlphaCode represent two fundamentally different starting points for AI-assisted programming: the former is product-oriented, while the latter is research-oriented. Both have inspired a large body of follow-up work, such as Salesforce’s CodeGen2, Meta’s InCoder, Tsinghua’s CodeGeeX, and many others. They also share several important similarities:

  • Two-stage training: Stage one uses massive GitHub source code for pre-training; stage two applies SFT to align the model with the target application.

  • Two-stage inference: Stage one (“addition”) performs large-scale sampling to generate many candidates; stage two (“subtraction”) ranks and filters them, selecting the most promising answers for submission.

The two-stage training techniques have been directly carried over to another major downstream application — ChatBot. In the next section, we will examine what additional techniques, beyond pre-training and SFT, are required to deliver a smooth and natural ChatBot experience.

The Pioneer: ChatGPT

In November 2022, ChatGPT burst onto the scene, powered by GPT-3.5. By that point, GPT-3.5 was no longer a pure LLM foundation model. It is widely believed to share the same underlying technology as InstructGPT. Therefore, in the following sections, we will use InstructGPT as the reference to explain how a ChatBot is actually built.

Let’s first provide a high-level overview of the stages required to train a ChatBot, so you can get a basic mental model:

  • Stage 0: PT (Pre-training). This stage builds the model’s overall capacity — essentially setting the ceiling for what the model is capable of across all dimensions.

  • Stage 1: SFT (Supervised Fine-tuning). This stage teaches the model the conversational format — it learns how a dialogue is supposed to unfold.

  • Stage 2: RLHF (Reinforcement Learning from Human Feedback). This stage is further divided into the RM (Reward Model) phase and the RL (Reinforcement Learning) phase. It unlocks a wide range of capabilities in the model, including but not limited to safety, reasoning, and stability.

I really like this diagram from AK. It’s simple and clear, capturing all the key points:

Pre-Train Stage

The pre-training approach is very similar to that of GPT-3. Here’s a quick recap of the important details: decoder-only architecture, 175B parameters, context window of 2048 tokens, vocabulary size of 50,257, trained on 300B tokens, with the original training corpus totaling 45TB. The data composition is shown below (the real ChatGPT is likely to have used even more data).

In addition to the largest 175B model, InstructGPT also trained 1.3B and 6B models as backups for various needs.

SFT Stage

Just like Codex and AlphaCode, this stage is critical to shaping the final application. Its core purpose is to give the model a clear purpose — to tell it who it is, where it comes from, and where it is going.

  • For coding assistant applications: Codex learns that when it sees a docstring, it should output the function body; AlphaCode learns that when it sees a problem, it should provide a solution.

  • For ChatBot applications: ChatGPT learns that when it receives a new input, it should provide relevant feedback and answers while taking context into account.

As with Codex and AlphaCode, the quality of the dataset in this stage is paramount. InstructGPT dedicates a significant portion of the paper to detailing how the data was collected. Let’s also go through how the data for each stage of InstructGPT was prepared.

First, there weren’t as many labelers as one might imagine — only about 40 reliable ones. They were first asked to generate high-quality prompts, i.e., the first message a user might send to ChatGPT. This process had two phases: cold start and product iteration.

  • Labeler-based (Cold Start): At the very beginning, there was no model and no real user cases, so labelers had to invent prompts from scratch.

    • Plain prompt: Labelers were asked to write only questions.
    • Few-shot prompt: Labelers were asked to write a question plus several examples.
  • User-based (After Product Launch): Once the first version of the model was deployed in the playground, real user data could be collected.

    • User prompt: Prompts were derived by analyzing requests from users on the waitlist application.

The left chart below shows the distribution of different prompt categories from real user data, while the right chart shows concrete prompt examples.

One of the most valuable contributions of the InstructGPT paper is that it provides many detailed, realistic prompt examples and references — most of which can be copied and used directly. The annotation platform used was Scale AI, founded by the 19-year-old MIT dropout and Chinese-American prodigy Alexandr Wang.

Once the prompts were ready, labelers could proceed to annotate the labels required for each training stage. Combining prompts with their corresponding labels produced the training data.

The prompt and label setups across the three training stages are summarized as follows:

📊 This section contains embedded Feishu content (tables, whiteboards, etc.). View the full version in the Feishu Knowledge Base

The SFT stage uses the same training method as the PT stage — unsupervised next-token prediction. It was trained for a total of 16 epochs, using a cosine learning rate decay schedule and a dropout rate of 0.2.

Training cost is far lower than the pre-training stage. According to AK, it takes less than one week on 100 GPUs.

RM Stage

For coding assistant applications, the PT and SFT stages may already be sufficient. However, for a ChatBot, the process continues.

  • The 13k training samples for SFT are still too few, resulting in insufficient supervisory signals.

  • After SFT, the model’s output variance is too large, and the quality of its answers fluctuates significantly.

Therefore, we need to find ways to provide the model with richer supervisory signals, unlocking its potential while making its performance more stable.

A natural idea is to train a separate Reward Model (RM) that scores or ranks the outputs of the SFT model. As shown below:

As illustrated in the left figure above, the SFT model generates K answers for each prompt. Humans then rank these answers from best to worst.

As shown in the right figure, another model (RM) is initialized from the SFT checkpoint. The input prompt + completion + <|reward|> is fed into the RM, and a scalar score is regressed at the <|reward|> token position. A ranking loss is then applied based on these scores, as follows:

Where:

  • (\binom{K}{2}) is the number of all possible pairs when randomly selecting 2 answers out of K.

  • (x) is the prompt, (y_w) and (y_l) are two randomly chosen completions from the K answers, where (y_w) is ranked higher than (y_l) by human annotators.

  • (r_\theta(\cdot)) is the scalar score predicted by the RM.

  • (\sigma(r_\theta(x, y_w) - r_\theta(x, y_l))) represents the probability that the RM predicts (y_w) is better than (y_l).

In this work, K = 9 answers are generated per prompt, yielding (C_9^2 = 36) pairs. Other papers typically use K = 4 (i.e., (C_4^2 = 6) pairs). The choice of 9 here is a result of balancing cost and benefit.

  • Annotation cost is O(K). Although the total cost increases with K, the marginal cost is relatively low. Once annotators have read the question and K answers, evaluating one additional answer is very fast. Thus, the annotation cost scales as O(K).

  • Annotation benefit is O(K²). Since the number of pairs is (C_K^2), the benefit scales quadratically with K.

A total of 33k prompts were used to train the RM. It is important to note that the RM obtained at this stage is tied to the SFT model, because it was trained on the (x, y) distribution produced by the SFT model.

Unlike the conclusions later drawn by Claude, InstructGPT found that making the RM significantly larger yields diminishing returns, so a 6B model is sufficient.

PPO Stage

After obtaining the SFT and RM models, the next step is to connect them, keep the RM frozen, and use the RM’s loss to perform gradient updates on the SFT model. The full loss function for this stage is as follows:

Here, (\pi_{\phi}^{\text{SFT}}) is the SFT network, and (\pi_{\phi}^\text{RL}) is initialized from the SFT network. It is also a GPT-like model capable of generating responses.

  • The first term is the joint gradient update between (\pi_{\phi}^\text{RL}) and the RM described earlier. Specifically, prompt-completion pairs are sampled from (\pi_{\phi}^\text{RL}), scored by the RM (r_\theta(x, y)), and the resulting loss is back-propagated to optimize the parameters of (\pi_{\phi}^\text{RL}).

  • The second term encourages the newly learned (\pi_{\phi}^\text{RL}) not to deviate too far from the original SFT model. This is achieved by constraining the output probability distributions with KL divergence. The reason is that the RM is bound to the SFT distribution; if the new policy’s output distribution drifts too far, the RM may no longer be valid.

  • The third term prevents (\pi_{\phi}^\text{RL}) from overfitting to the RM scoring task. The authors observed performance regression on other NLP tasks (e.g., SQuADv2). Therefore, the original SFT training loss is added back by sampling prompt-completion pairs from the SFT training data to continue supervised fine-tuning of (\pi_{\phi}^\text{RL}).

PPO (Proximal Policy Optimization) is an RL optimization method originally proposed by OpenAI. In this context:

  • PPO-ptx refers to the case where all three coefficients are non-zero.

  • PPO refers to the case where the third coefficient (\gamma = 0), while the first two coefficients remain non-zero.

Additionally, RM training and PPO training can be performed alternately: after obtaining a new (\pi_{\phi}^{\text{SFT}}) model, a matching RM is trained; then the RM is frozen and used to further optimize (\pi_{\phi}^{\text{SFT}}) according to the (\text{objective}(\phi)) loss. This process is repeated iteratively.

Experimental Results

As shown above, InstructGPT explored the benefits of different model sizes and training methods.

  • The gray dashed line represents the baseline GPT-175B-SFT.
  • GPT-1.3B-PPO already outperforms GPT-175B-SFT.

However, it is important to note that the evaluation set here follows the same distribution as the PPO training set, which gives the PPO algorithm an advantage.

In addition, from the perspective of output token probability distribution, models trained with SFT & RLHF tend to exhibit model collapse. That is, their entropy decreases. The comparison between davinci (a PT model) and text-davinci-003 (an SFT & RLHF model) is shown below:

Model Collapse

  • The davinci model produces more diverse outputs; the deeper the red, the lower the probability of the sampled token.
  • The text-davinci-003 model produces much more deterministic outputs, with a larger disparity in next-token probability distribution.

Summary

After gaining an understanding of each stage of InstructGPT, let’s look at the role of each phase:

  • PT stage: This stage establishes the model’s capacity and essentially determines the upper limit of the model’s capabilities across various dimensions.
  • SFT stage: This stage teaches the model the conversational format — i.e., how a dialogue should be structured and conducted.
  • RLHF stage (including both the RM and PPO phases): This stage unlocks a variety of the model’s capabilities, including but not limited to safety, reasoning, and stability.

The Challengers to ChatGPT

ChatGPT has sounded the horn for the race toward AGI. Major tech giants and smaller players have all entered the fray, striving to catch up with ChatGPT. Each brings their own unique strengths and approaches. Let’s take a look at what distinctive capabilities other companies’ chatbots possess.

Bard

First up is Bard, currently the strongest rival capable of going toe-to-toe with ChatGPT. It comes from Google, an established powerhouse. Although Bard’s development has not been entirely smooth—with fluctuating public reception—its recent switch to the PaLM 2 backend seems to have revitalized it.

Starting with GPT-4, the trend toward closed-source models has become prevalent. PaLM 2’s technical report contains relatively few details and focuses more on presenting results. In my view, Bard’s main highlights are threefold:

  • In choosing training data and model size, it fully implements the conclusions from the Chinchilla paper—both are equally important. Similar to DeepMind’s evolution from Gopher to Chinchilla, PaLM 2 is built upon PaLM: while the model size is reduced, the training data has been dramatically expanded.

  • It utilizes a richer dataset, covering multiple languages, and includes programming code, mathematical formulas, and other text types.

  • The network architecture continues to use the UL2 encoder-decoder structure.

Claude

Claude is Anthropic’s product. The company’s name alone—“Anthropic,” meaning “concerning human beings”—sounds exactly like an AGI-focused company. Its founding team consists of core early members from OpenAI who later parted ways due to differing philosophies and established their own venture.

Anthropic places extreme emphasis on the interpretability, safety, and reliability of AGI. Productization does not appear to be their top priority. Their technical approach is similar to OpenAI’s and was once ahead, but unfortunately ChatGPT beat them to the first strike.

In training, Anthropic also follows the four-stage PT-SFT-RM-PPO pipeline. Below are the key differences from ChatGPT.

Core Philosophy

Anthropic focuses on the HH (helpful and harmless) characteristics—responses must be useful but not harmful. These two goals often conflict. They found that training solely on helpful data yields very high Elo ranking scores (a higher-is-better metric), but at the cost of extreme vulnerability to attacks. This demonstrates the need to mix both types of data during training.

Data Collection

Anthropic hired annotators on Amazon’s mechanical Turk platform and had them play two distinct roles when asking questions:

  • Simulating normal users (Blue Team)

    • Ask positive, constructive questions: writing or editing documents, discussing and formulating plans, etc.
    • Select the more helpful responses.
    • Allow multi-turn conversations and open-ended interactions.
  • Simulating malicious users (Red Team)

    • Conduct simulated attacks by asking negative, provocative, or adversarial questions.
    • Select the responses that are less harmful.
    • Typically limited to single-turn dialogues.

Important notes:

  • The authors did not pre-train annotators on what constitutes helpfulness or harmfulness. This approach preserves data diversity.

  • Annotators were required to hold at least a master’s degree in the United States. Low-quality annotations were filtered out. The team identified a group of excellent MTurk annotators—roughly 20 people—who produced 80% of the data. The screening method was straightforward and effective: evaluating writing quality and expressive ability.

  • Higher-quality but smaller-scale datasets were annotated on Upwork (paid by the hour), while MTurk was used for task-based payment.

The annotation interface is shown below. Users choose between two options and can indicate different levels of confidence.

RM and PPO

Anthropic refers to the Reward Model as a Preference Model (PM). They discovered that larger PM models trained on more data continue to improve performance—a conclusion that differs from ChatGPT. In the ChatGPT paper, the authors noted that the RM model cannot be too large, as it becomes difficult to train and tends to diverge; therefore they chose a 6B RM model.

In the PPO stage, the loss function omits the third term (the SFT loss) from InstructGPT. The authors found that when both the Policy model and the PM are sufficiently large, performance continues to improve even without that term.

$$ r_{\text{total}} = r_{\text{PM}} - \lambda_{\text{KL}} D_{\text{KL}}(\text{policy} || \text{policy}_0) $$

MOSS

MOSS is an open-source ChatGPT-like model developed by the Computer Science Department of Fudan University in Shanghai. It also went through the complete SFT and PM stages, but adopted a simpler alternative approach for the PPO stage.

Data Collection

As mentioned earlier, the quality of conversational data is a critical factor in tuning chatbots. MOSS fully leveraged ChatGPT’s capabilities to assist in generating instructions and conversations, as shown below:

  • User-provided instructions. Human annotators first wrote seed questions that comply with the HHH (helpfulness, harmlessness, and honesty) principles. They then used self-instruction to have ChatGPT expand these seeds, producing a larger set of instructions that also adhere to the HHH principles.

  • Multi-turn conversation. Write a prompt template composed of the following 3 parts, feed it into ChatGPT, collect the outputs, and concatenate them with the inputs to form complete multi-turn dialogue data.

    • Part 1: Introduce the background, describing it as a conversation between a Human and an AI, and instruct ChatGPT to simulate this dialogue.
    • Part 2: Constrain the Human-AI conversation to follow the HHH principle (Helpful, Honest, Harmless).
    • Part 3: Use the large number of instructions generated through self-instruction as the initial state of the conversation.

Through the above process, multiple multi-turn conversation training datasets can be obtained. These are then split into SFT and PM (Preference Model) portions to be used in their respective training stages.

SFT & PM Stage

The training methodology is similar to that of InstructGPT and Anthropic.

PPO Stage

In the MOSS paper, several methods for further improving ChatBot performance after obtaining SFT and RM (Reward Model) are first listed:

  • Method 1: The naive approach is to use reject sampling without further training. The SFT model generates a large number of outputs, which are then ranked by the RM and the best one is directly returned.
    → Advantage: Easy to implement.
    → Disadvantage: Sampling is not very efficient.

  • Method 2: A better approach is to use PPO. It has a very high performance ceiling but is extremely difficult to implement. Currently, only a very small number of teams such as OpenAI can use it proficiently.
    → Advantage: Highly sample-efficient.
    → Disadvantage: Extremely hard to train and places very high demands on the PM model.

  • Method 3: Modify the training data by adding feedback tags.

    • Train different types of RM models to score different aspects of feedback (e.g., a quality-specific RM and a harmfulness-specific RM).
    • Use this tagged multi-turn conversation data to normally fine-tune an SFT model (as shown in the figure below).
    • During inference, prepend a prefix such as <quality: 100><harmful: False>.
    • Advantages: Easy to implement, relatively efficient, and allows continuous iterative improvement by alternating between SFT and RM stages.

MOSS ultimately chose Method 3.

ChatGLM2

ChatGLM2 is a 6B-parameter compact ChatBot developed by Tsinghua University. It moved away from the encoder-decoder architecture of the first-generation ChatGLM and returned to a decoder-only architecture. ChatGLM2 has undergone both SFT and RLHF training. Several memory-saving and acceleration techniques were also applied during deployment and inference:

  • Flash Attention: fuses the bmm-softmax-bmm operators.
  • Multi-Query Attention (MQA): shares key and value heads across multiple attention heads.

More model quantization and deployment acceleration techniques will be covered in detail in the later section “Transformer Quantization and TVM Deployment.”

The LLaMA Family

As we learned from the previous article A First Look at LLM Base Models, LLaMA was the pioneer and leader in the open-source LLM community. However, it only released the model weights without providing complete training code or training data. This led to two main lines of follow-up work:

  • Well-funded teams attempted to fully reproduce the LLaMA base model itself. The most representative project is RedPajama, which started by recreating the pre-training dataset and proceeded all the way to training and evaluation.
  • Resource-constrained teams focused on efficient fine-tuning for downstream applications. The most representative project is Alpaca-LoRA, also known as PEFT (Parameter-Efficient Fine-Tuning).

RedPajama

The RedPajama project is a collaborative effort by Together, Stanford, and other institutions to comprehensively reproduce LLaMA across three dimensions: the pre-training dataset, the SFT & RLHF dataset, and the base model itself. Its logo is a LLaMA wearing red pajamas.

As of July 2023, the project had successfully reproduced the LLaMA pre-training dataset. The next step is to collect instruction data submitted by users through the OpenChatKit platform to support subsequent SFT & RLHF training.

Alpaca

Unlike RedPajama’s goal of reproducing the LLaMA base model, Stanford’s Alpaca project focuses on performing instruction fine-tuning on LLaMA to create a ChatBot capable of following user instructions.

The core technique used is Self-Instruct to generate the SFT dataset. Each data point consists of an instruction and an instance.

The entire process is divided into four main steps, as shown below:

  • Step 1: Starting from 175 seed instructions, call the language model to generate a large number of new instructions.

  • Step 2: Use an LM to classify all instructions into two categories — those that belong to classification tasks and those that do not.

  • Step 3: Call the LM to generate instances

    • For non-classification tasks, use the input-first template
    • For classification tasks, use the output-first template
  • Step 4: Filter out low-quality results

Steps 1 through 3 all rely on the LM’s completion and in-context learning capabilities. The templates are as follows:

Alpaca-LoRA

Alpaca requires full supervised fine-tuning (SFT) on all weights of LLaMA-6B. To further reduce the cost of fine-tuning, LoRA (Low-Rank Adaptation) adopts the following approach:

  • While keeping the main-path parameters frozen, a low-rank shortcut is added in parallel. During training, the main path remains fixed and only the bypass is trained, dramatically reducing the number of trainable parameters.

  • At initialization, matrix B is set to zero, achieving a “zero-convolution” effect.

  • During inference, the bypass is folded back into the main path, similar to the re-parameterization technique.

Vicuna

Vicuna is a more engineering-oriented project. It integrates various training techniques available at the time, with the main selling point being “cheap and easy to use.”

Comparison is shown below:

📊 This is an embedded Feishu content (table/artboard, etc.). View the full version in the Feishu knowledge base

Final Remarks

Due to length constraints, it is impossible to cover all excellent ChatBot-related works. The article focuses more on organizing the main technical threads. Here is a summary of the entire post:

  • Starting from Codex and AlphaCode, it explains how SFT is applied to assist programming in downstream applications of LLM base models.

  • It then introduces how the representative ChatBot application, ChatGPT, acquires its powerful multi-turn dialogue capabilities after going through the four stages of PT–SFT–RM–PPO.

  • Finally, it reviews the technical solutions of other industry competitors such as Bard, Claude, MOSS, ChatGLM2, and the LLaMA family.

Teaser: The next article is planned to cover how Transformers are used in the pure Computer Vision domain. Stay tuned.

PS: The author, Aaron (Xiao A), has not personally implemented every detail mentioned above. Most of the content was summarized in a bottom-up manner by studying code and carefully reading excellent papers. Essentially, this is a knowledge porter that stands on the shoulders of giants. Therefore, it remains “talking on paper.” I sincerely welcome experts with real hands-on experience to critique and correct it — only through collision of ideas can sparks fly, and truth becomes clearer through debate.

If you would like to learn more about Transformer algorithms in NLP, CV, and multimodal domains, knowledge of distributed training, or how to perform PTQ quantization and deployment on TVM, feel free to follow me, aaronxic~ Zhihu Profile


References