Fine-Tuning, RLHF and Safety: How a Model Becomes an Assistant

How AI Models Are Built Beginner 5 min read Published
In this lesson

After pretraining, a model is like a student who has read the whole library but never had a conversation. Ask it “What’s a good name for a cat?” and it might reply “What’s a good name for a dog? What’s a good name for a fish?”, because in its training data lists of questions are common. Post-training fixes this. It is a much smaller amount of data and compute than pretraining, but it decides how the model *behaves*.

🎬 From autocomplete to assistant

  1. Asked “How do I make chai?”, the raw model continues with more recipe titles. It completes text; it doesn’t help.
  2. People write thousands of example conversations: a request, then an ideal helpful answer.
  3. The model writes two answers to the same request. A reviewer picks the better one.
  4. A reward model learns to predict which answers people prefer.
  5. The assistant writes answers, gets scored, and shifts towards higher scores.
  6. Testers try to trick it into harmful answers, and those cases go back into training.
  7. The same question now gets a clear, friendly, step-by-step recipe.

Step 1: Supervised fine-tuning (SFT)#

The model is trained on examples of prompt → ideal response, using the same next-token learning as pretraining, just on far fewer, far better examples (thousands to millions instead of trillions of tokens).

sft_examples = [
    {"prompt": "Explain recursion to a 10-year-old.",
     "response": "Recursion is when something is defined using a smaller copy of itself..."},
    {"prompt": "Write a polite leave request to my manager.",
     "response": "Dear Ms. Rao, I would like to request leave on..."},
]
for ex in sft_examples:
    print(len(ex["prompt"].split()), "->", len(ex["response"].split()), "words")

Output:

5 -> 12 words
8 -> 10 words

After SFT, the model answers instead of continuing. But good answers can differ in many subtle ways (tone, accuracy, safety), and those are hard to capture with examples alone.

Step 2–4: Learning from preferences (RLHF)#

It’s easier for a person to say “A is better than B” than to write the perfect answer. RLHF (Reinforcement Learning from Human Feedback) uses exactly that:

  1. Collect pairs of answers to the same prompt, with a human choice of which is better.
  2. Train a reward model that gives any answer a score predicting human preference.
  3. Use reinforcement learning to update the assistant so its answers get higher reward, while staying close to its SFT version (so it doesn’t learn weird tricks to game the score).

Here is a toy reward model: a scoring function built from what reviewers liked.

def reward(answer):
    score = 0
    if "step" in answer.lower():
        score += 2          # reviewers liked step-by-step answers
    if "i'm not sure" in answer.lower():
        score += 1          # and honesty when unsure
    if "guaranteed" in answer.lower():
        score -= 3          # and disliked overconfident promises
    score -= max(0, len(answer.split()) - 40) * 0.1   # and rambling
    return round(score, 1)

a = "Step 1: boil water. Step 2: add tea leaves and spices. Step 3: add milk and sugar."
b = "This guaranteed perfect chai recipe will change your life forever!"
print("A:", reward(a), "| B:", reward(b))

Output:

A: 2.0 | B: -3.0

A real reward model is itself a neural network trained on hundreds of thousands of comparisons, not hand-written rules, but it plays the same role: turning “what people prefer” into a number the training can push towards.

Watch a preference pair become a training signal#

import math
score_chosen = 2.0
score_rejected = -3.0
gap = score_chosen - score_rejected
p_correct = 1 / (1 + math.exp(-gap))
loss = -math.log(p_correct)
print(round(p_correct, 3), round(loss, 3))
  1. Line 1: math gives us exp and log.
  2. Line 2: The reward model’s score for the answer the human chose.
  3. Line 3: Its score for the answer the human rejected.
  4. Line 4: The gap: how strongly the reward model agrees with the human. Bigger is better.
  5. Line 5: A sigmoid turns the gap into a probability: “how likely the reward model is to pick the human’s choice”.
  6. Line 6: The training loss is low when that probability is high. Small loss = the reward model already agrees.
  7. Line 7: Probability 0.993, loss 0.007: this pair is already learned.

Other alignment methods you’ll hear about#

MethodIdea in one lineWho talks about it
RLHFHumans compare answers → reward model → reinforcement learningWidely used across labs, popularised by OpenAI’s InstructGPT work
Constitutional AI / RLAIFAn AI model compares answers using a written list of principles (a “constitution”), reducing the human labelling neededIntroduced by Anthropic for Claude
DPO (Direct Preference Optimization)Learn from preference pairs directly, with no separate reward model or RL stepA simpler, popular method from academic research, common in open models
Red-teamingExperts try to break the model on purpose; failures become new training dataDone by every major lab before release

This is why the same question gets different “personalities” from ChatGPT, Claude, Gemini and Grok. Their pretraining data overlaps a lot; their post-training choices (examples, reviewer guidelines, principles) differ.

Safety is a balance#

Too little alignment and a model may help with harmful requests or invent facts confidently. Too much and it refuses harmless questions (“over-refusal”). Labs measure both and tune between them, which is why model updates sometimes say “fewer unnecessary refusals” or “more careful with medical advice”.

Summary#

  • SFT teaches the assistant format from good examples.
  • Reward models turn human preferences into scores; RLHF pushes the model towards higher scores.
  • Constitutional AI uses written principles and AI feedback; DPO learns from preference pairs directly.
  • Post-training is small compared with pretraining but decides behaviour, tone and safety.

Next: how a finished model is served to millions of people, and why output tokens cost more than input tokens.

Quick quiz

3 questions. Check what stuck and earn 2 XP for each right answer.

1What does a reward model do in RLHF?
2Constitutional AI, introduced by Anthropic, mainly uses…
3Why might two chatbots trained on similar data behave very differently?

Progress is saved in this browser. Create a free account to keep it on every device.