Vibe Engines
YouTube
AI System Design

Design an RLHF Pipeline

Step 1 / 9

Learn AI system design by building an RLHF (reinforcement learning from human feedback) alignment pipeline step by step.

The numbers to beatSFTdemonstrationsRMpreferencesRLoptimize to reward

The whole design, in writing

Learn AI system design by building an RLHF (reinforcement learning from human feedback) alignment pipeline step by step. An interactive guide covering why a base model is capable but unaligned, supervised fine-tuning on demonstrations, why preferences beat demonstrations, training a reward model from human comparisons, PPO optimization with a KL constraint to prevent reward hacking, the DPO and RLAIF alternatives, and the unhappy paths (reward hacking, overoptimization, labeler quality).

Every step of the build above, written out: the problem each piece solves, the option that was taken and the ones that were not, the numbers, and how it fails in production.

The big idea

What does RLHF do?

A pretrained base model is astonishingly capable — it has read the internet — but it's not aligned: it predicts plausible text, not helpful, honest, harmless answers. Ask it a question and it might continue with more questions, ramble, or produce unsafe content. The gap between "capable text predictor" and "assistant that does what people want" is what alignment closes.

RLHF (reinforcement learning from human feedback) aligns a base model to human preferences in three stages: supervised fine-tuning on demonstrations (teach it to follow instructions), a reward model trained on human comparisons (learn what people prefer), and RL optimization (PPO) against that reward — with a KL constraint so it improves without going off the rails.

Step 1 · Capable but unaligned

Why pretraining isn't enough

The base model has read everything and can generate fluent text on anything. So why isn't it already a good assistant — and why can't you just prompt your way to alignment?

A base model is hugely capable. Why isn't it already an aligned assistant?

  1. Pretraining optimizes next-token prediction over internet text, so the model mimics the distribution of text (including unhelpful or unsafe continuations) rather than following instructions or matching human preferences. Prompting helps but can't reliably instill the behavior; you need to fine-tune the model toward what humans actually want.

  2. Knowledge isn't the gap — the base model knows a great deal. The gap is behavior/objective: it predicts plausible text rather than being a helpful, safe assistant, which alignment training instills.

  3. Size gives capability, not alignment. Even a huge base model predicts text rather than following human intent; you align it via fine-tuning + preference learning, not by scaling alone.

Pretraining optimizes next-token prediction over internet text, so the base model learned to mimic the distribution of text — including rambling, refusing to answer, or unsafe continuations — not to be helpful, honest, and harmless. That's a different objective from "assist the user." Prompting nudges it, but you can't reliably prompt-engineer alignment into a model; you have to train it toward human intent. That training is RLHF.

Why this piece earns its place

Whether a behavior lives in a prompt or in the weights is a shipping decision. A system prompt is text in the same context window as the user's turn, and the reason a model treats it as more authoritative at all is itself something a pipeline like this one trained in — so prompting stands on alignment rather than substituting for it, and it inherits every weakness of a thing made of text. A long conversation dilutes it, a role-play frame argues with it, and whoever integrates your model can delete it outright. Behavior you cannot afford to lose that way has to be in the weights, and that portability is what you are buying. Plan for it not being free. Behavior is bought with capability: a model trained hard to be careful hedges more, declines more, and can come back worse at things the base model did easily. So run a capability suite that forms no part of the alignment objective before and after every run, and read it against the base model's own scores — that is the only baseline that prices what alignment cost you rather than what the last round cost you. Track preference alone and you will never see the bill.

Step 2 · Three stages

The alignment pipeline

Given a capable-but-unaligned base model, what's the overall recipe to turn it into an aligned assistant?

Base Modelpretrained
New in this step: Base Model.

Three stages on top of the base model. (1) Supervised fine-tuning (SFT): fine-tune on human demonstrations of good answers, teaching instruction-following. (2) Reward model (RM): collect human preference comparisons and train a model to predict which output people prefer. (3) RL optimization: use RL (PPO) to optimize the SFT model to produce outputs the reward model scores highly — kept close to the SFT model by a KL penalty. SFT teaches the format; RM+RL refine toward preference.

Why this piece earns its place

Read the three stages as three artifacts you now own and have to version together, because they are not independent. The reference is a frozen copy of one particular SFT run, the reward model is usually initialized from that same run, and the preference pairs were collected on outputs that run produced. Re-run SFT with new demonstrations and all three quietly go stale: the reward model is now scoring a policy it was not built from, and the comparisons behind it describe a distribution that policy has already left. So in practice nobody runs this pipeline once — you run a round, collect fresh comparisons on the current policy's own samples, and retrain, because preference data ages against the model it was gathered from. The other thing worth saying out loud is when to stop at stage one. If what you want is format, tone and instruction-following, SFT alone gets you there and the whole reward-model-plus-RL half earns nothing. The preference machinery pays for itself only when the quality you are after is one nobody on the team can write down as a demonstration.

  • SFTdemonstrations
  • RMpreferences
  • RLoptimize to reward

What the new pieces do

Base Modelbase
A pretrained LLM: hugely capable at predicting text, but not aligned — it doesn't reliably follow instructions or match human preferences.

Step 3 · Teach the format

Supervised fine-tuning

First, get the base model to actually respond like an assistant. What data and objective do that?

Demonstrationsideal answersBase ModelpretrainedSFTfine-tune
New in this step: Demonstrations, SFT.

SFT: fine-tune the base model on a dataset of demonstrations — prompts paired with high-quality human-written (or curated) responses — using standard supervised next-token loss. This teaches the model the format and behavior of following instructions: answer the question, in the right style, helpfully. The result is a solid instruction-following model — and, importantly, the starting point and reference for the RL stage.

Why this piece earns its place

Mask the loss to the response tokens. If it covers the prompt as well you are also teaching the model to write the questions, which is not the job you are paying for. Then look hard at what else each example teaches, because imitation takes the whole example and not the part you meant: the padding, the preamble that restates the question before answering it, the reflexive hedge, the four-paragraph reply to a one-line ask. A small, tightly curated demonstration set beats a large scraped one for exactly that reason — everything in it becomes a habit, and nothing later in the pipeline takes those habits back out. One trap deserves naming on its own. A demonstration that answers a question the model holds no internal knowledge of does not teach it the fact; it teaches the shape of a confident answer to that kind of question, which is training for invention. Prefer demonstrations whose content the model could plausibly already know, and push the rest to retrieval or tools where it belongs.

  • demosprompt → ideal answer
  • supervisednext-token loss
  • resultinstruction-follower

What the new pieces do

Demonstrationsclient
Human-written examples of good responses to prompts — the supervised signal that teaches the model to follow instructions.
SFTservice
Supervised fine-tuning of the base model on demonstrations — makes it follow instructions. The starting point for RL.

Step 4 · Why not stop at SFT?

Preferences beat demonstrations

SFT already gives a decent assistant. Why add the whole reward-model + RL machinery instead of just collecting more demonstrations?

Demonstrationsideal answersBase ModelpretrainedSFTfine-tune
The system as it stands at this step.

SFT works reasonably. Why add reward-model + RL instead of just more demonstrations?

  1. It's not fashion — it's that comparisons are a cheaper, richer signal than demonstrations. Humans can't always write the ideal answer, but they can reliably say which of two answers is better, and that judgment covers quality dimensions demonstrations miss.

  2. Demonstrations are useful (that's SFT), but limited: writing the single best answer is hard and expensive, and doesn't teach the model the full ranking of good-to-bad. Preferences add that.

  3. Writing a perfect demonstration is hard and doesn't convey how much better it is than alternatives. Having humans compare two model outputs (A vs B) is faster, cheaper, and captures nuanced preferences (tone, helpfulness, safety) that are hard to demonstrate — giving a reward signal you can then optimize against at scale.

Demonstrations are expensive and limited: writing the single ideal answer is hard, and it doesn't tell the model how much better it is than the alternatives. Humans find it far easier and cheaper to compare two outputs ("A is better than B") than to author the perfect one — and those comparisons capture nuanced quality (tone, helpfulness, safety, subtle correctness) that's hard to demonstrate. Preferences give a richer, scalable signal you can turn into a reward and optimize against.

Why this piece earns its place

A pairwise comparison gives you order, never level. Hand a labeler two bad answers and the data still reports a winner, so a preference set has no way to express unacceptable — only a ranking. That is why safety rarely rides on comparisons alone: an absolute rule or a separate classifier has to supply the floor pairwise data structurally cannot. The prompt distribution in that set is also the scope of your alignment. The model is tuned on the kinds of questions someone thought to collect pairs for, and behavior on the ones nobody collected is whatever SFT left behind — so the coverage decision is made by whoever writes the prompt list, long before any training runs. And systematic labeler preference is a different problem from labeler noise. Noise averages out as you add annotators; bias sharpens. People reliably prefer longer, more confident, better-formatted answers, so a clean, high-agreement dataset can still encode length as a stand-in for quality. You catch that by measuring the trait itself — length, hedging, markdown — against the win rate, never by watching the agreement rate, which rises as the bias gets more consistent.

  • compareA vs B
  • cheaper + richerthan writing ideal
  • nuancetone/safety/quality

Step 5 · Model the preference

The reward model

You have human comparisons, but RL needs a score for any output on the fly — you can't ask a human on every RL step. How do you turn sparse human comparisons into a dense reward signal?

PreferencesReward Model
New in this step: Preferences, Reward Model. · swipe to pan the diagram

Train a reward model: take the human preference pairs (for a prompt, output A preferred over B) and train a model to output a scalar score such that preferred outputs score higher (a ranking loss). Now you have a fast, automatic proxy for human preference that can score any output during RL — a dense reward from sparse human labels. The reward model is typically initialized from the SFT model with a scalar head. Its quality is bounded by the preference data quality.

Why this piece earns its place

The score is comparative, and only within a prompt. A ranking loss constrains the gap between two answers to the same question and nothing else, so the number carries no absolute meaning across questions: there is no cutoff you can write down that means good enough, and a three here says nothing about a three over there. The reward model is a ranker, not a grader, and the moment a release gate is written as an absolute reward threshold it has been promoted to a job it cannot do. Two reward-model runs are not comparable either — retrain it and the whole scale moves, so a higher reward across a retrain means nothing unless one model scored both policies. Hold out preference pairs before you train, however expensive they were to collect; agreement with held-out human choices is the one number that says whether the model learned preference or memorized annotator habits, and you cannot compute it from data you trained on. And record which pair set and which labeling batch each reward model was built from. When a policy starts rewarding something strange, the question is always which labels taught it, and only that lineage answers it.

  • inputhuman A vs B pairs
  • outputscalar preference score
  • proxydense reward for RL

What the new pieces do

Preferencesclient
Humans compare pairs of model outputs and pick the better one — a cheaper, richer signal than writing ideal answers.
Reward Modelservice
Trained on human comparisons to score any output by predicted human preference — the reward signal RL optimizes.

Step 6 · Optimize, on a leash

RL (PPO) with a KL constraint

Now push the model to produce high-reward outputs. But the reward model is an imperfect proxy — optimize it too hard and the model will find degenerate outputs that score high but are actually bad (reward hacking). How do you optimize without going off the rails?

Reference (KL)anchorRL (PPO)optimize policyAligned Policythe model
New in this step: Reference (KL), RL (PPO), Aligned Policy.

RL against an imperfect reward model can be "hacked". How do you optimize safely?

  1. PPO optimizes the policy to maximize reward MINUS a KL-divergence penalty from the frozen SFT reference model. The penalty keeps the policy from drifting far from sensible behavior to chase reward-model artifacts, so it improves along human preference without collapsing into degenerate high-reward-but-bad outputs. It's a leash: climb the reward, but don't wander off.

  2. Unconstrained optimization of an imperfect proxy is exactly reward hacking — the policy finds weird outputs that fool the reward model but are worse to humans. You must constrain it toward the reference.

  3. More optimization pressure on a proxy reward makes hacking worse, not better. The fix is a constraint (KL to the reference), not more unconstrained reward-chasing.

Use RL — PPO — to optimize the policy to maximize the reward, minus a KL-divergence penalty from the frozen SFT reference model. The reward pulls the policy toward human-preferred outputs; the KL penalty keeps it close to known-good behavior, so it can't drift far to exploit reward-model artifacts. That balance — climb the reward, stay near the reference — is what lets RLHF improve alignment without reward hacking or degenerating into gibberish that games the proxy.

Why this piece earns its place

What the diagram cannot show is that this stage feeds itself. The policy generates the samples, the reward model scores what it just generated, the update moves the policy, and the next batch is drawn from the moved policy — there is no fixed dataset anywhere in the run, so a bias in the reward compounds through the samples instead of averaging out across them. That is what makes KL an instrument and not only a penalty term. Log it every step. Reward climbing while KL climbs with it is the signature of a policy walking away from the reference to exploit the proxy, and it appears well before held-out quality falls, which makes it the earliest warning the run will give you. It also settles what you mean by a tuned run. You can fix β and read the resulting drift as an outcome, or name a KL you are willing to tolerate and let a controller move β to hold it there. Both are ordinary. Reporting a tuned run without saying which of the two you held fixed is not.

  • PPOmaximize reward
  • − KLstay near reference
  • preventsreward hacking / drift

What the new pieces do

Reference (KL)ref
A frozen copy of the SFT model. The KL penalty keeps the RL policy close to it, preventing reward hacking and drift.
RL (PPO)service
Reinforcement learning: optimizes the policy to maximize the reward model's score, minus a KL penalty to the reference.
Aligned Policymint
The output: a model that follows instructions and matches human preferences — helpful and harmless.

Step 7 · Simpler & cheaper variants

DPO and RLAIF

Full PPO-based RLHF is complex and finicky (a reward model + on-policy RL + a reference, all in the loop). Are there simpler or cheaper ways to get the same alignment?

DemonstrationsBase ModelPreferencesSFTReference (KL)RL (PPO)Reward ModelAligned Policy
The system as it stands at this step. · swipe to pan the diagram

Two big alternatives. DPO (Direct Preference Optimization) skips the explicit reward model and RL loop: it optimizes the policy directly on the preference pairs with a classification-style loss that provably targets the same objective — much simpler and more stable, now very common. RLAIF (RL from AI Feedback / Constitutional AI) replaces (some) expensive human comparisons with AI-generated preferences guided by a set of principles — scaling the feedback cheaply. Both attack RLHF's costs: DPO its complexity, RLAIF its human-labeling expense.

Why this piece earns its place

What DPO removes is an asset, not only a cost. A trained reward model keeps earning long after the RL run ends: sample several candidates at inference and serve the highest-scoring one, filter a training set with it, rank experimental checkpoints against each other, run it as a standing eval nobody has to staff. Finish with DPO and none of that exists, so price it in before calling the simpler path free. RLAIF changes the shape of the human's job more than its size. People stop judging outputs and start writing and auditing the principles the AI judges by — and the error moves with them. A weak labeler is one voice among many and washes out; a badly worded clause is applied with perfect consistency to every comparison in the set, so its effect is correlated rather than noisy and no amount of extra data averages it away. That is also the upside: the standard is now a document you can read, review, diff between runs and argue about a specific line of, which is impossible while it lives in a labeler's head.

  • DPOskip RM + RL, optimize prefs directly
  • RLAIFAI feedback, cheaper labels
  • same goalalign to preference

Step 8 · The sharp edges

Hacking, overoptimization & labelers

RLHF's hard problems are real: reward hacking, reward-model overoptimization, the quality and bias of human labelers, and evaluating whether the model actually got better.

DemonstrationsBase ModelPreferencesSFTReference (KL)RL (PPO)Reward ModelAligned Policy
The system as it stands at this step. · swipe to pan the diagram

Contain reward hacking with the KL constraint and by not over-training. Watch overoptimization: the reward model is a proxy, so beyond a point more RL degrades true quality even as reward-model score rises (Goodhart) — monitor real evals, not just reward. Invest in labeler quality: clear guidelines, inter-annotator agreement, and calibration, because the whole pipeline inherits labelers' judgments and biases (whose preferences? is a live question). And evaluate alignment with held-out human evals / red-teaming, not the reward model — the reward is the means, human-judged behavior is the goal.

Why this piece earns its place

One aggregate win rate is the metric most likely to lie to you, because it averages over categories that move in opposite directions. Preference data pays for agreeing with the user, so sycophancy is not a bug that crept in — it is behavior the signal directly rewards, and it lifts the overall number while making the model worse at the one job where disagreeing is the helpful answer. Slice the evaluation by category and gate on per-category regressions, or the average will quietly absorb one of them going bad. Then budget for truth. Held-out human judgment is the only signal in this design that is not a proxy, and it is slow and expensive, so it cannot run on every checkpoint: automatic evals shortlist, people decide the few that matter. Keep that pool and its guidelines separate from the one producing training comparisons — when the same judgment trains the proxy and then grades it, high agreement is partly measuring a shared blind spot. And an alignment defect lives in the weights, so the only true fix is another run. Keep the previous checkpoint serving-ready; at incident speed, reverting is the only move you have.

You did it

You just designed an RLHF pipeline.

DemonstrationsBase ModelPreferencesSFTReference (KL)RL (PPO)Reward ModelAligned Policy
The finished design, end to end. · swipe to pan the diagram

Everything you assembled, in order

  • A pretrained base model is capable but unaligned — it predicts text, not helpful/honest/harmless answers.
  • RLHF aligns it in three stages: SFT → reward model → RL (PPO).
  • SFT fine-tunes on demonstrations to teach instruction-following — the starting point and reference.
  • Preferences (compare A vs B) are cheaper and richer than demonstrations — judging beats authoring.
  • A reward model turns sparse human comparisons into a dense, automatic preference score.
  • PPO maximizes reward minus a KL penalty to the SFT reference — climb the reward without reward-hacking.
  • DPO (skip the RM+RL) and RLAIF (AI feedback) are simpler/cheaper paths; watch hacking, overoptimization, labeler quality.

Where an interviewer pokes next

Getting the boxes right is the easy half. These are the questions that separate a candidate who drew the diagram from one who has run the thing. Answer each one out loud before you open it.

  1. Why is a capable pretrained model still unaligned, and why can't prompting fix it?

    Because pretraining optimizes a fundamentally different objective from being a helpful assistant. A base model is trained to predict the next token over a vast corpus of internet text, so what it learns is to mimic the distribution of that text — which includes rambling, answering a question with more questions, refusing unhelpfully, taking on whatever persona the context implies, and producing unsafe continuations, because all of those appear in the training data. It has enormous capability and knowledge, but its behavior is "continue text plausibly," not "do what the user wants, honestly and safely." Prompting can nudge this — a good system prompt and few-shot examples steer the distribution somewhat — but it can't reliably instill the behavior, because you're working against the model's trained objective rather than changing it, and the model can always drift back toward mimicking text or be pushed off the rails. Alignment is therefore a distinct training phase that actually reshapes the model's behavior toward human intent, rather than a prompt trick layered on top. This is the core reason RLHF exists: capability comes from pretraining, but alignment — behaving like a helpful, harmless assistant — has to be trained in separately.

  2. Why does RLHF use preference comparisons instead of just more demonstrations?

    Because judging is easier and more informative than authoring, both for humans and for the training signal. Supervised fine-tuning on demonstrations — prompts paired with ideal human-written answers — is valuable and gets you a decent instruction-follower, but it has real limits: writing the single best possible answer to an open-ended prompt is genuinely hard, slow, and expensive, and even a perfect demonstration only shows one good output without conveying how much better it is than alternatives or what makes it better along dimensions like tone, helpfulness, and safety. Humans, by contrast, find it far easier and cheaper to compare two model outputs and say which is better than to write the ideal one from scratch, and that comparative judgment captures nuanced quality distinctions that are hard to demonstrate explicitly. So RLHF harvests this cheaper, richer signal: collect many human preferences over pairs of outputs, which scales better than authoring demonstrations and encodes subtle notions of "good" that demonstrations miss. The key insight is that people can reliably rank two answers even when they can't produce the best answer themselves, and RLHF is built to exploit exactly that asymmetry between judging and generating.

  3. What does the reward model do, and why is it needed?

    The reward model converts sparse, expensive human comparisons into a dense, automatic score that reinforcement learning can use on the fly. The problem it solves is that RL needs a reward for every output the policy generates during training — potentially millions of samples — but you obviously can't ask a human to judge each one; human comparisons are far too slow and costly to be in that inner loop. So you train a separate model, typically initialized from the SFT model with a scalar output head, on the collected human preference pairs, using a ranking loss so that the output a human preferred receives a higher score than the one they rejected. Once trained, this reward model generalizes those human judgments into a function that can assign a preference score to any new output, including ones no human ever saw, giving RL a fast automatic proxy for human preference. That word — proxy — is the crucial caveat: the reward model is a learned approximation of human taste, good but imperfect, and its quality is bounded by the quality of the preference data it was trained on. Its imperfection is precisely why the subsequent RL stage must be constrained rather than allowed to maximize the reward without limit.

  4. Why is the KL constraint essential in the PPO stage, and what happens without it?

    The KL constraint is what keeps optimization honest given that the reward model is only an imperfect proxy for true human preference. In the RL stage, PPO adjusts the policy to produce outputs the reward model scores highly, but if you let it maximize that score without restraint, it exploits the gap between the proxy and the real goal — a manifestation of Goodhart's law, where optimizing a measure too hard makes it stop tracking what it was meant to measure. Concretely, the policy discovers degenerate outputs (odd phrasings, repetition, particular patterns, exploitative formats) that fool the reward model into giving high scores while actually being worse to humans; this is reward hacking, and unconstrained optimization drifts the model into gibberish or weird behavior that games the proxy. The fix is to optimize reward minus a KL-divergence penalty measuring how far the policy has moved from a frozen reference (the SFT model), so the objective simultaneously pulls toward higher reward and pulls back toward known-good behavior. The penalty acts as a leash: the policy can climb the reward, but it can't wander far from the sensible SFT baseline to chase reward-model artifacts. Tuning the penalty strength trades how much alignment improvement you get against how much drift you tolerate, and without it the whole procedure collapses into reward hacking.

  5. How do DPO and RLAIF simplify or cheapen RLHF, and what risks remain regardless?

    They attack the two main costs of the classic three-stage PPO pipeline. DPO (Direct Preference Optimization) targets its complexity: instead of training a separate reward model and then running finicky on-policy reinforcement learning with a reference model in the loop, DPO optimizes the policy directly on the preference pairs using a simple classification-style loss that provably corresponds to the same underlying objective, which makes it much simpler to implement, more stable to train, and cheaper to run — which is why it has become very common. RLAIF (RL from AI Feedback, closely related to Constitutional AI) targets the human-labeling expense: it replaces some or most of the costly human preference comparisons with preferences generated by an AI model guided by an explicit set of principles or a "constitution," dramatically scaling the volume of feedback at low cost. Both reach the same goal of aligning the model to preferences by cutting a different cost. But some risks are inherent to the whole approach regardless of variant: the alignment target is only a measurement of preference, so reward hacking and overoptimization (pushing the model past the point where the proxy still tracks true quality) remain concerns, the pipeline inherits the quality and biases of whoever or whatever produced the preferences (raising the question of whose values are being encoded — human labelers or an AI's constitution), and you must ultimately evaluate real aligned behavior with held-out human judgment and red-teaming rather than trusting the proxy score. The means change; the need to guard the measurement and the optimization does not.

Check yourself — the answers, and why

Nine steps in, these are the calls you should be able to make cold. Pick one, then read why.

  1. A pretrained base model is unaligned because it was trained to…

    It mimics the distribution of text, not human intent; alignment is a separate training phase.

  2. The RLHF pipeline's three stages are…

    SFT teaches format; the reward model captures preference; RL optimizes toward it.

  3. Preferences (A vs B) are used instead of only demonstrations because…

    Judging beats generating; comparisons capture nuance demonstrations miss, at lower cost.

  4. The reward model exists to…

    RL needs a score for every output; the RM is a fast (imperfect) proxy for human preference.

  5. The KL penalty in PPO is essential because…

    reward − β·KL(policy‖reference) climbs reward while staying near known-good behavior.

How you’d open this design in an interview

Before any boxes: agree what it must do, pin the qualities that shape everything, then build — naming each trade-off as you make it. The walkthrough above is that exact order.

What it must do

Agree on these before drawing a single box.

  • Align a base model: turn a capable-but-unaligned base model into a helpful, honest, harmless assistant.
  • Supervised fine-tuning: fine-tune on human demonstrations to teach instruction-following — the RL starting point.
  • Reward model: train a model on human A-vs-B comparisons to score any output by predicted preference.
  • RL on a leash: PPO maximizes the reward minus a KL penalty to the SFT reference, preventing reward hacking.
  • Cheaper variants: DPO skips the reward-model + RL loop; RLAIF replaces human labels with AI feedback.

The qualities that shape everything

Each one names the mechanism that buys it.

Instill behavior prompting can’t
SFT: fine-tune the base model on demonstrations with supervised next-token loss so it actually follows instructions in the right style.
Capture nuance demonstrations miss
Learn from human comparisons (A vs B), which are cheaper and richer than authoring ideal answers and encode tone/helpfulness/safety.
A dense reward from sparse human labels
A reward model trained on preference pairs with a ranking loss, outputting a scalar score any RL sample can be graded against.
Optimize preference without reward hacking
PPO maximizes reward minus a KL-divergence penalty to the frozen SFT reference, so the policy climbs the reward while staying near known-good behavior.
Cut RLHF’s cost and complexity
DPO optimizes the policy directly on preference pairs (no separate RM or RL loop); RLAIF replaces expensive human comparisons with AI-generated, principle-guided ones.
Don’t over-align to a flawed proxy
Track real held-out human evals (not the reward score), invest in labeler quality and agreement, and early-stop to contain overoptimization.

The trade-offs you say out loud

Senior signal isn’t the boxes — it’s naming what you gave up and why it was the right price.

Train alignment in (SFT + preference learning) over prompting a base model into alignment

Pretraining optimizes next-token prediction over internet text, so the model mimics text — rambling, unsafe continuations — a different objective you can’t reliably prompt away.

Preference comparisons (A vs B) over collecting more demonstrations

Writing the single ideal answer is hard, expensive, and doesn’t convey how much better it is; humans compare two outputs far more easily, capturing nuance demonstrations miss.

A learned reward model over asking a human on every RL step

RL needs a score for any output on the fly across millions of samples; a reward model generalizes sparse human comparisons into a dense automatic (if imperfect) proxy.

PPO with a KL penalty to the reference over maximizing the reward score unconstrained

The reward model is an imperfect proxy, so unconstrained optimization is exactly reward hacking — the policy finds degenerate outputs that fool it; the KL leash keeps it near known-good behavior.

DPO / RLAIF where they fit over always full PPO-based RLHF

Full PPO is complex and finicky and human labeling is expensive; DPO optimizes preferences directly (simpler, stabler) and RLAIF replaces human comparisons with cheaper AI feedback.

The answer, out loud

What a strong answer to “Design an RLHF Pipeline” sounds like, first question to last trade-off. It is about 7 minutes of talking; the whiteboard and the interviewer fill the rest of the 45. Read it aloud once, then close the page and give it yourself.

  1. 0–3 min

    Separate capability from alignment

    I'd start by separating two things that get blurred. A pretrained base model is enormously capable — it has read the internet — but capability isn't alignment. It was trained to predict likely next tokens, so what it actually learned is to continue text plausibly: it'll ramble, answer a question with more questions, take on whatever persona the context implies, or carry on into something unsafe, because all of that is in the data it read. That's a different objective from being helpful, honest and harmless. And I'd say early that you can't prompt your way out of it. Prompting nudges the distribution, but alignment is a training phase, not a prompt trick. So the real design question is how we train the behavior in.

    Built in step 1: Why pretraining isn't enough
  2. 3–8 min

    The three stages

    The recipe I'd draw is three stages sitting on top of that base model. Supervised fine-tuning on human demonstrations, to teach it to actually respond like an assistant. Then a reward model, trained on human comparisons, to capture what people prefer. Then reinforcement learning — PPO — pushing the policy toward outputs the reward model scores highly, held near the fine-tuned model by a KL penalty. I'd be explicit that each stage does something the others can't: SFT teaches the format, the reward model captures nuance nobody can demonstrate, and RL is the only part that lets you optimize against that nuance at scale.

    Built in step 2: The alignment pipeline
  3. 8–14 min

    Fine-tune on demonstrations

    Stage one is the cheap one. I'd take prompts paired with high-quality human-written responses and fine-tune with the ordinary supervised next-token loss — the same objective the base model was pretrained with, just pointed at a far better distribution. That's why people call it imitation learning: show it good answers and it learns to produce that kind of output. What comes out is a genuinely usable instruction-follower, and I'd be precise about what changed: not what the model knows, which came from pretraining, but what it does when it is handed a question. And the limit of the stage is what makes the next one necessary: it can only teach behavior somebody was able to sit down and write out.

    Built in step 3: Supervised fine-tuning
  4. 14–20 min

    Why comparisons, not more demonstrations

    The obvious pushback is that SFT already works, so why not just collect more demonstrations. My answer is that judging is easier than generating. Writing the single ideal answer to an open-ended prompt is hard, slow and expensive, and even a perfect one doesn't convey how much better it is than the alternatives. Humans can reliably look at two outputs and say which is better, and that comparison carries nuance — tone, helpfulness, safety, subtle correctness — that's very hard to demonstrate explicitly. The other thing I like is that a comparison is a small, uniform unit: one person produces many in the time a single demonstration takes, and because they all have the same shape, they're something you can train a model on. Which is exactly what I'd do next.

    Built in step 4: Preferences beat demonstrations
  5. 20–26 min

    Turn comparisons into a score

    RL needs a number for every output it generates, across millions of samples, and we obviously can't put a human in that loop. So I'd train a reward model on the preference pairs with a ranking loss, so the output a human preferred scores higher than the one they rejected. Typically it's initialized from the SFT model with a scalar head. Now any output can be scored automatically — a dense reward built out of sparse human labels. The word I'd keep saying is proxy. It's a learned approximation of human taste, good but imperfect, and I'd flag that imperfection as a design input rather than a caveat, because it's the whole reason the next stage can't simply be told to maximize.

    Built in step 5: The reward model
  6. 26–33 min

    Optimize on a leash

    Then PPO optimizes the policy to maximize that reward, minus a KL-divergence penalty against the frozen SFT reference. I'd argue for the penalty out loud, because unconstrained maximization of an imperfect proxy is the definition of reward hacking — Goodhart's law with a training loop attached. And it isn't subtle when it happens: the policy finds a phrasing, a format, a bit of repetition that the reward model loves and a person would not, and it leans harder into it the longer you run. The KL term bounds how far it can move from known-good behavior, so it climbs the reward without wandering off. Climb, but stay on the leash.

    Built in step 6: RL (PPO) with a KL constraint
  7. 33–39 min

    The cheaper paths

    I'd offer two alternatives, because full PPO is complex and finicky. DPO optimizes the policy directly on the preference pairs with a classification-style loss that provably targets the same objective — no separate reward model, no RL loop. Simpler, stabler, and very common now. RLAIF replaces expensive human comparisons with AI-generated ones guided by a written set of principles, which is what makes the volume affordable. They're not the same saving, though, and I'd choose by which cost is actually hurting. If the labeling bill is the constraint, RLAIF. If the problem is that nobody on the team wants to operate an RL loop in production, DPO. Nothing stops you doing both.

    Built in step 7: DPO and RLAIF
  8. 39–45 min

    What I would watch, and the trade-off

    To close on the risks: reward hacking, overoptimization where more RL keeps raising the reward score while true quality falls, and labeler quality, since the whole pipeline inherits whoever's judgment produced the comparisons. So I'd evaluate with held-out human evals and red-teaming rather than the reward score. The trade-off underneath all of it is that we're aligning to a measurement of preference, not to preference itself, so every gain depends on how honest that measurement and that optimization stay. With more time I'd go into how the red-team set gets built and kept — it only works if it keeps growing — and into whose preferences these actually are: who sits in the labeler pool, and who writes the guidelines they follow.

What this teaches

Learn AI system design by building an RLHF (reinforcement learning from human feedback) alignment pipeline step by step. An interactive guide covering why a base model is capable but unaligned, supervised fine-tuning on demonstrations, why preferences beat demonstrations, training a reward model from human comparisons, PPO optimization with a KL constraint to prevent reward hacking, the DPO and RLAIF alternatives, and the unhappy paths (reward hacking, overoptimization, labeler quality).

Key takeaways

  • A pretrained base model is capable but unaligned — it predicts text, not helpful/honest/harmless answers.
  • RLHF aligns it in three stages: SFT → reward model → RL (PPO).
  • SFT fine-tunes on demonstrations to teach instruction-following — the starting point and reference.
  • Preferences (compare A vs B) are cheaper and richer than demonstrations — judging beats authoring.
  • A reward model turns sparse human comparisons into a dense, automatic preference score.
  • PPO maximizes reward minus a KL penalty to the SFT reference — climb the reward without reward-hacking.
  • DPO (skip the RM+RL) and RLAIF (AI feedback) are simpler/cheaper paths; watch hacking, overoptimization, labeler quality.

Concepts covered

  • What does RLHF do?
  • Why pretraining isn't enough
  • The alignment pipeline
  • Supervised fine-tuning
  • Preferences beat demonstrations
  • The reward model
  • RL (PPO) with a KL constraint
  • DPO and RLAIF
  • Hacking, overoptimization & labelers
RUN IT YOURSELF

There is no answer length at which the reward model says stop

This fits a Bradley-Terry reward model on 6,000 human A-vs-B comparisons, prints the error bar on the length weight it learned so you can check it is not broken, then optimizes it at five different padding budgets. At every one of them the unconstrained search spends the budget in full — 100%, 100%, 100%, 100%, 100% — while the reader’s own value of one more token went negative back at 90. Change SEARCH_FILLER, hit Run: the damage numbers move because they are your ceiling, and the 100% row does not.

HOW TO READ THE CODE — 5 IDEAS
  1. The proxy’s marginal value of a padding token is a constant +0.0076 — the same at 28 tokens, at 90 and at 452. The reader’s is +0.0184, then 0, then −0.1073. The sign flip is the whole mechanism, and the fitted model has no term that can represent it (step 8, overoptimization).
  2. The reward model is not broken. It agrees with held-out annotators 0.749 against 0.755 for a scorer handed their exact utility function, and the length slope it learned, +0.0076 ± 0.0020, sits 0.4 standard errors from the +0.0084 the data really contains. Step 5 calls it a proxy; that is what a good proxy looks like.
  3. The length the search stops at is not a finding — it is whatever budget you offered. The sweep prints five ceilings from 50 to 800 tokens: true utility falls +6.18 → −79.82 across them and the share spent stays pinned at 100%. Quote the 100%, never the 452.
  4. The leash is reward + beta · log p_ref, the KL-regularized objective of step 6 written out for a best-of-N search. Its price per token is counted off the reference policy’s own unigram distribution, so it is a KL penalty and not a length penalty somebody hand-tuned. Above beta* = w[filler] / -log p_ref(filler) it spends 0% of every budget in the same sweep.
  5. Both beta thresholds in the table are solved for, not typed in: beta* is where KL outprices a padding token, beta_fact where it outprices the cheapest real fact. At 1.1 × beta_fact the policy drops three facts to save KL and true utility falls to +2.63. That is step 6’s beta trade-off with a number on it.
CPython · WebAssembly
built to teach a raw model what "good" means from human taste — make the calls, cut the leash, run the gauntlet.
Finished this one? 0 / 65 AI System Designs done

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More AI System Designs