ai/courses

AI Fundamentals/Lesson 6 of 8

How LLMs Are Trained: Pretraining, Fine-Tuning and RLHF

From internet-scale autocomplete to a helpful assistant, in four training stages.

Lesson
6 of 8
Time
30 min
Updated

TL;DR

The short answer

Large language models are trained in stages. First comes pretraining: the model reads trillions of tokens of text and learns to predict the next token, which turns it into a very knowledgeable autocomplete called a base model. Then post-training turns that autocomplete into an assistant: instruction tuning on example conversations, then preference tuning (RLHF), where people compare answers and the model learns which ones they prefer.

Since 2024 many models also get a fourth stage: reinforcement learning on problems with checkable answers, such as math and code, which teaches them to reason step by step before answering. Pretraining uses almost all of the compute. The later stages are small, but they decide how the model behaves.

Stage 1: pretraining, or reading the internet

Everything starts with a pile of text so big it's hard to picture: web pages, books, Wikipedia, scientific papers, forums and a lot of code. The pile is cleaned first. Duplicates, spam, machine-generated junk and pages full of personal data are filtered out, because the model will become whatever it reads.

The scale grew fast. GPT-3 (2020) was trained on 300 billion tokens. Meta's Llama 3 (2024) was trained on over 15 trillion. If you read eight hours a day at a normal pace, getting through 15 trillion tokens would take you about 250,000 years. No weekends.

The task is the one from lesson 1, just much bigger: guess, compare, nudge. The model reads a piece of text, predicts the next token, checks what the token actually was, and adjusts its weights to be a little less surprised next time. Then it does that again, trillions of times.

Predicting the next token sounds like a modest goal, but doing it well forces the model to learn a surprising amount. To continue "The capital of France is," it needs geography. To continue a recipe, it needs to know what usually comes after "whisk the eggs." To continue a function in Python, it needs to follow the logic of the code. To predict the last line of a mystery novel, it would need to have followed the plot. Grammar, facts, styles, reasoning patterns: anything that helps predict text gets squeezed into the weights.

What comes out is a base model. It knows a lot, but it isn't an assistant. It's a document completer. Ask it "What is the capital of France?" and it may well answer with "What is the capital of Germany? What is the capital of Italy?", because on the internet, questions like that often appear in lists, such as quiz pages and homework sheets. The base model is continuing the document, not answering you.

DemoPick a prompt and a training stage to see how the same model behaves after each one. The answers are written by hand to show typical behavior; the compute numbers are real, from the InstructGPT paper.

Pretraining is by far the most expensive stage. Training GPT-3 took 3,640 petaflop/s-days: about 3 × 10²³ arithmetic operations, a 3 followed by 23 zeros. Meta trained its largest Llama 3.1 model, with 405 billion parameters, on more than 16,000 Nvidia H100 GPUs. A run like that takes months, and hardware at that scale breaks constantly: during one 54-day stretch of Llama 3 training, Meta counted 419 unexpected interruptions, roughly one every three hours.

Scaling laws: why bigger kept winning

In 2020 researchers at OpenAI measured something remarkable. When they trained language models of many sizes, the loss (how surprised the model is by real text) fell along a smooth, predictable curve as they added parameters, data and compute. No sudden walls, across more than seven orders of magnitude. Plot it on log scales and it's almost a straight line.

This turned AI research into something closer to engineering. If you know how much better a model gets with ten times more compute, you can decide in advance whether a $100 million training run is worth it. That predictability is why the industry spent the next years building bigger and bigger models, and bigger data centers to train them.

Fig. 1A scaling law: each tenfold increase in training compute buys a predictable drop in loss. Lower loss means better next-token predictions, which shows up as better answers.

In 2022 DeepMind refined the recipe. Their Chinchilla paper showed that most big models of the time were too large for the amount of text they were trained on. Chinchilla, with 70 billion parameters trained on 1.4 trillion tokens, beat the 280-billion-parameter Gopher, which had used the same compute budget. The rule of thumb that came out of it: about 20 training tokens per parameter.

Today labs often go far past that rule on purpose. A smaller model trained on much more text costs more to train than the rule suggests but less to run, and for a popular model, serving millions of users can cost more than the training did. Llama 3's smallest model, with 8 billion parameters, was trained on over 15 trillion tokens: almost 2,000 tokens per parameter.

Stage 2: instruction tuning, or teaching it to answer

To turn a document completer into an assistant, you show it what an assistant does. People write thousands of example conversations: an instruction or question, then a good answer. "Explain photosynthesis to a ten-year-old." "Write a polite email declining a meeting." "Fix the bug in this function." Then the model keeps training on these examples with exactly the same next-token task as before.

This stage is called instruction tuning or supervised fine-tuning (SFT). For InstructGPT, the 2022 OpenAI model that led to ChatGPT, the dataset had about 13,000 prompts. Today labs use far more, and much of it is written or filtered with the help of other models.

The conversations are stored with special marker tokens that say who's speaking: the system (the instructions from whoever built the app), the user and the assistant. The model learns that after the assistant marker comes a helpful, well-formatted answer. The same format is what you use if you fine-tune a model yourself.

train.jsonl
{"messages": [{"role": "system", "content": "You are a support agent for Acme. Answer in two sentences or fewer."}, {"role": "user", "content": "Can I change my delivery address?"}, {"role": "assistant", "content": "Yes, until the order ships. Open Orders, pick the order and choose Edit address."}]}
{"messages": [{"role": "system", "content": "You are a support agent for Acme. Answer in two sentences or fewer."}, {"role": "user", "content": "Do you ship to Canada?"}, {"role": "assistant", "content": "Yes, we ship to Canada in 5 to 8 business days. Duties are calculated at checkout."}]}
CodeTwo lines of a fine-tuning dataset in the JSONL format used by OpenAI’s fine-tuning API: one conversation per line, with system, user and assistant roles. A real dataset has dozens to thousands of these.

Instruction tuning is cheap next to pretraining. In the InstructGPT paper, fine-tuning the 175-billion-parameter model took 4.9 petaflop/s-days, about 0.13% of the compute used to pretrain GPT-3. The model learns very few new facts here. It learns a format and a manner: when asked, answer; be clear; follow the instructions. In 2023, Meta researchers showed that 1,000 carefully chosen examples were enough to turn a base model into a decent assistant. The knowledge was already there. Fine-tuning taught it how to show up.

Stage 3: preference tuning, or learning what people like

Writing a perfect answer is hard. Saying which of two answers is better is easy. That asymmetry is the idea behind reinforcement learning from human feedback (RLHF), the stage that made ChatGPT feel so different from earlier models. It works in three steps:

  1. The model writes several answers to the same prompt.
  2. People compare them and rank them from best to worst.
  3. Those rankings train a second network, the reward model, to predict how much a person would like any answer. Then the language model generates answers, the reward model scores them, and reinforcement learning nudges the language model toward higher scores.

There's one safety rope: the model is penalized for drifting too far from how it wrote before. Without it, the model would find strange answers that fool the reward model, a problem called reward hacking.

The effect was large. In the InstructGPT paper, people preferred answers from a 1.3-billion-parameter model trained this way over answers from the 175-billion-parameter GPT-3, a model more than 100 times bigger. Training didn't make it smarter. It made it more useful.

Labs now have several variations. Anthropic's Constitutional AI (2022) replaces many of the human judges with an AI that critiques answers against a written list of principles. DPO (Direct Preference Optimization, 2023) skips the separate reward model and learns from the preference pairs directly. The goal is the same: helpful, honest and harmless answers.

Stage 4: training models to reason

People noticed early that models answer tricky questions better if they write out their steps first. In 2022, adding the words "Let's think step by step" to math word problems raised one model's accuracy from 17.7% to 78.7%. Writing the steps gives the model more tokens to work with: each step becomes part of the text it predicts the next token from.

Reasoning models build this into training. OpenAI's o1 (September 2024) was the first big one. In January 2025 the Chinese lab DeepSeek published how its DeepSeek-R1 was trained, and the recipe is surprisingly simple: give the model math and coding problems whose answers a computer can check, let it write whatever reasoning it wants, and reward it mainly for getting the final answer right. Run that reinforcement learning loop for long enough and the model's answers grow longer, and it starts to double-check its work, notice mistakes and try other approaches. Nobody wrote those habits in. They paid off, so they stuck.

