Part III · Large Language Models
Chapter 8
The Rise of Large Language Models
What happened when we simply predicted the next token — at scale.
In one sentenceTraining Transformers to predict the next token on vast text, at increasing scale, produced models with broad, reusable capabilities that can be steered with prompts.
The problem
One model for every task
By 2017 the Transformer existed, but language AI was still a collection of specialists. A sentiment classifier, a question answerer and a translation system were separate models, each trained on its own labelled dataset. Labels are slow and expensive to collect. Unlabelled text, on the other hand, was nearly unlimited.
Vision had already found a way around this: pretrain a network on ImageNet, then fine-tune it for a new task with a small dataset (Chapter 5). In 2018 language caught up. The idea was to pretrain a network on raw text with a task the text supplies itself, then fine-tune it on a little labelled data. ELMo, ULMFiT, OpenAI's GPT and Google's BERT all appeared that year Established. BERT, an encoder trained to fill in masked words, topped the benchmarks. GPT, a decoder trained to predict the next token, looked like the weaker cousin.
This chapter follows the weaker cousin. With the recipe barely changed, it was scaled about a thousandfold, and it turned out that one model could do many tasks with no fine-tuning at all.
The input
Text becomes tokens
A language model reads numbers, so text must be cut into units first. Whole words make the vocabulary open-ended, since every new name or typo is unknown. Single characters make sequences very long. Modern models use subword tokens: common words are single tokens, and rare words are spelled from a few pieces. Each token has an integer ID, and each ID selects one row of the model's embedding table.
The pieces are learned with byte-pair encoding (BPE). Start from single characters, count every adjacent pair in the corpus, merge the most frequent pair into a new symbol, and repeat. Train one below, on the tiny example from the paper that introduced BPE for translation. After five merges, the word lowest, which never appears in the corpus, is spelled from learned pieces as low + est_.
Try it · toy model
Learn byte-pair encoding by hand: merge the most frequent pair, again and again, and watch an unseen word get spelled from learned pieces.
Real tokenizers do exactly this on bytes, over huge corpora, until the vocabulary holds tens of thousands of pieces. GPT-2 used a byte-level BPE vocabulary of 50,257 tokens Established. Here are the real GPT-2 and GPT-4 tokenizers running in your browser. Try the Devanagari example, then numbers, then ask how many r's are in strawberry.
Try it
Type anything and watch the real GPT-2 and GPT-4 tokenizers split it into tokens and IDs: common words, rare words, numbers, code and other scripts.
Several well-known LLM quirks come straight from this step. The model never sees letters, so spelling questions are about something it never observes directly. Long numbers split into irregular chunks, so digit-by-digit arithmetic is awkward. And text in languages the vocabulary serves poorly costs more tokens, so it is more expensive and fills the context window faster.
The objective
Predict the next token
A GPT model is Chapter 7's decoder-only Transformer with one job. Read the tokens so far, and output a probability for every token in the vocabulary as the next one. Training compares that prediction with the token that actually came next, using cross-entropy. Thanks to the causal mask, a single pass over a 2,000-token document gives 2,000 predictions to learn from. No labels are needed, because the text provides its own answers. This is self-supervised learning, and it is why the training data can be as large as the web.
This is the same chain rule as the n-gram models of Chapter 6. The difference is that the context is now thousands of tokens handled by attention, rather than two words looked up in a count table.
Generating text runs the model in a loop: predict a distribution, choose a token, append it, and predict again. That is why chat replies appear word by word.
Train this objective over hundreds of billions of tokens of books, web pages and code, and you get a base model. It is a general-purpose text continuer that has absorbed a great deal of language, knowledge and style, along with its data's gaps and biases. A 2021 Stanford report called such broadly trained, widely adaptable models "foundation models" Established.
The scale-up
GPT-1 to GPT-3
| GPT-1 (2018) | GPT-2 (2019) | GPT-3 (2020) | |
|---|---|---|---|
| Parameters | about 117M | up to 1.5B | 175B |
| Training data | 7,000+ books | about 40 GB of web text | 300B tokens |
| Context window | 512 tokens | 1,024 tokens | 2,048 tokens |
| How it was used | fine-tune per task | zero-shot prompts | few-shot prompts |
The architecture barely changed. What changed was scale, and with it the way people used the model. GPT-1 was fine-tuned for each task and improved the state of the art on 9 of 12 Established. GPT-2 needed no fine-tuning to reach state-of-the-art results on 7 of 8 language-modelling benchmarks Established. It also produced rough summaries when an article was followed by "TL;DR:". GPT-3 could perform many tasks from just a few examples placed in its prompt.
These three numbers are easy to confuse. Parameters are capacity. Training tokens are experience. The context window is working memory during a single request. More of one does not make up for too little of another.
A new way to use a model
Learning from the prompt
GPT-3's paper was titled Language Models are Few-Shot Learners. Instead of fine-tuning, you write a prompt whose most natural continuation is the answer:
English: sea otter → French: loutre de mer
English: cheese → French: fromage
English: peppermint → French:
The model's weights do not change. It "learns" the task inside a single forward pass, as attention reads the examples. This is in-context learning. It grew much stronger with model size Established, and it turned programming a model into writing text. The examples may not teach what you would expect, though. Replacing the labels in few-shot examples with random ones often barely hurts accuracy Established, which suggests the examples mostly show the format and the kind of task. How transformers learn in context, and whether specific attention circuits ("induction heads") are the main mechanism, is still being studied Active research.
The puzzle
Why prediction goes so far
How can "guess the next word" produce translation, code and step-by-step explanations? One answer is that to predict human text well, you have to capture whatever produced it. Predicting the end of a proof is easier if you follow the proof. Predicting the next line of a program is easier if you know what the code does. Predicting "the capital of Nepal is…" is easier if you know the fact. Each regularity a model captures lowers its loss, so scale and diverse data push it to capture a great many Interpretation.
This has a precise form: prediction is compression. A model that gives the true next token probability p can encode it in about −log₂ p bits. Language models used as compressors beat standard compressors, even on images and audio Established.
The same view shows the limits. The objective rewards what is likely in the data, not what is true. A popular misconception is easy to predict, and a rare fact is learned weakly. Whether this kind of prediction amounts to understanding is still argued about Interpretation.
Scale as a plan
Bigger, predictably better
In 2020, Kaplan and colleagues found that language-model loss falls as a smooth power law in parameters, data and compute, across more than seven orders of magnitude Established. On a log–log plot, those trends are straight lines, so a lab could predict a large model's loss from small experiments and budget accordingly. Chinchilla (2022) corrected the recommended balance toward far more data per parameter Established. Chapter 9 works through the numbers.
Smooth loss curves raised a puzzle, because some benchmark scores seemed to switch on suddenly at a certain size. Are these emergent abilities real thresholds? Or do they appear because an all-or-nothing metric such as exact match turns steady gains into a jump? The answer is still debated Active research, and the concept card shows how much a metric can change the picture.
The last step
Choosing the next token
The model's output is a probability distribution, not a word. Something has to choose. Always taking the top token (greedy decoding) is predictable, but it gives the same bland answer every time. Sampling in proportion to the probabilities adds variety, but occasionally it picks something absurd from the long tail of unlikely tokens.
Three dials manage this. Temperature sharpens or flattens the distribution. Top-k keeps only the k likeliest tokens. Top-p (nucleus sampling) keeps the smallest set of tokens whose probabilities add up to p. Try them below on a toy model. Raise the temperature to 1.5 and watch unlikely words creep into the sentences, then set top-p to 0.9 and watch them disappear. Push the temperature higher still and a few get through again, because the flattened tail now holds enough probability to survive the cut.
Try it · toy model
Turn the temperature, top-k and top-p dials on a model's next-word probabilities, build a sentence word by word, and compare whole generations.
From model to product
From base model to ChatGPT
Ask a base model "What is the capital of France?" and it may continue with "What is the capital of Germany?", as a web page of quiz questions would. It models documents. It does not answer.
| Base model | Chat model | |
|---|---|---|
| Trained on | next-token prediction over web-scale text | the same, plus instruction tuning and preference tuning |
| Given a question | may continue the document in any direction | answers it |
| How to use it | build a prompt whose continuation is what you want | ask directly |
Two more training stages close the gap, and Chapter 10 covers them in detail. Instruction tuning fine-tunes on many tasks written as instructions with good responses. RLHF then optimises the model for responses people prefer, using the policy-gradient methods from Chapter 5. In InstructGPT, people preferred a tuned 1.3-billion-parameter model's answers to those of the 175-billion-parameter GPT-3 base Established. ChatGPT, released on 30 November 2022, put this behind a chat box and reached a mass audience within weeks Established.
Why it matters
Why it matters
This chapter holds the central fact of modern AI. One simple, self-supervised objective, applied at scale to a general architecture, produced models that could do a wide range of tasks. It did so without task-specific design, and without anyone fully predicting in advance what they would do.
- For an engineer, the practical consequences are tokens (cost, limits, quirks), prompts (in-context learning), decoding settings (temperature and top-p) and the difference between base and chat models.
- For a researcher, the open questions start here. Why does prediction produce capability? How does in-context learning work inside the network? Are new abilities predictable? How much of an assistant's behaviour comes from pretraining, and how much from tuning?
What comes next
Inside the machine
We have treated training as "predict the next token at scale". Chapter 9 opens that box: where the trillions of tokens come from and how they are cleaned, how tokenizers are built for real, what the loss curve and learning-rate schedule look like, how a model too big for one GPU is split across thousands, and what the scaling laws actually recommend. Chapter 10 then turns a base model into an assistant.
From a pretrained model to an assistant
Concepts in this chapter
Mark each one as you go. Must-know concepts are the core path.
- Autoregressive Next-Token PredictionA GPT-style model reads the tokens so far and outputs a probability for every possible next token; generating text means picking one, appending it, and repeating.Know wellMust know
- From Base Model to ChatGPTA pretrained base model continues text; instruction tuning and reinforcement learning from human feedback turn it into an assistant that answers questions and follows requests, which is what ChatGPT made public in 2022.UnderstandMust know
- Decoding: Greedy, Temperature, Top-k, Top-pA language model outputs a probability for every next token; a decoding strategy decides which one to use, trading predictability against variety.Know wellMust know
- GPT-1 → GPT-2 → GPT-3Between 2018 and 2020 OpenAI kept the same recipe (a decoder-only Transformer trained on next-token prediction) and scaled it about a thousandfold, and the way the models were used changed from fine-tuning to zero-shot to few-shot prompting.UnderstandMust know
- In-Context LearningIn-context learning is a model performing a new task from instructions or a few examples placed in its prompt, with no change to its weights.Know wellMust know
- Parameters, Tokens and Context WindowsThree numbers describe a language model's scale: how many learned parameters it has, how many tokens it was trained on, and how many tokens it can attend to at once (its context window).Know wellMust know
- Why Next-Token Prediction Goes So FarTo predict the next token of diverse human text well, a model is pushed to capture whatever regularities produced that text, which is why a simple objective yields broad abilities, and also why those abilities have characteristic limits.UnderstandMust know
- Pretrain, Then Fine-TuneTrain one model on a huge amount of unlabelled text first, then adapt it to each task with a small labelled dataset; around 2018 this replaced training every NLP model from scratch.UnderstandMust know
- Pretraining at ScalePretraining runs next-token prediction over a very large, diverse text corpus, producing a base model that has absorbed patterns of language, facts and reasoning styles from its data.Know wellMust know
- Scaling Laws (Preview)A language model's loss falls smoothly and predictably, as a power law, as its parameters, training data and compute grow, which turned 'make it bigger' into a plannable engineering decision.UnderstandMust know
- TokenizationA tokenizer splits text into subword pieces from a fixed vocabulary and maps each piece to an integer ID; the model only ever sees those IDs.Know wellMust know
- Emergent Abilities and the DebateSome abilities appear to jump from near chance to competent as models grow; whether these jumps are real phase changes or artefacts of all-or-nothing metrics is debated.UnderstandShould know
What do I actually need to remember?
- Pretrain once on unlabelled text, then adapt: the 2018 shift (ELMo, ULMFiT, GPT-1, BERT) that made the pretrained model the valuable asset.
- Text becomes subword tokens and integer IDs; BPE builds the vocabulary by merging frequent pairs. The model never sees letters.
- A GPT model outputs P(next token | all previous tokens); generation is predict → choose → append → repeat.
- Next-token prediction is self-supervised: every position of every document is a training example.
- GPT-1 → GPT-2 → GPT-3 kept the recipe and scaled it about a thousandfold, moving from fine-tuning to zero-shot to few-shot prompting.
- In-context learning: a frozen model performs a task from instructions or examples in its prompt, with no weight updates.
- Predicting diverse text well rewards capturing its regularities (prediction is compression), but the objective rewards likelihood, not truth.
- Loss falls as a smooth power law in parameters, data and compute; whether specific abilities 'emerge' suddenly is debated.
- Decoding: temperature reshapes the distribution, top-k and top-p cut the tail, greedy is deterministic but bland.
- A base model continues text; instruction tuning and RLHF make it an assistant, which ChatGPT brought to the public in 2022.
You do not need to memorize everything else. This list is the revision sheet.
Key papers
Deep contextualized word representations
Matthew E. Peters, Mark Neumann et al. · 2018 · NAACL 2018
ELMo: word vectors that change with the sentence, taken from a pretrained bidirectional LSTM language model. 'Bank' by a river and 'bank' with an account finally got different vectors.
- Problem
- Word2vec and GloVe give each word one vector regardless of context.
- What was new
- Use the internal states of a language model pretrained on a large corpus as contextual features for downstream models.
Universal Language Model Fine-tuning for Text Classification
Jeremy Howard, Sebastian Ruder · 2018 · ACL 2018
ULMFiT showed that 'pretrain a language model, then fine-tune the whole thing' works for NLP the way ImageNet pretraining worked for vision.
- Problem
- NLP models were trained from scratch per task and needed large labelled datasets.
- What was new
- Pretrain an LSTM language model on general text, fine-tune it on the target domain, then on the task, with techniques to avoid forgetting.
Improving Language Understanding by Generative Pre-Training
Alec Radford, Karthik Narasimhan et al. · 2018 · OpenAI technical report
GPT-1: a 12-layer decoder-only Transformer pretrained to predict the next token on over 7,000 unpublished books, then fine-tuned. It improved the state of the art on 9 of 12 tasks and set the template for every GPT since.
- Problem
- Labelled data for each language task is scarce, while unlabelled text is plentiful.
- What was new
- Generative pretraining of a Transformer decoder on long, contiguous text, followed by supervised fine-tuning with minimal task-specific changes to the architecture.
BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding
Jacob Devlin, Ming-Wei Chang et al. · 2018 · NAACL 2019
Made 'pretrain once, fine-tune everywhere' the default in NLP, using an encoder-only Transformer that reads context in both directions.
- Problem
- Language models read left-to-right, so their representations of a word couldn't use the words that came after it.
- What was new
- Masked language modeling: hide random tokens and train an encoder to fill them in from both sides.
Neural Machine Translation of Rare Words with Subword Units
Rico Sennrich, Barry Haddow, Alexandra Birch · 2015 · ACL 2016
Brought byte-pair encoding (BPE) to neural NLP — the ancestor of the tokenizers in GPT-style models.
- Problem
- Word-level vocabularies can't represent rare or unseen words; character-level models make sequences very long.
- What was new
- Start from characters and repeatedly merge the most frequent adjacent pair, yielding a vocabulary of subword units.
Language Models are Unsupervised Multitask Learners
Alec Radford, Jeffrey Wu et al. · 2019 · OpenAI technical report
GPT-2: a 1.5-billion-parameter model trained on 40 GB of web text that performed tasks with no fine-tuning at all (zero-shot), just from how the prompt was phrased.
- Problem
- Even pretrained models needed a labelled dataset and fine-tuning for every task.
- What was new
- Scale the same next-token objective to a bigger model and a large, diverse web dataset (WebText), with byte-level BPE, and evaluate zero-shot.
- Influenced
- Language Models are Few-Shot Learners
Language Models are Few-Shot Learners
Tom B. Brown, Benjamin Mann et al. · 2020 · NeurIPS 2020
GPT-3 (175B parameters) showed that a large enough language model can perform new tasks from a few examples in its prompt, without any gradient updates.
- Problem
- Each new NLP task needed its own labelled dataset and fine-tuning run.
- What was new
- Scale a decoder-only Transformer by ~100× and evaluate zero-, one- and few-shot 'in-context learning' across many tasks.
How to read it: 75 pages. Sections 1–2 and Figure 1.2 carry the core idea; Section 6 on broader impacts is worth reading too.
Scaling Laws for Neural Language Models
Jared Kaplan, Sam McCandlish et al. · 2020
Found that language-model loss falls as a smooth power law in parameters, data and compute — making model scale something you could plan.
- Problem
- There was no quantitative way to predict how much better a larger model would be.
- What was new
- Empirical power-law fits of loss against model size, dataset size and compute, over many orders of magnitude.
- Built on
- Attention Is All You Need
Training Compute-Optimal Large Language Models
Jordan Hoffmann, Sebastian Borgeaud et al. · 2022 · NeurIPS 2022
Showed that many large models were undertrained: for a fixed compute budget, parameters and training tokens should grow roughly in proportion.
- Problem
- Earlier scaling recommendations favoured very large models trained on comparatively little data.
- What was new
- Trained 400+ models to fit compute-optimal trade-offs; the 70B 'Chinchilla' model outperformed much larger models trained on fewer tokens.
Emergent Abilities of Large Language Models
Jason Wei, Yi Tay et al. · 2022 · TMLR
Catalogued tasks where performance stays near chance for small models and then jumps at larger scale, and named them 'emergent abilities'.
- Problem
- Smooth scaling laws for loss did not seem to predict when specific abilities would appear.
- What was new
- A definition (an ability absent in smaller models but present in larger ones) and a survey of examples across model families.
Are Emergent Abilities of Large Language Models a Mirage?
Rylan Schaeffer, Brando Miranda, Sanmi Koyejo · 2023 · NeurIPS 2023
The counter-argument: many apparent jumps come from all-or-nothing metrics such as exact match. Scored with continuous metrics, the same models improve smoothly.
- Problem
- Were emergent abilities a property of the models or of how researchers measured them?
- What was new
- A simple mathematical model plus re-analyses showing that nonlinear or discontinuous metrics can manufacture sharp transitions.
Rethinking the Role of Demonstrations: What Makes In-Context Learning Work?
Sewon Min, Xinxi Lyu et al. · 2022 · EMNLP 2022
A surprising result: replacing the labels in few-shot examples with random ones barely hurt performance. The examples mainly showed the format, the label space and the kind of input.
- Problem
- Nobody knew which parts of few-shot demonstrations actually drive in-context learning.
- What was new
- Controlled experiments across 12 models that vary labels, inputs and format independently.
In-context Learning and Induction Heads
Catherine Olsson, Nelson Elhage et al. · 2022
Proposed a concrete mechanism: 'induction heads', attention heads that complete [A][B] … [A] → [B]. Their appearance during training coincides with a jump in in-context learning.
- Problem
- In-context learning was observed but its mechanism inside the network was unknown.
- What was new
- Six lines of evidence linking induction heads to in-context learning: causal in small attention-only models, correlational in larger ones.
Language Modeling Is Compression
Grégoire Delétang, Anian Ruoss et al. · 2023 · ICLR 2024
Made the prediction–compression link concrete: a good predictor is a good compressor. Chinchilla 70B, trained mostly on text, compressed image patches and audio better than PNG and FLAC.
- Problem
- Is 'next-token prediction is compression' just a slogan, or measurable?
- What was new
- Use large language models with arithmetic coding as lossless compressors and compare them with standard compressors across text, images and audio.
Hierarchical Neural Story Generation
Angela Fan, Mike Lewis, Yann Dauphin · 2018 · ACL 2018
Popularised top-k sampling: pick only among the k most likely next words, which avoids both bland beam-search text and nonsense from the tail.
- Problem
- Beam search produced generic, repetitive stories; unrestricted sampling produced incoherent ones.
- What was new
- A story generator that first writes a premise, then the story; decoded with random sampling restricted to the top-k candidates.
The Curious Case of Neural Text Degeneration
Ari Holtzman, Jan Buys et al. · 2019 · ICLR 2020
Explained why maximising likelihood at generation time gives 'bland and strangely repetitive' text, and introduced nucleus (top-p) sampling, now a default setting in LLM APIs.
- Problem
- Greedy and beam search produce degenerate, repetitive text even from a good model, while pure sampling wanders into the unreliable tail.
- What was new
- Sample from the smallest set of tokens whose probabilities add up to p: the 'nucleus', whose size adapts to how confident the model is.
Finetuned Language Models Are Zero-Shot Learners
Jason Wei, Maarten Bosma et al. · 2021 · ICLR 2022
Instruction tuning: fine-tune on many tasks phrased as instructions and the model follows instructions for new tasks too. The 137B FLAN beat zero-shot GPT-3 on 20 of 25 tasks.
- Problem
- Base models were good at few-shot prompting but weak at simply following an instruction with no examples.
- What was new
- Fine-tune a pretrained model on over 60 datasets rewritten as natural-language instructions, then test on unseen task types.
Training language models to follow instructions with human feedback
Long Ouyang, Jeff Wu et al. · 2022 · NeurIPS 2022
InstructGPT: the supervised fine-tuning + reward model + RL recipe that turned GPT-3 into an instruction-following assistant, and the template for ChatGPT.
- Problem
- Pretrained language models continue text; they don't reliably follow instructions or behave helpfully.
- What was new
- Fine-tune on human demonstrations, train a reward model on human rankings, then optimize the model against it with PPO.
How to read it: Figure 2 is the three-step RLHF pipeline you'll meet in Chapter 10.
On the Opportunities and Risks of Foundation Models
Rishi Bommasani, Drew A. Hudson et al. · 2021
Named the shift: a single model trained on broad data and adapted to many tasks, a 'foundation model'. A long survey of capabilities, applications and risks.
- Problem
- The field lacked shared vocabulary for models like BERT and GPT-3 that serve as a base for many downstream systems.
- What was new
- The term 'foundation model' and a broad analysis of homogenisation, emergence and societal impact, from over a hundred authors at Stanford.
How to read it: Read the introduction (section 1) only; the rest is a reference to dip into.
LLaMA: Open and Efficient Foundation Language Models
Hugo Touvron, Thibaut Lavril et al. · 2023
Showed that smaller models trained on more tokens, using only publicly available data, can rival much larger ones, and released weights to researchers, starting the open-weight wave.
- Problem
- The strongest language models were closed, and very large.
- What was new
- Models from 7B to 65B parameters trained on trillions of tokens of public data; the 13B model outperformed GPT-3 (175B) on most benchmarks reported.
GPT-4 Technical Report
OpenAI et al. · 2023
Documented a large jump in capability, including human-level scores on many professional and academic exams, and marked the point where frontier labs stopped disclosing model size, data and training details.
- Problem
- How to report a frontier model's capabilities and risks when training details are withheld?
- What was new
- A multimodal (image and text input) model, predictable scaling of loss from much smaller runs, and a system card on safety work.
How to read it: Note what the report does not contain: architecture, parameter count, data and compute are all withheld.
Watch
Andrej Karpathy
[1hr Talk] Intro to Large Language Models
A clear one-hour overview of what LLMs are, how they are trained, and where they're going — good orientation for Part III.
Covers: Pretraining, fine-tuning, scaling, tool use, security issues.
Andrej Karpathy
Let's build the GPT Tokenizer
Many odd LLM behaviours trace back to tokenization; this shows you why by building a BPE tokenizer.
Covers: Unicode, bytes, byte-pair encoding, GPT-2/GPT-4 tokenizers, special tokens.
Andrej Karpathy
Deep Dive into LLMs like ChatGPT
A long, general-audience walk through the whole pipeline behind a chat model, from internet text to tokens to pretraining to post-training.
Covers: The full training stack behind a chat model, from internet text and tokens to a pretrained base model and the post-training that turns it into an assistant.
Andrej Karpathy
Let's reproduce GPT-2 (124M)
Build and train the smallest GPT-2 from scratch in PyTorch, then optimise it. For when you want to implement what this chapter describes.
Covers: The GPT-2 network in code, the engineering that makes training fast, and a full training run using the GPT-2 and GPT-3 papers' hyperparameters.
What came next?
Chapter 9
How an LLM Is Actually Built
What would it actually take to train a modern language model?
This chapter is being written.