Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college lesson →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

RLHF + ReasoningUnderstand the moving parts.

The post-training pass that turns a parrot into an assistant.

Suggested preparation: 02

WORKBENCH / CHANGE ONE THING

Turn a score gap into a preference

Compare reward differences and the resulting preference likelihood.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Compare two answers; distinguish a helpful rating from guaranteed truth.

Where this deserves more time

Reward modeling, PPO clipping, reference policy KL and reward hacking.

Open the complete high-school reading

Moment 01 / 11

Introduction to RLHF and Reasoning

Welcome. Today we introduce reinforcement learning from human feedback, the alignment stage that turns a next token predictor into a helpful assistant, and we will connect it to reasoning, reward modeling, and policy optimization.

The core idea is not more data, but a preference signal: humans rank candidate completions, we fit a reward model to those judgments, then optimize the policy against it while staying near the reference distribution through a K L penalty.

A base model is a pretrained conditional distribution over tokens, broad but unaligned; the assistant is that same initialization after supervised instruction tuning and preference optimization, sharpened toward helpful, harmless, honest behavior under evaluation.

The pipeline is supervised fine tuning, reward model training from comparisons, then policy optimization with PPO or a direct preference objective, followed by ablations that test data quality, reward hacking, and generalization.

By the end, you should be able to state the objective, explain why maximum likelihood pretraining is insufficient for alignment, and place InstructGPT style RLHF and direct preference optimization in one engineering framework.

Equations, code and original cards

RLHF and Reasoning: From Base Models to Aligned Assistants

• Preference learning: comparisons to reward model to policy optimization

• Base pretrained distribution versus aligned assistant: SFT, RLHF, DPO

• Outcomes: objectives, failure modes, ablations, reasoning evaluations

Moment 02 / 11

Mathematical Foundations: Reward Models and Preference Learning

We begin with the mathematical foundations of reward modeling: how scalar reward signals are learned from pairwise human preference data, the core machinery behind RLHF as in Ouyang et al. 2022.

The reward model is a neural network, typically initialized from the pretrained language model with the unembedding head replaced by a scalar projection, that assigns each prompt-response pair a single reward score.

The Bradley-Terry model then converts scores into preference probabilities: the probability that one completion is preferred is the logistic sigmoid of the difference between the two reward scores.

Concretely, the preferred item's score is exponentiated and normalized against the sum of exponentials; equivalently, this is a softmax over the two candidates, making preference a function of the reward gap.

Training minimizes the negative log likelihood of the observed preferences, which pushes the model to assign strictly higher reward to the completion the human labeler actually chose.

That loss is minus the log of the sigmoid of the winner's score minus the loser's score, a smooth convex objective in the reward difference, amenable to standard gradient-based optimization.

The reward itself is parameterized by network weights theta, and gradients of this pairwise loss flow back through both forward passes, updating the shared parameters by backpropagation.

Formally, the reward vector r is produced by the network f sub theta, a deterministic map from prompt-response features to a scalar score per candidate.

The gradient with respect to theta has a clean closed form: it is the sigmoid of the negative reward gap times the difference of the two score Jacobians, so errors scale with how confidently wrong the model is.

In summary: reward model, Bradley-Terry likelihood, logistic loss, and gradient descent give a principled, end-to-end trainable framework for distilling human preferences into a scalar reward signal.

Equations, code and original cards

Mathematical Foundations: Reward Models & Preference Learning

Reward Model as Neural Network

• Scalar score per prompt-response pair

Bradley-Terry Model

• Preference probability \(\hat{p}\)

\(\hat{p} = \sigma(r_w - r_l)\)

\hat{p} = \frac{e^{r_w}}{e^{r_w} + e^{r_l}} = \sigma(r_w - r_l)

• \(r_w\): Reward score of the preferred completion

• \(r_l\): Reward score of the dispreferred completion

• \(\sigma\): Logistic sigmoid; softmax over two candidates

Loss Function

• Negative log-likelihood: \(-\log \sigma(r_w - r_l)\)

\ell = -\log\sigma(r_w - r_l)

• Maximizes the reward margin between preferred and dispreferred

• Smooth, convex in the reward gap; standard gradient descent applies

Parameterization & Gradient

\mathbf{r} = f_\theta(\mathbf{x})\quad \text{with} \quad \mathbf{r} \in \mathbb{R}^n
\nabla_\theta \ell = - \frac{1}{\sigma(r_w - r_l)} \sigma'(r_w - r_l) \nabla_\theta (r_w - r_l)