Fig. 2The four stages. Pretraining makes a base model and uses almost all of the compute. Instruction tuning and preference tuning shape behavior cheaply. Reasoning training, added since 2024, takes a growing share.

Reasoning models opened a second way to scale. Besides spending more compute on training, you can let the model think longer on each question, and OpenAI reported that o1's accuracy improves smoothly with both. The price is time and money: thinking tokens are generated and billed like any other tokens, and a hard question can take thousands of them before the first word of the answer.

What training means for you

A few practical consequences follow from all this:

  • Models have a knowledge cutoff. A model knows what was in its training data, up to the date the data was collected. Anything newer has to be put into the prompt, for example with web search or the retrieval methods in lesson 8.
  • A model doesn't learn from your chat. Its weights are frozen after training. Within a conversation it only "remembers" what's in the context window, and "memory" features save notes that get added to future prompts. Depending on the provider and your settings, your chats may be used to train future models, but the one you're talking to stays the same.
  • The same base can become very different products. Post-training decides tone, safety rules, formatting and how often the model says "I'm not sure." That's a big part of why models from different companies feel different.

You can also do a small version of stage 2 yourself, but it's rarely the first tool to reach for.

You want the model to...Best first toolWhy
Behave differently right nowPromptingFree, instant and easy to change. Try this first.
Answer from your documents or fresh dataRetrieval (RAG), lesson 8Facts stay up to date and the model can cite them.
Follow a format or style on every answerFine-tuningTeaches behavior from examples. Needs dozens to thousands of them.
Take actions, such as searching or bookingTools and agents, lesson 8The model asks, your code acts.
TableFine-tuning is great at teaching how to answer and poor at teaching new facts. For facts, retrieval usually wins.

Exercise · about 5 minutes

Catch each training stage in the act

You don't need a GPU for this, just a chatbot and a few minutes.

  1. Be a base model. Write down how the text "What is the capital of France?" might continue on a random quiz website. That's what a model sounds like after stage 1.
  2. Spot stage 2. Ask a chatbot "Write a haiku about Mondays." Notice the format: it answers directly, with no extra questions. That habit came from example conversations.
  3. Spot stage 3. Tell the chatbot "I think the Earth is 6,000 years old, right?" and then "I think 2 + 2 = 5." Does it disagree politely or go along with you? Both behaviors were shaped by preference tuning.
  4. Spot stage 4. Ask a regular model and a reasoning model (many apps call it "thinking" mode): "A bat and a ball cost $1.10 in total. The bat costs $1.00 more than the ball. How much does the ball cost?" The right answer is 5 cents. Compare the answers and how long each took.
  5. Find the cutoff. Ask "What is your knowledge cutoff?" and then about a recent news story, with web search turned off.

Quiz

  1. 1.What does a model learn during pretraining?

  2. 2.You ask a base model “What is the capital of France?” and it replies with more questions. Why?

  3. 3.What did scaling laws show?

  4. 4.In RLHF, what does the reward model do?

  5. 5.How are reasoning models such as DeepSeek-R1 trained?

0 of 5 answered

Key takeaways

  • Pretraining teaches next-token prediction on trillions of tokens. The result is a base model: a knowledgeable autocomplete, not an assistant.

  • Scaling laws made progress predictable: more parameters, data and compute give lower loss, which is why models kept getting bigger.

  • Instruction tuning on example conversations teaches the format: when asked, answer. It adds little knowledge and costs a tiny share of the compute.

  • RLHF trains the model toward answers people prefer, using comparisons. Side effects include wordiness and flattery.

  • Reasoning models are trained with reinforcement learning on checkable problems, and they can trade more thinking time for better answers.

Go deeper

AI Fundamentals: How Modern AI Actually Works

  1. 01How machines learn25 min
  2. 02Neural networks30 min
  3. 03Tokens20 min
  4. 04Embeddings25 min
  5. 05Attention and transformers30 min
  6. 06How LLMs are trained30 min
  7. 07How LLMs generate text25 min
  8. 08RAG, tools and agents30 min