part I · chapter 2 of 17

Foundation models

What a language model is, how it is made, and why it behaves the way it does.

why it matters

You can explain why models hallucinate and why context windows matter, and choose a model as an engineering decision.

before this: chapter 1, Python and ML fundamentals

in this chapter · 11 sections
  1. 2.1What a language model is
  2. 2.2Tokens
  3. 2.3Embeddings: meaning as geometry
  4. 2.4The transformer
  5. 2.5How a model is made
  6. 2.6Open-weight and proprietary models
  7. 2.7The limits, and why they exist
  8. 2.8Choosing a model is an engineering decision
  9. 2.9The maths underneath
  10. 2.10Build it: one app, three providers
  11. 2.11Where people go wrong

Every chapter after this one treats a language model as a component: something you call, constrain, feed with data and measure. This chapter opens the box once, so that the component's behaviour stops being surprising. Why does it make things up? Why does a long prompt cost more than a short one? Why does the same question get two different answers? Each of those has a mechanical explanation, and you can reason about all of them once you know what the model is actually doing.

What a language model is

A language model is a function. It takes a sequence of tokens and returns a probability for every token that could come next.

That is the whole interface. Given "The capital of France is", a good model puts most of its probability on " Paris". Generating text is a loop around that function: pick a next token from the distribution, append it to the input, and ask again. A five-hundred-word answer is several hundred trips round that loop.

choosing the next token

The capital of France isnext token?

  1. " Paris" (6)84.3%
  2. " a" (3.4)6.3%
  3. " the" (3.1)4.6%
  4. " located" (2.5)2.5%
  5. " known" (2.1)1.7%
  6. " Lyon" (1)0.6%

Draw a few at each temperature and compare.

The scores are made up for the picture; the softmax is real. Low temperature almost always picks the top token; high temperature spreads the chances out, which is where variety (and odd answers) come from.

Two consequences follow straight away, and they explain a great deal of later behaviour:

  • The model has no separate step where it checks facts. It produces the continuation that is most plausible given everything it has seen. Usually plausible and true coincide. When they do not, you get a confident, fluent, wrong answer.
  • Output costs more than input, and takes longer. The prompt is read in one parallel pass, but every output token needs its own trip through the model. Chapter 3 turns this into numbers.

Tokens

Models do not see characters or words. They see : chunks of text from a fixed vocabulary, typically somewhere between thirty thousand and a quarter of a million entries. Most tokenizers are built with byte-pair encoding, which starts from single bytes and repeatedly merges the most common adjacent pair until the vocabulary is full. Common words end up as one token, rare words as several pieces.

A useful rule of thumb for English is about four characters, or three quarters of a word, per token. Tokens matter to an engineer for four practical reasons:

  1. Billing is per token, input and output priced separately.
  2. Limits are in tokens. The context window and the maximum output length are both token counts.
  3. Other languages cost more. Text in Hindi, Tamil or Japanese often needs several times as many tokens as the same meaning in English, so the same feature can cost more and fit less.
  4. Some failures are tokenization artefacts. A model asked to count the letters in a word is looking at two or three tokens, not at letters, which is why it often gets it wrong.

Always count tokens with the provider's own tokenizer, never by splitting on spaces.

Embeddings: meaning as geometry

The first thing a model does with a token is look it up in a table and replace it with a of numbers, its . During training these vectors move so that tokens used in similar ways end up close together. Distance in this space starts to mean something: related ideas sit near each other.

This idea is bigger than the inside of one model. Dedicated embedding models turn a whole sentence or paragraph into a single vector, and comparing those vectors is how semantic search works. Chapter 5 is built on it, and week 2 of the maths track covers the measures of "close" (cosine similarity, dot product, Euclidean distance).

The transformer

Almost every modern language model is a transformer, an architecture introduced in 2017. You do not need to implement one, but you should be able to explain its main idea.

Attention

The meaning of a word depends on the words around it. "Bank" means something different in "river bank" and "bank loan". Attention is the mechanism that lets each token gather information from the other tokens in the sequence, weighted by how relevant they are.

