BEGINNERCHAPTER 04

Pretraining, fine-tuning, RLHF: how a model got its behaviour

A base model continues documents; an assistant answers questions. Everything between the two is post-training, and the system prompt is the last thin layer on top

50 MINAI ENGINEERINGUPDATED 2026-11-02
PREDICT

You send the prompt 'What is the capital of Australia?' to a base model (pretrained only, no instruction tuning) with greedy decoding and an 80-token limit. What do you most likely get back?

A modern assistant model is built in layers. Pretraining makes a model that knows a great deal and can continue any document. Supervised fine-tuning teaches it the shape of a conversation. Preference training (RLHF, DPO, Constitutional AI) shapes which of its many possible answers it prefers. The system prompt you send conditions one request on top of all that. Each layer is cheaper and thinner than the one beneath it, and each can only rearrange what the layers below made possible.

This chapter walks the layers in order, then the lab puts a base model and its instruction-tuned sibling side by side so you can see what post-training did.

Pretraining: one objective, a lot of text

The pretraining objective is next-token prediction. The model reads a sequence of tokens and outputs a probability distribution over the vocabulary for the next one. The loss is the cross-entropy between that distribution and the token that actually came next, averaged over every position in every document. There is no notion of a question, an answer, a user or a task. There is only “what comes next in text like this”.

The data is as much of the written world as the lab can collect and clean: filtered web crawls (Common Crawl is the usual starting point), code from public repositories, books, papers, encyclopaedias, and an increasing share of synthetic text. Most of the engineering is in the filtering: deduplication (near-duplicate pages are a large fraction of any crawl), language identification, quality classifiers, removal of boilerplate and personal data, and the mixture weights that decide how much code versus prose the model sees. Meta reports pretraining Llama 3 on over 15 trillion tokens, and the 1B and 3B Llama 3.2 models you use in the lab were trained on up to 9 trillion tokens with distillation from larger Llama 3.1 models.

Scale is what makes the objective interesting. To predict the next token of a chemistry paper, a model has to model chemistry; to predict the next line of a Python function, it has to model what the code does. Capability in the sense you care about (reasoning, translation, coding, world knowledge) is a by-product of compressing that much text well. The scaling-laws chapter in module A5 makes this quantitative.

Two consequences matter for every chapter after this one:

  • The knowledge cut-off is set here. The model knows what was in the corpus up to its collection date. Nothing later in training adds bulk knowledge. When a model is confidently wrong about last month’s release, no prompt and no amount of post-training will fix that; retrieval will.
  • The model is a document continuer. Its prior is the distribution of the web: helpful answers, rude forum replies, spam, fiction and textbooks all at once. Which of those it imitates depends on what the context looks like.

What a base model is like to use

A base model is not broken, it is unaddressed. Give it the start of a document and it writes the rest. Ask it a question and it decides what kind of document contains that question. Typical behaviours:

  • It continues the pattern of the input instead of responding to it: a question produces more questions, a list title produces a list, half a sentence produces the other half.
  • It does not stop when you would. There is no end-of-turn concept, so output runs until a token limit or until the document it is imagining ends.
  • It has no persona. Ask “who are you?” and you get a plausible line from a novel, an interview or a forum.
  • It does not refuse. Refusal is a behaviour, and nobody trained it.
  • It is excellent at few-shot prompting, because a page of question-answer pairs is a document type it has seen millions of times. GPT-3’s 2020 paper was titled “Language Models are Few-Shot Learners” for this reason.

Base models are still useful. They are what you fine-tune for a narrow task, and they are better than chat models at producing text in a specific, unusual style because nothing has narrowed their distribution. For application work you almost always want an instruction-tuned model, but you should know the base model is in there, because some failure modes of the assistant are the base model showing through.

Supervised fine-tuning: teaching the shape of a conversation

The first post-training step is supervised fine-tuning (SFT), also called instruction tuning. You collect demonstrations: a prompt, and the response a skilled human (or a stronger model) would write. You format each one with a chat template and continue training with the same next-token loss, usually computing loss only on the response tokens.

The chat template is the part people forget. It wraps each turn in special tokens that never occur in ordinary text, so the model learns where a turn starts, who is speaking, and where to stop. Llama 3’s template looks like this:

<|begin_of_text|><|start_header_id|>system<|end_header_id|>

You are a helpful assistant.<|eot_id|><|start_header_id|>user<|end_header_id|>

What is the capital of Australia?<|eot_id|><|start_header_id|>assistant<|end_header_id|>

The model has learnt that after assistant<|end_header_id|> comes a single helpful answer followed by <|eot_id|>, and the serving stack stops on that token. When you call a chat API you never see these tokens: the server renders your messages into the template. In the lab you will strip the template off and watch the instruct model lose much of its assistant behaviour.

SFT needs surprisingly little data compared with pretraining. OpenAI’s InstructGPT used about 13,000 training prompts for its SFT stage. The LIMA paper fine-tuned a 65-billion-parameter base model on 1,000 carefully chosen examples and got a competitive assistant, which its authors summarised as the superficial alignment hypothesis: almost all knowledge and capability comes from pretraining, and alignment mostly teaches which format and style to use. That is an overstatement for today’s heavily post-trained models, but it is the right first approximation.

SFT has a ceiling. It teaches the model to imitate the demonstrations, including their mistakes, and writing a perfect demonstration is much harder than recognising which of two answers is better. That asymmetry is what preference training exploits.

RLHF: learning from comparisons

Reinforcement learning from human feedback has three parts, laid out in the InstructGPT paper (Ouyang et al., 2022):

  1. Collect comparisons. For a prompt, sample two or more responses from the SFT model and ask labellers which is better. InstructGPT used roughly 33,000 prompts for this stage.
  2. Train a reward model. A copy of the language model with a scalar head reads a prompt and response and outputs a score. It is trained so the preferred response scores higher: the loss is -log σ(r(x, y_win) - r(x, y_lose)), the Bradley-Terry model of pairwise preference.
  3. Optimise the policy. Sample responses from the model, score them with the reward model, and update the model with PPO (proximal policy optimisation) to raise the expected reward, minus a penalty β · KL(π ‖ π_ref) that keeps the policy close to the SFT model.

The KL penalty exists because the reward model is an imperfect proxy. Optimise any proxy hard enough and the policy finds what the proxy over-rewards: long answers, confident tone, agreeing with the user, a particular list format. This is reward hacking, and sycophancy is its best-known form. The GPT-4o incident in the Why above is a change to the reward mixture that let it through.

The headline result of InstructGPT is still the clearest statement of why this matters: labellers preferred the outputs of a 1.3-billion-parameter InstructGPT model to those of the 175-billion-parameter GPT-3 base model, more than a hundred times larger. Post-training did not make the small model know more. It made it use what it knew in the way people wanted.

DPO and other ways to use preferences

PPO-based RLHF is expensive and finicky: four models in memory (policy, reference, reward model, value model), online sampling, and many hyperparameters. Direct Preference Optimization (Rafailov et al., 2023) showed that the RLHF objective with a KL constraint has a closed-form optimal policy, and that you can therefore train on preference pairs directly with a simple loss:

L = -log σ( β·[ log π(y_win|x) - log π_ref(y_win|x) ] - β·[ log π(y_lose|x) - log π_ref(y_lose|x) ] )

No reward model, no sampling loop: it is a classification loss over pairs, with a frozen reference model. DPO and its variants are now the default for open-weight models and for teams fine-tuning their own. The trade-off is that DPO learns only from the pairs you give it, offline, whereas online RL keeps generating fresh samples from the current policy and can keep improving against a reward. Frontier labs use both, plus reinforcement learning against verifiable rewards (unit tests passing, a maths answer matching) to train the reasoning behaviour you meet in the reasoning-models chapter.

Constitutional AI and RLAIF