• Reward vector \(\mathbf{r}\) parametrized by neural network \(f_\theta\)

• Gradient scales as \(\sigma(r_l - r_w)\): confident errors dominate

Moment 03 / 11

Interactive Diagram: Stages of RLHF Training

Let's walk through the three stages of RLHF: supervised fine-tuning, reward model fitting, and policy optimization against that reward.

Stage one is supervised fine-tuning: we minimize the cross-entropy loss, the negative log likelihood of each human-written token given its context, over demonstration data.

This model guides later training by estimating how well outputs match human judgments.

Equations, code and original cards

Moment 04 / 11

On-Policy vs Off-Policy Alignment Techniques

Let's compare on-policy and off-policy alignment, the central design axis in RLHF. The distinction is where the training signal comes from: sampled live from the current policy, or drawn from a fixed, pre-collected preference dataset.

On-policy methods roll out fresh completions from the current policy at every update. The gradient signal always reflects the model's present behavior, so the objective tracks exactly the policy being optimized.

Proximal Policy Optimization, from Schulman et al. 2017, clips the importance-sampling ratio to stabilize updates; Group Relative Policy Optimization, from DeepSeekMath, drops the critic and normalizes rewards within sampled groups. Both demand costly generation each step.

Off-policy methods skip generation entirely. Direct Preference Optimization, Rafailov et al. 2023, reparameterizes the RLHF objective into a supervised loss on preference pairs; Odds Ratio Preference Optimization folds preference tuning into fine-tuning. No rollouts, no reward model.

Fixed preference data removes rollout cost but introduces distribution shift: the dataset reflects an older policy, so alignment quality degrades as the current model drifts from the data-generating distribution.

On the trade-offs: on-policy training pays for rollouts at every iteration, but the KL-constrained objective stays matched to the live policy, which empirically yields tighter alignment and stronger reasoning gains.

Off-policy methods train cheaply, but cannot correct errors the current policy actually makes; reasoning improvements are bounded by dataset coverage and the quality of the preference labels.

The choice is a budget decision: on-policy buys adaptability and alignment precision with compute; off-policy buys efficiency at the cost of distribution shift. Modern pipelines often combine both, bootstrapping with DPO before on-policy refinement.

Equations, code and original cards

On-Policy vs Off-Policy Alignment in RLHF

On-Policy Methods

Off-Policy Methods

• Samples rollouts from the current policy each update

• PPO (Schulman 2017); GRPO (DeepSeekMath 2024)

• Objective matches the live policy; no distribution shift

• KL penalty against a frozen reference policy

• Trains on fixed preference pairs; no rollouts

• DPO (Rafailov 2023); ORPO (Hong 2024)

• Supervised loss; no reward model or critic

• Distribution shift as policy drifts from data

Performance, Complexity, and Reasoning Impact

• On-policy: rollout cost per step; tracks the live policy

• Off-policy: cheap supervised updates; bounded by data coverage

• On-policy corrects errors the current model actually makes

• Off-policy alignment scales with preference label quality

Moment 05 / 11

Proximal Policy Optimization (PPO) Deep Dive

Proximal Policy Optimization, PPO, is the policy-gradient workhorse behind modern RLHF. We now dissect its machinery: the clipped surrogate objective, Generalized Advantage Estimation, and the KL-penalty variant, ending with practical failure modes.

Start with the formulation. PPO maximizes a clipped surrogate: the expectation of the minimum of the probability ratio times the advantage, and the ratio clipped to one plus or minus epsilon times that advantage. Clipping removes the incentive for updates that move the policy too far.

Reading the expression: r-t of theta is the new-policy probability over the old-policy probability for the sampled action. When the advantage is positive, clipping caps the objective once the ratio exceeds one plus epsilon, so the gradient vanishes beyond the trust region. Epsilon is typically 0.1 to 0.2.

Next, Generalized Advantage Estimation, GAE. The advantage estimate is an exponentially weighted sum of temporal-difference residuals, with lambda interpolating between high-bias one-step targets at lambda zero and high-variance Monte Carlo returns at lambda one.

Formally, the residual delta-t is the reward plus gamma times the value of the next state minus the value of the current state, and the advantage is the sum over l of gamma lambda to the l times delta t plus l. Lambda near 0.95 is the standard bias-variance compromise.

Now the variants. PPO-KL replaces clipping with an explicit penalty on the Kullback-Leibler divergence between old and new policies, with an adaptive coefficient targeting a fixed KL budget. PPO-Clip achieves the same trust-region effect with a one-line objective change.

Clip is simpler and dominates in practice; the KL penalty gives finer control when a hard divergence budget matters, as in RLHF where drifting too far from the supervised policy degrades fluency. Choose per your constraint, not fashion.

These pieces together gave the RLHF stage of InstructGPT, Ouyang et al. 2022, the recipe behind early ChatGPT. Ahead: reward hacking against a learned reward model, and the memory cost of holding policy, reference, value, and reward models simultaneously.

Equations, code and original cards

Proximal Policy Optimization (PPO) Deep Dive

Clipped surrogate objective, GAE, KL-penalty variant, and RLHF failure modes

1. PPO Formulation: Clipped Surrogate Objective

L^{CLIP}(\theta) = \mathbb{E}_t \left[ \min \left( r_t(\theta) \hat{A}_t, \mathrm{clip}(r_t(\theta), 1-\epsilon, 1+\epsilon) \hat{A}_t \right) \right]

• Ratio rt(θ) = π_θ(a_t|s_t) / π_θ_old(a_t|s_t); clip to 1 ± ε (ε ≈ 0.1–0.2)

• min of clipped/unclipped terms ⇒ zero gradient outside trust region

• \hat{A}_t: advantage estimate at timestep t

• Schulman et al. 2017; multiple epochs per rollout batch

2. Generalized Advantage Estimation (GAE)

\hat{A}_t^{GAE(\gamma,\lambda)} = \sum_{l=0}^{\infty} (\gamma \lambda)^l \delta_{t+l}

• Balances bias and variance via λ

• TD residuals: δ_t = r_t + \gamma V(s_{t+1}) - V(s_t)

• Enables stable advantage estimation

3. PPO Variants: PPO-KL and PPO-Clip

• PPO-KL: adaptive penalty on KL(π_θ_old ‖ π_θ), targets fixed KL budget

• PPO-Clip: same trust-region effect, one-line objective change

• Trade-off: divergence control vs implementation simplicity

• RLHF (Ouyang et al. 2022): KL to reference policy preserves fluency

Moment 06 / 11

Mathematical Derivations and Formulae in PPO

Here are the derivations behind Proximal Policy Optimization, PPO, the workhorse of RLHF for large language models. We will assemble the clipped surrogate, its gradient, the KL penalty, and the value loss into one objective.

The clipped surrogate L-clip of theta takes an expectation over time steps of the minimum of two terms: the probability ratio r-t times the advantage A-hat-t, and that ratio clamped to one plus or minus epsilon, times the same advantage.

Clipping bounds r-t of theta inside the interval one minus epsilon to one plus epsilon, so a single batch cannot move the policy too far and destroy training stability.

The gradient nabla-theta of L-clip tells us how to update the policy parameters. Where the ratio is unclipped, the usual likelihood-ratio gradient survives; where it is clipped, the gradient is zero.

That indicator on the unclipped region is the whole point: once the update hits the epsilon boundary, the objective stops rewarding further movement, so the learning signal cannot destabilize the policy.

The KL term is an adaptive trust region: it softly penalizes divergence between new and old policies, with beta nudged up or down to hold the measured KL near a target.

That adaptive penalty trades exploration against stability, keeping each policy update inside an effective trust region rather than relying on a fixed step size.

The value loss L-V-F of phi fits the critic by minimizing the expected squared error between the predicted value V-phi of s-t and the return target, tightening the advantage estimates used by the policy.

PPO maximizes one combined objective: the clipped surrogate for the actor, minus c-one times the value loss for the critic, plus c-two times an entropy bonus S of pi-theta that sustains exploration.

The final expression is exactly that sum: maximize L-clip, subtract the weighted value error, add the entropy bonus, and include the KL penalty, all estimated on rollouts from the old policy under teacher forcing.

In short, PPO couples a clipped surrogate and its indicator-gated gradient with an adaptive KL trust region, a fitted critic, and an entropy bonus. That combination is what makes RLHF updates stable enough to align language models at scale.

Equations, code and original cards

PPO: Clipped Surrogate, KL Trust Region, and Value Loss

L^{CLIP}(\theta) = \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]

• Clipped objective bounds the ratio \(r_t(\theta)\) in \([1-\epsilon,1+\epsilon]\)

• \(r_t(\theta) = \frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_{old}}(a_t|s_t)}\)

\nabla_\theta L^{CLIP}(\theta) \approx \mathbb{E}_t \left[ \nabla_\theta \min \left( r_t(\theta)\hat{A}_t, \; \text{clip}(r_t(\theta), 1-\epsilon, 1+\epsilon) \hat{A}_t \right) \right]
\quad= \mathbb{E}_t \left[ \mathbb{I}_{\text{unclipped}} \nabla_\theta r_t(\theta) \hat{A}_t \right]

• Indicator \(\mathbb{I}_{\text{unclipped}}\) gates the gradient path

• \(\hat{A}_t\): GAE advantage estimate

• Clipped region contributes zero gradient

L^{KL}(\theta) = \beta \; \mathbb{E}_t \left[ D_{KL} \left( \pi_{\theta_{old}}(\cdot|s_t) \parallel \pi_\theta(\cdot|s_t) \right) \right]

• Adaptive KL penalty as a soft trust region

• \(\beta\) tuned to hold KL near a target

L^{VF}(\phi) = \mathbb{E}_t \left[ \left( V_\phi(s_t) - V^{target}_t \right)^2 \right]
L^{PPO}(\theta, \phi) = L^{CLIP}(\theta) - c_1 L^{VF}(\phi) + c_2 S[\pi_\theta](s_t)

• Joint actor–critic objective

• \(S[\pi_\theta]\): entropy bonus for exploration

• \(c_1, c_2\) weight value loss and entropy

Moment 07 / 11

Code Exploration: PPO Implementation Snippets (Python/PyTorch)

Start with the policy network's forward pass: the state feeds through the trunk to produce logits, and we sample an action from the resulting categorical distribution, storing its log probability for the ratio later.

Next, examine reward computation and advantage estimation. PPO typically uses generalized advantage estimation, which trades bias against variance by exponentially weighting the temporal-difference residuals.

Now the PPO objective itself. The clipped surrogate constrains the probability ratio between new and old policies to the interval one minus epsilon to one plus epsilon, preventing destructively large policy updates.

Finally, the optimization step: multiple epochs of minibatch stochastic gradient descent on this surrogate, with gradient norm clipping and early stopping when the KL divergence exceeds a target threshold.

Equations, code and original cards

Moment 08 / 11

Advanced Techniques and Optimizations (2024–2026)

Welcome back. Today we examine the optimization frontier of reinforcement learning from human feedback, 2024 through 2026: critic-free policy gradients, compute-optimal scaling, reward hacking defenses, and multitask reward modeling for alignment at scale.

Consider Group Relative Policy Optimization, GRPO, introduced by DeepSeekMath in 2024. It eliminates PPO's value critic entirely, estimating advantages relative to a group of sampled completions, which roughly halves memory during training.

The objective retains PPO's clipped surrogate but replaces the learned value baseline with the group mean reward, normalized by the group standard deviation, plus a KL penalty against the reference policy.

Scaling laws remain our allocation compass. Kaplan's 2020 power laws and Hoffmann's Chinchilla analysis show compute-optimal training demands roughly twenty tokens per parameter, fixing the model size and duration tradeoff.

Reward hacking persists because the reward model is a frozen proxy of true preferences. Current defenses include reward model ensembles, KL-constrained updates, and adversarial audits of high-reward samples before gradient steps.

Finally, reward modeling is moving multitask: single preference models trained across helpfulness, safety, and reasoning domains, plus process reward models that score intermediate reasoning steps rather than final answers alone.

To summarize: GRPO removes the critic and regularizes against a reference policy; Chinchilla-style scaling fixes the compute budget; ensembles and KL control resist reward hacking; and multitask plus process reward models extend alignment across objectives. Together they define modern RLHF.

Clarification: No universal T proportional to N power1.5 law follows from GRPO.

Equations, code and original cards

Advanced Techniques and Optimizations (2024–2026)

• GRPO (DeepSeekMath 2024): critic-free PPO variant; group-normalized advantages roughly halve training memory

• Chinchilla scaling: compute-optimal training at ~20 tokens per parameter fixes the size-vs-duration tradeoff

• Reward hacking defenses: reward model ensembles, KL-constrained updates, adversarial audits of high-reward samples

• Multitask and process reward models: cross-domain alignment with step-level supervision of reasoning

A_i=(r_i-\bar r)/(\operatorname{std}(r)+\epsilon);\quad J=\mathbb E[\min(\rho_i A_i,\operatorname{clip}(\rho_i,1-\epsilon_c,1+\epsilon_c)A_i)-\beta D_{KL}(\pi_\theta\|\pi_{ref})]
C\approx6ND\quad\text{(rough dense-transformer training FLOPs)}

