1.1What is an LLM? 📖 Book §1.1
IntuitionPicture the autocomplete on your phone, trained on a large share of the public internet and made big enough to keep track of whole paragraphs instead of a few words. That is close to what a large language model is. It is a neural network that reads a piece of text and outputs, for every possible next token, how likely it is to come next.
The word large means two things. The model has a huge number of parameters (the adjustable numbers that training changes), and it is trained on a huge amount of text. GPT-2, which we will rebuild, has 124 million parameters in its smallest version. GPT-3 has 175 billion.
The surprising part is how simple the training task is. Predicting the next word does not sound like a recipe for writing essays or code. But to predict the next word in millions of different texts, a model has to pick up grammar, facts, style and some reasoning patterns along the way. When we say an LLM "understands", we mean it handles text in ways that are coherent and fit the context. We do not mean it has human-like awareness.
PlayNext-word prediction game
Where LLMs sit in the AI family
Artificial intelligence is the umbrella term for machines doing tasks we associate with intelligence. Machine learning is the part of AI in which systems learn their behavior from examples instead of following hand-written rules. Deep learning is the part of machine learning that uses neural networks with many layers. LLMs are one application of deep learning, aimed at text. Because they create new content, they also count as generative AI.
An everyday example makes the difference between the layers clear. Here are three ways to build a spam filter:
| Approach | Who decides what matters? | Example |
|---|---|---|
| Hand-written rules (AI, no learning) | A programmer writes every rule | if "WINNER" in subject: spam |
| Traditional ML | An expert picks features; the model learns how much each one counts | count of "free", number of !, has a link → logistic regression |
| Deep learning | The network learns its own features from the raw text | raw email text → neural network → spam probability |
1.2Applications of LLMs 📖 Book §1.2
IntuitionMost useful language tasks can be written as text in, text out. Put an instruction and some input text into a prompt, and the answer is simply the text that should come next. A model that is very good at continuing text can therefore help with a surprising range of jobs:
Older NLP systems were usually built for one of these tasks each, with a separate model and a separate dataset. What changed with LLMs is that a single pretrained model can be pointed at many of them, either just by prompting it or after a short fine-tuning run.
Quick check1.3Stages of building and using LLMs 📖 Book §1.3
IntuitionWhy build an LLM yourself when good ones already exist? The main reason here is understanding: once you have coded every piece, nothing about these models is a black box. There are practical reasons too. A model you control can be adapted to your own domain, where custom models often beat general ones. It can keep sensitive data in-house, run on a laptop or phone (no server round trip, no per-request fees), and change only when you decide.
However it is built, an LLM goes through two stages:
- Pretraining. The model learns to predict the next token on an enormous, varied collection of ordinary text. The result is a foundation model (also called a base model). It can continue a half-written sentence and do simple tasks when shown a few examples, but it was never trained to follow instructions or answer questions directly.
- Fine-tuning. Training continues on a much smaller dataset made for one purpose. The two kinds we will build are classification fine-tuning (texts with class labels) and instruction fine-tuning (instructions paired with good responses).
Where do the labels come from?
Traditional supervised learning needs a person to attach a label to every example. Pretraining gets around that. If the task is "predict the next token", then the next token in the text is the label. Every position in every document becomes a free training example. This is called self-supervised learning, and it is the reason pretraining can use trillions of tokens.
| Input the model sees | Target (label) |
|---|---|
LLMs | learn |
LLMs learn | from |
LLMs learn from | raw |
LLMs learn from raw | text |
1.4Introducing the transformer architecture 📖 Book §1.4
IntuitionAlmost every modern LLM is a transformer, a design introduced in 2017 in the paper Attention Is All You Need. It was first built for machine translation, and it has two halves. The encoder reads the whole source sentence and turns each word into a vector that captures its meaning in context (an embedding). The decoder then writes the translation one word at a time. At each step it looks at the encoder's vectors and at the words it has already written.
Both halves are made of layers built around self-attention. This mechanism lets every token look at every other token it is allowed to see and decide how much each one matters to it. That is how a model can link "it" to the noun three sentences back. Attention is important enough to get its own chapter (Chapter 3), so for now just remember that it is the part that moves information between positions.
Two famous descendants: BERT and GPT
Researchers soon found that each half works well alone. BERT keeps only the encoder and is trained with masked word prediction: hide some words and recover them from the context on both sides. GPT keeps only the decoder and is trained to predict the next word from the left context alone. The widget lets you watch both at work.
PlayEncoder vs decoder explorer
BERT-style encoders are strong at understanding tasks such as sentiment, topic and toxicity classification, because every word's representation uses both sides of the sentence. GPT-style decoders are built for generation: translation, summaries, stories and code. GPT models trained only on text completion also turned out to be flexible in another way. They can do tasks just from how the prompt is written:
Text completion
The best way to learn is
→ by doing it yourself.
Zero-shot
Convert to past tense:
I swim =>
→ I swam
Few-shot
hot => cold
up => down
early =>
→ late
In the zero-shot setting the model gets only a description of the task. In the few-shot setting the prompt also contains a handful of solved examples. In neither case do the weights change: the model infers the task from the context. Fine-tuning, by contrast, actually updates the weights.
Quick check1.5Utilizing large datasets 📖 Book §1.5
IntuitionA model can only pick up patterns that appear in its training data, so pretraining corpora are both huge and varied: filtered web crawls, curated web pages, books, encyclopedias and code. Sizes are counted in tokens, the units a model reads. For English text, a token is roughly a word or a punctuation mark. With modern subword tokenizers, 100 tokens are about 75 words. (Chapter 2 builds tokenizers from scratch.)
GPT-3 is a well-documented example. Its creators mixed five sources and trained on 300 billion tokens drawn from them. The size of each corpus was not the only thing that mattered. Each source was given a weight, and that weight decided how often the model saw it.
PlayPretraining data scale
Two practical lessons follow. First, scale is expensive: pretraining a GPT-3-class model was estimated to cost millions of dollars of cloud compute. Second, you rarely need to pay that cost yourself. Many pretrained models are openly available, and a foundation model can be fine-tuned on a small dataset with modest hardware.
This course follows the same route. In Chapter 5 we pretrain a small GPT on a single short story, which runs on a laptop, to see the whole training process work. Then we load OpenAI's released GPT-2 weights into our own code and use them for the fine-tuning chapters.
Quick check1.6A closer look at the GPT architecture 📖 Book §1.6
IntuitionGPT strips the transformer down to its decoder. It has no encoder and no source sentence. Only a stack of decoder blocks reads the text so far and predicts what comes next. To generate a longer text it repeats that one step in a loop: predict a token, append it to the input, predict again. A model that feeds its own outputs back in like this is called an autoregressive model.
This design is simpler than the original transformer, but much bigger in practice. The 2017 transformer stacked 6 encoder and 6 decoder blocks. GPT-3 stacks 96 decoder blocks with about 175 billion parameters. Newer open models such as Llama keep the same decoder-only core with small changes, so everything you learn by rebuilding GPT carries over.
Emergent behavior
GPT models are trained only to predict the next token. Even so, sufficiently large ones can translate, correct spelling, classify sentiment and answer questions, often without any task-specific training. Abilities like these, which nobody trained for directly, are called emergent behavior. The usual explanation is that the training data already contains countless examples of translations, corrections and Q&A, and predicting such text well requires the model to absorb those skills. One model, many tasks.
Under the hoodA language model assigns a probability to a whole text by chaining next-token predictions. For a sequence of tokens $x_1, \dots, x_T$:
$$P(x_1, x_2, \dots, x_T) \;=\; \prod_{t=1}^{T} P\big(x_t \mid x_1, \dots, x_{t-1}\big)$$Pretraining adjusts the parameters $\theta$ so that the real next tokens get high probability. Equivalently, it minimizes the average negative log-probability (the cross-entropy loss you will compute in Chapter 5):
$$\mathcal{L}(\theta) \;=\; -\frac{1}{T-1}\sum_{t=2}^{T} \log P_\theta\big(x_t \mid x_{<t}\big)$$In code, building the self-supervised targets is a single shift. A batch of token IDs with shape gives inputs and targets of the same shape, offset by one position:
ids = [40, 588, 4077, 8887, 13] # token IDs for "I like green tea."
inputs, targets = ids[:-1], ids[1:] # predict ids[t+1] from ids[:t+1]
# inputs : [40, 588, 4077, 8887]
# targets: [588, 4077, 8887, 13] (same length, shifted left by one)
# Generation is the same idea run in a loop (greedy version, Chapter 4):
for _ in range(max_new_tokens):
logits = model(context) # [batch, tokens, vocab_size]
next_id = logits[:, -1, :].argmax(dim=-1, keepdim=True) # last position only
context = torch.cat([context, next_id], dim=1) # append and repeat
The IDs above are illustrative, not from a real tokenizer. The real GPT-2 tokenizer appears in Chapter 2, and generate_text_simple in Chapter 4.
1.7Building a large language model 📖 Book §1.7
IntuitionNow you know enough to read the map. The course builds a GPT-like model in three stages, and every chapter is one stop along the way:
- Stage 1 · Build. Turn text into training examples (Chapter 2), implement attention (Chapter 3), and assemble the full GPT architecture (Chapter 4). At the end you have a model that works mechanically but produces gibberish, because it has not learned anything yet.
- Stage 2 · Pretrain. Write the training loop, measure loss, generate samples, and control randomness during decoding (Chapter 5, plus training extras in Appendix D). Then load OpenAI's pretrained GPT-2 weights, a foundation model we did not have to pay to train.
- Stage 3 · Fine-tune. Specialize the foundation model, first into a spam classifier (Chapter 6, plus LoRA in Appendix E), then into an assistant that follows instructions (Chapter 7).
Interactive roadmap
How to use this course
Each chapter follows the same four-step rhythm. Use it, and especially do not skip the third step:
1 · Understand
Read the short sections on the chapter page. Every section starts with why, then shows how.2 · Play
Use the widgets. Each one isolates a single idea and has a "Try this" prompt with a question to answer.3 · Build
Open the chapter's lab notebook and fill in the TODO cells. Automatic checks tell you right away if your code is correct, with hints when it is not.4 · Prove
Take the chapter quiz, review the flashcards over the next days, and try the stretch challenges in the lab.The next stop is Appendix A, a hands-on PyTorch primer. If you already know tensors, autograd and training loops, skim its quiz and go straight on to Chapter 2.
Quick checkCommon pitfalls
Chapter quiz
16 questions covering every type you will meet in later chapters. Your first answer to each question counts toward your best score. After that you can retry freely.
Flashcards
Spaced repetition with Leitner boxes. A card you know moves to a box that is reviewed less often, and a card you miss goes back to box 1. Come back over the next few days for the cards that are due.
Cheat sheet
The two training stages
- Pretraining: next-token prediction on huge unlabeled text → foundation model
- Fine-tuning: smaller labeled data → classifier or assistant
- Self-supervised:
targets = inputsshifted by 1
Architectures
- Transformer (2017): encoder + decoder, built on self-attention
- BERT: encoder-only, masked words, sees both sides
- GPT: decoder-only, next token, left context only, autoregressive
Prompting settings
- Zero-shot: instruction only
- Few-shot: instruction + a few solved examples
- Neither one changes the weights
Formulas
- $P(x_{1:T}) = \prod_t P(x_t \mid x_{<t})$
- $\mathcal{L} = -\text{mean}_t \log P(x_t \mid x_{<t})$
- passes over a source $=$ share $\times$ total tokens $\div$ source tokens
Numbers worth remembering
- GPT-2 small: 124M params, vocab 50,257, context 1,024 tokens
- GPT-3: 175B params, 96 layers, trained on 300B tokens
- 100 tokens ≈ 75 English words
Shapes you'll meet next
- token IDs:
- embeddings:
- logits: