✨ (posts): add deep dive into PPO for language models post
All checks were successful
Hugo Publish CI / build-and-deploy (push) Successful in 14s
All checks were successful
Hugo Publish CI / build-and-deploy (push) Successful in 14s
This commit introduces a new blog post detailing the Proximal Policy Optimization (PPO) algorithm as used in Reinforcement Learning from Human Feedback (RLHF) for Large Language Models (LLMs). The post covers: - The mapping of RL concepts to text generation. - The roles of the Actor, Critic, and Reward Model. - The use of Generalized Advantage Estimation (GAE) for stable credit assignment. - The PPO clipped surrogate objective for safe policy updates. - The importance of pretraining loss to prevent catastrophic forgetting. - The full iterative training loop.
This commit is contained in:
101
content/posts/A Deep Dive into PPO for Language Models.md
Normal file
101
content/posts/A Deep Dive into PPO for Language Models.md
Normal file
@@ -0,0 +1,101 @@
|
||||
Large Language Models (LLMs) have demonstrated astonishing capabilities, but out-of-the-box, they are simply powerful text predictors. They don't inherently understand what makes a response helpful, harmless, or aligned with human values. The technique that has proven most effective at bridging this gap is Reinforcement Learning from Human Feedback (RLHF), and at its heart lies a powerful algorithm: Proximal Policy Optimization (PPO).
|
||||
|
||||
You may have seen diagrams like the one below, which outlines the RLHF training process. It can look intimidating, with a web of interconnected models, losses, and data flows.
|
||||
|
||||
![[Pasted image 20250730232756.png]]
|
||||
|
||||
This post will decode that diagram, piece by piece. We'll explore the "why" behind each component, moving from high-level concepts to the deep technical reasoning that makes this process work.
|
||||
|
||||
### Translating RL to a Conversation
|
||||
|
||||
The first step is to understand how the traditional language of reinforcement learning maps to the world of text generation.
|
||||
|
||||
* **State (`s_t`)**: In a chat setting, the "state" is the context of the conversation so far. It's the initial prompt (`x`) plus all the text the model has generated up to the current moment (`y₁, ..., y_{t-1}`).
|
||||
* **Action (`a_t`)**: The "action" is the model's decision at each step. For an LLM, this means generating the very next token (`y_t`). A full response is a sequence of these actions.blob:https://aistudio.google.com/872e746f-88c1-40ec-8e45-fa0efce97299
|
||||
* **Reward (`r`)**: The "reward" is a numeric score that tells the model how good its full response (`y`) was. This score comes from a separate **Reward Model**, which has been trained on a large dataset of human preference comparisons (e.g., humans rating which of two responses is better). This reward is often only awarded at the end of the entire generated sequence.
|
||||
|
||||
Let's make this concrete. If a user provides the prompt **(x)**: *"The best thing about AI is"*, and the model generates the response **(y)**: *"its potential to solve problems."*, here is how it's broken down for training:
|
||||
|
||||
* **State 1**: "The best thing about AI is"
|
||||
* **Action 1**: "its"
|
||||
* **State 2**: "The best thing about AI is its"
|
||||
* **Action 2**: " potential"
|
||||
* **State 3**: "The best thing about AI is its potential"
|
||||
* **Action 3**: " to"
|
||||
* ...and so on for every generated token.
|
||||
|
||||
This breakdown transforms a single prompt-response pair into a rich trajectory of state-action pairs, which becomes the raw data for our learning algorithm.
|
||||
|
||||
### The Cast of Models: An Actor-Critic Ensemble
|
||||
|
||||
The PPO process doesn't rely on a single model but an ensemble where each member has a distinct role.
|
||||
|
||||
1. **The Actor (Policy LM)**: This is the star of the show—the LLM we are actively fine-tuning. Its role is to take a state (the current text) and decide on an action (the next token). We refer to its decision-making process as its "policy" (`π`).
|
||||
2. **The Critic (Value Model)**: This is the Actor's coach. The Critic doesn't generate text. Instead, it observes a state and estimates the *potential future reward* the Actor is likely to receive from that point onward. This estimate is called the "value" (`V(s_t)`). The Critic's feedback helps the Actor understand whether it's in a promising or a dead-end situation, which is a much more immediate learning signal than waiting for the final reward.
|
||||
3. **The Reward Model**: This is the ultimate judge. As mentioned, it's a separate model trained on human preference data that provides the final score for a complete generation. Its judgment is treated as the ground truth for training both the Actor and the Critic.
|
||||
|
||||
### The Challenge of Credit Assignment: Generalized Advantage Estimation (GAE)
|
||||
|
||||
A key problem in RL is assigning credit. If a 20-token response gets a high reward, was it because of the first token, the last one, or all of them? The Critic helps solve this. By comparing the reward at each step with the Critic's value estimate, we can calculate the **Advantage (`Â`)**.
|
||||
|
||||
A simple advantage calculation might be: `Advantage = reward + Value_of_next_state - Value_of_current_state`.
|
||||
|
||||
However, this can be noisy. PPO uses a more sophisticated technique called **Generalized Advantage Estimation (GAE)**. The formula looks complex, but the idea is intuitive:
|
||||
|
||||
`Â(s_t, a_t) = Σ(γλ)^l * δ_{t+l}`
|
||||
where `δ_t = r_t + γV(s_{t+1}) - V(s_t)`
|
||||
|
||||
* **γ (gamma)** is a discount factor (e.g., 0.99), which values immediate rewards slightly more than distant ones.
|
||||
* **λ (lambda)** is a smoothing parameter that balances the trade-off between bias and variance. It creates a weighted average of advantages over multiple future time steps.
|
||||
|
||||
In essence, GAE provides a more stable and accurate estimate of how much better a specific action was compared to the policy's average behavior in that state.
|
||||
|
||||
### The Heart of PPO: The Quest for Stable Updates
|
||||
|
||||
Now we arrive at the core innovation of PPO. We want to update our Actor model to take actions with higher advantages. The naive way to do this is to re-weight our training objective by an **importance sampling ratio**: `(π_new / π_old)`. This corrects for the fact that the data we are learning from was generated by a slightly older version of our policy.
|
||||
|
||||
However, this ratio is incredibly dangerous. If the new policy becomes very different from the old one, the ratio can explode, leading to massive, unstable gradient updates that destroy the model.
|
||||
|
||||
PPO solves this with its signature **Clipped Surrogate Objective**. The PPO loss function is:
|
||||
|
||||
`L_CLIP(θ) = Ê_t [ min( r_t(θ)Â_t, clip(r_t(θ), 1 - ε, 1 + ε)Â_t ) ]`
|
||||
|
||||
Let's translate this from math to English:
|
||||
* `r_t(θ)` is the probability ratio `π_new(a_t|s_t) / π_old(a_t|s_t)`.
|
||||
* The goal is to increase the objective by an amount proportional to the advantage `Â_t`.
|
||||
* **The `clip` function is the crucial safeguard.** It forbids the probability ratio from moving outside a small window (e.g., `[0.8, 1.2]`).
|
||||
|
||||
This means the algorithm says: "Let's update our policy to favor this good action. But if the required update would change the policy too drastically from the old one, we'll 'clip' the update to a more modest size." This creates a "trust region," ensuring stable, incremental improvements.
|
||||
|
||||
### Avoiding Amnesia: The Pretraining Loss
|
||||
|
||||
There's one final problem. If we only optimize for the PPO loss, the model might learn to "hack" the reward model by generating repetitive or nonsensical text that gets a high score. In doing so, it could suffer from **catastrophic forgetting**, losing its fundamental grasp of grammar and facts.
|
||||
|
||||
To prevent this, we introduce a second loss term. As seen in the diagram, we mix in data from the original **Pretraining Data** (or the dataset used for Supervised Fine-Tuning). We calculate a standard next-token prediction loss (`LM Loss`) on this high-quality data.
|
||||
|
||||
The final loss for the Actor is a combination of both objectives:
|
||||
|
||||
**Total Loss = Loss_PPO + `λ_ptx` * Loss_LM**
|
||||
|
||||
This brilliantly balances two goals:
|
||||
1. The `Loss_PPO` pushes the model towards behaviors that align with human preferences.
|
||||
2. The `Loss_LM` acts as a regularizer, pulling the model back towards its core language capabilities and preventing it from drifting into gibberish.
|
||||
|
||||
### The Full Training Loop
|
||||
|
||||
Now, we can assemble the entire process into a clear, iterative loop:
|
||||
|
||||
1. **Collect**: The current Actor policy `π_k` generates responses to a batch of prompts. These experiences—`(state, action, probability, reward, value)`—are stored in an **Experience Buffer**.
|
||||
2. **Calculate**: Once the buffer is full, we use the collected data to compute the advantage estimates `Â_t` for every single token-generation step.
|
||||
3. **Optimize**: For a few epochs, we repeatedly sample mini-batches from the buffer and update the Actor and Critic models. The Actor is updated using the combined `PPO-clip Loss` and `LM Loss`. The Critic is updated to improve its value predictions.
|
||||
4. **Flush and Repeat**: After the optimization phase, the entire experience buffer is discarded. The data is now "stale" because our policy has changed. The newly updated policy `π_{k+1}` becomes the new Actor, and we return to step 1 to collect fresh data.
|
||||
|
||||
This cycle of collection and optimization allows the language model to gradually and safely steer its behavior towards human-defined goals, creating the helpful and aligned AI assistants we interact with today.
|
||||
|
||||
***
|
||||
|
||||
**References:**
|
||||
|
||||
1. Schulman, J., Wolski, F., Dhariwal, P., Radford, A., & Klimov, O. (2017). *Proximal Policy Optimization Algorithms*. arXiv preprint arXiv:1707.06347.
|
||||
2. Schulman, J., Moritz, P., Levine, S., Jordan, M., & Abbeel, P. (2015). *High-Dimensional Continuous Control Using Generalized Advantage Estimation*. arXiv preprint arXiv:1506.02438.
|
||||
3. Ouyang, L., et al. (2022). *Training language models to follow instructions with human feedback*. Advances in Neural Information Processing Systems 35.
|
Reference in New Issue
Block a user