Moment 09 / 11

Open Research Questions and Cutting-Edge Variations

We turn now to the open problems in reinforcement learning from human feedback and reasoning training: reward model generalization, the exploration-exploitation tradeoff, multi-modal feedback, hybrid policy optimization, and alignment robustness under deployment.

First, reward model generalization. Learned reward proxies degrade under distribution shift, and Goodhart overoptimization is quantified by Gao, Schulman, and Hilton's twenty twenty-three scaling laws: the proxy reward keeps rising while true reward falls.

Second, exploration versus exploitation. The Kullback-Leibler penalty to the reference policy stabilizes PPO but induces entropy collapse and mode concentration; GRPO removes the critic yet still trades pass-at-k diversity against exploitation of high-reward modes.

Third, multi-modal feedback. Extending preference optimization beyond text to vision-language and audio reward models raises grounding and reward-hacking issues, while process supervision, as in Lightman et al.'s Let's Verify Step by Step, densifies the signal.

Fourth, hybrid on-policy and off-policy optimization. PPO is on-policy and sample-hungry; DPO is off-policy and cheap but stale. Online and iterative DPO variants attempt to recover freshness without PPO's variance and cost.

Finally, alignment robustness: jailbreaks, reward tampering, and specification gaming persist after RLHF, so red-teaming, scalable oversight, and mechanistic auditing become deployment requirements rather than optional evaluations.

These frontiers are coupled: reward misspecification amplifies exploration failure, multi-modal signals alter sample complexity, and off-policy staleness worsens Goodhart drift. Treat them as one interacting system when you design ablations and evaluations.

Equations, code and original cards

Open Problems in RLHF and Reasoning Training

Reward generalization, exploration, multi-modal feedback, hybrid policy optimization, and alignment robustness

Reward Model Generalization

Goodhart overoptimization under shift: proxy reward rises while true reward falls (Gao et al. 2023)

Exploration vs. Exploitation

KL-to-reference stabilizes PPO but drives entropy collapse; GRPO trades critic variance for pass@k diversity

Multi-Modal Feedback

Vision-language and audio reward models; process supervision densifies the signal (Lightman et al. 2023)

Hybrid On/Off-Policy Optimization

PPO sample-hungry versus DPO stale; online and iterative DPO recover freshness at lower variance

Alignment Robustness

Jailbreaks, reward tampering, specification gaming; red-teaming, scalable oversight, mechanistic auditing

Moment 10 / 11

Challenging Quiz: Conceptual and Computational Mastery

Now let's test your command of this material. Work each problem independently, reasoning from the reward model, the KL-constrained objective, and the PPO update, not from surface recall. Submit when ready, and I will walk through any step where your derivation diverges.

Equations, code and original cards

Moment 11 / 11

Summary and Key Takeaways

Let's close by consolidating the key takeaways from today's session on RLHF and reasoning.

First, RLHF is the critical stage that converts a base language model, trained purely on next-token likelihood, into a genuinely useful instruction-following assistant.

We then built the mathematical foundation: the Bradley-Terry reward model and the clipped PPO objective with its KL penalty against the frozen reference policy.

We surveyed modern optimizations, from reward-model ensembles to Direct Preference Optimization, which eliminates the RL loop entirely while improving stability and scalability.

Finally, we examined open problems: reward hacking, overoptimization against an imperfect proxy reward, and extending RLHF to elicit genuine multi-step reasoning.

I encourage you to think about how these pieces compose into robust assistants, and to pursue the research directions we flagged along the way.

Equations, code and original cards

Summary and Key Takeaways

• RLHF: converts base LLMs into aligned, instruction-following assistants

• Mathematical Foundations: Bradley-Terry reward modeling and clipped PPO

• Modern Optimizations: DPO, reward ensembles, distributed training

• Open Challenges: reward hacking, reasoning, and alignment research

Key Formula: Clipped PPO Objective with KL Penalty

J^{\mathrm{PPO}}(\theta) = \mathbb{E}_{t} \left[ \min \left( r_{t}(\theta) \hat{A}_{t},\, \mathrm{clip}\left( r_{t}(\theta), 1-\epsilon, 1+\epsilon \right) \hat{A}_{t} \right) \right]

Practical Insights & Future Outlook

• Reward models remain learned proxies; overoptimization invites reward hacking

• Mixed-precision and distributed methods make large-scale RLHF tractable

• Frontier research: process rewards for reasoning and bias mitigation

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

2 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.