Understanding large language models

Before writing any code, we need a clear picture of the thing we are about to build. This chapter answers four questions. What is an LLM? How is it trained? What is the transformer, and why does GPT use only half of it? What is the plan for the rest of the course?

You will learn to

  • Explain what an LLM is and where it sits inside AI, machine learning and deep learning
  • Describe the two training stages (pretraining and fine-tuning) and why pretraining needs no labels
  • Contrast encoder models (BERT) with decoder models (GPT), and zero-shot with few-shot prompting
  • Reason about the scale of pretraining data and the effect of the data mix
  • Find your way around the three-stage plan that the rest of the course follows

Time & materials

1.1What is an LLM?

Intuition

Picture 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.

Play

Next-word prediction game

Interactive

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.

Nested fields: AI contains machine learning, which contains deep learning, which contains LLMs Four nested rounded rectangles. Outermost: artificial intelligence, example rule-based chess engines. Inside: machine learning, example a spam filter on hand-picked features. Inside: deep learning, example image recognition. Innermost: large language models, example GPT and Llama. Artificial intelligence e.g. rule-based chess engines, expert systems Machine learning learns rules from data, e.g. spam filter on hand-picked features Deep learning many-layer neural networks learn their own features Large language models GPT, Llama, … (text in → text out)
Figure 1.1 Each field is a special case of the one around it. This course lives in the innermost box, but it uses tools from every layer (PyTorch, gradient descent, neural network layers).

An everyday example makes the difference between the layers clear. Here are three ways to build a spam filter:

ApproachWho decides what matters?Example
Hand-written rules (AI, no learning)A programmer writes every ruleif "WINNER" in subject: spam
Traditional MLAn expert picks features; the model learns how much each one countscount of "free", number of !, has a link → logistic regression
Deep learningThe network learns its own features from the raw textraw email text → neural network → spam probability
Both ML rows still need labeled examples (emails marked spam or not spam). Pretraining an LLM, as we will see, does not.
Quick check

1.2Applications of LLMs

Intuition

Most 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:

TranslationRewrite a text in another language. "Translate to Spanish: …" → "…"
SummarizationCondense a long report into a few sentences. article → 3 bullet points
Classification & sentimentLabel a review, a ticket or an email. "Great battery!" → positive
Question answeringAnswer questions, possibly from documents you provide. contract + question → answer
Writing & editingDraft emails, stories, articles, and fix grammar. bullet notes → polished email
CodeWrite, explain and debug programs. "sort a list in Python" → code
Assistants & chatHold a conversation that combines all of the above. dialogue history → next reply
Specialist searchSift through medical or legal text and point to the relevant passages. corpus + query → passages

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 check

1.3Stages of building and using LLMs

Intuition

Why 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:

Two-stage training: pretraining then fine-tuning Huge unlabeled text feeds pretraining by next-token prediction, which produces a foundation model. The foundation model is then fine-tuned either on labeled texts with classes, producing a classifier, or on instruction and response pairs, producing an assistant. STAGE A · PRETRAINING STAGE B · FINE-TUNING Raw text web pages, books, encyclopedias, code no labels · 10⁹–10¹³ tokens Foundation model completes text, few-shot learn by predicting the next token Classifier "spam" / "not spam" Assistant follows instructions texts + class labels instruction → response pairs Chapter 6 Chapter 7
Figure 1.2 Pretraining is expensive and general. Fine-tuning is cheap and specific. One foundation model can be fine-tuned many times for different jobs.
  1. 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.
  2. 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 seesTarget (label)
LLMslearn
LLMs learnfrom
LLMs learn fromraw
LLMs learn from rawtext
One 5-word sentence gives 4 training examples, and nobody had to label anything. Chapter 2 builds exactly these pairs with a sliding window.
Quick check

1.4Introducing the transformer architecture

Intuition

Almost 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.

The original encoder–decoder transformer translating a sentence The English input "I like green tea" is preprocessed and read by the encoder, which outputs context vectors. The decoder receives those vectors and the partial Spanish output "Me gusta el", and predicts the next word "té". "I like green tea" tokenize + embed Encoder sees the whole input at once context vectors one per input token "Me gusta el" tokenize + embed Decoder sees the vectors + its own past words "té" English in → Spanish out, one word at a time
Figure 1.3 The original transformer, caught in the middle of a translation. The decoder has already written "Me gusta el" and now predicts "té". The next step would append "té" and predict "verde".

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.

Play

Encoder vs decoder explorer

Interactive

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 check

1.5Utilizing large datasets

Intuition

A 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.

Play

Pretraining data scale

Interactive

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 check

1.6A closer look at the GPT architecture

Intuition

GPT 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.

The autoregressive generation loop of a decoder-only GPT The current context "The cat sat on the" goes into the GPT decoder stack, which outputs a probability for every vocabulary token. One token, "mat", is picked and appended to the context, and the loop repeats. Context The cat sat on the GPT decoder blocks × N next-token probs mat floor sofa … mat append to the context and repeat
Figure 1.4 Decoder-only generation. Each step sees only what has been written so far. Chapter 4 builds the decoder stack, and Chapter 5 adds smarter ways to pick from the probabilities than "take the top one".

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 hood

A 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.

Quick check

1.7Building a large language model

Intuition

Now 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:

Play

Interactive roadmap

Interactive

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 check

Common 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 = inputs shifted 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: