AI State of the Art
Fundamentals/LLM: Understanding Large Language Models/31 min
Section 47

What is an LLM? Definition, Scale, Emergent Capabilities

Listen as a podcast →

The simple formula that works: predict the next word

An LLM (Large Language Model) is a neural network (almost always a Transformer) trained on a single simple task:

Predict the next token given all the previous ones.

Given: "The black cat" Objective: Predict what comes next Answer: "sleeps", "jumps", "meows" (with probabilities)

Diagram of a decoder-only Transformer: the tokens LLM, s, are, cool and the period are turned into embeddings, added to positional embeddings, passed through a stack of layers (multi-head masked self-attention then a feed-forward network), then a linear layer and a softmax produce a probability distribution over the vocabulary for the next token.
The whole machinery of an LLM fits in this one diagram: text becomes tokens, tokens become vectors, the stack of Transformer layers reshapes them, and a final linear layer plus softmax turns the result into probabilities over the next token. Training simply compares that predicted token with the actual next token.Source : Cameron R. Wolfe, Deep (Learning) Focus

What makes it "Large":

  • Billions of parameters: GPT-1 has 117 million, GPT-3 has 175 billion, PaLM 540 billion, Llama 3.1 405 billion
  • Trillions of training tokens: a gigantic corpus of web text, books, code, scientific articles
  • A massive compute budget: thousands of GPUs (Graphics Processing Units) for months

The miracle: a mundane task is enough

The task is trivial. Predict the next word. Just that.

And yet, at sufficient scale, out come:

  • world knowledge (knowing that Paris is the capital of France)
  • mathematical logic (solving equations)
  • multi-step reasoning (breaking problems down)
  • code (producing working Python)
  • translation, without ever being given a single translated sentence pair

None of these capabilities is programmed explicitly. They emerge from the prediction task alone, and the word "emerge" is more contested than it looks, as the page on emergent abilities explains.

Tokenization: not words, pieces

LLMs don't process "whole words." They break text into tokens (word pieces or subwords):

InputTokens
"extraordinary"["extra", "ordinary"] or ["ext", "raord", "inary"]
"the"["the"]
"!"["!"]

The exact split depends on the model: these are not grammatical rules but pieces learned statistically from the corpus.

A useful rule of thumb: about 1.3 tokens per word in English. That is the conversion providers use to turn a text into a billed token count.

Common algorithms: BPE (Byte-Pair Encoding), WordPiece, SentencePiece.

The three levers of progress

The history of LLMs since 2018 is: increase three variables and watch the model get more capable. It isn't subtle, but it works every time. The figures below come from the publications of the labs concerned.

Lever 1: parameters (network size)

ModelYearParameters
GPT-12018117 million
GPT-220191.5 billion
GPT-32020175 billion
PaLM2022540 billion
Llama 3.12024405 billion

Observation: bigger means more capable, provided, as we'll see, the model is fed in proportion.

Lever 2: data (volume of training text)

ModelTraining tokens
GPT-1about 1 billion (the BooksCorpus dataset)
GPT-3300 billion
Llama 3.1 405B15.6 trillion
A classic trap: 570 GB is not 570 billion tokens

You will often read that GPT-3 was trained on 570 billion tokens. That is a mix-up of units.

The GPT-3 paper says two distinct things: the filtered version of Common Crawl weighs 570 gigabytes on disk, and the model was trained on 300 billion tokens in total, drawn from a mixture of sources. A gigabyte and a token are not the same unit, and only one of those two figures is a token count.

Observation: more text, and more varied text, means better regularities learned.

Lever 3: the compute budget

ModelCompute budget, in operations
GPT-3 175B3.1×10233.1 \times 10^{23} (that is, 3,640 petaflop/s-days)
PaLM 540B2.5×10242.5 \times 10^{24}, about 8 times more
Llama 3.1 405B3.8×10253.8 \times 10^{25}, about 120 times more than GPT-3