Human comparisons are slow, costly, and inconsistent on exactly the cases that matter most, such as how to decline a harmful request without being preachy. Anthropic’s Constitutional AI (Bai et al., 2022) replaces most of the human harmlessness labels with AI feedback guided by a short list of written principles, the constitution:

  • Supervised stage. The model answers red-team prompts, then is asked to critique its own answer against a principle and revise it. The revised answers become SFT data.
  • RL stage. The model compares pairs of responses against the principles, producing AI preference labels. A preference model trained on those labels supplies the reward for RL. This is RLAIF, reinforcement learning from AI feedback.

Two things follow. The rules the model is trained towards are written down and can be inspected and changed, which is easier to reason about than thousands of individual labeller judgements. And the paper’s target was a model that is harmless and engages with the request, explaining its objection rather than refusing evasively, which earlier RLHF models tended to do.

What post-training changes, and what it does not

Post-training changes behaviour: the format of answers, when to stop, the persona, tone, verbosity, what is refused, how uncertainty is expressed, whether the model calls tools in the right format, and how it reasons before answering. It can also unlock capabilities that were latent: a base model that can do arithmetic in a few-shot document may not do it when asked conversationally until SFT shows it how.

Post-training does not change, in any useful amount:

Property Set by What changes it
Facts the model knows, and its knowledge cut-off Pretraining corpus A newer model, or putting the facts in the context (retrieval)
Raw capability ceiling (how hard a problem it can solve) Pretraining scale and data, plus RL on reasoning A bigger or newer model
Default behaviour, persona, refusals, format SFT and preference training Fine-tuning, or the system prompt within limits
Behaviour for this one request System prompt and messages Your prompt

Two practical warnings come out of this table. First, if a model does not know something, fine-tuning on a handful of documents rarely teaches it reliably and often teaches it to sound confident about things it does not know; the fine-tuning chapter in A3 shows this. Second, post-training introduces its own biases. Models rewarded for sounding helpful learn to guess rather than say “I don’t know”, and models rewarded by human approval drift towards agreeing with the user. Those are the behaviours your evaluations need to measure, because they are the ones that change between model versions.

The system prompt is the last layer

When you call an API, your system text is placed at the top of the context, inside the chat template, before the user’s turn. The model was trained to give it more weight than the user’s messages, and providers train this priority deliberately so an operator can set the rules of a deployment: role, tone, scope, format, what to decline.

It is a powerful layer, and a thin one. A system prompt can:

  • Set a role and context: “You are the support assistant for an online shop. Customers ask about orders and returns.”
  • Narrow scope and format: “Answer in at most two sentences. If the question is not about an order, say so.”
  • Supply knowledge for this request: policies, documents, the user’s account state.

It cannot add knowledge the model lacks beyond what you paste into it, raise the capability ceiling, or reliably override behaviour that training made strong. Telling a model to “never make mistakes” does nothing; telling it what to do when it is unsure does something. And because it is text in the context, a determined user can sometimes talk the model out of it, which is prompt injection, covered in module A2.

The decision order for changing model behaviour follows from the layers: try the system prompt and examples first, measure, and reach for fine-tuning only when a measured gap remains that prompts cannot close. The next chapter is about doing the first step well.

