When we fine-tune a Large Language Model using standard next-token prediction, we teach it grammar, syntax, and basic pattern matching. But raw text generation alone doesn't guarantee that an LLM will be helpful. To truly align a model with human intent, we need a mechanism to reward desirable behavior and discourage toxic or unhelpful outputs.
With Reinforcement Learning with Human Feedback (RLHF) and its optimization algorithm, Proximal Policy Optimization (PPO), we can help align the model with human preferences with the help of Reward Modeling.
In this blog, we will explore the complete mathematical and architectural pipeline behind RLHF, walking step-by-step through preference modeling, KL divergence penalties, advantage estimation, and the clipped surrogate loss that keeps modern LLM alignment stable.
To understand how modern alignment works, we can look back at OpenAI's foundational InstructGPT paper, which established the blueprint for aligning base models like GPT-3 with human intent. The pipeline relies on three fundamental phases:
┌─────┐
Prompt ───► │ LLM │───► Response ───► Human Evaluation ───► Parameter Update
└─────┘
While effective, keeping a human in the loop to evaluate every single model generation during training is slow, expensive, and completely unscalable.
To bypass this bottleneck, InstructGPT introduced a brilliant proxy, it replaces the human evaluator with a trained neural network, or an LLM (the Reward Model):
┌─────┐ ┌──────────────┐
Prompt ───►│ LLM │───► Response ──────►│ Reward Model │───► Parameter Update
└─────┘ └──────────────┘
In the sections that follow, we will unpack the machinery behind this pipeline:
Before diving into how reinforcement learning updates our model, we need to understand the data that makes it all possible, along with the standard naming conventions used in the literature.
Quick Nomenclature Note of all the different LLMs used (Total 4):
πSFT) / Reference Model: The model fine-tuned on supervised chat conversations. Generally denoted as πSFT or πref. It serves as our baseline anchor.rψ): The scoring network trained to evaluate text quality, typically denoted as rψ (parameterized by weights ψ).πθ): The language model trained to generate text, typically denoted as πθ (parameterized by weights θ).πcritic): The language model used to estimate the value of states, denoted as πcritic; (parameterized by weights πSFT).To train the reward model, we use pairwise human preference data:
{
"prompt": "x: What is 2 + 2?",
"chosen": "y_w: The answer to 2 + 2 is 4.",
"rejected": "y_l: 2 + 2 is 5, but sometimes math is relative."
}
The Reward Model isn't built from scratch. It is initialized directly from our trained SFT checkpoint (πSFT) with some modifications:
┌──────────────┐
Prompt + Chosen (y_w) ───────► | | ───────► Scalar Score: +2.5 (r_w)
│ Reward Model │
Prompt + Rejected (y_l) ─────► | | ───────► Scalar Score: +0.5 (r_l)
└──────────────┘
The Reward Model is trained using the Bradley-Terry preference model, which computes the probability that the chosen response \(y_w\) is genuinely better than the rejected response \(y_l\) given a prompt \(x\):
Let's walk through how this works with actual numbers:
(This means our Reward Model calculates an 81.76% probability that the chosen response is better).
The loss function for training the Reward Model is the negative log-likelihood of the correct preference. We want to maximize this probability, which means minimizing the negative log-likelihood:
Calculated Loss Value:
To update the Reward Model \(r_{\psi}\) via backpropagation, we calculate the derivative of the loss with respect to both scalar scores (\(r_w\) and \(r_l\)):
Interpretation: The negative gradient for \(r_w\) pushes its score higher, while the positive gradient for \(r_l\) pushes its score lower, aligning the Reward Model closer to human preferences.
To know more about Bradley Terry preference model, and how Reward models are trained, you can refer to the this amazing substack: Bradley-Terry Model for Reward Modeling
To measure how much the new policy deviates from the SFT model, we use KL divergence (Kullback-Leibler divergence).
If we only reward the LLM based on the Reward Model's score rψ, the LLM will quickly figure out how to "hack" the reward model. It might start repeating nonsense words that accidentally trigger high scores, or drifting into unnatural language.
To prevent this, penalize the LLM if it strays too far from the original SFT model, πSFT. This is done using KL divergence (Kullback-Leibler divergence), which measures how much the new policy's token, πθ, probabilities have changed compared to the reference SFT model πSFT.
The final reward R(x, y) given to the PPO algorithm is:In this section, we will explore how the Policy LLM is fine-tuned using Proximal Policy Optimization (PPO) to align it with human preferences.
Here, we combine everything into PPO trainging step to update LLM weights (θ).
┌──────────┐ ┌──────────────┐
Prompt ───► │Policy LLM│───► Response ──────►│ Reward Model │───► Reward (R) ──► Update πθ with PPO
│ (π_θ) │ └──────────────┘
└──────────┘
The Policy LLM isn't built from scratch. It is initialized directly from our trained SFT checkpoint (πSFT) without any modifications.
The PPO algorithm uses a clipped surrogate loss function to update the policy parameters:
where
\(r_t(\theta)\) is the probability ratio, and
\( \epsilon \) is the clipping parameter, and
Ât is the estimated advantage (action-value) function.
The probability ratio \(r_t(\theta)\) is defined as:
PPO uses a secondary small neural network called the Critic.
Before looking at the reward, the Critic guesses: "Based on this prompt, I expect the model to get a score of around +1.0." If the actual combined reward turns out to be +2.5, the Advantage is +1.5 (2.5 - 1.0). This tells the model: "This response wasn't just good; it was better than expected."
Before we go thorugh the mathematics to understand the PPO loss function, lets calculate their derivatives.
we only look at the unclipped portion of the objective function (which is active when the model update stays within safe boundaries).
The PPO objective function ($J_{\text{CLIP}}$) that we want to maximize is:
$$J_{\text{CLIP}}(\theta) = \hat{\mathbb{E}}_t \left[ \min\left( r_t(\theta)\hat{A}_t, \, \text{clip}(r_t(\theta), 1-\epsilon, 1+\epsilon)\hat{A}_t \right) \right]$$Optimizers like Adam perform minimization (gradient descent), we define our PPO loss function ($L_{\text{PPO}}$) as the negative of the objective:
$$L_{\text{PPO}}(\theta) = - J_{\text{CLIP}}(\theta)$$When the probability ratio $r_t(\theta)$ is unclipped, the min function evaluates simply to the unclipped term. Therefore, for an unclipped step, we differentiate: $$ \begin{aligned} L_{\text{PPO}}(\theta) &= -\hat{\mathbb{E}}_t \left[ r_t(\theta)\hat{A}_t \right] \\ &= -\hat{\mathbb{E}}_t \left[ \frac{\pi_{\theta}}{\pi_{\text{SFT}}} \hat{A}_t \right] \\ &= -\hat{\mathbb{E}}_t \left[ \frac{\hat{A}_t}{\pi_{\text{SFT}}} \pi_{\theta} \right] \\ \text{Taking derivative w.r.t. } \theta: \\ \nabla_\theta L_{\text{PPO}} &= -\hat{\mathbb{E}}_t \left[ \frac{\hat{A}_t}{\pi_{\text{SFT}}} \cdot \nabla_\theta \pi_\theta \right] \text{since $\hat{A}_t$ and $\pi_{\text{SFT}}$ are constants w.r.t. $\theta$} \\ &= -\hat{\mathbb{E}}_t \left[ \frac{\hat{A}_t}{\pi_{\text{SFT}}} \cdot \pi_\theta \cdot \nabla_\theta \log \pi_\theta \right] \text{(using the log-derivative trick)} \\ &= -\hat{\mathbb{E}}_t \left[ r_t(\theta) \cdot \hat{A}_t \cdot \nabla_\theta \log \pi_\theta \right] \text{(substituting $r_t(\theta) = \frac{\pi_\theta}{\pi_{\text{SFT}}}$)} \\ \text{Final derivative w.r.t. } \theta: \\ \nabla_\theta L_{\text{PPO}} &= - r_t(\theta) \cdot \hat{A}_t \cdot \nabla_\theta \log \pi_\theta \end{aligned} $$
From above, the penalized reward, R = 2.4942.
Case 1 (Ratio is Clipped): When the derivative is zero
Let consider a simple example, where we have the following values:
Probability ratio rt(θ) = 1.2,Now, we can calculate the PPO Loss:
Now, the derivative of the PPO Loss:
Since, rt(θ) = 1.2 is at the upper clipping boundary (1 + ε = 1.2), the derivative of the loss function with respect to θ is zero.
This means that the optimizer will not update the model parameters for this particular step, as it has reached the maximum allowed change in probability ratio.
Interpretation: This is a safety break, if a policy update tries to push the model too far too fast, PPO will stop updating the weight in this direction.
Case 2 (Ratio is Not Clipped): When the derivative is non-zero
Let consider a simple example, where we have the following values:
Probability ratio rt(θ) = 1.05, (It falls strictly between 0.8 and 1.2, so no clipping occurs.)Now, we can calculate the PPO Loss:
Now, the derivative of the PPO Loss:
Since, rt(θ) = 1.05 is not at the clipping boundary (unclipped), the objective function depends directly on the model parameter, θ.
The model weights (θ) are successfully updated by the gradient descent, so that next time it sees a similar prompt, it is sightly more likely to gnerate this preferred style of respone.