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.

Lab 1: How language models produce text

Objectives: LO-1.1, LO-1.2, LO-1.3
Prerequisites: the Module 1 reading
Time: about 3 hours

In this lab you build the two halves of a tiny language model from scratch. First, a byte-pair encoding (BPE) tokenizer, which you train on a short text about a bicycle repair shop and use to count tokens in prose, Spanish, Python code, and numbers. Second, a trigram model, which predicts the next token from the two before it. Then you generate text with it, change the temperature and top-p settings, measure how they change the output’s variety, and watch what falls out of a context window.

No cell calls a real language model. The model here is the one you build, and every text it learns from was written for this course.

Each exercise ends with a check cell. Run it after your answer: it prints passed or fails with a message that says what is wrong. Run the cells in order, from the top. Some cells fail on purpose until you finish the exercise above them: each check, and the cells that use your answer.

Setup

The first cell imports what the lab uses and prints the versions it was written for. Every random choice in this lab uses a seed that the cell names, so every run gives the same results.

1. Characters, words, and tokens

The corpus, the text the model learns from, is a set of notes on how a bicycle repair shop works. Three more texts test the tokenizer on other kinds of writing: part of the notes in Spanish, a short Python program, and a list of prices and measurements. The next cell reads all four and counts their characters and words.

2. A byte-pair encoding tokenizer

A tokenizer turns text into a list of tokens, the units a model reads and writes. Byte-pair encoding builds its vocabulary from a training text. It starts with single characters, then repeats one step: find the pair of adjacent symbols that occurs most often, and merge it into a new symbol. After many merges, common words and word pieces have become single tokens, and rare words are still split into pieces.

This lab splits text into chunks before learning merges. A merge stays inside its chunk. Look at the space before each word in the output below. The pattern can keep that space with the letters that follow it. Other tokenizers can choose different boundaries.

Training counts each chunk once, with the number of times it occurs, as a tuple of symbols. count_pairs counts every adjacent pair of symbols, weighted by how often its chunk occurs. merge_pair replaces each occurrence of one pair in a chunk with the merged symbol, scanning from left to right.

train_bpe keeps each chunk’s frequency, so merging is fast even on a long text: a chunk such as " the" is merged once for all of its occurrences. Here is a tiny training text, the classic example from the BPE paper’s tradition, with words repeated so their counts differ.

Exercise L1.1 (LO-1.1, ★, about 15 minutes)

Predict the first three merges that train_bpe(tiny, 3) learns, before you run it. Work them out by hand: list the chunks with their counts, count the adjacent pairs, merge the most frequent, and count again. Notice that each chunk except the first starts with a space, which is a symbol like any other. Write your answer as a list of three pairs, each a tuple of two strings, such as [("a", "b"), ("ab", "c"), …].

Hint

The chunk " newest" occurs six times, so each of its pairs starts with a count of 6. A pair that also occurs in another chunk gets that chunk’s count added. After a merge, the new symbol can pair with its neighbors.

Now train on the shop notes with 300 merges, and encode a few sentences. The tokenizer prints each token in quotes, so you can see where the spaces went.

Words that are common in the training text, such as " mechanic", became single tokens. A word the text never uses, such as " replaced", splits into pieces, and so does nearly every Spanish word, because the merges were learned from English. Every digit is its own token, because the chunking splits digits apart. Real tokenizers make their own choices about digits, which is one reason a token count from one tokenizer doesn’t carry over to another.

Exercise L1.2 (LO-1.1, ★★, about 20 minutes)

  1. Write chars_per_token(text, merges), which returns the number of characters in text divided by the number of tokens encode gives it. More characters per token means the tokenizer packs the text more tightly, so the text costs fewer tokens.

  2. Before you measure the four texts, predict their order, from most characters per token to fewest, and write it in my_ranking, using the names in texts. Then run the check, which measures them.

Exercise L1.3 (LO-1.1, ★★, about 20 minutes)

A bigger vocabulary, from more merges, packs text into fewer tokens. Does it help every kind of text equally? Write tokens_by_merges(text, merge_counts), which trains a tokenizer on the prose (texts["prose"]) once for each number in merge_counts, and returns the list of token counts that each gives text, in the same order.

Hint

Train once per count with train_bpe(texts["prose"], n), then len(encode(text, ...)). Since training is the slow part, you may train once with the largest count and use the first n merges of the result for each smaller n: the first n merges never depend on later ones.

The next cell plots tokens per 100 characters against the number of merges, for each text. The four lines use colors and markers that readers with color vision deficiencies can tell apart. Before you run it, predict which line falls furthest.

The chart starts every line at 100 tokens per 100 characters, because with no merges each character is a token. The prose line falls furthest, to about 25 by 600 merges, because every merge was learned from it. The other three level off between about 60 and 75. The numbers line falls least, because digits are never merged: only the words and punctuation around them get shorter. A tokenizer is cheapest on text like its training text, and a model’s tokenizer is trained on far more text than this one.

3. Next-token probabilities

A language model gives, for every context, a probability for each token that could come next. A trigram model gets them by counting: for each pair of tokens in the training text, it counts which token followed that pair, and how often. The probability of a next token is its count divided by the total for that context:

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')}

The next cell encodes the prose with the 300-merge tokenizer and counts every trigram.

Exercise L1.4 (LO-1.2, ★, about 15 minutes)

Write next_token_probabilities(counts, context), which returns a dictionary from each token that followed context to its probability, using the formula above. For a context the model never saw, return an empty dictionary. counts maps each context, a tuple of two tokens, to a Counter of the tokens that followed it, like trigram_counts.