These figures are directly checkable: a training run's compute budget is about 6×N×D6 \times N \times D, six times the parameter count times the token count. For Llama 3.1: 6×405×109×15.6×1012=3.8×10256 \times 405 \times 10^9 \times 15.6 \times 10^{12} = 3.8 \times 10^{25}, exactly the figure Meta reported. The page on Kaplan's laws explains where the factor 6 comes from.

We give no dollar costs: labs do not publish them, and the estimates in circulation vary by orders of magnitude depending on the rental price assumed.

The key point: it's predictable

Kaplan et al. (OpenAI, 2020) found that the loss follows a regular curve, not one law, but three separate ones:

L∝N−0.076L∝D−0.095L∝C−0.050L \propto N^{-0.076} \qquad L \propto D^{-0.095} \qquad L \propto C^{-0.050}

LL is the loss, NN the parameter count, DD the token count, CC the compute budget. Each law is read "all else being equal". Plotted with both axes in logarithm, they are straight lines.

Consequence: you can plan. "With this budget I will reach this loss" becomes a calculation.

One important caveat, developed on the dedicated page: what the formula predicts is a loss, a statistical error in predicting the next token. Not a success rate on a given task. Nobody knows how to convert one into the other.

The debate: can scaling continue indefinitely?

Scaling laws describe the pre-training loss. But a score on a given task can plateau while the loss keeps falling, either because the task is saturated, or because the measurement itself is. The debate remains open.

"Emergent" capabilities: the scaling puzzle

At certain size thresholds, apparently new capabilities show up. No specialized training: the model is bigger, and it can suddenly do something it could not do before.

Four examples, before we say why the word "emergent" is contested.

In-context learning

GPT-2 does this poorly; GPT-3 (175 billion) does it well. Give it three examples in the prompt and it continues the pattern. The mechanism is laid out on the page about in-context learning.

Few-shot: Sentiment: "I love it!" -> positive Sentiment: "Meh..." -> neutral Sentiment: "Excellent!" -> ?

GPT-3 responds correctly ("positive") without fine-tuning.

Spelled-out reasoning

A small model gives a bare answer. A large model told to "think step by step" walks through its reasoning, this is chain-of-thought, covered on its own page.

Question: If I have 3 apples and my friend gives me 5, then I share half with my mom...

GPT-3: "Step 1: 3+5=83 + 5 = 8. Step 2: 8/2=48 / 2 = 4. Answer: 4 apples"

Explicit reasoning! And it helps performance.

Code generation

Not specifically trained on code, just a generic LLM. GPT-3.5?

Prompt: "Write a Python function that checks if a number is prime" Output: Correct, efficient, commented code.

Translation without examples

The model never received translated sentence pairs, no parallel Chinese-French corpus of the kind classical translation systems relied on. It did see Chinese and French separately in its corpus. And it translates anyway.

"Translate from Chinese to French: 你好 ->" Answer: "Bonjour"

What was missing, then, was not the language. It was the supervision.

The underlying debate

The question: do these capabilities emerge (genuinely new behaviour appears) or do they become visible (they were improving all along, but our thermometer could not see it)?

Both camps have serious arguments, and the dedicated page lays them out with the relevant papers. In short: what is observed is a sharp take-off in scores; what is disputed is whether it comes from the model or from the way we grade it.

Capabilities are sometimes unstable

"Can do" does not mean "always gets right." A model may translate nine sentences out of ten correctly and fail on the tenth, with no way to predict which. Newly acquired capabilities are often fragile to rephrasing.

Key models

GPT (OpenAI)

GPT-3 (2020) -> ChatGPT (2022, with RLHF) -> GPT-4 (2023, multimodal).

Open models

LLaMA (Meta, 2023), Mistral (2023), Mixtral (2024), Qwen (Alibaba), DeepSeek.

Claude (Anthropic)

Emphasis on safety and alignment, notably through Constitutional AI.

Gemini (Google DeepMind)

Natively multimodal: text, images, audio, video.

The training pipeline: 4 steps to go from nothing to an assistant

An LLM isn't born intelligent. It goes through 4 successive steps that progressively transform it from a neural network with random weights into an assistant capable of reasoning and following instructions. Each step builds on the previous one:

Four-column diagram of the LLM training pipeline: web text (over 1 trillion tokens) feeds language modeling and produces a pretrained LLM; demonstration data (10K to 100K prompt-response pairs) feeds supervised finetuning and produces the SFT model; human comparison data (100K to 1M) trains a reward model; finally prompts feed reinforcement learning, which produces the final model.
The full pipeline, with the data volumes shown under each stage. Notice how the nature of the data changes: first raw text in enormous quantity, then a few tens of thousands of carefully written examples, then comparisons between answers. The last two columns together make up RLHF.Source : DataSciOcean

Step 1, Pre-training (Base Training)

Objective: learn language and world knowledge.

The model ingests trillions of tokens of text (web, books, code, articles) and learns to predict the next token. This is the most expensive phase: thousands of GPUs for months.

Result: a "base" model that can complete text coherently. It knows facts, speaks several languages, can write code. But it doesn't yet know how to answer a question, ask it "What is the capital of France?" and it might continue with "What is the capital of Germany?" rather than answering "Paris."

-> Detailed on the GPT, pre-training and scaling laws pages.

Step 2, SFT, supervised fine-tuning

Objective: learn to follow instructions.

The base model is trained on thousands of examples of conversations (a question, then a good answer), written by humans or produced by other LLMs. The model learns the format: when asked a question, answer it.

Result: a model that follows instructions. Already usable, but it can still produce dangerous, misleading, or uneven answers.

-> Detailed on the instruction tuning page.

Step 3, Alignment

Objective: learn human preferences, be helpful, honest, and safe.

The model is refined so that it prefers good answers to bad ones. Several algorithms do this:

  • RLHF (Reinforcement Learning from Human Feedback) with PPO (Proximal Policy Optimization): a reward model scores answers, PPO corrects the model;
  • DPO (Direct Preference Optimization): direct training on preference pairs, with no reinforcement learning;
  • GRPO (Group Relative Policy Optimization): several answers to the same question are compared against each other, which removes the need for a critic model.

Result: an aligned assistant, it refuses dangerous requests, gives nuanced answers, and becomes usable by the public.

Step 4 (optional), Specialization

Depending on the final use, you can add:

  • RLVR (Reinforcement Learning with Verifiable Rewards) for mathematics and code, this is what produces reasoning models;
  • domain fine-tuning to adapt the model to a sector (medical, legal, finance);
  • distillation, which transfers a large model's behaviour into a smaller one.

The total cost of such a chain, for a frontier model, runs into tens of millions of dollars, but labs do not publish it, and the figures in circulation are reconstructions. Adapting an existing model with LoRA or QLoRA, by contrast, costs a tiny fraction of that, and that order of magnitude is checkable.

How an LLM generates text (the concrete mechanics)

Step by step, when you ask a question to an LLM:

1. Tokenization

Input: "Explain gravity" Tokens: ["Expl", "ain", "grav", "ity"]

The tokenizer breaks text into manageable pieces (not whole words, sub-units).

2. Embedding

Token "Expl" -> vector of numbers [0.2,−0.5,0.8,…][0.2, -0.5, 0.8, \ldots] Token "ain" -> vector of numbers [0.1,0.3,−0.2,…][0.1, 0.3, -0.2, \ldots]

Each token becomes a vector, that is, a list of numbers. Its length is the "model dimension": 4,096 for Llama 3 8B, 12,288 for GPT-3 175B. These vectors are learned during pre-training and frozen afterwards.

3. Passing through the Transformer

  • Layer 1: self-attention, then MLP
  • Layer 2: self-attention, then MLP
  • ...
  • Layer nn: self-attention, then MLP, with n=32n = 32 for Llama 3 8B, n=96n = 96 for GPT-3 175B

The MLP (Multi-Layer Perceptron) is simply a small conventional neural network, applied to each token independently. Self-attention is the mechanism by which each token consults the others.

Output: an updated vector for each token. At each layer, every token queries the others through attention, and the network refines its representation.

4. Predicting the next token

The last token's vector goes through a linear layer that produces one score per token in the vocabulary, on the order of 50,000 scores for GPT-2, 128,000 for Llama 3. These raw scores are called logits.

