Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 1: How language models produce text

Objectives: LO-1.1, LO-1.2, LO-1.3
Prerequisites: the course’s prerequisites, and Python for the labs if you are new to Python; this is the first module
Time: about 7 hours: 2 for this reading, 3 for Lab 1, and 2 for the practice

Every technique in this course works on one mechanism: a language model reads a sequence of tokens and predicts the next one, over and over. This module takes that mechanism apart, so the rest of the course has something concrete to build on. You will see how text becomes tokens and why the count of tokens, which sets both cost and limits, differs from the count of words. You will see where next-token probabilities come from, how a model turns them into text, and why the same prompt can give different answers. Last, you will see what the context window is and why a model remembers nothing it can’t see.

In Lab 1 you build a tokenizer and a model that predicts the next token from the previous two. You can inspect every count and every draw. That makes it possible to see how the same prompt can lead to two different continuations.

Text in, tokens out

A model doesn’t read characters or words. It reads tokens: pieces of text from a fixed vocabulary, each with a number. A common word is often one token. A rare word, a name, or a word in a language the vocabulary saw little of is split into several. A tokenizer turns text into tokens and back.

One way to learn a token vocabulary is byte-pair encoding (BPE). Sennrich, Haddow, and Birch adapted it from data compression to split rare words into pieces. The lab starts with single characters. A byte-level tokenizer starts with bytes. In either case, BPE counts every pair of adjacent symbols, merges the most frequent pair into one symbol, and then counts pairs again.

Worked example: three merges

Take a training text with three words: “ride” 4 times, “rider” twice, and “hide” 3 times. Start with each word as a sequence of characters, and count every adjacent pair, weighted by how often its word occurs:

PairWhere it occursCount
i dride (4), rider (2), hide (3)9
d eride (4), rider (2), hide (3)9
r iride (4), rider (2)6
h ihide (3)3
e rrider (2)2
  1. The most frequent pairs tie at 9. Break the tie by taking the pair counted first, i d, and merge it into the new symbol id. The words are now r id e, r id e r, and h id e.

  2. Count again. id e now occurs 9 times and wins, so merge it into ide: r ide, r ide r, h ide.

  3. Count again. r ide occurs 6 times, more than h ide (3) or ide r (2), so merge it: ride, ride r, h ide.

After three merges, “ride” is a single token, “rider” is two (ride and r), and “hide” is two (h and ide). The vocabulary favors what the training text repeats most. A large BPE tokenizer can learn tens of thousands of merges. It applies them to new text in the order it learned them.

Why token counts differ from word counts

Because the merges come from the training text, a tokenizer packs text like its training text tightly and splits other text into more pieces. In Lab 1, a tokenizer trained on English notes about a bicycle shop gives 3.2 characters per token on those notes, 1.6 on the Spanish version, and 1.5 on a Python program. In “The mechanic” the tokenizer keeps the space and “mechanic” in one token. In “El mecánico” the space and the second word take five tokens together. The first token is " mec", followed by "á", "n", "ic", and "o".

Four consequences follow for anyone who writes prompts:

Next-token probabilities

A language model, given a sequence of tokens, returns a probability for every token in its vocabulary: how likely that token is to come next. Write the probability that the next token is ww, given the context cc before it, as P(w∣c)P(w \mid c).

The simplest way to get these probabilities is to count. An n-gram model looks only at the last n−1n - 1 tokens. A trigram model (n=3n = 3) uses the last two. For each pair of tokens in the training text, it counts which tokens followed it, and divides:

P(w∣c)=count(c,w)∑w′count(c,w′)P(w \mid c) = \frac{\text{count}(c, w)}{\sum_{w'} \text{count}(c, w')}

Shannon built text this way in 1948, sampling letters and words by their counts in English to show how statistical structure makes text look more and more like language as nn grows.

Worked example: a trigram’s probabilities

Suppose the training text contains “the bike” 4 times: followed by " is" 3 times and " needs" once. Then

P(" is"∣"the bike")=34=0.75,P(" needs"∣"the bike")=14=0.25,P(\text{" is"} \mid \text{"the bike"}) = \frac{3}{4} = 0.75, \qquad P(\text{" needs"} \mid \text{"the bike"}) = \frac{1}{4} = 0.25,

and every other token gets probability 0. For a pair of tokens it has never seen, the lab’s model has no counts to turn into probabilities. One way to handle that case is to use the counts for the last token alone.

What real models do differently

A transformer is a neural network that can use relationships across a much longer context. Its learned weights let it assign next-token probabilities even to a sequence it never saw during training. The lab’s trigram model looks up counts for the last two tokens. Both models produce a distribution over possible next tokens, which lets us study how a token is chosen.

From probabilities to text

The model’s probabilities don’t say which token to write. A decoding rule decides. Text comes from a loop: get the probabilities for the context, choose a token, append it to the context, and repeat, until the model chooses a token that ends its turn or reaches a length limit.

Greedy decoding takes a most likely token at each step. In Lab 1, greedy decoding from “The mechanic” produces “The mechanic puts the bike in the tire. Then the mechanic puts the bike in the tire. Then…” until the length limit. In this trigram model, the same final pair leads to the same choice each time. In their experiments on open-ended text, Holtzman and colleagues also found that favoring high-probability sequences could lead to repetitive output.

Sampling instead picks each token at random, in proportion to its probability. A token with probability 0.55 is chosen about 55 times in 100. Two settings reshape the probabilities before the draw.

Temperature

Temperature TT raises each probability pip_i to the power 1/T1/T, then rescales them so they add up to 1:

pi′=pi1/T∑jpj1/Tp_i' = \frac{p_i^{1/T}}{\sum_j p_j^{1/T}}

Below 1, temperature sharpens the distribution toward the likeliest tokens; as TT approaches 0, sampling approaches greedy decoding. Above 1, it flattens the distribution toward unlikely tokens. At exactly 1, nothing changes.

Worked example. Take three tokens with probabilities 0.6, 0.3, and 0.1.

If one token has probability 1, every temperature leaves it at 1: temperature can’t create a choice where the model saw none.

Top-p

Top-p sampling, also called nucleus sampling, from Holtzman and colleagues, keeps only the most likely tokens whose probabilities add up to at least pp, drops the rest, and rescales.

Worked example. With 0.6, 0.3, and 0.1, and p=0.8p = 0.8: the first token alone reaches 0.6, which is less than 0.8, so add the second, reaching 0.9. Keep those two, and rescale: 0.6 / 0.9 = 0.667 and 0.3 / 0.9 = 0.333. The third token can no longer be chosen. Top-p cuts off the tail of unlikely tokens, where nonsense tends to come from, while leaving variety among the likely ones.

Why one prompt gives different answers

Because each token is sampled, two runs of the same prompt can choose differently at the first uncertain token, and every later token then follows a different context. In Lab 1, three seeds for the random number generator give three different continuations of “The mechanic”. The same seed reproduces the lab result. The Claude Messages API used in this course has no seed parameter.

On current Claude models you can’t turn the variety down with temperature either. Anthropic’s documentation for the Messages API says that Claude models from version 4.7 on don’t support temperature, top_p, or top_k: a request that sets one to anything but its default returns an error, and with API version 2026-10-21 or later, a request that sets one at all does. So variety is a fact of working with these models, and the course treats it that way:

The context window

A model reads a limited number of tokens at once: its context window. Anything outside the window can’t affect the prediction, however important it is. The trigram model’s window is two tokens. The current Claude models have a 1M-token context window, and can write up to 128K tokens in one response, according to Anthropic’s models overview.

The Claude Messages API is stateless. To make an earlier detail available in a new request, the application can send the relevant turns or a summary containing that detail. Module 2 builds a conversation history and keeps it inside the window.

Worked example: will it fit?

A 300-page manual has about 90,000 words. At the overview’s rule of thumb of 555,000 words per 1M tokens, it takes about 90,000 / 555,000 × 1,000,000 ≈ 162,000 tokens. It fits in a 1M-token window with room for instructions and an answer. Count with the real tokenizer before you rely on it: the rule of thumb is an average, and code, numbers, and many languages take more tokens per word.

Common misconceptions

Summary

Self-check

Answer each question before you open its answer.

  1. A tokenizer was trained only on English. Will it give more or fewer tokens per word for French text than for English, and why?

    Answer

    More. Its merges were learned from English, so common English words and word pieces are single tokens, while French words split into smaller pieces of the English merges.

  2. A next token has probability 0.2. After temperature 0.5 is applied, is its new probability higher, lower, or impossible to tell without the other probabilities?

    Answer

    Impossible to tell. The new value is 0.2 squared, 0.04, divided by the sum of every squared probability, so it depends on the others. Next to one token at 0.8, it falls to 0.04 / (0.64 + 0.04), about 0.059. Among five tokens at 0.2 each, it stays at 0.2.

  3. With probabilities 0.5, 0.3, 0.15, and 0.05, which tokens does top-p sampling with p=0.9p = 0.9 keep?

    Answer

    The first three: 0.5 + 0.3 = 0.8 is less than 0.9, and adding 0.15 reaches 0.95. The token at 0.05 is dropped.

  4. Why can’t you make a current Claude model give the same answer every time by setting its temperature to 0?

    Answer

    Current Claude models don’t let you set one: the API returns an error if a request sets the temperature to anything but its default. Their outputs vary from run to run, so you narrow the variety with the prompt and measure it with repeated runs.

  5. A user tells a chat assistant their name in one conversation, and the next day, in a new conversation, the assistant doesn’t know it. What happened?

    Answer

    Nothing went wrong. The model keeps nothing between requests, and the new conversation’s requests don’t contain the earlier one. The assistant could know the name only if the program put it into the new request.

Further reading

References
  1. Sennrich, R., Haddow, B., & Birch, A. (2016). Neural Machine Translation of Rare Words with Subword Units. Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers), 1715–1725. 10.18653/v1/P16-1162