4. Choosing the next token

A model’s probabilities don’t say which token to write. A decoding rule does. The simplest is greedy decoding: always take the most likely token. The next cell generates 40 tokens after “The mechanic” that way. Before you run it, predict what goes wrong.

Greedy decoding falls into a loop: once the last two tokens repeat, the most likely next token repeats too, and nothing can break the cycle. Large models loop less, but Holtzman and colleagues showed that always choosing likely tokens makes their text repetitive and bland as well. Sampling instead picks each token at random, in proportion to its probability.

Two settings reshape the probabilities before sampling. Temperature TT raises each probability to the power 1/T1/T and rescales them to add up to 1. Below 1 it sharpens the distribution toward the likeliest tokens; above 1 it flattens it toward the unlikely ones. Top-p, or nucleus sampling, keeps only the most likely tokens whose probabilities add up to at least pp, and rescales those.

Exercise L1.5 (LO-1.2, ★★, about 15 minutes)

Write apply_temperature(probs, temperature), which returns a new dictionary of probabilities: each pi1/Tp_i^{1/T}, divided by their sum. Raise ValueError if the temperature isn’t positive.

Predict first: for {"a": 0.5, "b": 0.25, "c": 0.25} at temperature 0.5, what is the new probability of "a"?

Exercise L1.6 (LO-1.2, ★★, about 20 minutes)

Write top_p_filter(probs, p). Sort the tokens from most to least likely, breaking ties by the token’s text in alphabetical order. Keep tokens from the top until their probabilities add up to at least p, then rescale the kept ones to add up to 1. With p of 1, keep every token.

With both settings in place, generate samples a continuation of a prompt. It takes a seed, so one seed always gives the same text, and different seeds give different draws.

The first and last lines match, because they use the same seed. The three seeds give three different texts from one prompt: sampling, not the prompt, is where the variety comes from.

Exercise L1.7 (LO-1.2, LO-1.3, ★★, about 25 minutes)

Write continuations(prompt, n_tokens, runs, temperature=1.0, top_p=1.0), which returns a list of runs continuations, one for each seed from 0 to runs - 1. Return only the generated part of each text, without the prompt.

Then predict, before you run the check: of 50 continuations of “The bike is ready. The”, how many start with the token " mechanic" at temperatures 0.5, 1, and 2? The context (".", " The") gives that token a probability of about 0.55. Write your guesses in my_guesses; they aren’t checked, so guess honestly. The check counts the word “mechanic” alone, not the token " mechanics", which also follows this context.

A lower temperature concentrates the draws on " mechanic"; a higher one spreads them over rarer tokens. Top-p of 0.5 keeps only " mechanic" in this context, since its probability alone passes 0.5, so every draw starts with it. Neither setting makes the model know more: they only change how often it takes a token it already rated unlikely.

The next cell draws the probabilities of all ten tokens that followed (".", " The") in the prose, at three temperatures. Each temperature has its own color and hatching. Before you run it, predict which bars grow and which shrink at temperature 2.

At temperature 0.5, " mechanic" takes about 0.90 of the probability and the rest nearly vanish. At temperature 2, it drops to about 0.28, and the seven tokens seen only once each rise from about 0.03 to about 0.07. One of them is "y", the piece left over when the tokenizer splits “They” into " The" and "y": a model chooses tokens, not words.

Current Claude models don’t let you set a temperature: the API documentation says that a request that sets temperature, top_p, or top_k to anything but its default returns an error. Their outputs still vary from run to run, so you can’t switch the variety off. Module 3 narrows it with clearer prompts, and Module 7 measures it with repeated runs.

5. The context window

A model reads only a limited number of tokens at once: its context window. The trigram model’s window is two tokens, so nothing earlier in the text can change its prediction. A real model’s window is far larger, 1M tokens for the current Claude models, but anything outside it is just as invisible. The Messages API is stateless. The chat program in Module 2 makes earlier turns available by including them in its next request.

Exercise L1.8 (LO-1.3, ★, about 15 minutes)

Write fit_to_window(tokens, window), which returns the last window tokens of the list, the part a model with that window would see. Raise ValueError if window is less than 1. Then run the check, which puts a note at the start of a long text and shows what a 500-token window keeps.

A model with a 500-token window would answer “What color is the bike?” without the note, and a model that has no fact to use may still write a confident answer. Long inputs need a plan for what stays inside the window, which Modules 2 and 10 build.

To compare with a real window, the next cell estimates how many copies of the shop notes would fit in 1M tokens. Anthropic’s models overview says 1M tokens is roughly 2.5M characters on the current Claude tokenizer, so the estimate uses 2.5 characters per token instead of this lab’s tokenizer.

Summary

  • A tokenizer turns text into tokens. BPE learns its vocabulary by merging the most frequent pair of symbols, again and again, so it packs text like its training text tightly and splits unfamiliar text, such as another language, code, or numbers, into more tokens.

  • A language model gives a probability for every possible next token. The trigram model gets them by counting; a real model computes them with a neural network, from the whole context.

  • Text comes from repeatedly choosing a next token. Greedy choice loops in the shop example. Temperature sharpens or flattens the probabilities, and top-p cuts off the unlikely tail.

  • One prompt gives different outputs because each token is sampled. Current Claude models don’t let you set a temperature, so their variety is managed with the prompt and measured with repeated runs.

  • Each Messages API request supplies its own context, including any earlier turns it needs.

Next, do the Module 1 practice.