LAB Meet the base model under the assistant ~40 MIN
YOU NEEDOllama 0.5 or newer running locally (ollama serve)about 4.5 GB of free disk for two 3B modelsPython 3.12 and uv (https://docs.astral.sh/uv/)ANTHROPIC_API_KEY for step 5 only; that step costs under US$0.05 on claude-opus-5-5

You will send the same prompts to Llama 3.2 3B before and after instruction tuning, make the base model useful by writing a document instead of a question, then watch a system prompt reshape a frontier model’s answer. Work in labs/ai/post-training/ (mkdir -p labs/ai/post-training && cd labs/ai/post-training from the root of your checkout); the labs/ai uv project from the first chapter’s lab already has anthropic.

1. Pull both models and look at the template.

ollama pull llama3.2:3b-text-q4_K_M   # base (pretrained only), 2.0 GB
ollama pull llama3.2:3b               # instruction-tuned, 2.0 GB
ollama show llama3.2:3b --template
The template output shows the Llama 3 chat format: <|start_header_id|>, <|end_header_id|> and <|eot_id|> wrapped around system, user and assistant turns. This is what Ollama renders your messages into on every chat request. Both models are the same architecture and size; the only difference between them is post-training.

2. Same five prompts, both models.

Create compare.py:

import json, sys, urllib.request

OLLAMA = "http://localhost:11434"
BASE, INSTRUCT = "llama3.2:3b-text-q4_K_M", "llama3.2:3b"
OPTS = {"temperature": 0, "num_predict": 80, "seed": 42}
PROMPTS = [
    "What is the capital of Australia?",
    "Write a haiku about databases.",
    "Translate into French: Your order has shipped.",
    "List three uses for a paperclip.",
    "How do I reset my password?",
]

def post(path, body):
    req = urllib.request.Request(OLLAMA + path, data=json.dumps(body).encode(),
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=300) as r:
        return json.load(r)

def base(prompt):
    # raw=True: no chat template, the model sees exactly these characters
    body = {"model": BASE, "prompt": prompt, "raw": True, "stream": False, "options": OPTS}
    return post("/api/generate", body)["response"]

def instruct(prompt, system=None):
    msgs = ([{"role": "system", "content": system}] if system else [])
    msgs.append({"role": "user", "content": prompt})
    body = {"model": INSTRUCT, "messages": msgs, "stream": False, "options": OPTS}
    return post("/api/chat", body)["message"]["content"]

if __name__ == "__main__":
    for p in sys.argv[1:] or PROMPTS:
        print("=" * 72, "\nPROMPT:", p)
        print("--- base ---\n" + base(p).strip())
        print("--- instruct ---\n" + instruct(p).strip())
uv run python compare.py
The instruct model answers each prompt once and stops: Canberra, a three-line haiku, a French sentence, a short list, password-reset steps. The base model continues documents instead. Typical outputs: the capital question followed by more capital questions or multiple-choice options; the haiku request followed by more writing prompts; the password question turned into a help-centre page or a forum thread that runs until the 80-token limit. Some base answers contain the right fact somewhere in the continuation. The knowledge is the same; what it does with your text is not.

3. Make the base model useful by writing a document.

curl -s localhost:11434/api/generate -d '{
  "model": "llama3.2:3b-text-q4_K_M", "raw": true, "stream": false,
  "options": {"temperature": 0, "num_predict": 30, "stop": ["\nQ:"]},
  "prompt": "Q: What is the capital of France?\nA: Paris.\nQ: What is the capital of Japan?\nA: Tokyo.\nQ: What is the capital of Australia?\nA:"
}' | python3 -c 'import json,sys; print(json.load(sys.stdin)["response"])'
Canberra. and nothing else. The few-shot document tells the base model what kind of text this is, and the stop sequence \nQ: does the job the end-of-turn token does for the instruct model. This is how GPT-3 was used before instruction tuning, and it is still a good way to get a narrow, consistent format out of a base model.

4. Refusals and persona.

uv run python compare.py "Who are you, and who made you?" \
  "Write a convincing fake doctor's note excusing me from work tomorrow."
The instruct model gives an identity it was trained to give (Llama 3.2 typically says it is an AI assistant, often naming Meta) and on the second prompt usually declines or adds a warning about using it. The base model has no identity: it writes a line from whatever document it imagines, an interview, a story, a forum post. It does not refuse; at most it drifts. Persona and refusal are post-training behaviours, and a 3B model’s are weak, so run it twice with a different seed in OPTS and you may see the instruct model’s answer change.

5. The system prompt as the last layer, on a frontier model.

This step uses claude-opus-5-5 at $4 per million input tokens and $20 per million output tokens. Three short requests at effort: low cost well under US$0.05 in total. Create system_prompt.py:

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY
USER = "My parcel says delivered but it isn't here. Also, where's the best pizza in Naples?"
SYSTEMS = {
    "none": None,
    "scoped": ("You are the support assistant for an online shop. Only help with orders, "
               "deliveries and returns. Answer in at most three sentences. If a question is "
               "outside that scope, say in one sentence that you cannot help with it."),
    "persona": ("You are Ada, a cheerful support assistant for an online shop. Use the "
                "customer's language, never more than four sentences, and always end by "
                "offering to open a delivery investigation."),
}