softmax:logits⟶probabilities summing to 1\text{softmax} : \text{logits} \longrightarrow \text{probabilities summing to 1}

The softmax function exponentiates each score and divides by the sum of all of them: it turns arbitrary scores into a probability distribution, a categorical distribution, laid out in distributions.

Result: P("the")=0.6P(\text{"the"}) = 0.6, P("in")=0.2P(\text{"in"}) = 0.2, P("between")=0.1P(\text{"between"}) = 0.1, and so on.

5. Sampling

You draw a token at random from that distribution. The temperature controls how you draw: every logit is divided by it before the softmax. The draw itself and temperature's exact effect are covered in sampling.

TemperatureEffect on the logitsBehaviour
0limiting case, no draw at allalways take the most probable token; output is reproducible
1logits unchangeddraw according to the model's own probabilities
2logits halved, so pulled togethergaps flatten out, rare tokens become reachable

The mechanism is arithmetic: dividing by a number above 1 brings the scores closer together, which evens out the probabilities, which increases variety. Dividing by a number below 1 does the opposite.

6. Auto-regression (the loop)

Initial prompt: "Explain gravity"

IterationInputOutputNew prompt
1"Explain gravity""It's""Explain gravity It's"
2"Explain gravity It's""a""Explain gravity It's a"
3"Explain gravity It's a""force""Explain gravity It's a force"

Continues until </s> or max_tokens.

Each generated token becomes the input for the next prediction. It's auto-regressive: the model feeds on its own output to keep generating.

Diagram of autoregressive generation: the prefix So long and thanks for is encoded token by token, passes through the Transformer blocks, and a language modeling head (linear layer then softmax) produces the token all; that token is then fed back as input, shown by dashed arrows, to produce the, and so on.
The dashed arrows are the heart of the loop: every token produced by the softmax drops back to the bottom of the diagram to become one more input. The model does not plan its sentence; it replays the same computation for each word with a slightly longer prefix.Source : DSCI 575 course, UBC Master of Data Science
Predicting is not understanding

Mechanically, an LLM does exactly three things:

  1. transforms vectors by multiplying them with learned weight matrices;
  2. produces a probability distribution over the vocabulary;
  3. draws a token from that distribution.

Is that understanding? The question is open, and it is better left open than settled too quickly either way. What is certain is that the result is useful.

Hard limitations

  • Hallucinations: the model generates false facts with apparent confidence, because it optimizes for statistical plausibility, not factual truth
  • Context window: limit on tokens it can process at once (improving, but remains a constraint)
  • No persistent memory: each conversation starts from scratch (unless an external memory system is added)
  • Fragile reasoning: can fail on minor variations of the same problem
  • Computational cost: enormous training, and inference also consumes significant resources

Why LLMs took over

  • Architecture: the Transformer scales well, which no earlier architecture did
  • Data: text is abundant and already written
  • Compute: the required GPUs can be bought
  • Flexibility: one model covers hundreds of tasks, switched by changing the prompt

Why this matters

An LLM is a network trained on a trivial task (predict the next token) at an unusual scale (billions of parameters, trillions of tokens).

That combination produces a remarkably flexible tool: answering questions, producing code, translating, summarizing, arguing, roughly anything that can be framed as "generate text."

The three levers (parameters, data, compute) govern progress, and do so predictably. No magic breakthrough.

What the newly appearing capabilities reveal is that the regularities of written language contain far more than expected (logic, reasoning, world knowledge) implicitly encoded in the statistics of text.

The following pages cover the exact scaling laws (Kaplan then Chinchilla), pre-training, and the alignment techniques that turn a text completer into an assistant.

The following sections explore the exact scaling laws, how to optimize training, and how to build real systems with these models.

Check your understanding0 / 4

1. You read that GPT-3 was trained on 570 billion tokens. What should you make of that?

2. You ask a freshly pretrained model, with no SFT and no alignment, what the capital of France is. What might it answer?

3. Mechanically, what does a temperature of 2 do?

4. What exactly do Kaplan's scaling laws predict?