如何训练你的GPT:逐行注释版从零构建指南
A guide to building a world-class language model from absolute scratch. Taught like you're five. Built like you're an engineer.
I made this with the goal of learning something I didn't understand completely. Specifically the attention part. I use AI a lot to understand key concepts and verifying them.
https://camo.githubusercontent.com/5a2f51ec18ed17a970ae25ba807aecaec6061755dd098513b45e396cef963087/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f63686170746572732d31322d626c7565https://camo.githubusercontent.com/a1e50303622ed62c5474046122842ad62aade03f2fdf408f3843c67c2b20f884/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c696e65732d372532433530302532422d677265656ehttps://camo.githubusercontent.com/3573903cb0b27b22c0d0f4c7319c826eaa3cbe1627fcbf079226496652e03bfb/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f746f706963735f6578706c61696e65642d32362d7465616chttps://camo.githubusercontent.com/567308e77f1eb3c96c180176d659fbcbb7b53d71b90958683f2a507bbd9a888c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f6465253230636f6d6d656e7465642d3130302532352d627269676874677265656ehttps://camo.githubusercontent.com/bef3d88f926eaa501c981d990c44aa579a3ea2c3eeabeb03cda6bd63fa123744/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7072657265717569736974652d707974686f6e2532306261736963732d6f72616e6765https://camo.githubusercontent.com/f6b796f510f6e98ae74c80e2e10dcb55df6fedc3d17621a4eef2c88abe42bafd/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6172636869746563747572652d4c4c614d41253230332532307374796c652d707572706c65https://camo.githubusercontent.com/edc49e0653cdb8ec3a1ff620c08b054f53813ed17cde6b120f50ccd1ec372d8e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f707572706f73652d6c6561726e696e672532306f6e6c792d6c6967687467726579https://colab.research.google.com/github/raiyanyahya/how-to-train-your-gpt/blob/master/notebooks/colab_train.ipynb
•
📖 What Is This?
https://github.com/raiyanyahya/how-to-train-your-gpt#-what-is-this
This is a 12-chapter, 7,500+ line interactive textbook that teaches you how to build, train and run a modern language model from absolute scratch. The same family of architecture behind ChatGPT, Claude, LLaMA and Mistral.
Alongside the chapters there are 26 standalone topic explainers covering every technique in depth. RoPE, attention, RMSNorm, SwiGLU, KV cache, AdamW, mixed precision and more. Plus two narrative walkthroughs that trace a single sentence through the entire model step by step. Each file follows the same style: child language, no jargon, a code example you can run.
You won't just read about Transformers. You'll write every line yourself: tokenizer, embeddings, attention, training loop, inference engine. Every single line annotated to explain what it does and why it's there.
•
🤔 Why This Exists
https://github.com/raiyanyahya/how-to-train-your-gpt#-why-this-exists
Most ML tutorials fall into one of two traps:
• *The goal:** After finishing, you won't just know that attention "works". You'll understand the variance argument behind 1/√d_k. How RoPE captures relative position through rotation. Why pre-norm beats post-norm for deep networks. And exactly where every gradient flows during backpropagation.
•
👥 Who Is This For?
https://github.com/raiyanyahya/how-to-train-your-gpt#-who-is-this-for
• *🔧 Prerequisites:** Python basics (variables, functions, classes, pip install). That's it. No calculus, no linear algebra, no PyTorch experience required. We teach those as we go.
•
🗺️ Chapters
https://github.com/raiyanyahya/how-to-train-your-gpt#%EF%B8%8F-chapters
⭐ Start with Chapter 0 (https://github.com/raiyanyahya/how-to-train-your-gpt/blob/master/chapters/00_overview.md) and read sequentially. Each builds on the previous.
•
🏗️ What You'll Build
https://github.com/raiyanyahya/how-to-train-your-gpt#%EF%B8%8F-what-youll-build
💎 ~860 lines of core model code, ~2,600 lines of explanation and diagrams
•
🏛️ Architecture
https://github.com/raiyanyahya/how-to-train-your-gpt#%EF%B8%8F-architecture
This guide implements the latest publicly-documented decoder-only Transformer:
ℹ️ GPT-4 and Claude architectures are proprietary/undisclosed. This teaches the best publicly-confirmed architecture: what LLaMA 3, Mistral and Qwen 2.5 use.
•
🚀 Quick Start
https://github.com/raiyanyahya/how-to-train-your-gpt#-quick-start
1. Clone
git clone https://github.com/raiyanyahya/how-to-train-your-gpt.git
cd how-to-train-your-gpt
2. Create environment
python -m venv gpt_env
source gpt_env/bin/activate # Mac/Linux
gpt_env\Scripts\activate # Windows
3. Install dependencies (CPU version. For GPU see below)
pip install torch tiktoken datasets numpy matplotlib --index-url https://download.pytorch.org/whl/cpu
Or use the requirements file
pip install -r requirements.txt
4. Verify GPU (optional but recommended)
python -c "import torch; print(f'CUDA: {torch.cuda.is_available()}')"
5. Start reading!
open chapters/00_overview.md
Run the training script:
python main.py
This uses the tiny config (d_model=256, 4 layers) by default. Training takes a few minutes on CPU. For the GPT-2 scale config (151M params, 768 dims, 12 layers), edit the config in main.py and uncomment the larger configuration.
💻 The default config uses a tiny model (d_model=256, 4 layers, 17M params) that runs in minutes on CPU. For the full GPT-2 scale (151M params, 768 dims, 12 layers), edit the config in main.py and uncomment the larger configuration. You'll need a GPU for that one.
•
📓 Jupyter Notebooks
https://github.com/raiyanyahya/how-to-train-your-gpt#-jupyter-notebooks
Alongside the textbook, each chapter has a companion notebook you can run live. These strip away the explanations and give you pure, clean code that executes from top to bottom. If the textbook teaches you why, the notebooks let you see it happen.
We're going to run this whole project on a very small dataset so you can watch training happen in minutes rather than weeks. Every notebook is self-contained. Open it, run all cells and you'll see the model learn in real time.
Install everything you need
pip install jupyter tiktoken torch numpy datasets matplotlib --index-url https://download.pytorch.org/whl/cpu
Start with chapter 2 (tokenization)
jupyter notebook notebooks/02_tokenization.ipynb
Notebooks live in the notebooks/ directory, one per chapter. Open any of them and hit Cell → Run All.
•
📚 Topic Explainers
https://github.com/raiyanyahya/how-to-train-your-gpt#-topic-explainers
Each concept in this guide has a dedicated deep dive inside explanations and examples WIP/. These are written in the simplest possible language. No jargon. No formulas before analogies. Every explainer covers what, where, why, when and how with a code example you can run.
The last two files are narrative walkthroughs. A Token's Journey follows one sentence through the entire model. The Complete Story covers every component across 22 parts. Read these after the chapters to see how everything connects.
•
📖 How to Read
https://github.com/raiyanyahya/how-to-train-your-gpt#-how-to-read
Each chapter follows the same 4-step structure:
💡 Tip: Lost in the code? Jump back to the analogy. Confused by the math? Skip to the worked example.
•
✨ What Makes This Different
https://github.com/raiyanyahya/how-to-train-your-gpt#-what-makes-this-different
•
🎯 Skills You'll Gain
https://github.com/raiyanyahya/how-to-train-your-gpt#-skills-youll-gain
• ✅ Explain how GPT-4 tokenizes text using BPE
• ✅ Understand why RoPE, RMSNorm and SwiGLU replaced older techniques
• ✅ Compute attention scores manually for a 3-token sentence
• ✅ Debug a Transformer training loop (loss spikes, flat lines, overfitting)
• ✅ Choose sampling parameters (temperature, top_k, top_p) for different use cases
• ✅ Understand why KV caching is critical for production inference
• ✅ Read modern ML papers with confidence (you'll recognize every component)
•
🔮 Next Steps After Finishing
https://github.com/raiyanyahya/how-to-train-your-gpt#-next-steps-after-finishing
•
📁 File Structure
https://github.com/raiyanyahya/how-to-train-your-gpt#-file-structure
•
"Any sufficiently explained technology is indistinguishable from magic. Until you build it yourself."
⭐ Star this repo if you found it useful | 🐛 Issues & PRs welcome | 📖 Happy learning!