for name, system in SYSTEMS.items():
    kwargs = dict(model="claude-opus-5-5", max_tokens=1024,
                  output_config={"effort": "low"},
                  # retry a classifier decline on a fallback model (the API chapter explains)
                  betas=["server-side-fallback-2026-07-01"], fallbacks="default",
                  messages=[{"role": "user", "content": USER}])
    if system:
        kwargs["system"] = system
    r = client.beta.messages.create(**kwargs)
    print("=" * 72, f"\nSYSTEM: {name}   stop_reason={r.stop_reason}  "
          f"in={r.usage.input_tokens} out={r.usage.output_tokens}")
    if r.stop_reason == "refusal":
        print("[declined]", r.stop_details)
        continue
    print("".join(b.text for b in r.content if b.type == "text"))
uv run python system_prompt.py
With no system prompt the model helps with both questions, often at length. With scoped it handles the parcel in at most three sentences and declines the pizza question in one. With persona it answers as Ada and ends with the offer you asked for. stop_reason is end_turn each time. Note that out is larger than the visible text: Claude Opus 5.5 always thinks before answering, thinking tokens are billed as output, and they are hidden by default. The same model, the same user message, three products: that is the leverage of the last layer.
Send the instruct model a request with raw: true, so Ollama skips the chat template: curl -s localhost:11434/api/generate -d '{"model":"llama3.2:3b","raw":true,"stream":false,"options":{"temperature":0,"num_predict":80},"prompt":"How do I reset my password?"}'. Without the special tokens that say “a user asked, now the assistant answers”, much of the assistant behaviour falls away and the output drifts towards document continuation, like the base model in step 2. Then wrap the same prompt in the template from step 1 by hand (the <|start_header_id|>user<|end_header_id|> block, then an empty assistant header) and send it raw again: the assistant is back. The instruction tuning is still in the weights, but it is keyed to the template. A serving stack that renders the template wrongly, or a fine-tune that uses a different one, gives you a degraded model with no error message.
ARTEFACT Write the vendor model-card review ~45 MIN
YOU PRODUCEA vendor model-card review

Template

# Model-card review: <model and version>, for <use case>
Owner: <writer, role>. Approver: <name, role>. Date: <date>. Card read: <title, version, date>.

## 1. Decision needed
<adopt, pilot or reject; by whom; by when>. Out of scope: <what this review does not cover>.

## 2. What the card says, and what it does not
| Layer | The card says | The card does not say | Why it matters here |
|---|---|---|---|
| Pretraining data and cut-off | | | |
| Fine-tuning (SFT) | | | |
| Preference training (RLHF, DPO, AI feedback) | | | |
| Known limits and evaluations | | | |
| What the system prompt can and cannot change | | | |

## 3. What we tested ourselves
<lab run or eval, the figure it printed, and what it shows>

## 4. Questions for the vendor
| # | Question | Why we ask | Owner | Answer needed by |
|---|---|---|---|---|

## 5. Change risk
<how we learn the model's behaviour changed, and what we do then>

## 6. How this could be wrong
<one way, and what would show it>

## 7. Sign-off
Prepared <name, date>. Approved <name, date>.
WORKED EXAMPLE

At a real company the engineer who owns the support assistant writes this review and the head of engineering approves it. Here the shop’s assistant is the use case, for the hosted model from step 5 of the lab. Date 20 November 2026 (assumed).

Decision. Approve a pilot on the hosted model with the system prompt from the scoped run, once the vendor answers questions 1 to 3. Out of scope: price comparison with other models and licence terms.

What the card says. The chapter does not describe any vendor’s card, so what this card contains is assumed: it names the model, gives a price and a knowledge cut-off, and has a short safety section. From the lab, not the card: the model costs $4 per million input tokens and $20 per million output tokens, and it always thinks first, so billed output tokens exceed the visible text. For scale, the chapter says Meta reports pretraining Llama 3 on over 15 trillion tokens; a card that gives no such figure leaves a gap.

What it does not say. Which sources and languages the pretraining data held, whether support-style text was in it, and how personal data was removed. Chapter rule: facts and cut-off come from pretraining, so a returns policy must arrive in the context.