Each token produces three vectors from its embedding: a query (what am I looking for), a key (what do I contain) and a value (what I will pass on if chosen). A token's query is compared with every key; the scores are turned into weights with softmax; and the token's new representation is the weighted sum of the values. In matrix form, for a whole sequence at once:

Attention(Q,K,V)=softmax(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

When every token attends to the tokens of the same sequence, it is self-attention. Running several attentions side by side, each free to learn a different kind of relationship (grammar, reference, topic), and concatenating the results is multi-head attention.

Position, and the causal mask

Attention on its own has no notion of order: "dog bites man" and "man bites dog" contain the same tokens. Positional encoding adds order back in. The original paper added sine waves of different frequencies; most current models use rotary embeddings (RoPE), which rotate the query and key vectors by an angle that depends on position.

A model that generates text must not peek at the future, so each token may only attend to the tokens before it. That restriction is the causal mask.

Encoders and decoders

The original transformer had two halves. An encoder reads a whole input with attention in both directions; a decoder generates output one token at a time with the causal mask. Today's chat models are decoder-only. Encoder-only models (the BERT family) never went away: they are what many embedding and reranking models are built on, because they read a whole passage at once.

A model is many such layers stacked: attention, then a small feed-forward network, each wrapped with a residual connection and normalisation, repeated dozens of times. The billions of parameters live mostly in those layers' weight matrices.

How a model is made

Models go through stages, and knowing them explains the different kinds of model you can choose between.

  1. Pre-training. The model reads an enormous amount of text and learns to predict the next token. This is where its knowledge and language ability come from, and it is by far the most expensive stage. The result is a base model: it continues text, but it does not follow instructions. Ask a base model a question and it may well answer with three more questions, because that is a plausible continuation.
  2. Supervised fine-tuning. The base model is trained further on examples of instructions paired with good responses. Now it answers questions instead of continuing them. This produces an instruct (or chat) model.
  3. Preference tuning. Humans or other models compare pairs of responses, and the model is tuned to prefer the better one, with methods such as RLHF or DPO. This is where helpfulness, tone and refusals are shaped.

Reasoning models are trained further to produce a long chain of intermediate thinking before the final answer. They do better on maths, code and multi-step problems, and they cost more and take longer for the same question, because the thinking is made of tokens too. Use one when the task genuinely needs it, not by default.

Multimodal models take images, audio or video as well as text. Vision language models put images into the same sequence as text tokens, so you can ask questions about a screenshot or a scanned invoice. Speech-to-text and text-to-speech models sit at the edges of voice products. Chapter 10 covers them.

Open-weight and proprietary models

Some models are only available through a provider's API (OpenAI's GPT models, Anthropic's Claude, Google's Gemini). Others publish their weights so anyone can run them (Meta's Llama, Mistral, Qwen, DeepSeek, and many more). Neither is better in general. They trade off differently:

ConcernProprietary APIOpen weights
Quality at the top endusually leadsclose behind, and closing
Getting startedan API keyhardware, serving, operations
Cost shapeper token, scales with usemostly fixed: GPUs whether busy or idle
Data controldata leaves your networkstays on your machines
Customisationprompting, some fine-tuningfull fine-tuning, any change you like
Upgradesthe provider retires models on its scheduleyou choose when anything changes

Many real systems use both: a strong proprietary model for hard requests and a small open model, run on your own machines, for high-volume simple ones. Chapter 9 shows how to route between them.

The limits, and why they exist

Hallucination

A hallucination is a fluent, confident statement that is false. It follows directly from what a model is: it predicts plausible continuations, and a plausible citation or statistic looks just like a real one. Hallucination is reduced, not solved, by bigger models. In an application you manage it with engineering: give the model the facts in its context (chapter 5), ask it to cite sources and check the citations, let it say "I don't know", and measure how often it is wrong (chapter 12).

The knowledge cutoff

A model knows nothing that happened after its training data was collected, and nothing about your private data at all. Retrieval is the fix for both.

The context window

The context window is the maximum number of tokens the model can take in at once, prompt and answer together. Windows are large now, but bigger is not free. Cost and latency grow with every token you send, and models are often better at using information near the start and end of a long context than in the middle. A focused prompt with the right ten passages usually beats one with every document you have.

Non-determinism

Because each token is sampled from a distribution, the same prompt can produce different answers. Lowering the temperature makes output more consistent, but even at zero, small numeric differences on the provider's hardware can change a token, and one changed token changes everything after it. Design for it: validate outputs, and evaluate over many runs rather than one.

Choosing a model is an engineering decision

"Use the most powerful model" is not a decision, it is the absence of one. Choose the way you would choose a database, against the requirements of this feature:

  • Quality on your task, measured on your own examples, not a public leaderboard.
  • Latency: time to the first token for a chat, total time for a background job.
  • Cost per request at your expected volume.
  • Context window and maximum output length.
  • Structured output and tool calling support, which chapter 4 relies on.
  • Data handling: where requests are processed, and whether they are retained.
  • Stability: how often the provider changes or retires the model.

The maths underneath

Maths note 5 gives the precise version of "a language model is a function over the next token". The probability of a whole sequence factors, by the chain rule of probability, into a product of next-token probabilities:

P(x1,…,xT)=∏t=1TP(xt∣x<t)P(x_1, \ldots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_{<t})

Each factor is exactly what one forward pass of the model computes. Training pushes these probabilities up on real text, and generation samples from them one factor at a time.

The model's last layer produces a raw score, a logit ziz_i, for every token in the vocabulary, and softmax turns the scores into probabilities that add up to one:

pi=ezi∑jezjp_i = \frac{e^{z_i}}{\sum_j e^{z_j}}

Maths note 6 adds temperature and sampling to this, and chapter 4 uses it. Maths note 12 returns to the attention formula above and explains the dk\sqrt{d_k}: without it, the dot products grow with the vector size, softmax saturates, and almost all the weight lands on a single token.

Build it: one app, three providers

Build one small feature, for example "summarise this support ticket and give it a category", against three providers, and compare them honestly.

  1. Write the feature once behind a small interface, so the provider is a parameter: complete(provider, prompt, schema).
  2. Collect twenty real inputs, including a few awkward ones (very long, very short, another language, an angry customer).
  3. Run every input through every provider. For each call record the output, input and output tokens, time to first token, total time, and cost.
  4. Ask for the result as JSON and record whether it parsed and matched the schema.
  5. Read the outputs side by side and score them yourself, with a simple rubric written down before you start.
  6. Write a short note: which model would you ship for this feature, and why.
type Result = {
  provider: string;
  ok: boolean;           // parsed and matched the schema
  inputTokens: number;
  outputTokens: number;
  firstTokenMs: number;
  totalMs: number;
  costUsd: number;
};

You will very likely find that the most expensive model is not the right answer for every feature, which is the lesson of the exercise.

Where people go wrong

  • Believing a model knows things the way a database does. It predicts text. Give it the facts you need it to use.
  • Choosing from a leaderboard. Public benchmarks measure someone else's task. Measure yours.
  • Ignoring tokens until the bill arrives. Count them from the first prototype.
  • Hard-coding one provider everywhere. Put model calls behind one small interface early, so changing models is a configuration change, not a refactor.

you reached the end of the chapter

build this

The same small app on three providers; compare quality, latency, tokens, price and structured output.

the maths underneath

  • maths note 3

    Matrices and linear layers

    y=Wx+b\mathbf{y} = W\mathbf{x} + \mathbf{b}

    A transformer is mostly matrix multiplication, and brute-force vector search is one matrix times one vector.

  • maths note 5

    Probability foundations

    P(x1,…,xT)=∏t=1TP(xt∣x<t)P(x_1, \ldots, x_T) = \prod_{t=1}^{T} P(x_t \mid x_{<t})

    This is how a language model defines the probability of a text, and why a ten-step agent at 95% per step finishes only 60% of the time.

  • maths note 12

    Transformer maths, end to end

    Attention(Q,K,V)=softmax(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

    Read the attention formula, size a GPU for a model and explain why long contexts cost so much.

check yourself

Tick what you could explain to someone else, out loud, without notes.