What Large Language Models Are and How They Evolved
Objectives
- Explain how a language model turns text into probabilities for the next token
- Compare n-gram models, RNNs and Transformers
- Describe why modern open models still resemble GPT-2
- Outline the stages of building, pretraining and fine-tuning an LLM
Introduction: why start with the big picture
This book will take you from an empty Python file to a working GPT-style language model that you have coded, trained and fine-tuned yourself. That is a long road, and on a long road a map helps. This first chapter is the map. Before we write a single line of PyTorch, we need a clear and honest picture of what a large language model (LLM) actually is, what problem it solves, and why it is built the way it is.
The central idea is surprisingly modest. A language model does one thing: given some text, it estimates how likely each possible next piece of text is. Everything that makes chatbots seem fluent, from answering questions to writing code, grows out of that single skill applied over and over. Once you see this clearly, much of the mystery around LLMs falls away, and the engineering choices you meet later in the book start to make sense.
We will approach the subject in four steps. First, we will look closely at next-token prediction and how a model turns text into a probability for every possible continuation. Second, we will walk through the history of language modelling, from simple counting-based n-gram models, through recurrent neural networks, to the Transformer architecture that powers today's systems. Third, we will see why GPT-2, a model released in 2019, is still an excellent blueprint for understanding modern open models. Finally, we will lay out the stages of building, pretraining and fine-tuning an LLM, which is also the structure of the rest of this book.
No prior knowledge is assumed. Where a term such as embedding or attention appears, we introduce it informally here and return to it in depth in a later chapter. Treat this chapter as the guided tour before the hands-on work begins in the next chapter, where we set up Python, NumPy and PyTorch.
The one job of a language model: predicting the next token
Imagine reading the sentence fragment "The cat sat on the". Without thinking, you probably expect the next word to be "mat", "floor", "sofa" or something similar. You would be surprised by "democracy" and astonished by "purple running". Your expectation is not a single answer but a spread of beliefs: some continuations feel very likely, many feel possible, and most feel absurd. A language model is a program that captures exactly this kind of spread of beliefs in numbers.
Formally, a language model assigns a probability to every possible next unit of text, given the text that came before it. Those units are called tokens. A token is often a whole word, but it may also be part of a word, a punctuation mark, a space followed by a word, or even a single byte. We will spend a whole chapter on tokenisation later; for now it is enough to know that text is chopped into a sequence of tokens, and each token is given an integer id from a fixed vocabulary. GPT-2, for example, uses byte-level byte-pair encoding with a vocabulary of 50,257 tokens.
Given the token ids for "The cat sat on the", the model produces one score for every token in its vocabulary. These raw scores are called logits. A logit can be any real number, positive or negative, so on its own it is not a probability. To turn logits into probabilities, the model applies the softmax function: it exponentiates each score, which makes all of them positive, and then divides each by the sum of all of them, so that the results add up to exactly one. The token with the highest logit receives the highest probability, but every token gets some probability, however tiny.
The result is a probability distribution over the whole vocabulary, which we can write as P(next token | previous tokens). This is called a conditional distribution because it depends on the context. Change the context to "The stock market" and the same model will push probability towards tokens such as "fell", "rose" and "crashed" instead of "mat".
There is a useful piece of mathematics hidden here. The probability of a whole sentence can be broken down into a product of next-token probabilities. The probability of "The cat sat" equals the probability of "The", times the probability of "cat" given "The", times the probability of "sat" given "The cat". This is just the chain rule of probability, and it means that a model which is good at predicting the next token is automatically a model of whole sequences of text. Nothing more is needed to describe language than this chain of conditional predictions.
From probabilities to generated text
A probability distribution over the next token is useful in itself, but chatbots do not show you distributions; they show you text. The bridge between the two is autoregressive generation. The word autoregressive simply means that the model's own outputs are fed back in as inputs.
The loop works like this. You give the model a prompt. It computes the distribution for the next token. You choose one token from that distribution and append it to the text. Now the text is one token longer, so you ask the model for the next distribution, choose again, append again, and continue. Generation stops when the model produces a special end-of-text token or when you reach a length limit you have set. Every long, fluent answer you have seen from an LLM was produced this way, one token at a time.
How you choose the token at each step matters a great deal. The simplest strategy is greedy decoding: always pick the single most probable token. It is predictable, but it tends to produce dull and repetitive text, sometimes getting stuck in loops where the same phrase repeats. An alternative is sampling, where you draw the next token at random according to the model's probabilities, so a token with probability 0.3 is chosen about thirty percent of the time. Sampling gives more varied output. Two common controls refine it. Temperature rescales the logits before the softmax: a temperature below one sharpens the distribution towards the most likely tokens, while a temperature above one flattens it and makes surprising choices more frequent. Top-k sampling throws away all but the k most likely tokens and renormalises the remaining probabilities before drawing. We will implement these strategies ourselves in a later chapter.
It is worth pausing on what this means. The model has no separate module for answering questions, translating, or writing poems. It has one mechanism, next-token prediction, and a loop around it. The apparent variety of skills emerges from what kinds of text the model has learned to continue, and from how it has been fine-tuned to behave, as we will see at the end of this chapter.
The short program below makes the idea concrete. It takes a handful of invented logits for a tiny five-word vocabulary, converts them to probabilities with softmax, and compares greedy choice with temperature sampling. You do not need to understand every line yet; the next chapter introduces PyTorch properly.
import torch
vocab = ["mat", "floor", "sofa", "moon", "democracy"]
logits = torch.tensor([3.0, 2.2, 1.8, 0.1, -2.0]) # invented scores
probs = torch.softmax(logits, dim=0)
for word, p in zip(vocab, probs):
print(f"{word:10s} {p.item():.3f}")
# Greedy: always the most likely token
print("greedy:", vocab[torch.argmax(probs).item()])
# Sampling with temperature
torch.manual_seed(0)
for t in (0.5, 1.0, 1.5):
p_t = torch.softmax(logits / t, dim=0)
idx = torch.multinomial(p_t, num_samples=1).item()
print(f"temperature {t}: {vocab[idx]}")
If you run it, you will see that "mat" takes the largest share of the probability and is always the greedy choice, while sampling occasionally picks "floor" or "sofa", and does so more often as the temperature rises. "Democracy" keeps a small but non-zero probability: the model never rules anything out completely, it simply makes some continuations very unlikely.
Counting words: n-gram language models
Language models are much older than neural networks. For decades the standard approach was the n-gram model, and understanding it helps us appreciate what later models improved on.
An n-gram is simply a sequence of n consecutive words. A bigram is a pair of words such as "the cat"; a trigram is a triple such as "the cat sat". An n-gram model makes a strong simplifying assumption: the next word depends only on the previous n minus 1 words, not on everything that came before. This is called a Markov assumption, and it turns the impossible task of modelling all possible histories into something tractable. A bigram model, for example, predicts the next word using only the single word before it.
How does such a model learn its probabilities? By counting. To estimate the probability that "cat" follows "the", you count how many times the pair "the cat" appears in a large body of text, called a corpus, and divide by how many times "the" appears at all. If "the" appears 1,000 times and "the cat" appears 20 times, the model estimates a probability of 0.02. This count-and-normalise method is known as maximum likelihood estimation, because these are the probabilities that make the training corpus as likely as possible.
The following code builds a tiny bigram model from a toy corpus. It is deliberately simple, and it is a useful mental reference point: everything a GPT model does is, at heart, a far more powerful version of this table of conditional probabilities.
from collections import Counter, defaultdict
corpus = "the cat sat on the mat . the dog sat on the floor .".split()
pair_counts = defaultdict(Counter)
for prev, nxt in zip(corpus, corpus[1:]):
pair_counts[prev][nxt] += 1
def next_word_probs(prev):
counts = pair_counts[prev]
total = sum(counts.values())
return {w: c / total for w, c in counts.items()}
print(next_word_probs("the")) # {'cat': 0.25, 'mat': 0.25, 'dog': 0.25, 'floor': 0.25}
print(next_word_probs("sat")) # {'on': 1.0}
N-gram models were the workhorses of speech recognition and machine translation for many years, and they are fast and easy to understand. Their weaknesses, however, are fundamental. The first is sparsity: most possible word sequences never appear in any corpus, however large, so the model assigns them a count of zero and therefore a probability of zero, even when they are perfectly sensible. Practitioners developed smoothing techniques to shift a little probability onto unseen sequences, but that only patches the symptom. The second weakness is the fixed, short window. A trigram model cannot know that a sentence began with "The keys to the cabinet" when it is deciding between "is" and "are" ten words later. Making n larger makes sparsity dramatically worse, because the number of possible n-grams grows exponentially. The third weakness is that words are treated as unrelated symbols. Seeing "the cat sat" many times tells the model nothing about "the kitten sat", because to the model "cat" and "kitten" are simply two different strings with no shared meaning.
The n-gram era also left us a lasting tool for measuring how good a language model is: perplexity. The idea is to take some held-out text the model never saw, ask how much probability the model gives to each actual next token, and summarise the result. In practice perplexity is computed as the exponential of the average negative log-likelihood per token, which is the same as the exponential of the cross-entropy loss we will use to train our own model. Lower perplexity means the model was less surprised by the real text, so lower is better. A helpful intuition is that a perplexity of 20 means the model is, on average, about as uncertain as if it were choosing uniformly among 20 tokens. One caution matters for later chapters: perplexity depends on the tokeniser, so two models that split text differently cannot be compared directly by their perplexity scores.
Neural language models and recurrent networks
The weaknesses of n-gram models pointed to two needs: a way to represent words so that similar words share information, and a way to use longer contexts without an explosion in the number of things to count. Neural networks addressed both.
The first key idea is the embedding. Instead of treating each word as an isolated symbol, a neural language model maps each word or token to a vector, a list of numbers, perhaps a few hundred long. These vectors are learned during training. Because the network is rewarded for predicting well, words that appear in similar contexts end up with similar vectors. "Cat" and "kitten" drift close together, so evidence about one helps predictions about the other. This directly attacks the sparsity problem: the model no longer needs to have seen an exact sequence to give it a sensible probability. Early neural language models in the early 2000s fed the embeddings of a fixed window of previous words into a small feed-forward network. They generalised better than n-grams, but they still looked at only a fixed number of previous words.
The second idea is the recurrent neural network (RNN), which removes the fixed window. An RNN reads text one token at a time and keeps a hidden state, a vector that acts as a running summary of everything read so far. At each step it combines the current token's embedding with the previous hidden state to produce a new hidden state, and from that hidden state it predicts the next token. In principle, the hidden state can carry information from the very start of a document all the way to the end.
In practice, plain RNNs struggled to remember things over long distances. When they are trained, the error signal has to flow backwards through every time step, and over many steps it tends either to shrink towards nothing or to blow up, problems known as vanishing and exploding gradients. Variants such as the Long Short-Term Memory (LSTM) network and the gated recurrent unit added learned gates that decide what to keep, what to forget and what to output, which made it much easier to carry information over longer spans. For several years in the 2010s, LSTMs were the state of the art for language modelling, translation and speech.
RNNs still had two important limitations. The first is the bottleneck: the entire history must be squeezed into a single fixed-size hidden state, so details from far back are easily overwritten. Researchers working on translation added an attention mechanism that let the decoder look back at all of the encoder's hidden states rather than relying only on the last one, which helped a great deal and planted the seed for what came next. The second limitation is sequential computation. Because each step depends on the previous hidden state, an RNN cannot process the tokens of a sentence in parallel. Modern hardware such as GPUs is fastest when it can do many identical computations at once, so RNNs left much of that power unused and were slow to train on very large datasets.
Those two limitations, the hidden-state bottleneck and the step-by-step computation, are exactly what the next architecture removed. The attention idea that had been bolted onto RNNs turned out to be powerful enough to replace recurrence entirely.
The Transformer: attention is all you need
In 2017 a team at Google published a paper with a bold title, "Attention Is All You Need". It introduced the Transformer, an architecture that relies entirely on attention and drops recurrence and convolutions altogether. Almost every major language model since then is built on it.
The heart of the Transformer is self-attention. Instead of passing information along a chain one step at a time, self-attention lets every token look directly at every other token in the sequence and decide how much each one matters for its own representation. When the model processes the word "it" in "The animal didn't cross the street because it was too tired", self-attention allows the representation of "it" to draw heavily on "animal". There is no bottleneck: any token can reach any other token in a single step, however far apart they are.
The paper proposed a specific form called scaled dot-product attention. Each token produces three vectors, called a query, a key and a value. A token's query is compared with every token's key using a dot product; the resulting scores are scaled and passed through a softmax to give attention weights; and the token's new representation is the weighted sum of the values. The paper also introduced multi-head attention, which runs several of these attention operations side by side so that different heads can specialise in different kinds of relationships. We will code all of this, step by step, in the attention chapter.
Just as important as the modelling power is the efficiency. Because self-attention computes the relationships between all positions at once, using large matrix multiplications, the tokens in a sequence can be processed in parallel during training. This made Transformers much faster to train than RNN and LSTM models, and it meant they could make full use of GPUs and be scaled to far more data and parameters.
Attention on its own has no sense of order: it would treat "dog bites man" and "man bites dog" the same way. To fix this, the original Transformer added positional encodings, fixed patterns of sine and cosine values, to the token embeddings so that each position carries a distinct signature. Later models, including GPT-2, learn their position embeddings instead, and many current models use yet another scheme, as we will see shortly.
One historical detail matters for this book. The original Transformer was an encoder-decoder model designed for machine translation. The encoder reads the whole source sentence, say in English, with every token able to see every other token. The decoder then generates the translation, say in German, one token at a time, attending both to its own previous outputs and to the encoder's representation. Researchers soon realised that the two halves could be used separately. Encoder-only models such as BERT became popular for understanding tasks such as classification. Decoder-only models became the family of generative LLMs we are going to build: they keep the decoder's masked self-attention over previous tokens, drop the connection to an encoder, and use the result purely to predict what comes next.
GPT: the decoder-only Transformer
OpenAI's GPT series took the decoder half of the Transformer and trained it for one purpose: next-token prediction on huge amounts of ordinary text. The name stands for Generative Pretrained Transformer. The first GPT appeared in 2018, and GPT-2 followed in 2019.
A decoder-only model has a single stack of Transformer blocks and no encoder. The crucial ingredient that makes it a language model is causal masking. During training, the model sees an entire sequence at once, but each position is only allowed to attend to itself and to positions before it, never to positions after it. Without this mask, the model could simply look ahead and copy the answer. With the mask, every position in a training sequence becomes its own prediction exercise: position one predicts token two, positions one and two predict token three, and so on. A single training sequence of a thousand tokens therefore provides a thousand next-token predictions, all computed in parallel. This is the combination of the Transformer's parallelism and the language-modelling objective that made large-scale training practical.
GPT-2 is a good model to study because it is simple, well documented and openly available. It is a decoder-only Transformer trained purely on next-token prediction over unlabeled text. Its training data, called WebText, consisted of roughly 40 GB of text gathered from around eight million web pages that had been linked from Reddit posts with a minimum amount of karma, with Wikipedia pages removed. It represents input text with byte-level byte-pair encoding, the same kind of tokeniser we will use through the tiktoken library. Compared with the first GPT, it also moved layer normalisation to the start of each sub-block and added one more normalisation after the final block.
GPT-2 was released in several sizes, all able to handle a context of 1,024 tokens. The paper reports the smallest model as having about 117 million parameters, and the largest about 1.5 billion. You will often see the smallest model described as having about 124 million parameters instead; that is the commonly used figure from a later recount of the released weights, and it is the number our own code will produce when we count parameters. That smallest version is the size we will build in this book, and later we will even load OpenAI's published GPT-2 weights into our own from-scratch code.
The GPT-2 paper also made an observation that shaped the next several years of research. Without any task-specific training, a large enough language model could perform tasks such as answering questions or summarising simply by being given a suitable prompt, an ability called zero-shot learning. Performance on these tasks improved steadily as the model got bigger, roughly log-linearly with capacity. In other words, simply training a larger next-token predictor on more text produced a more capable general-purpose system. GPT-3, released in 2020 with 175 billion parameters, pushed the same recipe much further and showed that a sufficiently large model could often pick up a new task from just a few examples written into the prompt. The architecture, however, was still recognisably the same decoder-only Transformer, which is why the lessons of GPT-2 carry over so directly.
Why modern open models still resemble GPT-2
You might reasonably ask whether it is worth learning a 2019 design when newer models appear every month. The answer is a confident yes, because the core architecture has changed surprisingly little. A detailed comparison of recent open-weight models concludes that they remain structurally close to GPT-2's decoder-only design. If you open the code of a current open model, you will still find the same skeleton: token embeddings, a stack of repeated Transformer blocks, each with an attention part and a feed-forward part joined by residual connections and normalisation, and a final layer that turns the last hidden states into logits over the vocabulary.
What has changed are the components inside that skeleton, usually in the name of efficiency or stability at large scale. Several refinements are now very common:
- Rotary position embeddings (RoPE) replace GPT-2's learned absolute position embeddings, encoding position by rotating query and key vectors.
- RMSNorm replaces standard layer normalisation with a slightly simpler and cheaper operation.
- Grouped-query attention lets several attention heads share the same keys and values, which saves memory during generation.
- Mixture-of-experts layers replace a single feed-forward network with many expert networks, only a few of which are active for any given token, so a model can have a very large total parameter count while using only a fraction of it per token.
The same comparison describes further variations, such as multi-head latent attention, which compresses keys and values to shrink the memory used during generation, and sliding-window attention, which limits how far back some layers look. It also notes that small modern models differ in shape, for instance one trading width for depth compared with another of similar size.
The key point for a learner is that each of these is a modification of a part you will already understand after building GPT-2. Swapping layer normalisation for RMSNorm is a change of a few lines. Grouped-query attention is a variation on the multi-head attention you will write. The companion code for the book this approach is based on includes bonus material implementing newer architectures such as Llama and Qwen3 from scratch, precisely because the step from GPT-2 to them is small once the foundations are in place. Learning GPT-2 well is therefore not learning history; it is learning the common core of the field.
A map of the pipeline: from text to probabilities
Now that we know where the architecture came from, let us trace the path that a piece of text takes through a GPT-style model. This pipeline is the backbone of the whole book, and each stage will get its own chapter.
The first stage is tokenisation. Raw text is a string of characters, but neural networks work with numbers. A tokeniser splits the text into tokens and maps each to an integer id. GPT-2 uses byte-pair encoding (BPE), which starts from individual bytes and repeatedly merges the most frequent adjacent pairs into new tokens, building up a vocabulary of common subwords. A tokeniser therefore has three jobs: learning its vocabulary and merge rules, encoding text into tokens and decoding tokens back into text. Because byte-level BPE works on the raw bytes of UTF-8 text, it can represent any input, including words it never saw during training, and decoding reverses encoding exactly, so nothing is lost. It also shortens sequences, because a typical token covers several characters, and it lets the model see recurring pieces such as "ing" that help it generalise. GPT-2 also first splits text into chunks such as letters, numbers and punctuation using a regular expression, so that merges never cross those boundaries.
You can try GPT-2's tokeniser today with OpenAI's tiktoken library, which you install with pip install tiktoken and which loads encodings by name:
import tiktoken
enc = tiktoken.get_encoding("gpt2")
ids = enc.encode("The cat sat on the mat.")
print(ids) # a short list of integers
print([enc.decode([i]) for i in ids]) # the text of each token
print(enc.decode(ids)) # round-trips to the original text
The second stage is embedding. Each token id is used to look up a learned vector in an embedding table. On its own, this vector says what the token is, but not where it sits in the sequence, so GPT-2 adds a second learned vector that depends on the position. The sum of the token embedding and the position embedding is the input to the network.
The third stage is the stack of Transformer blocks. Each block contains causal multi-head self-attention, which lets each position gather information from earlier positions, followed by a small feed-forward network applied to each position separately. Around these sit layer normalisation and shortcut (residual) connections, which keep training stable when many blocks are stacked; in GPT-2 the normalisation comes at the input of each sub-block. The smallest GPT-2 has twelve such blocks. As the vectors pass upward through the blocks, they become richer and richer representations of each token in its context.
The fourth stage is the output head. After a final normalisation, a linear layer maps each position's vector to one logit per vocabulary entry, and softmax turns these into the next-token probabilities we met at the start of the chapter. During training, we compare these probabilities with the token that actually came next, using the cross-entropy loss, and adjust every weight in the model to make the correct token a little more likely. During generation, we take the distribution at the last position, choose a token, append it and run the pipeline again, which closes the autoregressive loop described earlier. The first diagram in this chapter shows the whole path, from raw text to the chosen token and back again.
From architecture to assistant: building, pretraining and fine-tuning
An architecture is only an empty structure with random numbers inside. Turning it into a useful model involves three broad stages, and this book follows them in order. The companion code repository that inspires our approach is organised the same way: it covers preparing text data and tokenisation, coding attention, building a GPT model, pretraining on unlabeled data and then fine-tuning, all in plain PyTorch without external LLM libraries.
Stage one: building. First we prepare the data and write the model. Data preparation means tokenising a body of text and slicing it into training examples. A common method is a sliding window: we take a chunk of tokens of a fixed context length as the input and the same chunk shifted by one token as the target, then move the window along by a chosen stride to make the next example. Then we code the components: embeddings, causal attention and multi-head attention, the feed-forward network, layer normalisation and the full GPT model, including counting its parameters.
Stage two: pretraining. Next we train the model on unlabeled text using the next-token objective. Unlabeled means nobody has to annotate anything; the text itself supplies the right answers, because the target at each position is simply the next token. We write a training loop that measures the loss on training and validation data and generates sample text so we can watch the model improve. Real pretraining of large models uses enormous datasets and clusters of GPUs and is far beyond a laptop. Our code is designed to run on ordinary computers, using small text such as a short story for demonstrations. To get a genuinely capable model without the expense, we will then load OpenAI's pretrained GPT-2 weights into our own implementation. We will also add common training improvements such as learning-rate warmup, cosine decay and gradient clipping.
Stage three: fine-tuning. A pretrained model is a skilled text continuer, but not necessarily a helpful one. Fine-tuning continues training on a smaller, targeted dataset. One kind adapts the model for a specific task such as classification, for example detecting spam messages; another teaches it to follow instructions by training on pairs of instructions and good responses. Research on instruction following showed why this matters: making a model bigger does not by itself make it better at doing what users intend. OpenAI's InstructGPT work first fine-tuned GPT-3 on human-written demonstrations, then trained a reward model from human rankings of outputs, and finally optimised the model against that reward with reinforcement learning, a process known as reinforcement learning from human feedback (RLHF). Strikingly, human raters preferred the outputs of a 1.3-billion-parameter InstructGPT model over those of the 175-billion-parameter GPT-3.
Instruction data usually follows a fixed template. The Stanford Alpaca project, for example, fine-tuned a 7-billion-parameter LLaMA model on roughly 52,000 instruction-following examples, each laid out as an instruction, an optional input and a response under fixed headings. The model learns that text after the response heading should be a helpful answer to what came before. Judging whether those answers are good is harder than measuring a loss, so the companion code includes a script that asks a larger model, run locally through Ollama, to act as a judge and score the responses.
Full fine-tuning updates every weight, which is expensive for big models. Parameter-efficient methods avoid this. The best known, LoRA, keeps the pretrained weights frozen and trains only small additional low-rank matrices, and the companion code covers it in an appendix. Freezing works because PyTorch only computes gradients for parameters that require them; calling requires_grad_(False) on part of a model removes those parameters from the backward pass. We will return to this when we fine-tune our own model.
A short case study: the same mechanism, different behaviour
To see how the stages shape behaviour, picture a small team that wants a model to answer customer questions about their software product. They start with a pretrained GPT-2-sized model. When they type "How do I reset my password?", the model happily continues the text, but it might produce another question, a forum signature or a rambling story, because on the web a question is often followed by more questions rather than an answer. The pretrained model is doing its one job perfectly well; it is simply continuing text in the style it learned.
The team then collects a few thousand examples of real support questions paired with good answers, formats each as an instruction followed by a response, and fine-tunes the model on them. Nothing in the architecture changes. The tokeniser, embeddings, Transformer blocks and output head are all identical. What changes is the distribution over next tokens: after the response marker, the model now puts high probability on helpful, direct answers. If storage is a concern because they want separate versions for several products, they can use LoRA and keep only a small set of extra weights per product.
This scenario captures the main lesson of the chapter. The capabilities of an LLM do not come from special-purpose machinery but from a single next-token predictor, a general architecture that can learn rich patterns, and a sequence of training stages that shape what the model has learned to predict.
Summary and what comes next
This chapter has given you the map for the rest of the book. We began with the single job of a language model: turning a context into a probability for every possible next token. The model computes a raw score, or logit, for each token in its vocabulary, softmax turns those scores into a probability distribution, and the chain rule shows that predicting the next token well is the same as modelling whole sequences. Generation is a loop around this prediction: choose a token, greedily or by sampling with controls such as temperature and top-k, append it, and predict again.
We then traced the history of language modelling. N-gram models estimate next-word probabilities by counting word sequences in a corpus, under the assumption that only the last few words matter. They are simple and fast but suffer from sparsity, short fixed windows and no notion of word similarity, and they gave us perplexity, the evaluation measure still used today. Neural language models introduced learned embeddings so that similar words share information, and recurrent networks such as LSTMs carried a hidden state through the text to remove the fixed window. Their bottleneck and, above all, their step-by-step computation limited how far they could scale. The Transformer replaced recurrence with self-attention, letting every token look directly at every other and allowing whole sequences to be processed in parallel. GPT models kept only the decoder, added a causal mask and trained on next-token prediction over vast amounts of unlabeled text. GPT-2 showed that scaling such a model brings general abilities that improve steadily with size; its smallest version, about 117 million parameters in the paper's own reporting and about 124 million in the usual recount, is the model we will build.
We saw that modern open-weight models remain close to GPT-2's decoder-only design, with refinements such as rotary position embeddings, RMSNorm, grouped-query attention and mixture-of-experts layers. Learning GPT-2 thoroughly therefore teaches you the common core of today's models. We laid out the pipeline that our model will follow: text is tokenised with byte-pair encoding, tokens and positions are embedded as vectors, a stack of Transformer blocks builds contextual representations, and an output head produces next-token probabilities. Finally, we outlined the three stages of creating a useful model: building the data pipeline and architecture, pretraining on unlabeled text, and fine-tuning for a task or for following instructions, possibly with efficient methods such as LoRA.
Every one of those stages will be written in Python with PyTorch. In the next chapter, "Python, NumPy and PyTorch Essentials", we install and set up a working environment, learn to create and reshape tensors, see how broadcasting lets tensors of different shapes work together, and use PyTorch's Dataset and DataLoader classes to feed data in batches. Automatic differentiation, the machinery that lets PyTorch compute gradients and train models for us, follows in Chapter 3, "Neural Networks and Gradient Descent". With those foundations in place, we can start building the pipeline one box at a time.
from collections import Counter, defaultdict
corpus = "the cat sat on the mat . the dog sat on the floor .".split()
pair_counts = defaultdict(Counter)
for prev, nxt in zip(corpus, corpus[1:]):
pair_counts[prev][nxt] += 1
def next_word_probs(prev):
counts = pair_counts[prev]
total = sum(counts.values())
return {w: c / total for w, c in counts.items()}
print(next_word_probs("the"))
print(next_word_probs("sat"))
import torch
vocab = ["mat", "floor", "sofa", "moon", "democracy"]
logits = torch.tensor([3.0, 2.2, 1.8, 0.1, -2.0])
probs = torch.softmax(logits, dim=0)
print("greedy:", vocab[torch.argmax(probs).item()])
torch.manual_seed(0)
for t in (0.5, 1.0, 1.5):
p_t = torch.softmax(logits / t, dim=0)
idx = torch.multinomial(p_t, num_samples=1).item()
print(f"temperature {t}: {vocab[idx]}")
import tiktoken
enc = tiktoken.get_encoding("gpt2")
ids = enc.encode("The cat sat on the mat.")
print(ids)
print([enc.decode([i]) for i in ids])
print(enc.decode(ids))
Key takeaways
- A language model does one job: it maps a context to a probability for every possible next token, using logits and softmax.
- Text generation is an autoregressive loop of predicting, choosing a token greedily or by sampling, appending it and repeating.
- N-gram models count word sequences; they are simple but suffer from sparsity, short windows and no notion of word similarity.
- Neural models added embeddings, and RNNs added a running hidden state, but sequential computation limited their scale.
- The Transformer uses self-attention to connect all tokens directly and train in parallel; GPT keeps only its decoder with a causal mask.
- Modern open models remain close to GPT-2, with refinements such as RoPE, RMSNorm, grouped-query attention and mixture-of-experts.
- Building a useful LLM involves building data and architecture, pretraining on unlabeled text, and fine-tuning for tasks or instructions.
Common mistakes
- Thinking an LLM looks up answers in a database or has separate modules for each task.: Remember that every output comes from repeated next-token prediction; abilities emerge from training data and fine-tuning.
- Assuming a token is always a whole word.: Tokens from byte-pair encoding are often subword pieces or include a leading space; inspect them with tiktoken.
- Believing the original Transformer was a GPT-style model.: The original Transformer was an encoder-decoder for translation; GPT uses only a decoder stack with causal masking.
- Expecting a pretrained model to behave like a helpful assistant.: Pretraining teaches continuation; instruction fine-tuning is what teaches the model to answer requests helpfully.
See the full ebook: Build a Large Language Model From Scratch