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.
Mostly, the differences between your model and big production models are differences 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 basic transformer setup (embeddings, attention, blocks, training) is the same, but modern models add refinements to make them work better:
- 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.
- Following pretraining (which we just discussed), they undergo Instruction Tuning and RLHF (Reinforcement Learning from Human Feedback), which teach them to answer questions politely and not just predict the next word.
The end-to-end pipeline ties together every box on the "where we are" map, from reading the text all the way to generating new text.
In Business
That entire script could essentially be your house-style assistant. You'd run it anytime you update your company's corpus of documents. Train overnight with your new docs, run model validation, and then put that new checkpoint into production for your marketers to use.
Code¶
In this script, we copied every line of code from previous chapters. We download the data, tokenize the data, create the DataLoaders, build the 825,000-parameter model, train it for 3,000 steps, save a checkpoint, and sample from our 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. Previously even a pretrained model required tuning (more labeled examples and a training run) before it could be used for a new task. At 175 billion parameters the authors discovered that if you plug two or three examples into the prompt, the model will mimic the pattern with zero weights updated. We now refer to this as prompting, and it's why you can converse with a language model and don't have to retrain it.
The step that turns a text predictor into an assistant. A model trained to continue text is not the same as a model that follows your instructions. It will gleefully continue your question by asking you more questions. The authors gathered human demonstrations of good responses and human rankings of response candidates, then fine-tuned based on that feedback. This is important for how you should read this book because humans liked a 1.3 billion parameter model trained this way better than the 175 billion parameter model it came from. This book is about capability. Helpfulness is orthogonal to that.
Why the field started building bigger. Prior to this work, choices of model size, text volume to train on, and compute budget had been guesswork. This paper measured all three variables and discovered error decreases smoothly and predictably across an extremely wide range of model sizes. Turning model building into a cost/budget exercise explained why the industry then scaled up for the next few years. It also shows why there is a limit to how well the model you train yourself will do, because roughly 825,000 parameters and about a million characters of Shakespeare buy you a certain quality of text, 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 }
Next up: You're done! Go build something amazing.