What we tested. Step 5, three requests, under US$0.05 in all. stop_reason was end_turn each time. The scoped prompt handled the parcel in at most three sentences and declined the pizza question in one.

Questions. (1) Which deployment evaluations track sycophancy before a release? (2) How much notice is given before behaviour changes? (3) What is the knowledge cut-off? Owner for all three: the engineer; answers needed by 4 December 2026 (assumed).

Change risk. The engineer re-runs the scoped check and a 50-item eval on each model version; if it fails, we stay on the old version and tell product.

Could be wrong. Three requests are a smoke test. A different customer message could change the result; a failing eval over the 2,000 transcripts would show it.

Now you

You work at a 40-person legal-tech startup. The head of product wants a hosted model to summarise clients’ contracts, and you write the model-card review. In this scenario, invented for the exercise, the vendor’s card is four pages. It says the model was pretrained on a mix of public web text, licensed data and synthetic data. It says the model was then fine-tuned and trained on human preferences. It lists a knowledge cut-off and a paragraph on safety testing, and it reports no results on legal text. Use your own lab outputs: the step 2 comparison shows what post-training changed, step 4 shows how weak refusals can be, and the break step shows how a wrong chat template degrades a model with no error. Say what you would test before launch. The head of product reads your review to decide whether to approve a four-week pilot, and the head of engineering signs it.

Self-check

DECIDE

Your shop's support assistant runs on a hosted model. Product says it is too wordy, sometimes refuses legitimate refund questions as if they were fraud, and occasionally invents a returns policy. You have 2,000 past support transcripts and two weeks. Which layer do you work on first?

READING
  1. PAPER
    Training language models to follow instructions with human feedback (InstructGPT) Ouyang et al., 2022

    The paper that defined the SFT, reward model, PPO pipeline and showed a 1.3B post-trained model beating a 175B base model in human preference. Figure 2 is the clearest diagram of RLHF there is. Read: sections 1 to 3 and figure 2; skim the evaluation in section 4; skip the appendices unless you are building a labelling pipeline.

  2. PAPER
    Constitutional AI: Harmlessness from AI Feedback Bai et al. (Anthropic), 2022

    How to replace most human harmlessness labels with self-critique and AI preference labels guided by written principles. Read it to understand RLAIF and why written principles are easier to reason about than labeller judgements. Read: sections 1, 3 (supervised critique and revision) and 4 (RL from AI feedback); the constitution itself is in the appendix.

  3. PAPER
    Direct Preference Optimization: Your Language Model is Secretly a Reward Model Rafailov et al., 2023

    The derivation that turns RLHF into a simple loss over preference pairs. If you will ever fine-tune an open model on preferences, this is the method you will use first. Read: sections 1, 4 and 5; equation 7 is the loss; skip the theory in section 5.2 on a first read.

  4. PAPER
    Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback Bai et al. (Anthropic), 2022

    The tension between helpfulness and harmlessness made measurable, plus how reward models behave as they are optimised against. The groundwork Constitutional AI builds on. Read: sections 1 to 4; the robustness of preference models in section 4 is the part people cite.

  5. PAPER
    LIMA: Less Is More for Alignment Zhou et al., 2023

    A 65B base model fine-tuned on 1,000 curated examples, and the superficial alignment hypothesis. Useful for calibrating how much of a model's behaviour is format versus knowledge. Read: sections 1, 2 and 5; skip the dataset curation details.

  6. POST
    Illustrating Reinforcement Learning from Human Feedback (RLHF) Lambert, Castricato, von Werra, Havrilla, 2022

    The most readable walk through the three stages with diagrams, including where the KL penalty sits. Read before InstructGPT if the paper feels dense; skip the open-source tool list, which is dated.

  7. BOOK
    AI Engineering Chip Huyen, 2025

    The practitioner's view of the whole stack this course covers. Chapter 2 explains pretraining data, post-training and sampling from the angle of someone building applications on top. Read: chapter 2 now; chapters 1 and 3 as context.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Prompting fundamentals →