The Whole Book on One Page¶
Every chapter, in order, in one scroll. This edition is here for the things a chapter page cannot do: searching the whole book with your browser's own find, printing it, or reading it straight through without clicking. Use the contents on the left to jump to any chapter or section.
It is a long page, carrying all 75 figures, so give it a moment on a slow connection. The ordinary way to read the book is chapter by chapter, starting at the preface, and there is also a PDF and an EPUB.
First draft: December 17, 2025. Last updated: October 2026.
Preface: Why This Book Exists¶
There's plenty of information available to learn about AI and LLMs. So why create another one?
Well, most either fall into one of three traps or lead you down a rabbit hole of tutorial hell.
Tutorial hell is a state of learning paralysis where you're constantly consuming content on how to code from others. You may feel as though you are learning, but you never build anything on your own. After running someone's code and getting a successful result, you feel good. Why did it work? Close your laptop and think about it, and you have no idea. You've been watching someone cook a hundred times, but you have not cooked anything yourself.
The three traps that lead there:
- Too shallow. You copy and paste the code and follow along. You produce an output, but you don't understand any of the decisions behind it, so the moment something breaks or changes, you're stuck.
- Too deep. These read like research papers, expect prior courses in linear algebra and calculus, and assume you already have a graduate-level background. Most readers bounce off in chapter two.
- Too demanding on hardware. The content can be great, but it assumes you have a modern GPU, a cloud computing account, and several dedicated weekends free, which rules out most people.
This book takes a different approach.
It's going to balance theory and code. There will be explanation so you can grasp what you're creating and why each piece is there. There will be code that you can run on your computer today.
Each chapter will be composed of an explanation with an analogy, followed by code that implements it and then a quick recap of the lesson. Nothing will be hand-waved. If there is code doing something, there will be a reason given in that chapter.
Today means on your computer. No GPUs or cloud providers needed. I have done this on a ThinkPad T14 Gen 1 (Intel Core i7, 32GB RAM, 2020). It's an old business laptop without a GPU. It took roughly 20-30 minutes to complete one full training run. So if it can run on my machine it will run on yours.
Python and PyTorch, that's it. No sign-ups.
Who Is This Book For?¶
Business students. You will be using AI tools on a weekly basis and will purchase them, oversee them or answer for them at some point in your career. You just want to understand what they are doing without a technical degree. I provided an image for each concept along with a real-life analogy and business scenario. All scripts are already coded. Just copy them, run them and understand what each line does. Then play with the values one at a time.
Beginners who learn by building. You know some Python, you're curious about AI, and using someone else's model isn't enough because you want to understand how it works. You want to go from zero to a working language model, line by line, without getting stuck in tutorial hell.
Instructors and professors. You want material ready for class, with concepts clear enough to teach, code that runs on a student's laptop in a single class session, and a structure that maps cleanly to a lecture. This book is designed for that. Every chapter has a lecture deck, a 15-minute assignment and a notebook that runs in a browser.
IT/IS professionals. You work with AI tools every day but want to understand what's happening inside them. You don't need a PhD for that, just a clear explanation of the architecture, a working example, and code you can read and modify.
Parents teaching their kids. If you want to show your child how AI works as well as how to use it, this book gives you a hands-on project you can work through together. Build something real, ask questions, and break it and fix it, because that is how learning sticks.
A Note on AI Assistance¶
This book was written by Truong (Jack) Luu. AI tools helped with writing plans, code drafts, and editing. All code was reviewed, edited, and tested by the author on a local machine. Every example in this book runs exactly as shown.
Truong (Jack) Luu jackluu.io
Introduction: Five Phases, One Loop¶
Before you write a line of code, it helps to know where the thing you are about to build sits. Artificial intelligence came in five waves, and each wave kept what worked and changed one idea. The model in this book belongs to the fourth wave, and it inherits almost everything from the second.
Figure I.1: Five waves of artificial intelligence. From the second wave onward, every one of them learns the same way.
Where this book sits¶
There are about four phases that I'll break down. Phase one was 1950 to roughly 1985. You wrote down a set of rules by hand. If you want to do X you will do Y. There were thousands of these rules that were being written down. ELIZA came out in 1966. It mimicked being a therapist by finding key words in your statement and asking you a question. It knew nothing but humans spoke to it as if it did. We still assume something understands what it's saying if it can speak in proper sentences.
Phase two was 1985 to 2011. We no longer wrote down the rule. By giving a computer 10,000 examples of emails and whether they were spam or not, we can allow it to figure it out on its own. This is where our math from the book comes into play. Computers only understand numbers. So you make a guess and see how far off you are and update your numbers. Later models use this technique.
Phase three was 2012-2016. More layers of numbers with more data to compute it on. An image classifier using this technique beat its competition by such a large margin that no one could dispute it in 2012.
Phase four was 2017-2023. Learning what comes next. Instead of classifying what something was it predicted what was next. Two things made this possible. One is taking all words and creating vectors. This allows us to group words together that have similar meanings to them in the vector space. Two is attention. Attention was introduced in 2017 and allows you to look at all previous words and weight their importance when predicting what will come next. The rest of this book will walk you through these concepts on a smaller scale.
The fifth phase is 2023 to today. Not much changed in the model itself. Give it some objectives and it can call functions and create a task list that it'll complete step by step. It's still predicting the next word, and that's what you're going to make in this book.
Table I.1: The five phases, and what changed at each one.
| Phase | Roughly | What changed | What the machine does |
|---|---|---|---|
| Rules | 1950 to 1985 | People write every rule | Matches patterns, follows conditions |
| Machine learning | 1985 to 2011 | Learn the rule from examples | Guess, measure the error, adjust |
| Deep learning | 2012 to 2016 | Far more layers and data | The same loop, much bigger |
| Generative AI | 2017 to 2023 | Produce the next piece, not a label | Embeddings and attention, same loop |
| Agentic AI | 2023 onward | Give the model tools and a goal | The same model, inside a system |
One loop, running for forty years¶
Every phase from the second onward runs the same three steps.
Figure I.2: The loop behind every model from the second phase onward.
It makes a prediction, then we measure how incorrect the prediction was. Then another process changes the weights to hopefully get a better prediction. And it does this over and over again millions of times. You will build all three parts. Predictions in Chapter 10, measuring error in Chapter 11 and changing weights in Chapter 13.
There is no step that asks if what is produced is truthful. The model is rewarded for producing text that fits the pattern of its training data. A made-up answer fits that pattern just as well as a true one. So you will see language models produce false statements with confidence. You cannot engineer your way out of this, since the loop only cares about fitting the pattern, and you will notice it happen when your own model writes made-up Shakespeare in Chapter 17.
A layer is a stack of small regressions¶
Once you draw a line of best fit on a scatter plot you've trained a model. You've found a slope and intercept, calculated how far off each point was and then found the slope and intercept that minimize that error. It's as simple as a guess, a measuring stick and finding the closest fit.
Neural networks just repeat this process over and over. Every node in a neural network will take the input into that layer multiply it by its own set of weights and sum them together. It'll also add a bias which acts as the intercept. This means we now have a slope for every input and an intercept for each unit. This means every node in a neural network is a regression. By multiplying the inputs with our set of weights we're doing this for hundreds of nodes at a time in one matrix multiplication. We can then chain these layers together to make a network. Nothing in this book will be harder than that but there is a lot more to it. In Chapter 3 we'll dive deeper into the matrices and in Chapter 8 we'll create a layer.
The four parts you are about to build¶
Follow one guess from a chatbot and you pass through four pieces, in this order.
- The dictionary. Words are turned into lists of numbers, positioned so that words used alike sit near each other. This is the embedding, covered in Chapter 5.
- The structure. Layers of numbers, each doing its small job and handing the result to the next. Attention lives here, in Chapters 6 through 10.
- The ruler. A single number saying how far the guess landed from the right answer. This is the loss, covered in Chapter 11.
- The messenger. The error is carried back through every layer, telling each weight which way to move. This is backpropagation, and it runs the training in Chapter 13.
Why build it by hand¶
Having a calculator is great if you know math. If you don't know how to do math then you won't know when the calculator returns an incorrect number. Because you would have no way of knowing that it was incorrect.
You can ask a language model to generate code for you, write you a memo or even tell you about itself. If you have not made one yourself, you won't be able to tell when it is incorrect or describe why it's wrong. At the end of this you will have created each component of a language model and been able to train it on your computer. Watch it decrease in error and see what it has to say for itself. It will no longer look like some fancy paragraph on your screen.
Further Reading¶
Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2017). ImageNet classification with deep convolutional neural networks. Communications of the ACM, 60(6), 84–90. https://doi.org/10.1145/3065386
Rosenblatt, F. (1958). The perceptron: A probabilistic model for information storage and organization in the brain. Psychological Review, 65(6), 386–408. https://doi.org/10.1037/h0042519
Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323, 533–536. https://doi.org/10.1038/323533a0
Weizenbaum, J. (1966). ELIZA: A computer program for the study of natural language communication between man and machine. Communications of the ACM, 9(1), 36–45. https://doi.org/10.1145/365153.365168
Module 1: Foundations¶
Figure M1.1: Foundations in the big picture.
In this first module, we set up our workspace and prepare the raw material for our language model. For business readers, imagine you are building an assistant to draft text in your company's house style, trained on the company's archive. Think of this module as data preparation. Before any system can find patterns, the text must be translated into numbers it can process.
In this module you will:
- Set up Python and PyTorch on your computer
- Understand what a language model does
- Learn how tensors work as the foundation for our math
- Build a tokenizer to chop text into manageable pieces
- Create embeddings that give those pieces mathematical meaning
Chapters¶
- Chapter 1: Setting Up Your Environment
- Chapter 2: What Is an LLM?
- Chapter 3: Tensors and PyTorch
- Chapter 4: Tokenization
- Chapter 5: Embeddings
Chapter 1: Environment Setup¶
Figure 1.1: Before you build, you set up your tools.
Your environment is the tools used to run the code. Installing your environment gives you everything you need to build and execute the model (Figure 1.1). After installation, the code functions in the same manner for you as it does here.
In this chapter you will:
- Install Python and open a terminal to run commands.
- Download the project code using Git.
- Set up an isolated workspace for your packages.
- Download the training dataset.
Words to Know
- Terminal: a text-based window where you type commands.
- Repository: a folder of code stored online.
- Virtual Environment: a separate toolbox for one project, so what you install for it stays out of your other projects.
- Package Manager: a tool that downloads and installs packages, the ready-made pieces of code a project uses.
In Business
Engineering teams agree on common standards for dev environments so they never have to deal with the "but it works on my machine" issue. If a team was building a house-style AI assistant to write emails, they would do the same. Thanks to virtual environments and locked-down package versions, new employees can begin contributing to the assistant right away, and code runs the same on laptops as it does on production servers.
Two Ways to Follow Along¶
This will work in your browser or on your local machine. Pick one below and you can always change later.
In your browser, no installation required. Each chapter page will have a "Run it in your browser" link at the top. This will launch the chapter as a Google Colab notebook. Colab allows you to run Python code using Google's computers for free. All you need is a Google account. Run the first cell to download the code for this project and the Shakespeare text. Then you can run each cell below it in order. If you use this option, skip Steps 1 to 6 and look over Steps 7 and 8 to see what your output should look like. Then continue on to Chapter 2.
On your local machine. Complete Steps 1 to 8 below. Once installed you will be able to run all the scripts in this book with one command whether you are connected to the internet or not.
Step 1: Install Python¶
Python is the programming language this entire tutorial uses, and we need version 3.10 or newer. You can download it from the official website (Figure 1.2).
Figure 1.2: Download the Python 3.13 installer.
Windows:
- Open your web browser and go to python.org/downloads
- Click the button to download Python 3.13.x.
- Run the downloaded
.exeinstaller. - Critical: On the first screen of the installer, tick the checkbox labeled "Add Python to PATH" at the bottom. PATH is a list of directories for the computer to search when running commands. If you leave the box unticked, Python will not be recognized when you type commands.
- Click "Install Now".
macOS:
- Open your web browser and go to python.org/downloads
- Click the button to download Python 3.13.x.
- Run the downloaded
.pkginstaller and follow the prompts.
Step 2: Open a Terminal¶
The terminal is where you will run your code.
Windows:
Press Win + R, type cmd, and press Enter. A black window appears with a blinking cursor.
macOS:
Press Cmd + Space to open Spotlight, type Terminal, and press Enter.
Verify your Python installation by running this command:
You should see Python 3.10 or newer printed to the screen. (On macOS, if python is not found, type python3 --version instead.)
Step 3: Install Git¶
Git downloads the project code from the internet. Figure 1.3 shows the download page.
Figure 1.3: Download Git to get the project files.
Windows:
- Go to git-scm.com/download/win
- Download the "64-bit Git for Windows Setup".
- Run the installer and click "Next" through every screen.
macOS:
Open your terminal and type git --version. If it is not installed, macOS will ask if you want to install the "Command Line Developer Tools". Click Install.
Verify Git is installed (open a new terminal window on Windows):
You should see a message confirming your Git version.
Step 4: Download the Project¶
Now download the project code with a single command.
Then move into the project folder:
Step 5: Create a Virtual Environment¶
Different projects need different versions of the same library, so a virtual environment gives this project its own isolated box of packages (Figure 1.4).
Figure 1.4: A virtual environment isolates your project's libraries.
Make sure your terminal is inside the build-llm-from-zero folder, then run:
Windows:
macOS:
You will see (venv) appear at the start of your terminal prompt. You must run the activate command every time you open a new terminal window.
Step 6: Install PyTorch and Dependencies¶
With the virtual environment active, install the required libraries using pip, Python's package manager.
First, install PyTorch (we use a CPU-only version):
Then install the other libraries:
Step 7: Download the Shakespeare Dataset¶
We will train our model to write in a specific style using a selection of Shakespeare's plays. (Dataset credit: the Tiny Shakespeare text comes from Andrej Karpathy's char-rnn project, https://github.com/karpathy/char-rnn)
$ python src/utils/download_data.py
Dataset ready: src/data/shakespeare.txt (1089 KB)
Dataset statistics:
Total characters : 1,115,394
Unique characters: 65
First 200 characters:
----------------------------------------
First Citizen:
Before we proceed any further, hear me speak.
All:
Speak, speak.
...
The text ships with the project, so this step checks it rather than downloading it. If the file were missing, the script would download it and check that it is exactly the same text the book was built from.
Step 8: Verify Everything Works¶
Run the setup verification script to confirm all pieces are ready:
$ python src/ch00_setup_check.py
Chapter 1: Checking your environment...
[OK] Python: 3.13.13
[OK] PyTorch: 2.6.0+cpu
[OK] NumPy: 2.5.3
[OK] Requests: 2.34.2
[OK] Shakespeare dataset found: 1,115,394 characters
[OK] Quick tensor test passed
All checks passed! You are ready to start Chapter 2.
If you see this, you are ready to begin.
Watch Out
If a script fails with ModuleNotFoundError: No module named 'torch', your virtual environment is not active. Run the activate command again (venv\Scripts\activate on Windows, source venv/bin/activate on macOS).
Key Takeaways¶
- You installed Python (the language), Git (code downloader) and PyTorch (math library), and you opened a terminal.
- A virtual environment keeps this project's packages isolated.
- Always activate your virtual environment before working on this project.
- Once the setup check passes, your environment is ready for the next step in our map.
Check Your Understanding¶
- What does a virtual environment do?
- How do you know if your virtual environment is active?
- What is the command to move into the project folder?
Assignment¶
Assignment 1: Read your setup check
About 15 minutes. You run one script and write no code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch00_setup_check.pyas it is. Copy everything it prints. - Read it. Count the lines that start with
[OK]. Next to each one, write a few words that say what the script checked. - Compare. Put your output beside the output printed in Step 8. Which version numbers are different on your computer? Which numbers are exactly the same as in the book?
- Explain it. In two or three sentences a manager could follow, say why a team runs a check like this before anyone starts work.
Hand in: your output, your note on each [OK] line, your answers to step 3, and your sentences.
Further Reading¶
The library you are typing into. This paper argues for the design of the tool this book uses, where you write the model as ordinary Python that runs line by line, so you can print a tensor or stop in a debugger, and still get the speed of compiled code underneath. That design is why the code in this book can be read top to bottom and still trains a real model.
Paszke, A., Gross, S., Massa, F., Lerer, A., Bradbury, J., Chanan, G., Killeen, T., Lin, Z., Gimelshein, N., Antiga, L., Desmaison, A., Köpf, A., Yang, E., DeVito, Z., Raison, M., Tejani, A., Chilamkurthy, S., Steiner, B., Fang, L., ... Chintala, S. (2019). PyTorch: An imperative style, high-performance deep learning library (arXiv:1912.01703). arXiv. https://doi.org/10.48550/arXiv.1912.01703
Note. The Tiny Shakespeare text used throughout the book comes from Andrej Karpathy's char-rnn project: https://github.com/karpathy/char-rnn{ .note }
Chapter 2: What Is an LLM?¶
Figure 2.1: What the whole system does, before we zoom in.
With our environment set up in the previous chapter, we turn to the model itself (Figure 2.1). A Language Model (LM) seems like a magic box that understands what you type, but it performs one specific, simple task.
In this chapter you will:
- Learn the single rule that drives all language models.
- See how models generate long answers one step at a time.
- Understand how reading data replaces human teachers.
Words to Know
- Token: one small piece of text, here a single character.
- Language Model: a system that predicts the next token in a sequence.
- Autoregressive: building an answer one piece at a time, feeding each new piece back in before predicting the next one.
- Parameters: the numbers inside the model that adjust during training.
Theory: The Next-Token Engine¶
Imagine you are texting a friend and you type: "I am so hungry, I could eat a". Before you finish, your phone suggests: horse. Or pizza.
Figure 2.2: The core task of a language model is guessing what comes next.
Your phone is doing next-word prediction (Figure 2.2), guessing what word is most likely to come next based on everything you typed so far. A Large Language Model (LLM) does the same thing. Given a sequence of tokens, it predicts what comes next. Everything else in this book builds a machine that can do this well.
How It Talks Back¶
If the model only predicts the next token, how does it write an essay? It predicts one token, adds it to the text, and predicts again, a loop called autoregressive generation.
- You type:
"What is the capital of France?" - The model predicts the next token:
"Paris". - That output is added to the input:
"What is the capital of France? Paris". - It predicts the next token:
" is". - And repeats until it decides to stop.
Figure 2.3: In autoregressive generation, each predicted token is added to the input.
The model never thinks about the whole answer at once (Figure 2.3). It keeps predicting the next piece, over and over, and the sentence builds up step by step.
What is a Token?¶
The smallest unit that our model will work with is called a token. This could be a word or a portion of a word or just one character.
In this book we will be working with characters as our tokens. So each character including spaces and punctuation is considered a token. We choose to work with characters because our vocabulary size is very small (65 characters total in our Shakespeare dataset). And it's easy to follow what each character means. Real models will use a portion of words called subwords instead of just characters. But the math is the same.
The Power of Self-Supervised Learning¶
When you want to make your model "Large", you give it millions of parameters. Parameters are just values in the model that we can adjust. We train our model by adjusting these values until it can generate decent responses.
There is a type of training where you don't need a teacher to tell the model if it's right or wrong. This is known as self-supervised learning.
Because we're working with language, we have the answer already. So if we have a sentence that says "Hello world", the model gets these practice questions automatically:
- See
H, predicte. - See
He, predictl. - See
Hel, predictl.
Figure 2.4: The text itself provides the practice questions.
Because no human labels are needed, you can train a model on millions of pages of raw text (Figure 2.4). The model reads the data and learns the patterns.
Try It: The Numbers Game¶
We can test next-character prediction on real data. If we see the letters "the ", what is the most likely next character in Shakespeare?
We wrote a tiny script to scan our training data and count every character that follows "the ".
$ python src/examples/ch02_next_char.py
What follows 'the ' in Shakespeare?
's': 573 times
'w': 459 times
'c': 448 times
'p': 426 times
'm': 376 times
This is what the model learns to do, but instead of counting by hand, it uses math to work out how likely each next character is.
In Business
A company that builds an AI assistant to draft emails in its own house style uses the same idea. The model trains on the company's archive of past writing and learns what character or word typically follows another, which is how the assistant picks up the company's voice and terminology.
Watch Out
It is easy to think the model "understands" the text. All it does is calculate the most probable next token from patterns in its training data.
Key Takeaways¶
- A language model predicts the next token.
- Autoregressive generation refers to feeding the model’s own outputs back as input.
- Tokens are segments of text; they could be characters or words.
- We use the raw text itself as the “answer key” in self-supervised learning.
- As you can see, everything here revolves around next-token prediction! The first stop on our map will cover the math and tools we use to create a language model.
Check Your Understanding¶
- What does a language model predict?
- Why is it called "autoregressive"?
- How does self-supervised learning differ from having a teacher grade the work?
Assignment¶
Assignment 2: New word, new guess
About 15 minutes. You change one word and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch02_next_char.pyas it comes. Cut and paste the five letters and counts. - Change one word. Locate the line
prefix = "the ". The prefix is what the program searches for. Replacethewithmyand keep the space before the closing quotation mark, so that your line looks likeprefix = "my ". Run the program again. - Compare. What letter is first now? Which letters appear in both groups? Think of one word Shakespeare could write after
mythat starts with the new first letter. - Explain it. In two or three sentences a manager could understand, explain why the most common next letter changed when you changed one word.
Hand in: both lists of five letters and counts, your answers to step 3, and your sentences.
Further Reading¶
One model, many jobs, no retraining. The researchers wanted to know if a model trained exclusively to predict the next word would learn capabilities nobody had trained it for. Because it was trained on such a broad, diverse swath of web pages, it started answering questions, summarizing, and translating with zero task-specific training when given a prompt that made those tasks obvious. That answered the architectural question of how to build a system for text generation in favor of a decoder architecture that predicts the next token. That's the model we cover in Chapter 10.
Memory, before attention. Sequential models read a sentence one word at a time and had mostly forgotten it by the end, due to the vanishing gradient as error flowed back through time steps. This work introduced a cell with gates that controlled what to remember, what to forget and what to output. Gate cells like this powered essentially all serious language applications for two decades. The cell poses the question of what the model should remember from earlier in the sentence. Attention later modeled the same concept using a different mechanism.
Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8), 1735–1780. https://doi.org/10.1162/neco.1997.9.8.1735
Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language models are unsupervised multitask learners [Technical report]. OpenAI. https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf
Chapter 3: Tensors and PyTorch¶
Figure 3.1: Tensors are the containers that carry data through every stage.
Like we learned in the last chapter we know what our language model needs to do. So we can begin creating (Figure 3.1). We need to convert text to numerical values but first we need something to store and manipulate these numerical values efficiently. Tensors are used to hold data and PyTorch allows us to perform calculations on these tensors. Your numbers may vary slightly depending on your computer or version of PyTorch.
In this chapter you will:
- Learn what a tensor is and how it stores data.
- See how tensor shapes represent different dimensions.
- Understand how matrix multiplication transforms data.
- Turn raw scores into probabilities using Softmax.
Words to Know
- PyTorch: a Python library (ready-made code) that does math on large sets of numbers very quickly.
- Tensor: a container of numbers, arranged as a list, a table, or a stack of tables.
- Shape: how big a tensor is in each direction, such as how many rows and how many columns.
- Matrix Multiplication: a way of multiplying two tensors that turns data from one shape into another.
- Softmax: a function that turns any numbers into probabilities that sum to 1.
Theory: The Data Containers¶
PyTorch is a Python library that allows us to compute mathematical operations on large arrays of numbers efficiently. If we didn't have PyTorch, training would take weeks to run instead of minutes because pure Python can't handle millions of computations fast enough.
Figure 3.2: Tensors can be 1D (a list), 2D (a table), or 3D (a stack of tables).
A tensor holds numbers: a list, a table, or a stack of tables (Figure 3.2). Programmers refer to a tensor as a multi-dimensional array. If you've ever worked with a spreadsheet, you already understand 2D tensors, and a 3D tensor is just a stack of spreadsheets.
In this book, we work mostly with 3D tensors. Their dimensions, or shape, represent:
- B = Batch size (how many sequences we process at once)
- T = Time (how many tokens in each sequence)
- C = Channel size (how many numbers we use to represent each token)
We write shapes like (B, T, C). For example, (32, 128, 128) means "32 sequences, each 128 tokens long, each token described by 128 numbers."
Matrix Multiplication as Data Transformation¶
Figure 3.3: Matrix multiplication transforms data from one shape to another.
You can use the matrix multiplication operation @ on tensors to make your neural network transform data. This is shown in Figure 3.3. If the inner dimensions match then you can multiply the tensors. For example (3, 4) @ (4, 5) = (3, 5).
If we say that (3, 4) means we have 3 students each with 4 test scores. And (4, 5) means 4 test scores each mapped to 5 skill ratings. We get (3, 5). So now we have 3 students each with 5 skill ratings.
Softmax: Turning Scores into Probabilities¶
Softmax is a mathematical function that converts any list of numbers (known as logits) to probabilities (Figure 3.4). The values produced are guaranteed to all be positive and sum to exactly 1.0. Softmax does this by taking the exponential of each number, which grows very rapidly and thus exaggerates the difference between numbers even more.
Figure 3.4: Softmax forces numbers into a 0-to-1 range where they total exactly 1.0.
Code: Basic Operations¶
The code below shows the basic PyTorch operations we will use.
| src/ch02_tensors.py (excerpt) | |
|---|---|
Run the file to see how PyTorch handles these:
$ python src/ch02_tensors.py
--- 1. Creating tensors ---
1D tensor: tensor([1., 2., 3., 4.])
shape: torch.Size([4])
2D tensor:
tensor([[1., 2., 3.],
[4., 5., 6.]])
shape: torch.Size([2, 3])
...
--- 2. Shapes and dimensions ---
x shape: torch.Size([2, 5, 8]) - (batch=2, time=5, channels=8)
...
3D matmul: torch.Size([2, 5, 8]) @ torch.Size([8, 4]) = torch.Size([2, 5, 4])
...
Softmax([1.0, 2.0, 3.0]) = [0.0900, 0.2447, 0.6652]
Sum = 1.0000
What just happened:
- Lines 2 and 5 created 1D and 2D tensors, printing their shapes.
- Line 7 looked at a 3D tensor with a shape of
(2, 5, 8), representing(Batch, Time, Channels). - Line 9 multiplied a 3D tensor by a 2D matrix. PyTorch did the same multiplication at once for every sequence in the batch. We call this batched matrix multiplication, and it lets us avoid writing repetitive code to do the step one sequence at a time (which would be slow in Python).
Shape Check
Table 3.1 shows the tensor shapes before and after matrix multiplication.
Table 3.1: Tensor shapes before and after matrix multiplication.
| Tensor | Shape | Meaning |
|---|---|---|
x |
(2, 5, 8) |
2 sequences, 5 tokens each, 8 numbers per token |
W |
(8, 4) |
Transformation weights: 8 inputs to 4 outputs |
y |
(2, 5, 4) |
2 sequences, 5 tokens each, now 4 numbers per token |
Try It
Open src/ch02_tensors.py, change logits = torch.tensor([1.0, 2.0, 3.0]) to [1.0, 2.0, 10.0], and run it. Notice how the highest number takes almost 100% of the probability after Softmax.
In Business
When we construct our house-style email assistant, the text information is stored in multi-dimensional arrays called tensors. Those mathematical operations we discussed are how it learns through massive amounts of data to identify patterns of your company's written voice.
Watch Out
A shape mismatch is the most common error in PyTorch. If you try to multiply (3, 4) and (5, 6), PyTorch will crash because the inner dimensions (4 and 5) do not match, so always check your shapes.
Key Takeaways¶
- A tensor is a container of numbers, which programmers call a multi-dimensional array.
- Shape
(B, T, C)= batch × time × channels, the standard convention in this book. @is matrix multiplication, and the inner dimensions must match.- Softmax turns any numbers into probabilities that sum to 1.
- PyTorch handles batches automatically using batched matrix multiplication, so we write no code that repeats the step for each sequence.
- Tensors are ready to hold our data, and the next stage in our map turns text into tokens.
Check Your Understanding¶
- What does the shape
(32, 128, 128)represent in our(B, T, C)format? - Why do the inner dimensions need to match in matrix multiplication?
- What is the difference between logits and probabilities?
Assignment¶
Assignment 3: One number, new shape
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch02_tensors.pyas it is. Copy the line of output that starts with3D matmul:. - Change one number. Find the line
W = torch.randn(8, 4).Wholds the transformation weights. It takes in 8 numbers for each token and gives back 4. Change the4to6and run the script again. - Compare. Which numbers in the
3D matmul:line changed? Which stayed the same? How many numbers describe each token now? - Explain it. In two or three sentences a manager could follow, say what the multiplication changed about the data and what it left alone.
Hand in: both 3D matmul: lines, your answers to step 3, and your sentences.
Further Reading¶
The library you are typing into. This paper argues for the design of the tool this book uses, where you write the model as ordinary Python that runs line by line, so you can print a tensor or stop in a debugger, and still get the speed of compiled code underneath. That design is why the code in this book can be read top to bottom and still trains a real model.
Paszke, A., Gross, S., Massa, F., Lerer, A., Bradbury, J., Chanan, G., Killeen, T., Lin, Z., Gimelshein, N., Antiga, L., Desmaison, A., Köpf, A., Yang, E., DeVito, Z., Raison, M., Tejani, A., Chilamkurthy, S., Steiner, B., Fang, L., ... Chintala, S. (2019). PyTorch: An imperative style, high-performance deep learning library (arXiv:1912.01703). arXiv. https://doi.org/10.48550/arXiv.1912.01703
Chapter 4: Tokenization¶
Figure 4.1: Tokenization in the big picture.
In the last chapter we learned how to use tensors to store our information. So now that we're moving on to the next part of our map (Figure 4.1), we need to convert our text into numbers. A language model cannot understand patterns in our text if it's not converted to numbers. Neural networks operate on mathematics so we have to represent our text as numbers. This chapter will cover how to make our tokenizer which will take our text and split it into smaller chunks and give each one a number.
In this chapter you will:
- Understand why neural networks need numbers
- Build a character-level vocabulary from the Shakespeare dataset
- Write functions to encode text into integers and decode it back
- Prepare the data for training by splitting it into two sets
Words to Know
- Token: one small piece of text, here a single character.
- Tokenizer: a translator that cuts text into tokens and gives each token a number.
Theory¶
Neural Networks Are Number Machines¶
Figure 4.2: A tokenizer turns each character into a number.
Neural networks aren't able to read. So how would you give them a string of characters such as "Hello"? They deal with arrays of numbers that they can multiply and add together. In order to give the neural network characters we have to turn them into numbers. This process is called tokenization (Figure 4.2).
You want to create some kind of dictionary that if the character a is the number 0 then it will always be 0. This is known as your vocabulary.
The Simplest Tokenizer¶
Text can be tokenized in many ways. You can have a dictionary for each word (tokenizing at the word level) or you can combine frequent characters like th.
We will be using the most basic form of tokenization which is at the character level. Every character that appears in our dataset will have its own corresponding integer.
Say our vocabulary was {a: 0, b: 1, c: 2}, then the word cab would be converted to [2, 0, 1].
The Shakespeare data has 65 unique characters. It has all upper case characters, lower case characters, space, line break and some punctuation and one number. If we assign each of these characters an ID from 0-64 we can convert any sentence in shakespeare to a list of integers.
In Business
If you’re training an assistant to generate text in your organization’s house style, decisions about tokenization can have ramifications. Character-level tokenization leads to longer sequences, while word-level tokenization leads to smaller sequences but requires an enormous vocabulary. Byte-Pair Encoding (BPE) is a compromise widely used in modern enterprise assistants. It merges frequently occurring character sequences into single tokens. We use character-level here because it simplifies the math, while our model learns from its archive (our Shakespeare dataset).
The Training and Validation Split¶
Figure 4.3: Hiding part of the data lets us test whether the model learned.
Once we encode all of Shakespeare into one long list of numbers, we split it into two piles (Figure 4.3):
- Training set (90%): The data the model studies to learn patterns.
- Validation set (10%): The data we hide from the model, used to test it later.
We withhold data so we can test whether our model has learned patterns that generalize to the rest of the text, or if it has simply memorized the passages we showed it during training. If a model does well on the training set but poorly on the validation set, we say it has memorized the training text. This is known as overfitting.
Watch Out
Our tokenizer knows nothing outside of the characters it saw during training. If you give it a number (1 or 2 for example), an emoji, or a Chinese character, Python will throw a KeyError since that character isn't part of our 65-character vocabulary.
Code¶
We write our tokenizer in Python, load the dataset, and encode it.
File:
src/ch03_tokenizer.pyRun it:python src/ch03_tokenizer.py
| src/ch03_tokenizer.py (excerpt) | |
|---|---|
The code does three things:
- Line 3 uses
set(text)to find every unique character in the entire text. - Line 3 uses
sorted()to put them in alphabetical order so the IDs stay consistent. - Lines 6 and 7 build two lookup tables, which Python calls dictionaries: one to go from character to ID (
char_to_id), and one to go back (id_to_char).
Figure 4.4: How the tokenizer processes the dataset.
The script processes the dataset step by step (Figure 4.4). Next, we write the translation functions:
| src/ch03_tokenizer.py (excerpt) | |
|---|---|
Line 3 converts a string (a piece of text) into a list of whole-number IDs, and line 7 converts them back into text.
Now we run the script to see what our 65 characters look like and to test a quick round-trip.
$ python src/ch03_tokenizer.py
!$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
...
--- Testing encode / decode ---
Original : 'Hello, World!'
Encoded : [20, 43, 50, 50, 53, 6, 1, 35, 53, 56, 50, 42, 2]
Decoded : 'Hello, World!'
Round-trip matches: True
--- Encoding the full dataset ---
What just happened:
- The script loaded over a million characters from the dataset.
- It found exactly 65 unique characters. Notice the space and newline characters at the start.
- It translated the string "Hello, World!" into a list of integers.
- It translated those integers back to prove no data was lost.
Finally, we encode the entire dataset into a PyTorch tensor and split it.
Training tokens : 1,003,854
Validation tokens: 111,540
Tokenizer ready! Ready for Chapter 5.
Try It¶
See how different inputs are converted into numbers. We wrote a short script that imports our tokenizer and encodes a few business phrases.
Try It
Open the terminal and run the example script. Notice how every letter, space, and punctuation mark is assigned a specific number from our vocabulary.
Key Takeaways¶
- Neural networks work with numbers. They can't directly work with text. That's why we need to convert text into numbers first.
- This process is called tokenization. We tokenize our texts as numbers based on a static vocabulary.
- We will be using a character-level tokenizer with a vocabulary of 65 characters.
encode()converts strings to lists of IDs.decode()converts IDs back to strings.- We divide our data into training data ("Learn from these") and validation data ("Test on these").
Check Your Understanding¶
- How come we need to turn our text into numbers to use with a language model?
- If we attempt to encode a character that wasn't in the training data using our character-level tokenizer, what will happen?
- Why do we need a validation set?
- How many unique characters are in our vocabulary?
Assignment¶
Assignment 4: Same word, new numbers
About 15 minutes. You change one word and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch04_tokenizer_demo.pyunaltered. Copy the three rows it outputs, which will be phrases with their lists of numbers. - Change one word. Locate the line
"URGENT!",. It's one of the three phrases we'll convert to numbers with this script. Replace the wordURGENTwithurgent, making it all lowercase letters, but leave the rest of the line intact, so it says"urgent!",. Run the script again. - Compare. Which numbers changed in the second row? Which did not, and what letter does it represent? Two numbers in your new row are also in the
invoicerow. What two letters do they represent? - Explain it. In two or three sentences someone who manages you would understand, explain why the model sees
URGENT!andurgent!are two different pieces of text when people reading them understand it's the same word.
Hand in: both sets of three rows, your answers to step 3, and your sentences.
Further Reading¶
Why real models do not use a character vocabulary. Chapter 4 assigns a unique token to every character. This keeps the vocabulary small and the code concise. Models used in production tokenize text into word pieces instead. Common words are not split, rare words are split into subwords, and no word is ever unknown. This paper describes the algorithm, which remains the basis of the tokenizers included with modern models today.
Sennrich, R., Haddow, B., & Birch, A. (2015). Neural machine translation of rare words with subword units (arXiv:1508.07909). arXiv. https://doi.org/10.48550/arXiv.1508.07909
Chapter 5: Embeddings¶
Figure 5.1: We have IDs, and now each one gets a learned vector.
In the previous chapter, we turned text into tokens (Figure 5.1), but tokens are arbitrary numbers. To predict what comes next, the model needs to understand how characters relate to each other. In this chapter you will:
- Map simple token IDs to large vectors of numbers.
- Learn how these vectors capture meaning as coordinates.
- Add position information so the model knows the order of characters.
Words to Know
- Vector: A list of numbers that works like coordinates on a map, giving a token its place among the others.
- Embedding: A lookup table that gives each token ID its own vector.
Theory¶
The Problem with IDs¶
Figure 5.2: Token IDs are arbitrary labels.
After tokenization, we have our tokens as integers: A=13, B=14, a=39. The issue with using these numbers directly in our neural network is shown in Figure 5.2. Our neural network learns by finding numbers and multiplying them by each other. So it would see Z (token 38) as roughly three times as large as A (token 13). It might learn that Z is more important than A simply because of how we assigned token values.
Similar to an employee ID number they aren't five times as much of an employee just because their number is 105 and someone else's is 21. We need to convert these values into something our "Numbers Machine" can learn correlations from.
Vectors as Coordinates of Meaning¶
Figure 5.3: An embedding table maps each ID to a vector of numbers.
We fix this by using a lookup table known as an embedding (Figure 5.3). For each token ID we assign a vector which is just a set of decimals also known as floating-point numbers. Our model will have 128 floats per character.
Now when our model sees 39 for the letter a it will instead see [0.55, 0.03, -0.89, ...]. We can think of these 128 floats as coordinates, and characters that appear in similar contexts will gradually be moved closer together in this 128-dimensional space during training. Our net will understand that capital and lowercase versions of a letter behave similarly, so their vectors become similar. This is something our model learns.
Position Embeddings¶
Figure 5.4: The final representation combines what the token is with where it sits.
There is also an issue with our current model in that it reads all of the characters simultaneously. There is no way for our model to distinguish between "cat" and "act". They are made of the same characters.
The answer is to create a second lookup table called the positional embedding (Figure 5.4). Similar to before, we will look up a row in this table based on what position the character is in the sequence. We don't care about the token ID for this table. So position 0 will have a 128-number vector assigned to it. Position 1 will have another vector and so on.
Now that we have our token embedding and positional embedding, we will just add them together. Our network will learn to represent the information of what character this is and what position it is at using these 128 numbers. Since we now have a way to represent the character and position we have finished our Embeddings block from Figure 5.1. Now we have an array of numbers to feed into the next block.
In Business
When you build an assistant that writes in your company's house style, embeddings turn your archive into a map of meaning. Token embeddings capture the vocabulary, while the position embeddings give the model the order of the characters, which is what lets it pick up the shape of an invoice or a polite greeting.
Code¶
We use src/ch04_embeddings.py to create and combine these two tables.
| src/ch04_embeddings.py (excerpt) | |
|---|---|
When we run it, the script prints this:
$ python src/ch04_embeddings.py
--- 2. Looking up embeddings ---
Input token_ids shape : torch.Size([2, 5])
Token embeddings shape: torch.Size([2, 5, 128])
(B=2, T=5, C=128)
...
--- 3. Positional embeddings ---
Position indices: [0, 1, 2, 3, 4]
Position embeddings shape: torch.Size([5, 128])
--- 4. Combining token + position embeddings ---
Final x shape: torch.Size([2, 5, 128])
(B=2, T=5, C=128)
What just happened:
- Line 1 created a lookup table for the 65 characters in our vocabulary.
- Line 2 translated a batch of token IDs into their embedding vectors.
- Line 3 created a second lookup table for the sequence positions.
- Line 6 added the token and position vectors to create the final input
x.
Shape Check: Table 5.1 shows the dimensions of our data structures.
Table 5.1: Tensor shapes before and after the embedding layer.
| Variable | Shape | Meaning |
|---|---|---|
token_ids |
[B, T] |
Batch size by Time (sequence length). |
token_embeddings |
[B, T, C] |
C is the embedding dimension (128). |
position_embeddings |
[T, C] |
One vector per position. |
x |
[B, T, C] |
The combined input for the model. |
Try It¶
Try It
In src/ch04_embeddings.py, add one more token ID to each row of token_ids (any number from 0 to 64) and change T from 5 to 6. Run the script again. The output shape grows from [2, 5, 128] to [2, 6, 128], but the parameter counts stay exactly the same. The lookup tables do not care how much text you process at once.
Watch Out
A common mistake is trying to look up a token ID that is not in the vocabulary. If your vocab_size is 65, the valid IDs are 0 to 64. Passing an ID of 65 will crash the program with an "index out of bounds" error.
Key Takeaways¶
- Token IDs are arbitrary labels and cannot be used directly for math.
- Embeddings are learned lookup tables that map token IDs to vectors.
- These vectors act as coordinates that capture relationships and meaning.
- Positional embeddings are added to tell the model the order of the characters.
Check Your Understanding¶
- Why do neural networks struggle with raw token IDs?
- How many numbers make up a single character's embedding vector in our model?
- Why do we need positional embeddings in addition to token embeddings?
- Does the size of the embedding table depend on the batch size?
Assignment¶
Assignment 5: Bigger ID, bigger numbers?
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch04_embeddings.pyas it is. Copy the line that starts withFirst token's embedding. It shows the first 8 of the 128 numbers for the first token. - Change one number. Find the line
token_ids = torch.tensor([[3, 14, 7, 2, 50], [10, 22, 45, 1, 8]]). These are ten token IDs. Change the first one,3, to38, so the line starts withtoken_ids = torch.tensor([[38, 14,. Run the script again. - Compare. Did the 8 numbers change? Are they bigger, now that the ID is bigger? Did any shape, or any count under
--- Summary ---, change? - Explain it. In two or three sentences a manager could follow, say what the token ID is used for here, and whether the size of the ID matters.
Hand in: both First token's embedding lines, your answers to step 3, and your sentences.
Further Reading¶
Meaning becomes geometry. If every word gets its own ID number, the model learns nothing from the numbering, and "king" sits as far from "queen" as it does from "toaster". This paper trained a deliberately cheap prediction task so that words used in similar company ended up with similar vectors, and did it fast enough to run on billions of words. Embeddings, the subject of Chapter 5, start here, and so does the vector search behind modern recommendation and retrieval.
Mikolov, T., Chen, K., Corrado, G., & Dean, J. (2013). Efficient estimation of word representations in vector space (arXiv:1301.3781). arXiv. https://doi.org/10.48550/arXiv.1301.3781
Module 2: Building the Model¶
Figure M2.1: Building the Model in the big picture.
Our data is ready, so we now build the engine. In business terms, this means constructing the logic pipeline that processes information for your house-style writing assistant. We will build the transformer architecture piece by piece, focusing on how attention allows the model to understand context.
In this module you will:
- Build self-attention so words can look at each other
- Expand to multi-head attention for multiple perspectives
- Add feed-forward layers to process what the attention found
- Combine these into a complete transformer block
- Stack the blocks into the full GPT architecture
- Enforce causal language modeling so the model cannot cheat
Chapters¶
- Chapter 6: Self-Attention (Single Head)
- Chapter 7: Multi-Head Attention
- Chapter 8: Feed-Forward and Norms
- Chapter 9: The Transformer Block
- Chapter 10: The Full GPT Architecture
- Chapter 11: Causal Language Modeling
Chapter 6: Self-Attention (Single Head)¶
Figure 6.1: Attention builds context by looking across the sequence.
Chapter 5 gave our tokens meaning through embeddings, but reading one word at a time is not enough. To understand "it" in "the trophy didn't fit in the suitcase because it was too big", you have to connect "it" back to "trophy". In this chapter you will:
- Learn how tokens "look" at each other to build context.
- Use the Query, Key, Value (QKV) system to find relevant information.
- See how attention is a weighted average of numbers.
- Apply a causal mask to hide the future.
Words to Know
- Self-Attention: The step where each token looks at the tokens before it and decides how much each one matters to its own meaning.
- Query (Q): A list of numbers that says what a token is looking for.
- Key (K): A list of numbers that says what a token has to offer.
- Value (V): A list of numbers holding the information a token passes on when it is picked.
- Causal Mask: A filter that hides the tokens that come later, so a token sees only itself and the past.
Theory¶
The Problem: Context Matters¶
If a model only considers one token at a time, it has no memory, so it cannot connect subjects to verbs or adjectives to nouns. Every token needs to "look at" the other tokens and decide which ones matter most to its own meaning.
The QKV System¶
Self-attention solves this using three vectors for every token:
- Query (Q): What am I looking for?
- Key (K): What do I offer?
- Value (V): What information do I actually contain?
Think of this as a party. You want to meet with someone that knows about marketing (Query). A person walks up to you and has Marketing Director on their name tag (Key). They match so you talk to them and learn from their knowledge (Value).
In our model, each token will generate its own Q, K, and V vectors. By taking their embedding and multiplying by weight values they can be used to look for information as well as provide it.
Attention is a Weighted Average¶
Figure 6.2: Token 5 blends the values of tokens 0 to 5.
Since attention is a weighted average (Figure 6.2), when calculating the final value of token 5 we take a mix of all tokens that it has access to. There isn't a "best" token chosen.
We will take all of our Queries and multiply them by all of our Keys (q @ k.transpose) to give us an attention score for each token pairing. Then we divide by sqrt(head_size) (head size being the size of our attention heads which in this case is 32). This will keep our numbers small. After this we use softmax to normalize these numbers into percentages (weights) that sum to 1.0 (or 100%).
Token 5 may produce weights that look something like this for the following example (Figure 6.3). Keep in mind these weights have been rounded for display, so they add up to about 100% (100.1%):
- Token 0: 19.9%
- Token 1: 20.4%
- Token 2: 12.2%
- Token 3: 12.1%
- Token 4: 21.4%
- Token 5: 14.1%
Figure 6.3: Token 5's attention weights from an untrained head on random input.
Token 5's final output is 19.9% of the value of token 0, plus 20.4% of the value of token 1, and so on for all six tokens. The "Numbers Machine" builds context by blending the numbers of the most relevant past tokens. On our map (Figure 6.1), gathering context in this way completes the "Attention" stage.
The Causal Mask¶
Figure 6.4: A lower triangular mask lets each token see only itself and the past.
Because the model processes all tokens at once, token 5 could see token 6. When training we would not want this as token 5 would be able to cheat , because token 5 would copy the answer from the future and would not learn to predict it.
So we apply a causal mask to the scores with a triangular pattern of negative infinities (See Figure 6.4). This is done before applying the softmax function. As we know softmax will convert -infinity into exactly 0.0. Token 5 will pay 0% attention to tokens 6, 7, 8, and 9 and can only see itself and the past.
In Business
A simple keyword search over a customer support chat treats every word independently. A system with self-attention can connect the word "refund" in message 4 back to the "broken screen" mentioned in message 1, so it has the full conversation history in view when it generates a reply in the company's house style.
Code¶
Figure 6.5: Q and K produce the masked weights, which then multiply V.
We use src/ch05_self_attention.py to build the SingleHeadAttention class (Figure 6.5).
Running the script prints the attention weights:
$ python src/ch05_self_attention.py
--- Attention weights (what token 5 attends to) ---
Token 5 attends to tokens 0..5 (future tokens masked):
token 0: 0.199 #####
token 1: 0.204 ######
token 2: 0.122 ###
token 3: 0.121 ###
token 4: 0.214 ######
token 5: 0.141 ####
token 6: 0.000
token 7: 0.000
token 8: 0.000
token 9: 0.000
Self-attention done! Ready for Chapter 7.
What just happened:
- Lines 1 to 3 created independent Query, Key, and Value vectors.
- Line 7 computed the attention scores between all tokens.
- Line 10 masked the future tokens (notice tokens 6 to 9 have exactly 0.000 weight).
- Line 17 created the output (for example, token 5 created its output by taking a weighted average of tokens 0 through 5).
Shape Check: Table 6.1 lists the shapes of the attention variables.
Table 6.1: Tensor shapes during the self-attention calculation.
| Variable | Shape | Meaning |
|---|---|---|
q, k, v |
[B, T, head_size] |
Queries, Keys, and Values. head_size is 32. |
scores |
[B, T, T] |
Attention scores between every pair of tokens. |
weights |
[B, T, T] |
The softmax probabilities (summing to 1 per row). |
out |
[B, T, head_size] |
The final context-aware output vectors. |
Try It¶
Try It
Remove the scale division in the demo at the bottom of src/ch05_self_attention.py by changing scale = HEAD_SIZE ** -0.5 to scale = 1.0. Run it again. Notice how the weights become much more extreme: token 4 rises from 0.214 to 0.383, and tokens 2 and 3 fall to about 0.015. Without the scaling, most of the weight piles onto a few tokens.
Watch Out
Be careful with the transpose step, because we only want to swap the last two dimensions (Time and head_size) to compute the dot product properly. If you use .T, it might flip the Batch dimension too and crash your shape calculations, so always use .transpose(-2, -1).
Key Takeaways¶
- Self-attention builds context by letting tokens "look" at other tokens.
- The QKV system works like a search engine, where Queries match with Keys to retrieve Values.
- Attention is a weighted average of the Values.
- A causal mask sets future scores to negative infinity so the model cannot cheat.
Check Your Understanding¶
- What is the difference between a Query and a Key?
- Why do we divide the attention scores by the square root of the head size?
- What happens to a score of negative infinity when passed through softmax?
- Why is the causal mask necessary for a language model?
Assignment¶
Assignment 6: New numbers, same mask
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch05_self_attention.pyas it is. Copy the ten weights it prints for token 5. - Change one number. Near the bottom of the file, find
torch.manual_seed(42). The seed fixes the random starting numbers, so every run prints the same weights. Change42to any whole number you like and run the script again. - Compare. Which of the ten weights changed? Which ones did not? What do the weights for tokens 0 to 5 add up to now?
- Explain it. In two or three sentences a manager could follow, say why four of the rows print the same value under any seed.
Hand in: both sets of ten weights, your answers to step 3, and your sentences.
Further Reading¶
The first attention. Translation models of the day read the whole source sentence, squeezed it into a single fixed vector, and wrote the translation from that. Long sentences lost too much in the squeeze, so this paper let the model look back over every input word and decide, at each output word, which ones mattered. That weighted look-back is attention. Three years later the Transformer kept this idea and threw out everything around it.
The architecture this book builds. Reading a sequence one step at a time is slow, because step 500 cannot start until step 499 has finished, and distant words stay hard to connect. This paper removed the step-by-step reading and kept only attention, plus a note of each token's position. Every token can then be processed at once, and that made training on very large amounts of text practical. The model you build in Chapters 6 to 10 is this design, made small.
Bahdanau, D., Cho, K., & Bengio, Y. (2014). Neural machine translation by jointly learning to align and translate (arXiv:1409.0473). arXiv. https://doi.org/10.48550/arXiv.1409.0473
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention is all you need (arXiv:1706.03762). arXiv. https://doi.org/10.48550/arXiv.1706.03762
Chapter 7: Multi-Head Attention¶
Figure 7.1: We run multiple attention heads at the same time to gather richer context.
In Chapter 6, we built one attention head, which acts as a single "reader" scanning the text. But one reader is rarely enough to catch everything. In this chapter you will:
- Run multiple attention heads in parallel.
- Understand how different heads learn to track different patterns.
- Concatenate their outputs into a single rich representation.
Words to Know
- Multi-Head Attention: Running several attention heads at the same time, so the same text is read in several different ways.
- Concatenation: Joining several lists of numbers end to end to make one longer list.
- Projection: A final step that blends the heads' joined outputs into one list of numbers for each token.
Theory¶
One Reader Isn't Enough¶
Figure 7.2: Each head reads the same input through its own filters, and their outputs are concatenated and projected.
When you read a sentence, you track multiple things at once:
- Who is the subject?
- What action is happening?
- What is the tone, serious or sarcastic?
A single attention head can only "look" for one kind of pattern at a time. Multi-head attention fixes this by running several heads in parallel (Figure 7.2). Think of it as a team of readers, each highlighting different details, who then combine all their notes.
How It Works¶
Multi-head attention repeats the mechanism from Chapter 6:
- Run 4 independent attention heads (each one a
SingleHeadAttentionfrom Chapter 6) on the same input. - Each head produces an output of 32 numbers (
head_size). - Glue (concatenate) all 4 outputs together:
4 heads × 32 numbers = 128 numbers. - Apply a final projection, one more step that blends them.
Because each head starts with different random weights (its own Q, K, and V filters), no two heads ever see the text the same way, and training pushes them further apart.
Why Four Heads and Not One Big One¶
Four readers sound expensive, and people are often surprised by what they cost.
A head's filters are sized by its head_size, not by the full 128 channels. Split 128 channels across four heads and each head gets filters that are a quarter as wide. Multiply it out and the totals match exactly:
| src/examples/ch07_head_budget.py | |
|---|---|
$ python src/examples/ch07_head_budget.py
4 heads of 32: 49,152 numbers
1 head of 128 : 49,152 numbers
Same budget: True
Four points of view cost the same as one, so every model in this family uses many heads.
Do the Heads Really Differ?¶
We can check whether they differ on the model you will train in Chapter 13.
The script below loads the trained weights, feeds in a real line of Shakespeare, and prints how much attention the last character pays to each earlier character, one row per head.
| src/examples/ch07_heads_differ.py (excerpt) | |
|---|---|
$ python src/examples/ch07_heads_differ.py
Prompt: "JULIET: O Romeo"
Attention paid by the last character, one row per head:
J U L I E T : _ O _ R o m e o
head 0: 0.02 0.04 0.01 0.06 0.03 0.04 0.04 0.02 0.06 0.04 0.05 0.04 0.11 0.38 0.07
head 1: 0.02 0.02 0.03 0.03 0.04 0.08 0.12 0.06 0.05 0.07 0.02 0.10 0.16 0.14 0.06
head 2: 0.04 0.07 0.04 0.06 0.05 0.11 0.04 0.06 0.09 0.07 0.07 0.06 0.09 0.09 0.06
head 3: 0.03 0.02 0.01 0.05 0.05 0.03 0.03 0.05 0.04 0.04 0.05 0.08 0.12 0.25 0.14
Sharpest focus per head: 0->'e' (0.38) 1->'m' (0.16) 2->'T' (0.11) 3->'e' (0.25)
Head 0 is paying 0.38 of its attention to the character just before the end. The rest it hardly cares about. Head 3 kind of does this as well but not as pronounced. It's splitting its attention between e and the final o. Head 1 shares its attention across the colon, the m and the e. Head 2 pays very little attention to any single character with the largest weight being 0.11 and the smallest being 0.04 which is almost uniform.
So we see that our heads are acting differently but not as nicely as you may have heard. One is sharp, one is more smooth. One is spread out and one is not doing much of anything. In a trained model, some heads do very little. No one made them act this way and we can't promise that head 1 is the "grammar head". These are just 4 different attention heads with their initial values generated by a seed.
Watch Out
You may be tempted to tell yourself a story about what each head is doing: one head is tracking nouns, another is tracking periods. Sometimes, a head really is nicely interpretable like that and researchers have found some in big models. Often it isn't, though, as head 2 makes clear. See the numbers before you weave your tale.
The Output Projection¶
Once the 4 heads are concatenated, we feed the 128 numbers through one last linear layer. This is called the proj layer.
Why do we have this extra layer? Each head may find duplicate information. The projection layer learns that if head 1 and head 3 both found the same pattern, it should give it more weight. And if head 2 is unsure, the projection layer learns to ignore it. This will mix the 4 separate perspectives into a single context vector of 128 numbers. Now that we have the projection in place, the "Attention" stage of our map is complete (Figure 7.1).
Another option would have been to simply take an average of the 4 heads instead of gluing them together. If we did this we would have 32 numbers instead of 128. The problem with doing this is head 0 has a sharp focus on one character while head 2 has a flat spread. If we average these they'll both have some kind of average attention to some characters. By gluing the heads together we allow each head to provide its answer and the projection will learn how much to weight each head's answer.
In Business
Figure 7.3: Multi-head attention gathers different perspectives.
Imagine training an assistant to write emails in your company's house style. You don't just look for one pattern. You monitor tone, formatting, and word choice (Figure 7.3). Multi-head attention does the same thing, but asks 4 different "departments" to analyze the text, before producing a cohesive executive summary.
Code¶
Figure 7.4: The heads run in parallel, get concatenated, and projected.
We use src/ch06_multihead_attention.py to build the MultiHeadAttention class (Figure 7.4).
| src/ch06_multihead_attention.py (excerpt) | |
|---|---|
Running the script compares one head with four:
$ python src/ch06_multihead_attention.py
--- Comparing one head vs multi-head ---
Single head output shape: torch.Size([2, 10, 32]) (head_size=32)
Multi-head output shape: torch.Size([2, 10, 128]) (C=128)
Multi-head output has 4x more channels - it sees 4 perspectives at once.
Multi-head attention done! Ready for Chapter 8.
What just happened:
- Line 2 ran 4 independent attention heads at the same time.
- Line 2's result is that each head produced an output with 32 channels.
- Line 5 concatenated them into 128 channels (the original embedding dimension).
- Line 8 applied the projection, which blends the 128 channels and keeps the shape of the input. The same line also applied dropout, which Chapter 14 explains.
Shape Check: Table 7.1 lists the shapes as the data passes through the heads.
Table 7.1: Tensor shapes during the multi-head attention step.
| Variable | Shape | Meaning |
|---|---|---|
head_outputs |
4 × [B, T, 32] |
A list of outputs from the 4 heads. |
out (after cat) |
[B, T, 128] |
The 4 outputs joined end-to-end. |
out (final) |
[B, T, 128] |
The blended representation, ready for the next step. |
Try It¶
Try It
Edit src/utils/config.py to use 8 heads instead of 4. Set n_heads = 8. Run the script again. Pay attention to how head_size is now automatically set to 16 to keep the final concatenated size at 128 (8 × 16 = 128). We can have more viewpoints, but with less granularity within each one.
Watch Out
Your embedding dimension (n_embd) has to be divisible by your number of heads (n_heads) for multi-head attention to operate cleanly. Setting n_embd = 128 and n_heads = 5 will crash the program, as it won't be able to cleanly divide the channels.
Key Takeaways¶
- Multi-head attention runs several single-head attention modules in parallel.
- Splitting the channels across heads costs nothing: four heads of 32 hold the same 49,152 numbers as one head of 128.
- The heads do end up different, but not in a tidy way. In our trained model one head is sharp, one is soft and one is close to flat.
- The outputs are concatenated, not averaged, so that no head's answer is diluted by the others before the projection can weigh it.
- A final linear projection blends the separate perspectives.
- The output shape
[B, T, C]is exactly the same as the input shape, so layers stack easily.
Check Your Understanding¶
- Why is one attention head not enough to understand complex text?
- If
n_embd = 256andn_heads = 8, what is thehead_size? - Four heads of 32 hold the same number of weights as one head of 128. Why does splitting cost nothing?
- Why do we concatenate the heads rather than average them?
- In the run above, head 2's attention was almost flat. What does that tell you about the claim that each head learns its own linguistic role?
- What is the purpose of the final projection layer?
Assignment¶
Assignment 7: Same heads, new word
About 15 minutes. You change one word and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch07_heads_differ.pyas it is. Copy the last line it prints, the one that startsSharpest focus per head. - Change one word. Near the top of the file, find
PROMPT = "JULIET: O Romeo". The prompt is the line of text the model reads. ChangeRomeotolove, keep the quotation marks, and run the script again. - Compare. Which character does each head focus on most now? Which heads pick the character just before the last one in both runs? Which two heads have the smallest numbers in both runs?
- Explain it. In two or three sentences a manager could follow, say how the four heads differ, and why it is worth testing a second prompt before you say what job a head does.
Hand in: both Sharpest focus per head lines, your answers to step 3, and your sentences.
Further Reading¶
The architecture this book builds. Reading a sequence one step at a time is slow, because step 500 cannot start until step 499 has finished, and distant words stay hard to connect. This paper removed the step-by-step reading and kept only attention, plus a note of each token's position. Every token can then be processed at once, and that made training on very large amounts of text practical. The model you build in Chapters 6 to 10 is this design, made small.
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention is all you need (arXiv:1706.03762). arXiv. https://doi.org/10.48550/arXiv.1706.03762
Chapter 8: Feed-Forward and Norms¶
Figure 8.1: With attention built, we now process that context.
While attention (from Chapter 7) lets a token gather information from its neighbors, gathering information is only half the job. The token still needs to process that information and decide what to do with it. In this chapter you will:
- Build a feed-forward network to process context.
- Use a GELU curve to help the model learn smoothly.
- Add Layer Normalization to keep the math stable.
Words to Know
- Feed-Forward: The step after attention, where each token works on its own to process the information it gathered.
- GELU: A smooth curve that replaces negative numbers with near-zero values.
- LayerNorm: A step that resets numbers to a safe size so training stays stable.
Theory¶
Thinking on Your Own¶
Attention is like listening to your team explain their ideas, while feed-forward is going back to your desk and thinking it over yourself.
Figure 8.2: The network expands each token to 512 numbers, then compresses it back to 128.
The feed-forward layer is a small neural network that operates on each token individually. As seen in Figure 8.2 we take each token which is 128 numbers long and increase it to be 512 numbers. We have more room with this 4x expansion to expand the thinking out and give it to the feed-forward network, which will return us to 128 numbers at the end.
The Smooth GELU Curve¶
Inside the feed-forward network, we apply a mathematical curve called GELU.
Figure 8.3: GELU replaces a hard switch with a smooth dimmer.
The neural network has to have some non-linearity (a curved line) to be able to learn complex patterns. An older choice is ReLU. This function is like an on/off switch where anything less than 0 will equal 0 and any number greater than 0 will remain as is.
GELU works more like a dimmer switch (Figure 8.3). Anything with a high negative value will be close to 0. Numbers close to 0 will have a slight decrease and any positive number will remain about the same.
When we train our network we use math (calculus) to work out how to adjust the model's weights. Having an abrupt turn can cause the math to act unstable which the GELU function helps with by having a smoother turn. This is why you see GELU used in most current models.
Keeping Numbers Safe with LayerNorm¶
When you have numbers traveling through many layers of your neural network, they can become too large or too small. Similar to compound interest once numbers start multiplying each other by a lot they can reach absurdly large or small numbers which don't allow our training to work correctly.
This is where Layer Normalization (LayerNorm) comes into play. We take all the numbers that travel through each token and normalize them. After a LayerNorm we will always have an average of 0 and std of 1. These numbers are printed out as mean and std in the cell below.
Figure 8.4: LayerNorm centers messy numbers back around zero.
It's similar to taking a marathon race and having everyone's timer start from zero after each lap (Figure 8.4). The leader doesn't change, it just makes the values smaller. We apply LayerNorm before each major step in modern models, and this will allow our attention and feed-forward layers to receive better inputs.
In Figure 8.1 we take what we learned from our attention layer and run it through our feed-forward network. LayerNorm keeps the math stable before sending the output to the next layer.
Code¶
| src/ch07_feedforward.py (excerpt) | |
|---|---|
Run the script to see the feed-forward layer and LayerNorm in action.
$ python src/ch07_feedforward.py
--- GELU activation ---
GELU is like ReLU (zeros out negatives) but with a smooth curve.
Input : [-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0]
GELU : [-0.004, -0.159, -0.154, 0.0, 0.346, 0.841, 1.954, 2.996]
ReLU : [0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 2.0, 3.0]
--- Layer Normalization ---
LayerNorm re-centers and re-scales values at each position.
Before LayerNorm: mean=5.23, std=9.13
After LayerNorm: mean=0.0000, std=1.0039
What just happened:
- Lines 7 and 9 build a feed-forward network that expands from 128 to 512, then back to 128.
- Line 8 applies GELU, which gently reduces negative numbers instead of snapping them to zero.
- We passed messy numbers through LayerNorm and saw them neatly centered at zero with a standard spread of 1.
Shape Check:
- Input to FeedForward:
[Batch, Time, 128] - Output of FeedForward:
[Batch, Time, 128]
Try It¶
Try It
Open src/ch07_feedforward.py and modify the LayerNorm input to have a very large spread: x_single = torch.randn(config.n_embd) * 1000 + 500. Execute the script again. Note that LayerNorm still normalizes it back to mean 0 with standard deviation of 1.
In Business
Suppose you were trying to train an assistant that would write emails for you in your company's house style. If your ML system was shaky, it might produce nonsense. LayerNorm is like having a manager verifying work in between steps so that the data never gets too out of line before proceeding to the next group.
Key Takeaways¶
- The feed-forward layer processes each token independently to build meaning.
- It expands the token's data 4x to give the model a wider workspace.
- GELU provides a smooth mathematical curve to make training stable.
- LayerNorm resets numbers to a safe size so deep networks do not break.
Check Your Understanding¶
- Why does the feed-forward network expand its input size by 4?
- What happens to a strongly negative number when it passes through GELU?
- What is the average value of a token's numbers immediately after LayerNorm?
Assignment¶
Assignment 8: Dimmer or switch
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch07_feedforward.pyas it is. Copy the three lines it prints underGELU activation: theInput,GELUandReLUlines. - Change one number. Find the line
sample = torch.tensor([-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0]). These are the eight test numbers the script feeds to GELU and to ReLU. Change the first one,-3.0, to-2.0and run the script again. The list now holds-2.0and2.0, two numbers of the same size with opposite signs. - Compare. What does GELU print for
-2.0, and what does it print for2.0? What does ReLU print for the same two numbers? Which of the two, GELU or ReLU, gives-3.0and-2.0exactly the same result? - Explain it. In two or three sentences a manager could follow, say what GELU does to a positive number and to a negative number of the same size, and why the chapter calls GELU a dimmer and ReLU a switch.
Hand in: both sets of three lines, your answers to step 3, and your sentences.
Further Reading¶
The line that keeps training stable. As numbers pass through a deep stack they drift, some growing, some shrinking, until learning stalls. Layer normalization rescales each token's vector back to a standard spread before the next step, using only that token's own numbers, so it works the same whatever the batch size. It is one line in Chapter 8 and one of the reasons deep Transformers train at all.
The smooth switch inside the feed-forward layer. A network needs a non-linear step, or every layer collapses into one. The common choice cut everything negative to zero, a hard switch. GELU fades instead of cutting, which gives the optimizer a gentler surface to work on and is the activation used in GPT-style models, including the one in Chapter 8.
Ba, J. L., Kiros, J. R., & Hinton, G. E. (2016). Layer normalization (arXiv:1607.06450). arXiv. https://doi.org/10.48550/arXiv.1607.06450
Hendrycks, D., & Gimpel, K. (2016). Gaussian error linear units (GELUs) (arXiv:1606.08415). arXiv. https://doi.org/10.48550/arXiv.1606.08415
Chapter 9: The Transformer Block¶
Figure 9.1: We combine our pieces into a reusable building block.
After processing information with feed-forward and normalizing the math in Chapter 8, we now have all the ingredients. Multi-head attention lets tokens talk to each other, feed-forward layers let tokens think for themselves, and LayerNorm keeps training stable. In this chapter you will:
- Combine these parts into a single Lego brick called a Transformer block.
- Add residual connections so deep networks can learn effectively.
- Stack multiple blocks to build depth.
Words to Know
- Transformer Block: A reusable block of code containing attention, feed-forward, and normalization.
- Residual Connection: A shortcut that lets information skip a step, keeping the original signal intact.
Theory¶
Putting the Pieces Together¶
A single Transformer block combines our tools into one unit, and its forward pass is two lines of code:
x = x + self.attn(self.ln1(x)) # "listen, then add to what I know"
x = x + self.ff(self.ln2(x)) # "think, then update what I know"
Notice the x = x + ... pattern, which is what makes deep neural networks work.
Trick 1: The Residual Connection¶
Rather than overwrite the data in a token with the output of the attention layer, we add the fresh information onto the original input. This is known as a residual connection, also called a skip connection (Figure 9.2).
Figure 9.2: Residual connections provide a direct highway through the block.
Picture a game of telephone. By the time you get to the 10th person they most likely won't know what was said at the beginning. This is where residual connections come into play. You would have a copy of the message written down to help people along the chain.
When backpropagating during training these values need to flow backwards through all the layers. Without residual connections these values can become too big or too small. Because we are adding the original value through the +x highway we can pass values through many layers stacked on top of each other.
Trick 2: Pre-Layer Norm¶
Notice that we apply LayerNorm before each major step: attention(LayerNorm(x)).
This is the modern "pre-norm" convention used by GPT models (Figure 9.3). We normalize the data before doing the heavy lifting. This means that attention and feed-forward always operate on well-behaved numbers, stabilizing training early on.
Figure 9.3: Normalize the data before the hard work.
Stacking Blocks¶
A single Transformer block is very powerful but we need to have more than one, so we chain many together (Figure 9.4). We will use 4 blocks.
As mentioned before each block will build on what the previous one did for each token's list of numbers. You can think of it as reading through a story many times. You might first learn who all the people are, then you may learn what they want and on your third read through you could figure out what the story is about. Similar idea with each Transformer block learning simpler concepts then moving onto harder ones.
Figure 9.4: Stacking blocks allows the model to find complex patterns.
Stacked Transformer blocks on the overview map in Figure 9.1 are the main component of our engine. Our engine is now ready to convert the embeddings into lists of numbers that represent the context of each token.
Code¶
Run the script to see a block process data and to check the parameter count.
$ python src/ch08_transformer_block.py
One TransformerBlock parameters: 197,888
MultiHeadAttention : 65,664
FeedForward : 131,712
LayerNorms (x2) : 512
Input shape: torch.Size([2, 10, 128])
Output shape: torch.Size([2, 10, 128]) (same as input)
--- Residual connection demonstration ---
The input is never lost -- it always flows through.
Original token norm : 11.470
Attention output norm: 4.599
After residual norm : 12.903 (combined)
--- Stacking multiple blocks ---
Stacking 4 blocks:
Params per block: 197,888
Total params : 791,552 (4 x 197,888)
Input shape: torch.Size([2, 10, 128])
Output shape: torch.Size([2, 10, 128]) (unchanged after 4 blocks)
What just happened:
- Lines 4 through 8 build a block containing attention, feed-forward, and LayerNorm.
- Line 12 shows the residual connection combine the original token data with the attention output. The three
normlines print the overall size of each list of numbers. - We stacked 4 blocks and saw the data flow through smoothly.
Shape Check:
- Input to TransformerBlock:
[Batch, Time, 128] - Output of TransformerBlock:
[Batch, Time, 128]
The block is shape-preserving. The input and output have identical shapes, so we can stack blocks like Lego bricks.
Try It¶
Try It
Edit src/ch08_transformer_block.py and modify the number of layers in the stack from config.n_layers to 12. Execute the script once more. Keep track of how the total number of parameters increases. The output shape stays precisely the same.
In Business
You want building blocks when you build software. Things you can plug together and scale up. A Transformer block is a building block. So if your house-style writing assistant isn't smart enough, you just stack more blocks and train longer. No need to invent a new architecture!
Key Takeaways¶
- A Transformer block combines LayerNorm, attention, and feed-forward layers.
- Residual connections (
x + ...) create a direct highway for data, so deep models can learn effectively. - Pre-norm applies LayerNorm before the hard work to stabilize the math.
- Because blocks preserve the shape of the data, we can stack them modularly.
Check Your Understanding¶
- Why do we add the attention output to the original input (
x + attention)? - What does "pre-norm" mean?
- Why does the Transformer block output exactly the same shape it took in?
Assignment¶
Assignment 9: New numbers, same highway
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch08_transformer_block.pyas it is. Copy four lines:Original token norm,Attention output norm,After residual normandTotal params. Here a norm is one number that says how large a token's list of numbers is overall. - Change one number. Find the line
torch.manual_seed(42). The seed fixes the random starting numbers, so every run prints the same values. Change42to any whole number you like and run the script again. - Compare. Which of the four lines changed, and which did not? In your new run, which is larger, the original token or the attention output? Is
After residual normcloser to the original token or to the attention output? - Explain it. In two or three sentences a manager could follow, say what the three norm lines show about a residual connection: what the block keeps and what it adds.
Hand in: both sets of four lines, your answers to step 3, and your sentences.
Further Reading¶
The shortcut that makes depth possible. Stacking more layers used to make networks worse, because the learning signal degraded on the way down. This paper added the input of a block back onto its output, which gave the signal a clear path through. It was shown on image models, and every Transformer block, including the one in Chapter 9, uses it.
The architecture this book builds. Reading a sequence one step at a time is slow, because step 500 cannot start until step 499 has finished, and distant words stay hard to connect. This paper removed the step-by-step reading and kept only attention, plus a note of each token's position. Every token can then be processed at once, and that made training on very large amounts of text practical. The model you build in Chapters 6 to 10 is this design, made small.
He, K., Zhang, X., Ren, S., & Sun, J. (2015). Deep residual learning for image recognition (arXiv:1512.03385). arXiv. https://doi.org/10.48550/arXiv.1512.03385
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention is all you need (arXiv:1706.03762). arXiv. https://doi.org/10.48550/arXiv.1706.03762
Chapter 10: The Full GPT Architecture¶
Figure 10.1: We connect everything to output a prediction.
We have built all the core components of a Transformer model in previous chapters, so we can now assemble them (Figure 10.1). In this chapter you will:
- Build the full GPT model from end to end.
- See how data flows through the entire pipeline.
- Understand the final raw scores, called logits.
Words to Know
- LM Head: The model's last step, which turns each token's internal numbers into one score for every character in the vocabulary.
- Logits: The raw scores the model outputs for each possible next token.
Theory¶
The Final Assembly¶
The complete GPT model is simple once you have the pieces.
Figure 10.2: The full forward pass of the GPT model.
It flows like a production assembly line (Figure 10.2):
- Turn text into a list of numbers (Token IDs).
- Look up the meaning and position vectors (Embeddings).
- Process them through a stack of Transformer blocks.
- Tidy up the numbers one last time (Final LayerNorm).
- Map the internal 128 numbers back to the 65 possible characters (LM Head).
Tracing the Flow¶
To trace a concrete example, suppose we feed the model the word "ROMEO" (5 tokens).
Step 1: Input
The input is [30, 27, 25, 17, 27]. These are the specific token IDs for the characters "ROMEO", where 'R' is 30, 'O' is 27, 'M' is 25, and 'E' is 17 according to our vocabulary.
Step 2: Embeddings The model converts these 5 IDs into 5 rich vectors (128 numbers each), combining both meaning and position.
Step 3: Transformer Blocks
The data passes through 4 blocks. After 4 blocks, the token O (at the end) has looked at all the previous letters. Its 128 numbers now encode something like "I am the last letter of a name from a famous play."
Step 4 & 5: Final Output A final LayerNorm stabilizes the numbers, and then the LM Head (Language Model Head) takes those 128 numbers and turns them into 65 numbers. The number is 65 because our Shakespeare dataset has exactly 65 unique characters.
Figure 10.3: The LM Head projects internal data back to our vocabulary.
The model outputs 65 scores for every token in the sequence (Figure 10.3), and each position independently predicts the character that comes next. The highest score at the final position is the model's best guess for what comes after "ROMEO".
What Are Logits?¶
Those 65 numbers that our LM Head gives us are known as logits.
A logit is a technical term for "raw score" (see Figure 10.4). They can be negative, zero, or very large. They also don't sum to equal 1 so we cannot call them probabilities. We will turn these raw scores into percentages later in Chapter 11 when we learn how to generate text. But just remember a bigger logit equals a higher chance of that character being chosen.
Figure 10.4: Logits are the raw scores for the next character.
On the big picture map in Figure 10.1, we have now built everything from Text to Next-Token Scores. The model is fully assembled, but right now it only outputs random guesses, so we need to train it.
Code¶
Run the script to see the parameter breakdown and a test run.
$ python src/ch09_gpt_model.py
Model parameter breakdown:
Token embedding : 8,320
Position embedding: 16,384
4 Transformer blocks: 791,552
LM head : 8,320
LayerNorm (final): 256
---
TOTAL : 824,832
Input shape: torch.Size([2, 10]) (B, T)
Output shape: torch.Size([2, 10, 65]) (B, T, vocab_size)
At each position, model outputs 65 scores.
The highest score = best guess for next character.
First position logits (top 5 scores):
token 26: 1.861
token 21: 1.195
token 44: 1.118
token 57: 1.071
token 34: 0.972
Note: these are random (untrained model).
What just happened:
- Line 1 assembles the complete GPT class.
- Line 12 creates the four blocks, which hold 791,552 of the model's 824,832 parameters (weights). The original GPT-2 Small had 117 million. Our model uses the same architecture, scaled down.
- Line 38 finishes the forward pass, where the model outputs 65 logits (scores) for each position.
Shape Check:
- Input token IDs:
[Batch, Time] - Output logits:
[Batch, Time, 65](Vocab size is 65)
Try It¶
Try It
Open src/ch09_gpt_model.py, find the line config = GPTConfig() and add a new line under it: config.n_layers = 6. Run the script again. The parameter count increases, and the blocks hold the vast majority of the model's parameters.
In Business
Building the final GPT architecture is like assembling a complete production pipeline from modular components. In our house-style writing assistant, we combine a data reader (embeddings), an analysis engine (the blocks), and an output formatter (the LM head). Because it is modular, you can upgrade the engine (add more layers) without rewriting the rest of the pipeline.
Key Takeaways¶
- The full model stacks embeddings, Transformer blocks, and a final LM head.
- The LM head is the last step, which turns each token's internal numbers into one score for every character in the vocabulary.
- The model outputs logits, which are raw scores for the next token and are not probabilities yet.
- Our complete model has ~825K parameters, so this architecture can be built at a small scale.
Check Your Understanding¶
- If the input sequence has 10 tokens, how many predictions does the model make?
- Why does the LM head output exactly 65 numbers per token?
- What is a logit?
Assignment¶
Assignment 10: Shorter text, same model
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch09_gpt_model.pyas it is. Copy three lines: theTOTALline and the two shape lines,Input shapeandOutput shape. - Change one number. Near the bottom of the file, find the line
B, T = 2, 10.Bis how many test sequences the script feeds in, andTis how many tokens each one holds. Change10to5, the length ofROMEO, and run the script again. - Compare. Which numbers in the two shape lines changed, and which did not? Did the
TOTALline change? How many sets of 65 scores does the model now give for each sequence? The five scores at the bottom shift too. They come from an untrained model, so set them aside. - Explain it. In two or three sentences a manager could follow, say what the model hands back when it reads a five-character input such as
ROMEO, and why a shorter input does not make the model itself any smaller.
Hand in: both sets of three lines, your answers to step 3, and your sentences.
Further Reading¶
One model, many jobs, no retraining. The researchers wanted to know if a model trained exclusively to predict the next word would learn capabilities nobody had trained it for. Because it was trained on such a broad, diverse swath of web pages, it started answering questions, summarizing, and translating with zero task-specific training when given a prompt that made those tasks obvious. That answered the architectural question of how to build a system for text generation in favor of a decoder architecture that predicts the next token. That's the model we cover in Chapter 10.
Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language models are unsupervised multitask learners [Technical report]. OpenAI. https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf
Chapter 11: Causal Language Modeling¶
Figure 11.1: We define the model's goal, predicting the next token.
In Chapter 10 we pieced together the Transformer architecture. Our engine is ready, but an engine needs a task to complete (see Figure 11.1). In this chapter we provide our model with a goal, causal language modeling. Causal language modeling is predicting the next token using only prior tokens. We also learn how to judge its performance.
In this chapter you will:
- Shift the training sequence to create input and target pairs.
- Understand cross-entropy loss as a measure of surprise.
- See how generation is a loop of predicting and appending.
Words to Know
- Logits: The raw scores the model outputs before they are turned into probabilities.
- Softmax: A mathematical function that squashes a list of any numbers into positive percentages that add up to 100%.
- Cross-Entropy Loss: A mathematical way to measure how wrong the model's predictions are. Lower is better.
- Autoregressive: A process that uses its own past outputs as inputs for its next step.
Theory¶
The Training Trick: One Pass, Many Examples¶
So how do we train a model to predict the next token? Well, we could give it one token and have it predict what the next one is. Then we'd see if it's right and give it two tokens. This would take way too long.
With causal language modeling we can get T training examples all at once from one forward pass through our sequence of length T.
Figure 11.2: One sequence provides multiple training examples simultaneously.
The model predicts over the entire sequence (Figure 11.2). Since there is a causal mask (described in Chapter 6), position 2 has no visibility of position 3, and each position can only see prior context. Thus the model can make a legitimate guess for the next token at each position.
Input and Target: The Shifted Pair¶
To implement this efficiently, we take our sequence of text and create two slightly different copies:
- Input (
x): The sequence missing its last token. - Target (
y): The sequence missing its first token.
Basically this means that the character at each position i in the input, $x[i]$, is trying to predict the symbol at position i in the target, $y[i]$. So for our example sequence "HELLO", x would be "HELL" and y would be "ELLO". At position 0, "H" predicts "E", and at position 1, "E" (given "H" as previous context) predicts "L", etc.
Logits and Probabilities¶
When our model makes predictions, it outputs raw numbers called logits, which are neither a single character nor a clean percentage.
Figure 11.3: Softmax converts raw scores into valid percentages.
Logits can be any real number. Negative. Positive. Small. Large. To interpret them, we run them through a function called softmax (Figure 11.3). Softmax rescales all the logits so they are positive and add up to exactly 1.0 (or 100%), resulting in a probability distribution over our 65 possible characters.
Measuring Success: Cross-Entropy Loss¶
Now that we can calculate probabilities, we need some way to evaluate how our model is doing. This is where cross-entropy loss comes into play.
You can think of loss as how surprised the model is that a given character is next. If the true next character is "A" and the model gave "A" a 99% probability then it's not very surprised so the loss would be low. If it gave "A" a 1% probability then it's very surprised and the loss would be high.
If our model was totally random it would predict all of our 65 characters with an equal chance of about 1.5%. Using some math, we can find that the loss for this scenario is about 4.17. We want to minimize this during training.
With that we've completed our Next-Token Scores section of our map. Now that our model can predict and determine how incorrect it is we can start training.
Code¶
Figure 11.4: The model produces logits for the input, which are compared to the target to calculate loss.
The code below implements this (Figure 11.4).
| src/ch10_causal_lm.py (excerpt) | |
|---|---|
And how to run the full script:
$ python src/ch10_causal_lm.py
--- 1. Constructing input/target pairs ---
Sequence: [20, 17, 30, 30, 33, 1, 35, 53, 56, 30]
Input x: [20, 17, 30, 30, 33, 1, 35, 53, 56]
Target y: [17, 30, 30, 33, 1, 35, 53, 56, 30]
At each position i, x[i] predicts y[i].
--- 2. Computing cross-entropy loss ---
Logits shape : torch.Size([4, 20, 65])
Targets shape: torch.Size([4, 20])
Loss (random model): 4.3070
Expected loss for random: 4.1744
--- 3. Text generation ---
We extend a starting sequence one token at a time.
Generated IDs (first 10): [0, 54, 34, 5, 55, 18, 63, 52, 43, 10]
Output shape: torch.Size([1, 51])
After training (Chapter 13), this will produce real text!
What just happened:
- Lines 1 and 2 slice a short sequence of 10 tokens into an input
xof length 9 and a targetyof length 9 to demonstrate input/target pairs. - Line 4 passes a random batch of 4 sequences, 20 tokens each, into the untrained model to get logits for the loss computation step.
- Lines 7 to 10 calculate the cross-entropy loss, which is 4.3070, close to our expected random guessing loss of 4.1744.
- The output shows we generated 50 tokens. The machinery works, but the weights are still random, so the characters are too.
Shape Check:
The shapes below are from the loss computation step. Note that instead of using a single sequence of length 10 here we use 4 sequences of length 20. Shapes at each step are shown in Table 11.1.
Table 11.1: Tensor shapes for the cross-entropy loss calculation.
| Variable | Shape | Meaning |
|---|---|---|
token_ids |
[4, 20] |
A batch of 4 sequences, 20 tokens each. |
logits |
[4, 20, 65] |
A score for each of the 65 possible next characters, at every position. |
loss |
[] |
A single number, the average surprise. |
Try It¶
To see how confidence affects the loss, we can simulate different prediction scenarios manually.
Lines 14 and 15 calculate the loss when the model is confident and correct, which gives a much lower loss.
$ python src/examples/ch11_loss_demo.py
Scenario 1: Guessing blindly (50% / 50%)
Loss: 0.6931
Scenario 2: Confident and right (88% for 'A')
Loss: 0.1269
Scenario 3: Confident and wrong (88% for 'B')
Loss: 2.1269
Try It
Open src/examples/ch11_loss_demo.py and change logits_right to [[5.0, 0.0]] to make the model even more confident. Run the script and see how close to zero the loss gets.
In Business
Imagine you are trying to train an assistant to write text in your organization's house style. Causal language modeling is how you teach it to write like your organization does. It reads through thousands of past emails and reports (target sequences) and figures out which words are likely to come after other words in your specific context. The loss lets you know how similar its predictions are to your historical data.
Watch Out
PyTorch's F.cross_entropy() function expects the logits to already be flattened, with one row of scores for each token. F.cross_entropy() wants a 2D table of shape [Total Tokens, VOCAB_SIZE], not the model's 3D stack of tables [BATCH, TIME, VOCAB_SIZE]. That's why there's a logits.view(B * T_len, config.vocab_size) in that code. Forgetting that view is a common bug.
Key Takeaways¶
- A single forward pass on a sequence of length
TprovidesTseparate training examples, which makes training efficient. - The target sequence is the input sequence shifted one position into the future.
- The model outputs raw logits, which softmax converts into probabilities.
- Cross-entropy loss measures how "surprised" the model is by the correct answer. We want this number to be as low as possible.
- An untrained model guessing among 65 characters will have a loss of approximately 4.17.
Check Your Understanding¶
- If your sequence is "DATA", what is the input sequence
xand the target sequencey? - Why do we need softmax before we can interpret the model's output as percentages?
- If a model is perfectly confident and perfectly correct, what should its cross-entropy loss be?
Assignment¶
Assignment 11: One number, two lists
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch10_causal_lm.pyas it is. Copy the first three lines of numbers it prints:Sequence,Input xandTarget y. - Change one number. Find the line
example_ids = torch.tensor([20, 17, 30, 30, 33, 1, 35, 53, 56, 30]). These ten numbers are the token IDs of one short sequence. Change the1in the middle to50and run the script again. - Compare. Your new number shows up in
Input xand inTarget y. Is it in the same place in both lists? Which number ofInput xsits directly above your new number inTarget y? Which end of the sequence is missing fromInput x, and which end is missing fromTarget y? - Explain it. In two or three sentences a manager could follow, say how a single piece of text supplies both the questions and the correct answers for training.
Hand in: both sets of three lines, your answers to step 3, and your sentences.
Further Reading¶
Train once, reuse everywhere. Labeled examples are expensive, and every new task used to need its own pile of them. BERT trained one Transformer on ordinary text by hiding words and asking it to fill the blanks, then adapted that single model to many tasks with a small amount of labeled data each. It reads in both directions at once, which the causal mask in Chapter 11 forbids. That mask is the difference between a model that fills blanks and one that writes forward.
Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2018). BERT: Pre-training of deep bidirectional transformers for language understanding (arXiv:1810.04805). arXiv. https://doi.org/10.48550/arXiv.1810.04805
Module 3: Training and Generation¶
Figure M3.1: Training and Generation in the big picture.
With the engine built, it is time to turn it on. For a business use case, this is where we train the house-style assistant on your company's archive and then deploy it to generate value. We will feed it Shakespeare to teach it to write, and then explore how to control its creativity.
In this module you will:
- Prepare a dataset and data loader for training
- Write the training loop that improves the model
- Save your progress using checkpoints
- Learn how greedy and sampling generation work
- Use temperature and top-k to control text creativity
- Put it all together into a complete pipeline
Chapters¶
- Chapter 12: Dataset and DataLoader
- Chapter 13: The Training Loop
- Chapter 14: Checkpointing
- Chapter 15: Greedy and Sampling
- Chapter 16: Temperature and Top-k
- Chapter 17: Putting It All Together
Chapter 12: Dataset and DataLoader¶
Figure 12.1: We begin the training module by preparing our data pipeline.
We have our model, and we know from Chapter 11 that our goal is to predict the next token. Now we need to feed data into the engine. Instead of pushing one character at a time, we will feed the model thousands of examples simultaneously. In this chapter, we build a pipeline to prepare and batch our Shakespeare dataset.
In this chapter you will:
- Use a sliding window to generate training examples.
- Understand how batches process multiple sequences in parallel.
- Build a PyTorch Dataset and DataLoader.
Words to Know
- Block Size: The maximum number of tokens the model can look at at one time (its context window).
- Batching: Grouping multiple training examples together and processing them at the same time.
- Dataset: A PyTorch tool that defines how to fetch one training example from the text.
- DataLoader: A PyTorch tool that automatically groups single examples into batches and shuffles them.
Theory¶
The Sliding Window¶
In the last chapter, we saw how a single sequence provides multiple training examples. But how do we extract these sequences from a large text file like our selection of Shakespeare's plays?
We use a sliding window (Figure 12.2).
Figure 12.2: A sliding window creates multiple, overlapping examples from one long text.
So basically you have a window that can only see so many characters. We will call this our block_size (the maximum length our model can use as context). Once we place our window at the start of our text we can extract our first sequence. Then we move the window over by 1 character and extract the next sequence. We do this until we get to the end of our text.
Processing in Parallel: Batches¶
If we fed each sequence to the model one by one, training would crawl. Modern computers, especially those with graphics chips (GPUs), are very good at doing the same math on many pieces of data at once, and they are wasted on one sequence at a time.
To see how much batching matters, we can time it:
$ python src/examples/ch12_batch_speed.py
32 sequences, one at a time : 2.191 s
the same 32 as one batch : 0.245 s
batching is 9.0x faster on this machine
This is 9x faster. This is without using a GPU on your average computer. As seen from the log, the model in Chapter 13 trained for around 8 minutes on the computer that logged it. It would have taken more than an hour if we fed in one sequence at a time. With a GPU there is even more difference because there are thousands of processors available.
Figure 12.3: A batch stacks multiple independent examples into a single block.
We group multiple sequences together into a batch (Figure 12.3). If our batch size is 32, we pass 32 independent sequences through the model in one go. The model processes them in parallel, calculates the loss for all 32, and averages it out.
Why 32 and Not 1, or 1,000¶
There are two reasons why you want to batch. Speed is one. The other is how accurate your steps will be.
When we take our loss we get a step to adjust our weights. If our batch size were 1, we would be stepping in the direction that one snippet of Shakespeare tells us to. That could be a stage note or a long sequence of talk or maybe just blank space. We would jump in each direction and try to correct ourselves heavily each time. If we average 32 random chunks of Shakespeare together we get a more accurate step in the direction that the text wants to go as a whole.
A batch size of 1,000 would have two drawbacks. One being that all those sequences need to fit in memory. On a laptop, memory is the limit you hit first. You also wouldn't get much more accurate directions if you averaged 1000 snippets instead of 32 but your step would take 30x longer. There's nothing magic about a batch size of 32, and you'll see other books use 16 or 64. It's big enough to be accurate and small enough to fit.
Once we get to our "Training" step on our map we can begin to plug our batched data into our model and start the training loop.
Code¶
To handle this efficiently, we use two built-in PyTorch tools: Dataset and DataLoader (Figure 12.4).
Figure 12.4: The Dataset handles the sliding window, and the DataLoader stacks the examples into a batch.
Run the full script to see the pipeline produce one batch:
$ python src/ch11_dataloader.py
Data loaded: 1,115,394 total tokens
Train : 1,003,854 tokens
Val : 111,540 tokens
Dataset sizes:
Train examples: 1,003,726
Val examples: 111,412
DataLoader config:
Batch size : 32
Train batches per epoch: 31,367
--- Inspecting one batch ---
x_batch shape: torch.Size([32, 128]) (batch_size, block_size)
y_batch shape: torch.Size([32, 128]) (batch_size, block_size)
First example in batch:
x (input) : 'ness! serious vanity!\nMis-shapen chaos of well-seeming for...
y (target) : 'ess! serious vanity!\nMis-shapen chaos of well-seeming form...
(y is x shifted by 1 character)
DataLoader ready! Ready for Chapter 13.
What just happened:
- We loaded our text file and converted it to token IDs.
- Lines 12 and 14 comprise the sliding window in
TextDataset. Line 12 cuts the slice of text beginning at positionidx. Line 14 cuts the same slice shifted one character to the right, its target. - Lines 21-23 instantiate a
DataLoaderwhich batches and shuffles our training data automatically. One pass through all of the batches is known as an epoch, the term in the output above. - We grabbed one batch and inspected it to confirm the target
yis the inputxshifted by one character.
Shape Check:
Table 12.1 lists the shapes of the batched input and target.
Table 12.1: Tensor shapes for the batched input and target sequences.
| Variable | Shape | Meaning |
|---|---|---|
x_batch |
[32, 128] |
32 sequences, each containing 128 input characters. |
y_batch |
[32, 128] |
32 sequences, each containing 128 target characters. |
Try It¶
We can see the sliding window in action with a tiny dataset.
Lines 12 and 13 slice the array to create overlapping sequences for the input and target.
$ python src/examples/ch12_batching_demo.py
Data: [10, 20, 30, 40, 50, 60, 70]
Block size: 3
Example 1:
Input : [10, 20, 30]
Target : [20, 30, 40]
Example 2:
Input : [20, 30, 40]
Target : [30, 40, 50]
Example 3:
Input : [30, 40, 50]
Target : [40, 50, 60]
Example 4:
Input : [40, 50, 60]
Target : [50, 60, 70]
Try It
Open src/examples/ch12_batching_demo.py. Change block_size to 4, run it again, and notice how the number of available examples decreases.
In Business
Say you want to train your company's house-style assistant from an archive of 100,000 corporate documents. You're not going to point to one word at a time and make it learn. Processing information in batches allows the assistant to read through 32 documents (emails, papers, books) at once and learn from them all. That's how training remains fast when it needs to happen at scale.
Watch Out
Be careful about your dataset's __len__. If you have 100 characters, with block_size 10, you can only have 90 starting positions. Why? Because you need 11 characters to provide a single example, 10 for the input and 1 more for the target. That's why the code uses len(self.data) - self.block_size.
Key Takeaways¶
- A sliding window extracts overlapping sequences from a continuous block of text.
- Batching processes multiple independent sequences in parallel, which speeds up training.
- PyTorch's
Datasetdefines how to grab a single example. - PyTorch's
DataLoaderhandles the tedious work of grouping examples into batches and shuffling them.
Check Your Understanding¶
- If you have a sequence of 1000 tokens and a block size of 100, how many examples can a sliding window extract?
- Why is batching important for training speed?
- Why do we shuffle the training data?
Assignment¶
Assignment 12: Follow one number
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch12_batching_demo.pyas it is. Copy the four examples it prints, each with its Input and its Target. - Change one number. Find the line
data = torch.tensor([10, 20, 30, 40, 50, 60, 70]). These seven numbers stand in for a text of seven characters. Change the40in the middle to any whole number that is not already in the list, and run the script again. - Compare. In how many examples is your number part of the Input? In how many is it part of the Target? How many examples does the script print now, and did that count change?
- Explain it. In two or three sentences a manager could follow, say how a sliding window turns one text into many training examples, and why one character can appear in several of them.
Hand in: both sets of four examples, your answers to step 3, and your sentences.
Further Reading¶
Why the field started building bigger. Before this, deciding how large to make a model, how much text to train it on, and how much compute to spend was guesswork. The paper measured all three and found the error falls along smooth, predictable curves across a very wide range of sizes. Model building became a budgeting exercise, which is why the industry spent the following years scaling up. The same curves also explain the ceiling on the model you train here, because about 825,000 parameters and about a million characters of Shakespeare buy a certain quality of text, and no more.
Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B., Chess, B., Child, R., Gray, S., Radford, A., Wu, J., & Amodei, D. (2020). Scaling laws for neural language models (arXiv:2001.08361). arXiv. https://doi.org/10.48550/arXiv.2001.08361
Chapter 13: The Training Loop¶
Figure 13.1: The model makes predictions, measures its error, and adjusts its weights to improve.
With our data batched and ready from Chapter 12, we have a model that can guess the next character, but right now, its guesses are no better than chance. In this chapter, we will write the loop that teaches it the patterns of the text it reads.
In this chapter you will:
- Understand gradient descent as walking down a hill.
- See what the learning rate does, by measuring three of them.
- Build the four-step training loop.
- Watch the model learn in real time, and read what its loss means.
Words to Know
- Optimizer: The algorithm that updates the model's weights. We use Adam, a popular and steady choice.
- Gradient: The direction we need to move our weights to increase the error. We move in the opposite direction to decrease it.
- Backpropagation: The mathematical process of calculating the gradient for every single weight in the model.
- Learning Rate: How far the optimizer moves the weights on each step. If it is too small, training crawls, and if it is too large, it can overshoot.
Theory¶
Walking Down the Hill¶
How does a model learn? Well, say you are on a bumpy hillside and you're blindfolded. You want to get to the bottom of that hill (where the loss is at its minimum).
You would not be able to see how far down that hill goes but you could feel the direction of the hill around you. If the hill was higher to your right you would know to step to your left.
Figure 13.2: The optimizer takes small steps down the loss landscape to lower the loss.
This is gradient descent (Figure 13.2). The slope under your feet is the gradient, calculated by backpropagation, and taking a small step downhill is the optimizer updating the weights.
The Four-Step Loop¶
Training is a repetitive cycle that we run thousands of times (Figure 13.3):
Figure 13.3: The four steps of the training loop.
- Forward Pass: We pass a batch of data through the model to get its predictions.
- Calculate Loss: We compare the predictions to the correct targets using cross-entropy.
- Backward Pass: PyTorch automatically works out the gradient for every weight in the model (
loss.backward()). The part of PyTorch that does this is called autograd. - Optimizer Step: The optimizer adjusts the weights slightly in the right direction (
optimizer.step()).
How Big Should the Step Be?¶
Gradient descent tells you which way is downhill but not how far to walk. That distance is the learning rate, and it is the one number beginners most often get wrong.
Our config sets it to 0.0003. To see where that comes from, train the same model three times from the same starting weights, changing only the learning rate:
| src/examples/ch13_learning_rate.py | |
|---|---|
$ python src/examples/ch13_learning_rate.py
lr=0.003 start 4.33 after 150 steps 2.35
lr=0.0003 start 4.33 after 150 steps 2.60
lr=3e-05 start 4.33 after 150 steps 3.31
Most people need the lesson on the bottom row. At 0.00003 we are taking such small steps that we have hardly moved by 150 steps. The loss is at 3.31 compared to 4.17 if we guessed randomly. So it's learning just extremely slowly.
You may wonder about the top row. With 10x the learning rate we got there faster with a loss of 2.35 versus our learning rate which reached 2.60. Why doesn't the book use this?
Because 150 steps is not 3,000 steps. When taking larger steps you run the risk of bouncing off the bottom of the valley or blowing up. Our example only ran for 150 steps so we don't know. 0.0003 will get us to 1.74 with the whole example. You could try running 0.003 for 3000 steps and see what happens.
The "Aha!" Moment: It Learned¶
At the beginning of training, loss is about 4.3. Recall from Chapter 11 that completely random guessing between 65 characters has an expected loss of 4.17. Initially our model is even worse than random!
But as the loop runs, the numbers start to move.
Figure 13.4: Over 3,000 steps, the training loss falls from 4.33 to 1.74.
The loss falls quickly (Figure 13.4). By step 300 it is already at 2.7, and by step 3,000 it reaches 1.74.
What the Loss Number Actually Means¶
It's pretty difficult to understand what a loss of 1.74 means by itself. So we can convert this to a probability.
As you can see there is only one value used for cross-entropy. It's the probability the model assigned to the actual next character. Cross-entropy takes this value and uses its negative logarithm as the loss. Undoing the logarithm allows us to get the probability that we can understand:
$ python src/examples/ch13_loss_meaning.py
random guessing loss 4.17 -> 1.5% on the right character
step 1 loss 4.33 -> 1.3% on the right character
step 300 loss 2.70 -> 6.7% on the right character
step 3000 loss 1.74 -> 17.6% on the right character
At the start, the model assigns around 1.3% probability to the correct character. This is slightly worse than the 1.5% we'd get if we picked from the 65 possible characters at random. At the end of training it has increased this probability 12x which is great. Though we still have our model guessing the wrong answer 4 out of every 5 times.
Keep this in mind when thinking about your model. It knows what letters follow other letters. It knows about word length, end of line and who is speaking. It doesn't know English. And it definitely doesn't know what any of this means. We will show you this in Chapter 17. Our model will write "Praviour soul to shall that that are the and not,". You can see Shakespeare but no meaning.
The "Training" section of our map is finished. Our model knows how to generate the next character in its corpus.
Code¶
The core loop is simple to write in PyTorch.
Run the full script to watch the loss fall:
$ python src/ch12_train.py
Chapter 13: The Training Loop
Model parameters: 824,832
Training on : cpu
Steps : 3,000
Batch size : 32
Block size : 128
Starting training... (eval every 300 steps)
step 1/3000 | train loss: 4.3280 | val loss: 4.2114 | elapsed: 3s | ETA: 7595s
step 300/3000 | train loss: 2.7016 | val loss: 2.5433 | elapsed: 55s | ETA: 496s
...
step 900/3000 | train loss: 2.2633 | val loss: 2.1889 | elapsed: 160s | ETA: 372s
step 1200/3000 | train loss: 2.1185 | val loss: 2.1053 | elapsed: 210s | ETA: 314s
step 1500/3000 | train loss: 2.0174 | val loss: 2.0078 | elapsed: 248s | ETA: 248s
What just happened:
- Line 1 creates an Adam optimizer to handle the weight updates.
- Line 3 shows 3,000 steps of training. Since the log above reached the halfway point after 248 seconds, the whole run took roughly eight minutes on the machine that generated it. On the author's 2020 laptop (described in the Preface), that same run took 20-30 minutes.
- Lines 11-13 compute gradients and perform the weight update. During the run you see the training loss drop from 4.33 to 1.74. Two losses are printed to the log. The train loss is calculated on text that the model sees as it trains. The val loss is calculated on the held-out text from Chapter 4.
- We saved the trained weights to a file so we can load them later.
Shape Check:
Table 13.1 lists the parameter count.
Table 13.1: Total adjustable parameters in the language model.
| Variable | Shape | Meaning |
|---|---|---|
model.parameters() |
824,832 |
The total number of individual numbers (weights) the optimizer is adjusting. |
Try It¶
We can see the mechanics of PyTorch's automatic gradients on a tiny scale.
Lines 19, 26, and 27 show PyTorch computing the gradient and using it to adjust the weight toward the target.
$ python src/examples/ch13_autograd_demo.py
Initial weight: 2.00
Step 1: Output=6.00, Loss=36.00, Gradient=-36.00
Step 2: Output=11.40, Loss=0.36, Gradient=-3.60
Step 3: Output=11.94, Loss=0.00, Gradient=-0.36
Final weight: 4.00
Try It
Open src/examples/ch13_autograd_demo.py. Change the starting weight to 10.0 and watch how the gradient pulls it down instead of pushing it up, always aiming for the target output of 12.
In Business
Training is where you make the investment. When your company trains its house-style assistant, it is paying for compute time to run this loop billions of times on thousands of documents. The loss curve becomes your lead dashboard metric because as long as validation loss continues to decrease, your assistant is improving its emulation of your corporate voice.
Watch Out
Always remember to run optimizer.zero_grad() before loss.backward(). By default, PyTorch accumulates gradients (it sums them). If you forget to zero them before starting the backward pass, your model will take a step based on a mix of the current batch and all the previous batches and will thus go in the wrong direction.
Key Takeaways¶
- Training is a loop of four steps: Forward, Loss, Backward, Step.
- Gradient descent finds the lowest loss by taking small steps downhill.
- We use the
torch.optim.Adamoptimizer to manage the complex math of updating the weights. - The model starts by guessing blindly (loss > 4.17), but over 3,000 steps, it learns the patterns of the text and the loss falls.
Check Your Understanding¶
- What are the four main steps inside the training loop?
- What does
loss.backward()actually do? - Why is a dropping loss curve a good sign?
Assignment¶
Assignment 13: Shrink the step
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch13_autograd_demo.pyas it is. Copy the five lines it prints: the initial weight, the three steps and the final weight. - Change one number. Find the line
weight -= 0.05 * weight.grad. The0.05is the learning rate: how far the weight moves on each step. Change0.05to0.0003and run the script again. - Compare. Which printed lines are the same in both runs? After three steps, how close does the output get to the target of 12 in each run? Is the loss still falling in the second run?
- Explain it. In two or three sentences a manager could follow, say what a learning rate that is too small for the job costs a company that pays for every training step.
Hand in: both sets of five lines, your answers to step 3, and your sentences.
Further Reading¶
How a network learns anything at all. When a network with layers in the middle gave a wrong answer, nobody could say which of the middle weights was at fault. This paper sent the error backwards through the network and gave each weight a share of the blame in proportion to how much it moved the result. Every model in this book learns that way, and so does every model in production today. In the training loop, loss.backward() does this job.
The optimizer on one line of your training loop. Backpropagation says which way each weight should move but not how far. Adam gives every weight its own step size, adapted from how that weight has been moving recently, so rarely used weights can take larger steps and volatile ones settle down. It is the default in the training loop in Chapter 13 and in most training loops elsewhere.
Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization (arXiv:1412.6980). arXiv. https://doi.org/10.48550/arXiv.1412.6980
Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323, 533–536. https://doi.org/10.1038/323533a0
Chapter 14: Checkpointing¶
Figure 14.1: We have trained the model, and now we save its weights.
Training a language model takes time. Once the model learns from the data, you need to save its knowledge so you can use it later without retraining. In this chapter you will:
- Save a trained model to a file.
- Load a saved model back into memory.
- Switch the model from training mode to evaluation mode.
Words to Know
- Checkpoint: a file that saves a model at one point in training, with its learned weights and its configuration (how it is built).
- State Dict: a PyTorch dictionary (a lookup table) that pairs each layer of the model with its learned weights.
- Dropout: A technique that randomly turns off some neurons (small parts of the model) during training, so it cannot simply memorize the data.
Theory¶
The Checkpoint File¶
Figure 14.2: The checkpoint stores the model's structure and its learned weights.
A checkpoint is a saved model file. You learn weights while you are training your model. The model learns these weights and saves them into what is called a lookup table. PyTorch will refer to this as the state_dict which is short for state dictionary. It contains the names of the layers and the associated weights for that layer.
You may ask why we need more than the weights? Well, you could quit your program and come back the next day. PyTorch would not know how many layers or attention heads you have in your model. So we need to save our model's configuration (the architecture skeleton) along with its state dictionary (the learned weights). We will also be saving the current step we are at in training and the validation loss.
Restoring the Model¶
Loading a checkpoint happens in three steps:
- Load the saved dictionary from the file on disk.
- Build an empty model using the saved configuration.
- Pour the saved weights into the empty model.
Once the model is loaded, you must call model.eval(). During training, neural networks often use a technique called dropout, which randomly turns off some neurons to prevent the model from memorizing the data. Calling model.eval() turns off dropout, so that all neurons are active and the same input always gives the same scores (the model is deterministic).
Figure 14.3: In evaluation mode, dropout is off, so the same input always gives the same scores.
On the "where we are" map, saving the checkpoint captures the model after the training loop, so it is ready to generate new text in the final stage.
In Business
In our house-style assistant, the training process analyzed your company's archive to learn its voice, and if the server restarts, you don't want to re-read the entire archive. A checkpoint saves that learned company voice to a tiny file that you can load instantly on any machine.
Code¶
We use the PyTorch torch.load() function to read our checkpoint file, and model.load_state_dict() to apply the weights.
Running the script loads the checkpoint created at the end of the previous chapter.
$ python src/ch13_checkpoint.py
--- 2. Load the checkpoint ---
Loading checkpoint from: checkpoints/model.pt
Trained for : 3000 steps
Val loss : 1.7228
Model config : 4 layers, 128 embd, 4 heads
--- 3. Rebuild the model from the checkpoint ---
Model rebuilt successfully: 824,832 parameters loaded
--- 4. Verify the model works ---
Input shape : torch.Size([1, 10])
Output shape: torch.Size([1, 10, 65]) (looks good!)
--- 5. Show checkpoint file size ---
Checkpoint file size: 4.18 MB
(Small enough to share by email!)
Checkpointing done! Ready for Chapter 15.
Figure 14.4: Checkpoint loading, from file to ready model.
What just happened:
- Line 1 loaded the checkpoint
model.ptfrom disk. - Line 8 built an empty
GPTmodel using the loaded configuration. - Line 9 populated the model with the 824,832 learned parameters.
- Line 12 switched the model to evaluation mode.
- We verified the checkpoint file is tiny (just over 4 megabytes).
Shape Check¶
Table 14.1 lists the tensor shapes when verifying the loaded model.
Table 14.1: Input and output shapes for the restored model.
| Tensor | Shape | What it means |
|---|---|---|
dummy_ids |
[1, 10] |
1 sequence of 10 token IDs. |
logits |
[1, 10, 65] |
65 vocabulary scores for each of the 10 positions. |
Try It¶
Try It
You can look inside the checkpoint with a small script that loads the file. The repository already has one:
| src/examples/ch14_inspect_checkpoint.py (excerpt) | |
|---|---|
Lines 9 and 10 print the keys and the training step from the loaded checkpoint dictionary.
Key Takeaways¶
- A checkpoint saves the model's configuration and learned weights to a file.
- You rebuild the model by creating an empty network with the configuration, then loading the weights with
load_state_dict. - Always call
model.eval()after loading a model to turn off training features like dropout. - A model with 825,000 parameters takes up only about 4 MB of disk space.
Check Your Understanding¶
- Why do we need to save the model's configuration in the checkpoint along with the weights?
- What happens if you forget to call
model.eval()before generating text? - What PyTorch function do we use to apply the saved weights to the newly built model?
Assignment¶
Assignment 14: Open the save file
About 15 minutes. You change one word and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch14_inspect_checkpoint.pyas it is. Copy the two lines it prints. - Change one word. Find the line
print("Training step:", checkpoint.get("step")). The word insideget(...)names the item the script takes out of the file. Insideget(...), change"step"to"gpt_cfg", another name from the list of keys. Keep the quotation marks, and run the script again. - Compare. The label still says
Training step:, but what follows it now? Which of its numbers match the lineModel config : 4 layers, 128 embd, 4 headsfrom this chapter's run? Which other numbers do you recognize from earlier chapters? - Explain it. In two or three sentences a manager could follow, say why the save file must hold this configuration and not only the learned weights.
Hand in: both outputs, your answers to step 3, and your sentences.
Further Reading¶
The library you are typing into. This paper argues for the design of the tool this book uses, where you write the model as ordinary Python that runs line by line, so you can print a tensor or stop in a debugger, and still get the speed of compiled code underneath. That design is why the code in this book can be read top to bottom and still trains a real model.
Paszke, A., Gross, S., Massa, F., Lerer, A., Bradbury, J., Chanan, G., Killeen, T., Lin, Z., Gimelshein, N., Antiga, L., Desmaison, A., Köpf, A., Yang, E., DeVito, Z., Raison, M., Tejani, A., Chilamkurthy, S., Steiner, B., Fang, L., ... Chintala, S. (2019). PyTorch: An imperative style, high-performance deep learning library (arXiv:1912.01703). arXiv. https://doi.org/10.48550/arXiv.1912.01703
Chapter 15: Greedy and Sampling¶
Figure 15.1: We are ready to generate new text with the trained model.
So far we've trained and loaded our model. Now we'd like to actually use it to generate some text. However, our model outputs a list of 65 scores (also known as logits), one for each possible character. We need to devise a strategy to choose a winner. In this chapter you will:
- Generate text by always choosing the highest-scoring character (greedy decoding).
- Generate text by choosing characters randomly based on their probabilities (sampling).
- Compare the trade-offs between deterministic and creative text generation.
Words to Know
- Greedy Decoding: always picking the single highest-probability token.
- Sampling: choosing the next token randomly, giving higher-probability tokens a better chance to be selected.
Theory¶
Greedy Decoding¶
One method we can use is simply selecting the most likely token each time. This is known as greedy decoding.
Although we may want to select the "best" answer every time, the problem with this is we will frequently get into a loop. Suppose our model knows a phrase. It will select the next most likely token for that phrase. Now that token is included in the context so it will select the next token in that phrase. And so on it will repeat that phrase infinitely.
Since we are always choosing the most likely token greedy decoding is a deterministic method. Given the same prompt, we will receive the same output.
Sampling¶
We can avoid getting stuck in loops with something called sampling. Rather than automatically choosing the highest-scoring character, we convert the raw scores (also called logits) to percentages (probabilities) and pick a winner at random.
Figure 15.2: Greedy decoding always takes the tallest bar, and sampling draws randomly from the distribution.
When there's a 60% chance of the letter e occurring it will occur 60% of the time. When x has a 1% chance it will be selected less often. But there's still a chance it can happen. Which is good as it breaks the loop and makes your text more interesting. Downside being you won't get the same text each time it runs because it will select a different draw. All code snippets in this book use a seed (torch.manual_seed(42)) to lock the draw so when you run it you'll receive the same text.
Generation takes New Text back to the Tokens step on our "where we are" map. We generate one character and append it to our prompt then loop back.
In Business
With our house-style assistant, greedy or sampling depends on the job. You want greedy decoding if the assistant is reading out an answer to a factual question from your company manual. It should be predictable (even though greedy can still be wrong). You want sampling if it is writing a creative marketing email in your company voice. It should be varied, creative, and try new things.
Code¶
We implement both strategies in the same generation loop. The core difference is how next_id is chosen.
Line 7 picks the character with the single highest score for greedy decoding. Lines 17 and 18 turn the scores into probabilities and draw a winner randomly for sampling.
Figure 15.3: The generation loop predicts one character at a time and appends it to the context.
You may have noticed we are using ids[:, -cfg.block_size:], which will grab only the last block_size tokens of our current text (the context) before we pass it to the model. We need to keep this as our model was trained to only understand a max of our block size which is 128. So we want to give our model no more than that. Notice that we use logits[:, -1, :] since we only care about what score the next letter will be at the last position.
As you can see there are two ways to go about this using ROMEO:\n as our prompt.
$ python src/ch14_generate_greedy.py
--- GREEDY (always picks highest-score token) ---
ROMEO:
I will the come the some the stand the son,
And the so shall the see the shall the see the stand
...
--- SAMPLING (picks randomly from distribution) ---
ROMEO:
My must greather, but what it? whom, he ere.
EBRUTUS:
Morcy there bagainVain, I will ever may
To epated as great that the appral tankswain
...
--- Observations ---
Greedy tends to be more repetitive.
Sampling is more varied but can make unexpected choices.
$ python diagrams/charts/ch15_probabilities.py
Saved ch15-probabilities.png and ch15-probabilities.pdf
Figure 15.4: Greedy always picks the tallest bar. Sampling can pick any bar, in proportion to its height.
What just happened:
- The greedy approach quickly got stuck in a repetitive loop ("the shall the shall...").
- The sampling approach produced varied, non-repetitive text, but it included some strange spellings ("greather", "bagainVain") because it occasionally picked low-probability characters.
Shape Check¶
Table 15.1 lists the shapes used during the character prediction step.
Table 15.1: Tensors used during the text generation loop.
| Tensor | Shape | What it means |
|---|---|---|
logits[:, -1, :] |
[1, 65] |
65 vocabulary scores for the final character in the sequence. |
next_id |
[1, 1] |
1 chosen character ID. |
Try It¶
Try It
Different starting prompts create different context for the model. The script below shows how sampling handles new prompts.
Lines 6 and 9 generate new text starting from two different prompts.
Key Takeaways¶
- Greedy decoding always chooses the highest-scoring token, which leads to predictable but repetitive text.
- Sampling chooses the next token randomly based on the probability distribution, and the text comes out varied and natural.
- The generation loop works by predicting one character, appending it to the context, and repeating the process.
- We crop the input context to the model's maximum
block_sizebefore each prediction.
Check Your Understanding¶
- Why does greedy decoding often get stuck repeating the same phrase?
- What PyTorch function do we use to randomly pick a token based on its probabilities?
- Why do we slice the logits tensor with
[:, -1, :]in the generation loop?
Assignment¶
Assignment 15: Which half changes
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch14_generate_greedy.pyas it is. Copy the text under the GREEDY heading and the text under the SAMPLING heading. - Change one number. In the demo part of the file, find
torch.manual_seed(42). The seed fixes the random draws, so every run of the script picks the same characters. Change42to any whole number you like and run the script again. - Compare. Which of the two texts changed? Which one is the same, character for character? In the greedy text, which words keep coming back?
- Explain it. In two or three sentences a manager could follow, say which rule you would choose for a task that must give the same answer every time, and what you give up by choosing it.
Hand in: both pairs of texts, your answers to step 3, and your sentences.
Further Reading¶
Why always picking the likeliest word goes wrong. Always taking the highest-scoring next token, which Chapter 15 calls greedy decoding, produces flat and repetitive text, and this paper shows that this happens because human writing is not made of the most predictable word at every turn. Their alternative keeps the smallest set of tokens whose probabilities add up to a chosen share and samples from that. How you choose the next token matters as much as how well the model was trained.
Holtzman, A., Buys, J., Du, L., Forbes, M., & Choi, Y. (2019). The curious case of neural text degeneration (arXiv:1904.09751). arXiv. https://doi.org/10.48550/arXiv.1904.09751
Chapter 16: Temperature and Top-k¶
Figure 16.1: We tune how the text is generated.
Random sampling produces diversity, but sometimes at the cost of coherence. The model might select a rare character which violates grammar or produces an unrecognizable word. We’ll want some reins on the randomness. In this chapter you will:
- Use temperature to adjust how risky the model's choices are.
- Use top-k to cut the list of choices short, so the model cannot pick truly bad characters.
- Combine these controls for optimal text generation.
Words to Know
- Temperature: a number the scores (logits) are divided by before they become probabilities. A low temperature plays it safe, and a high one takes risks.
- Top-k: a limit that lets the model sample only from the k most likely next tokens, where k is a number you choose (40 here).
Theory¶
There are two knobs between the model's raw scores and the character it ultimately selects. Temperature alters the odds. Top-k pruning determines which characters are eligible. They are independent, and you will usually set both.
Figure 16.2: Temperature changes the shape of the odds, and top-k changes how many characters stay in the running.
Temperature¶
Temperature is essentially one mathematical operation applied to logits just before softmax. We divide each logit by one scalar value, and that alters the distribution over characters.
Figure 16.3: Low temperature sharpens the choice, and high temperature flattens it.
- Low temperature (e.g., 0.5): Dividing by a number smaller than 1 pushes the scores further apart, so the top choice becomes overwhelmingly favored and the model plays it safe.
- High temperature (e.g., 2.0): Dividing by a large number squishes the scores together. The probabilities flatten out, meaning unusual choices become more likely, and the model takes risks.
- T = 1.0: This is standard sampling, where the model uses its learned probabilities exactly as they are.
Top-k¶
There is still a probability at any given temperature that could result in the wrong character being chosen. That chance might be 0.001%. If you sample enough times you will eventually see a mistake.
By using top-k sampling we can cap our selection pool. If we set top_k = 40, we would take all 65 character choices, keep the 40 with the highest scores, and drop the bottom 25 by setting their probabilities to zero. By dropping these choices we are preventing any sampling from occurring on those lower end values.
Figure 16.4: Top-k keeps the highest-scoring characters and zeroes the rest. Drawn here with ten characters and k = 4, while the book's code uses 65 and k = 40.
These controls adjust the Next-Token Scores on the "where we are" map, right before generation loops back to produce the New Text.
In Business
When creating boilerplate text for compliance documentation with the house-style assistant, you may want to choose a lower temperature (0.5) setting so that the text it generates is always as close to the safe outputs as possible. However, if you want witty taglines to market your business, try using a higher temperature (0.9) setting with top-k sampling (40) to get creative, surprising results that still conform to grammatical norms.
Code¶
We apply temperature and top-k right before the softmax function in the generation loop.
Line 2 divides the scores by the temperature to adjust randomness. Line 7 discards any score below the top-k threshold by setting it to negative infinity.
Figure 16.5: The code applies temperature, then top-k, then softmax.
We implement top-k in PyTorch using masked_fill. We take the score of the 40th best token (threshold), and change any token with lower score to -inf. When we apply softmax to turn scores into probabilities, -inf becomes exactly 0.
The run below shows how different settings affect the generated text.
$ python src/ch15_generate_sampling.py
--- temp=0.5, top_k=40 ---
JULIET:
My must grace prove a son the come on my lord.
...
--- temp=0.8, top_k=40 ---
JULIET:
That will, my call thee for thee king win a be parder
The his in suppy ascented a not a say?
...
--- temp=1.0, top_k=40 ---
JULIET:
Look, do indo witned me devise thy grohed:
A give gring brothe whith ighers paison:
...
--- temp=1.5, top_k=40 ---
JULIET:
fattlyals give niet, thou stain, viful-wid thel,
Brob dayse mernion shing you fea,
...
--- temp=1.0, no top_k ---
JULIET:
Than mide smear of thou I am go vious, you me
now you scalf them frate ell, to 'till will she
...
--- Sweet spot ---
temperature=0.8 to 1.0 and top_k=40 usually gives the best results.
What just happened:
- At
temp=0.5, the text is coherent but relies heavily on common, safe words. - At
temp=0.8to1.0, the text feels more natural and varied. - At
temp=1.5, the text quickly fills with made-up words ("fattlyals"). - A temperature between 0.8 and 1.0, combined with
top_k=40, typically works best.
Shape Check¶
Table 16.1 lists the shapes of tensors used during top-k filtering.
Table 16.1: Tensors modified during the top-k sampling process.
| Tensor | Shape | What it means |
|---|---|---|
threshold |
[1, 1] |
The cutoff score (the 40th highest value). |
logits |
[1, 65] |
65 scores, where 25 of them have been set to -inf. |
Try It¶
Try It
Open the script src/examples/ch16_explore_temp.py and run it. It initializes with a very low temperature (0.1), and you will see it is essentially doing greedy decoding (picking the safe top character every time).
Key Takeaways¶
- Temperature adjusts the spread of the probabilities. Low temperature makes the model conservative, while high temperature makes it creative and risky.
- Top-k restricts the model from ever picking the worst-scoring tokens and so prevents bizarre errors.
- To combine them, first apply temperature, then apply top-k to filter out the bad options, and finally convert to probabilities with softmax.
- A combination of
temperature=0.8andtop_k=40is a widely used default for high-quality text generation.
Check Your Understanding¶
- If you set the temperature to 0.1, what happens to the gap between the highest and lowest scores?
- Why do we replace the eliminated scores in top-k with negative infinity (
-inf) instead of0? - Which step must happen first in the code: applying top-k or calculating softmax probabilities?
Assignment¶
Assignment 16: Turn up the heat
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch16_explore_temp.pyas it is. Copy the text the model writes afterJULIET:. - Change one number. Near the bottom of the file, find
temperature=0.1. Temperature is the number the scores are divided by before the model draws a character. Change0.1to2.0and run the script again. The lineGenerating with T=0.1...is a fixed label, so it will still say 0.1. - Compare. Which text keeps repeating the same words? Which one is full of made-up words? Which one is closer to real English?
- Explain it. In two or three sentences a manager could follow, say why neither setting would suit an assistant that writes to customers, and which way you would turn the dial from each one.
Hand in: both texts, your answers to step 3, and your sentences.
Further Reading¶
Where top-k sampling comes from. This paper is about writing stories from a prompt, and along the way it introduced the sampling rule you use in Chapter 16: keep only the k most likely next tokens and draw from those. It keeps the text varied without letting the model pick something absurd from the long tail.
Why always picking the likeliest word goes wrong. Always taking the highest-scoring next token, which Chapter 15 calls greedy decoding, produces flat and repetitive text, and this paper shows that this happens because human writing is not made of the most predictable word at every turn. Their alternative keeps the smallest set of tokens whose probabilities add up to a chosen share and samples from that. How you choose the next token matters as much as how well the model was trained.
Fan, A., Lewis, M., & Dauphin, Y. (2018). Hierarchical neural story generation (arXiv:1805.04833). arXiv. https://doi.org/10.48550/arXiv.1805.04833
Holtzman, A., Buys, J., Du, L., Forbes, M., & Choi, Y. (2019). The curious case of neural text degeneration (arXiv:1904.09751). arXiv. https://doi.org/10.48550/arXiv.1904.09751
Chapter 17: Putting It All Together¶
Figure 17.1: The last stage on the map, new text.
You've coded up a language model from scratch. Step by step, you coded the functions to tokenize text, vectorize it, perform self-attention, stack transformer blocks, train the model weights with gradient descent, and sample new text at temperature with top-k sampling. In the last chapter, you will:
- Run the complete end-to-end pipeline in a single script.
- See the full architecture in action.
- Understand how your model relates to modern, production-grade LLMs.
Words to Know
- End to End: a process that runs every step on its own, from raw text to a trained model and its generated text.
- Instruction tuning: An extra round of training, after the kind done in this book, that teaches the model to answer questions and follow instructions.
- RLHF: Reinforcement Learning from Human Feedback, a way to train a model on people's feedback so it answers politely and as people prefer.
Theory¶
The Full Architecture¶
Reflect on what you've built. You coded the same components that powered GPT-2. GPT-2 is the architecture behind GPT-3, GPT-4, and many other contemporary LLMs.
Figure 17.2: The complete system, from raw text to new text.
The differences between your model and a large production model are mostly a matter of scale:
- Vocabularies: We used 65 characters, while they use 50,000+ subword tokens.
- Size: We gave each token a list of 128 numbers (a 128-dimensional embedding) and stacked 4 layers, while they use lists of thousands of numbers and nearly a hundred layers.
- Data: We trained on 1 megabyte of Shakespeare, while they train on terabytes of internet text.
- Hardware: We trained for a few minutes on a CPU, while they train for months on thousands of specialized GPUs.
How Real Models Differ¶
The fundamental transformer architecture (embeddings, attention, blocks, training) remains the same, but modern models add refinements that improve performance:
- Instead of simple position lookups, they might use Rotary Positional Embeddings, which help models understand relative distances between words better.
- Instead of standard multi-head attention, they might use Grouped-Query Attention, which saves memory and speeds up text generation.
- After pretraining (what we just covered), they go through Instruction Tuning and RLHF (Reinforcement Learning from Human Feedback), which teach them to answer questions politely and not simply predict the next word.
The end-to-end pipeline connects every stage on the "where we are" map, from reading the text to generating new text.
In Business
This entire script would be your house-style assistant. In the enterprise you would run this pipeline any time your company archive is updated. Overnight, you'd train on new documents, validate your model, and push the new checkpoint into production for your marketing and compliance teams to use.
Code¶
In the script below, we've copied every line of code from previous chapters. It downloads the data, tokenizes the data, makes the DataLoaders, constructs the 825,000-parameter model, trains it for 3,000 steps, saves a checkpoint, and samples from the model.
Figure 17.3: The full script runs every step in order.
Now we run the whole script once to check that every stage works (programmers call this a smoke test).
$ python src/ch16_full_pipeline.py
[1/7] Downloading dataset...
...
[2/7] Tokenizing...
...
[3/7] Creating DataLoaders...
...
[4/7] Building model...
...
[5/7] Training for 3000 steps...
...
step 1 | train: 4.2726 | val: 4.1660 | elapsed: 2s | ETA: 6148s
...
step 3000 | train: 1.7323 | val: 1.7411 | elapsed: 474s | ETA: 0s
...
[6/7] Saving checkpoint...
...
[7/7] Generating text...
...
GENERATED TEXT (temperature=0.8, top_k=40):
...
ROMEO:
Praviour soul to shall that that are the and not,
What just happened:
- The model trained successfully and loss steadily decreased.
- It generated brand new, Shakespeare-like text based on the patterns it learned.
- While it makes some logical or grammatical mistakes, the character names, sentence structures, and vocabulary strongly mimic the training data.
$ python diagrams/charts/ch17_generated_text.py
Saved ch17-generated-text.png and ch17-generated-text.pdf
Figure 17.4: A sample from the trained model at temperature 0.8 and top-k 40.
Shape Check¶
Table 17.1 lists the parameter count of the fully assembled network.
Table 17.1: Final parameter count of the completed model.
| Tensor | Shape | What it means |
|---|---|---|
model parameters |
824,832 |
The total number of weights the model learned during training. |
Try It¶
Try It
Test drive the final model like a deployed service would by loading the saved file model_final.pt and responding to a user's prompt. You are already provided with a script that accomplishes this in the repo:
Lines 6 and 8 check if the final checkpoint exists and fall back to a previous save if it doesn't.
Key Takeaways¶
- You built the complete GPT architecture from scratch.
- The fundamental components (tokenization, embeddings, self-attention, transformer blocks, and gradient descent) are the core of all modern LLMs.
- Larger models mostly scale up these same components with more data, more parameters, and better hardware.
- Refinements like RLHF and instruction tuning are applied after this pretraining process.
Check Your Understanding¶
- What is the difference between the model we built and GPT-2?
- Why does the model output sometimes contain spelling or logic errors despite being fully trained?
- What is the purpose of an end-to-end pipeline in a business setting?
Assignment¶
Assignment 17: Ask a new question
About 15 minutes. You change one word and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/examples/ch17_deploy.pyas it is. Copy the prompt and everything the model writes after it. - Change one word. Find the line
prompt = "USER: What is the news?\n". The prompt is the text the model continues. Change the wordnewsto any other English word, in plain letters only, and leave the rest of the line as it is. Run the script again. - Compare. Does the model answer either question? What does it write instead? What do the two replies have in common?
- Explain it. In two or three sentences a manager could follow, say why this model continues your text in the shape of a play, and what extra training a real assistant gets so that it answers.
Hand in: both prompts with their replies, your answers to step 3, and your sentences.
Further Reading¶
Where prompting came from. Even a pre-trained model normally had to be fine-tuned, with fresh labeled examples and a training run, before it could do a new job. At 175 billion parameters the authors found that if you write two or three examples into the prompt, the model follows the pattern with no weights changed. People now call this prompting, and it is why you can talk to a language model and do not have to retrain it.
The step that turns a text predictor into an assistant. A model trained to continue text is different from a model that does what you ask, and it will happily continue your question with more questions. The authors collected human demonstrations of good answers and human rankings of competing answers, and fine-tuned on that feedback. This matters for how you read this book, because people preferred a 1.3 billion parameter model trained this way to the 175 billion parameter model it came from. This book deals with capability, and helpfulness is a separate problem.
Why the field started building bigger. Before this, deciding how large to make a model, how much text to train it on, and how much compute to spend was guesswork. The paper measured all three and found the error falls along smooth, predictable curves across a very wide range of sizes. Model building became a budgeting exercise, which is why the industry spent the following years scaling up. The same curves also explain the ceiling on the model you train here, because about 825,000 parameters and about a million characters of Shakespeare buy a certain quality of text, and no more.
Brown, T. B., Mann, B., Ryder, N., Subbiah, M., Kaplan, J., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., Agarwal, S., Herbert-Voss, A., Krueger, G., Henighan, T., Child, R., Ramesh, A., Ziegler, D. M., Wu, J., Winter, C., ... Amodei, D. (2020). Language models are few-shot learners (arXiv:2005.14165). arXiv. https://doi.org/10.48550/arXiv.2005.14165
Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B., Chess, B., Child, R., Gray, S., Radford, A., Wu, J., & Amodei, D. (2020). Scaling laws for neural language models (arXiv:2001.08361). arXiv. https://doi.org/10.48550/arXiv.2001.08361
Ouyang, L., Wu, J., Jiang, X., Almeida, D., Wainwright, C. L., Mishkin, P., Zhang, C., Agarwal, S., Slama, K., Ray, A., Schulman, J., Hilton, J., Kelton, F., Miller, L., Simens, M., Askell, A., Welinder, P., Christiano, P., Leike, J., & Lowe, R. (2022). Training language models to follow instructions with human feedback (arXiv:2203.02155). arXiv. https://doi.org/10.48550/arXiv.2203.02155
Note. The Tiny Shakespeare text used throughout the book comes from Andrej Karpathy's char-rnn project: https://github.com/karpathy/char-rnn{ .note }
Glossary¶
Every term the book defines, in alphabetical order, with a plain definition and the chapter where it is first explained.
Table A.1: Glossary of terms used in this book.
| Term | Meaning | Chapter |
|---|---|---|
| Autoregressive | Building an answer one piece at a time, feeding each new piece back in before predicting the next one. | 2 |
| Backpropagation | The mathematical process of calculating the gradient for every single weight in the model. | 13 |
| Batching | Grouping multiple training examples together and processing them at the same time. | 12 |
| Block Size | The maximum number of tokens the model can look at at one time (its context window). | 12 |
| Causal Mask | A filter that hides the tokens that come later, so a token sees only itself and the past. | 6 |
| Checkpoint | A file that saves a model at one point in training, with its learned weights and its configuration (how it is built). | 14 |
| Concatenation | Joining several lists of numbers end to end to make one longer list. | 7 |
| Cross-Entropy Loss | A mathematical way to measure how wrong the model's predictions are. Lower is better. | 11 |
| DataLoader | A PyTorch tool that automatically groups single examples into batches and shuffles them. | 12 |
| Dataset | A PyTorch tool that defines how to fetch one training example from the text. | 12 |
| Dropout | A technique that randomly turns off some neurons (small parts of the model) during training, so it cannot simply memorize the data. | 14 |
| Embedding | A lookup table that gives each token ID its own vector. | 5 |
| End to End | A process that runs every step on its own, from raw text to a trained model and its generated text. | 17 |
| Feed-Forward | The step after attention, where each token works on its own to process the information it gathered. | 8 |
| GELU | A smooth curve that replaces negative numbers with near-zero values. | 8 |
| Gradient | The direction we need to move our weights to increase the error. We move in the opposite direction to decrease it. | 13 |
| Greedy Decoding | Always picking the single highest-probability token. | 15 |
| Instruction tuning | An extra round of training, after the kind done in this book, that teaches the model to answer questions and follow instructions. | 17 |
| Key (K) | A list of numbers that says what a token has to offer. | 6 |
| Language Model | A system that predicts the next token in a sequence. | 2 |
| LayerNorm | A step that resets numbers to a safe size so training stays stable. | 8 |
| Learning Rate | How far the optimizer moves the weights on each step. If it is too small, training crawls, and if it is too large, it can overshoot. | 13 |
| LM Head | The model's last step, which turns each token's internal numbers into one score for every character in the vocabulary. | 10 |
| Logits | The raw scores the model outputs for each possible next token. | 10 |
| Matrix Multiplication | A way of multiplying two tensors that turns data from one shape into another. | 3 |
| Multi-Head Attention | Running several attention heads at the same time, so the same text is read in several different ways. | 7 |
| Optimizer | The algorithm that updates the model's weights. We use Adam, a popular and steady choice. | 13 |
| Package Manager | A tool that downloads and installs packages, the ready-made pieces of code a project uses. | 1 |
| Parameters | The numbers inside the model that adjust during training. | 2 |
| Projection | A final step that blends the heads' joined outputs into one list of numbers for each token. | 7 |
| PyTorch | A Python library (ready-made code) that does math on large sets of numbers very quickly. | 3 |
| Query (Q) | A list of numbers that says what a token is looking for. | 6 |
| Repository | A folder of code stored online. | 1 |
| Residual Connection | A shortcut that lets information skip a step, keeping the original signal intact. | 9 |
| RLHF | Reinforcement Learning from Human Feedback, a way to train a model on people's feedback so it answers politely and as people prefer. | 17 |
| Sampling | Choosing the next token randomly, giving higher-probability tokens a better chance to be selected. | 15 |
| Self-Attention | The step where each token looks at the tokens before it and decides how much each one matters to its own meaning. | 6 |
| Shape | How big a tensor is in each direction, such as how many rows and how many columns. | 3 |
| Softmax | A function that turns any numbers into probabilities that sum to 1. | 3 |
| State Dict | A PyTorch dictionary (a lookup table) that pairs each layer of the model with its learned weights. | 14 |
| Temperature | A number the scores (logits) are divided by before they become probabilities. A low temperature plays it safe, and a high one takes risks. | 16 |
| Tensor | A container of numbers, arranged as a list, a table, or a stack of tables. | 3 |
| Terminal | A text-based window where you type commands. | 1 |
| Token | One small piece of text, here a single character. | 2 |
| Tokenizer | A translator that cuts text into tokens and gives each token a number. | 4 |
| Top-k | A limit that lets the model sample only from the k most likely next tokens, where k is a number you choose (40 here). | 16 |
| Transformer Block | A reusable block of code containing attention, feed-forward, and normalization. | 9 |
| Value (V) | A list of numbers holding the information a token passes on when it is picked. | 6 |
| Vector | A list of numbers that works like coordinates on a map, giving a token its place among the others. | 5 |
| Virtual Environment | A separate toolbox for one project, so what you install for it stays out of your other projects. | 1 |
Ten Papers That Built Generative AI¶
Every idea in this book was somebody's result first. These ten papers are the ones the rest stands on: each solved a problem that was blocking the field, and each changed what people built afterwards. They are in the order the story runs, from how a network learns at all to how a text predictor became something you can give instructions to.
You do not need the mathematics to follow them. Each entry says what was not working, what the paper did about it, and why it still matters, and then gives the reference so you can read the original. All ten are free to read.
Table B.1: The ten papers, in the order the ideas arrived.
| # | Paper | Year | What it settled |
|---|---|---|---|
| 1 | Backpropagation | 1986 | Gave every weight in a deep network its share of the blame. |
| 2 | Long short-term memory | 1997 | Gave a sequence model a memory it could keep over long text. |
| 3 | Word vectors | 2013 | Turned word meaning into distance in a vector space. |
| 4 | Attention | 2014 | Let a model look back over its input and weigh what mattered. |
| 5 | The Transformer | 2017 | Kept attention, removed the step-by-step reading. |
| 6 | Pre-training and transfer | 2018 | Trained one model on plain text, then reused it everywhere. |
| 7 | Decoder-only language models | 2019 | Showed next-token prediction alone learns many tasks. |
| 8 | Scaling laws | 2020 | Made the pay-off from more data and compute predictable. |
| 9 | Few-shot prompting | 2020 | Taught a model a task from examples in the prompt. |
| 10 | Learning from human feedback | 2022 | Turned a text predictor into something that follows instructions. |
Backpropagation (1986)¶
How a network learns anything at all. When a network with layers in the middle gave a wrong answer, nobody could say which of the middle weights was at fault. This paper sent the error backwards through the network and gave each weight a share of the blame in proportion to how much it moved the result. Every model in this book learns that way, and so does every model in production today. In the training loop, loss.backward() does this job.
In this book: Chapter 13.
Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323, 533–536. https://doi.org/10.1038/323533a0
Long short-term memory (1997)¶
Memory, before attention. Sequential models read a sentence one word at a time and had mostly forgotten it by the end, due to the vanishing gradient as error flowed back through time steps. This work introduced a cell with gates that controlled what to remember, what to forget and what to output. Gate cells like this powered essentially all serious language applications for two decades. The cell poses the question of what the model should remember from earlier in the sentence. Attention later modeled the same concept using a different mechanism.
In this book: Chapter 2.
Hochreiter, S., & Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8), 1735–1780. https://doi.org/10.1162/neco.1997.9.8.1735
Word vectors (2013)¶
Meaning becomes geometry. If every word gets its own ID number, the model learns nothing from the numbering, and "king" sits as far from "queen" as it does from "toaster". This paper trained a deliberately cheap prediction task so that words used in similar company ended up with similar vectors, and did it fast enough to run on billions of words. Embeddings, the subject of Chapter 5, start here, and so does the vector search behind modern recommendation and retrieval.
In this book: Chapter 5.
Mikolov, T., Chen, K., Corrado, G., & Dean, J. (2013). Efficient estimation of word representations in vector space (arXiv:1301.3781). arXiv. https://doi.org/10.48550/arXiv.1301.3781
Attention (2014)¶
The first attention. Translation models of the day read the whole source sentence, squeezed it into a single fixed vector, and wrote the translation from that. Long sentences lost too much in the squeeze, so this paper let the model look back over every input word and decide, at each output word, which ones mattered. That weighted look-back is attention. Three years later the Transformer kept this idea and threw out everything around it.
In this book: Chapter 6.
Bahdanau, D., Cho, K., & Bengio, Y. (2014). Neural machine translation by jointly learning to align and translate (arXiv:1409.0473). arXiv. https://doi.org/10.48550/arXiv.1409.0473
The Transformer (2017)¶
The architecture this book builds. Reading a sequence one step at a time is slow, because step 500 cannot start until step 499 has finished, and distant words stay hard to connect. This paper removed the step-by-step reading and kept only attention, plus a note of each token's position. Every token can then be processed at once, and that made training on very large amounts of text practical. The model you build in Chapters 6 to 10 is this design, made small.
In this book: Chapter 6, Chapter 7, Chapter 9.
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention is all you need (arXiv:1706.03762). arXiv. https://doi.org/10.48550/arXiv.1706.03762
Pre-training and transfer (2018)¶
Train once, reuse everywhere. Labeled examples are expensive, and every new task used to need its own pile of them. BERT trained one Transformer on ordinary text by hiding words and asking it to fill the blanks, then adapted that single model to many tasks with a small amount of labeled data each. It reads in both directions at once, which the causal mask in Chapter 11 forbids. That mask is the difference between a model that fills blanks and one that writes forward.
In this book: Chapter 11.
Devlin, J., Chang, M.-W., Lee, K., & Toutanova, K. (2018). BERT: Pre-training of deep bidirectional transformers for language understanding (arXiv:1810.04805). arXiv. https://doi.org/10.48550/arXiv.1810.04805
Decoder-only language models (2019)¶
One model, many jobs, no retraining. The researchers wanted to know if a model trained exclusively to predict the next word would learn capabilities nobody had trained it for. Because it was trained on such a broad, diverse swath of web pages, it started answering questions, summarizing, and translating with zero task-specific training when given a prompt that made those tasks obvious. That answered the architectural question of how to build a system for text generation in favor of a decoder architecture that predicts the next token. That's the model we cover in Chapter 10.
In this book: Chapter 2, Chapter 10.
Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., & Sutskever, I. (2019). Language models are unsupervised multitask learners [Technical report]. OpenAI. https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf
Scaling laws (2020)¶
Why the field started building bigger. Before this, deciding how large to make a model, how much text to train it on, and how much compute to spend was guesswork. The paper measured all three and found the error falls along smooth, predictable curves across a very wide range of sizes. Model building became a budgeting exercise, which is why the industry spent the following years scaling up. The same curves also explain the ceiling on the model you train here, because about 825,000 parameters and about a million characters of Shakespeare buy a certain quality of text, and no more.
In this book: Chapter 12, Chapter 17.
Kaplan, J., McCandlish, S., Henighan, T., Brown, T. B., Chess, B., Child, R., Gray, S., Radford, A., Wu, J., & Amodei, D. (2020). Scaling laws for neural language models (arXiv:2001.08361). arXiv. https://doi.org/10.48550/arXiv.2001.08361
Few-shot prompting (2020)¶
Where prompting came from. Even a pre-trained model normally had to be fine-tuned, with fresh labeled examples and a training run, before it could do a new job. At 175 billion parameters the authors found that if you write two or three examples into the prompt, the model follows the pattern with no weights changed. People now call this prompting, and it is why you can talk to a language model and do not have to retrain it.
In this book: Chapter 17.
Brown, T. B., Mann, B., Ryder, N., Subbiah, M., Kaplan, J., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., Agarwal, S., Herbert-Voss, A., Krueger, G., Henighan, T., Child, R., Ramesh, A., Ziegler, D. M., Wu, J., Winter, C., ... Amodei, D. (2020). Language models are few-shot learners (arXiv:2005.14165). arXiv. https://doi.org/10.48550/arXiv.2005.14165
Learning from human feedback (2022)¶
The step that turns a text predictor into an assistant. A model trained to continue text is different from a model that does what you ask, and it will happily continue your question with more questions. The authors collected human demonstrations of good answers and human rankings of competing answers, and fine-tuned on that feedback. This matters for how you read this book, because people preferred a 1.3 billion parameter model trained this way to the 175 billion parameter model it came from. This book deals with capability, and helpfulness is a separate problem.
In this book: Chapter 17.
Ouyang, L., Wu, J., Jiang, X., Almeida, D., Wainwright, C. L., Mishkin, P., Zhang, C., Agarwal, S., Slama, K., Ray, A., Schulman, J., Hilton, J., Kelton, F., Miller, L., Simens, M., Askell, A., Welinder, P., Christiano, P., Leike, J., & Lowe, R. (2022). Training language models to follow instructions with human feedback (arXiv:2203.02155). arXiv. https://doi.org/10.48550/arXiv.2203.02155
The rest of the reading¶
These are the papers behind particular pieces of the model you built. Each one also appears at the end of the chapter that uses it.
Ba, J. L., Kiros, J. R., & Hinton, G. E. (2016). Layer normalization (arXiv:1607.06450). arXiv. https://doi.org/10.48550/arXiv.1607.06450
Fan, A., Lewis, M., & Dauphin, Y. (2018). Hierarchical neural story generation (arXiv:1805.04833). arXiv. https://doi.org/10.48550/arXiv.1805.04833
He, K., Zhang, X., Ren, S., & Sun, J. (2015). Deep residual learning for image recognition (arXiv:1512.03385). arXiv. https://doi.org/10.48550/arXiv.1512.03385
Hendrycks, D., & Gimpel, K. (2016). Gaussian error linear units (GELUs) (arXiv:1606.08415). arXiv. https://doi.org/10.48550/arXiv.1606.08415
Holtzman, A., Buys, J., Du, L., Forbes, M., & Choi, Y. (2019). The curious case of neural text degeneration (arXiv:1904.09751). arXiv. https://doi.org/10.48550/arXiv.1904.09751
Kingma, D. P., & Ba, J. (2014). Adam: A method for stochastic optimization (arXiv:1412.6980). arXiv. https://doi.org/10.48550/arXiv.1412.6980
Krizhevsky, A., Sutskever, I., & Hinton, G. E. (2017). ImageNet classification with deep convolutional neural networks. Communications of the ACM, 60(6), 84–90. https://doi.org/10.1145/3065386
Paszke, A., Gross, S., Massa, F., Lerer, A., Bradbury, J., Chanan, G., Killeen, T., Lin, Z., Gimelshein, N., Antiga, L., Desmaison, A., Köpf, A., Yang, E., DeVito, Z., Raison, M., Tejani, A., Chilamkurthy, S., Steiner, B., Fang, L., ... Chintala, S. (2019). PyTorch: An imperative style, high-performance deep learning library (arXiv:1912.01703). arXiv. https://doi.org/10.48550/arXiv.1912.01703
Rosenblatt, F. (1958). The perceptron: A probabilistic model for information storage and organization in the brain. Psychological Review, 65(6), 386–408. https://doi.org/10.1037/h0042519
Sennrich, R., Haddow, B., & Birch, A. (2015). Neural machine translation of rare words with subword units (arXiv:1508.07909). arXiv. https://doi.org/10.48550/arXiv.1508.07909
Weizenbaum, J. (1966). ELIZA: A computer program for the study of natural language communication between man and machine. Communications of the ACM, 9(1), 36–45. https://doi.org/10.1145/365153.365168