{"slug": "how-to-train-your-gpt", "title": "How to Train Your GPT", "summary": "A new 12-chapter, 7,500+ line interactive textbook teaches readers how to build, train, and run a modern language model from scratch, covering the architecture behind ChatGPT, Claude, LLaMA, and Mistral. The guide, written in child-friendly language with no jargon, includes 28 standalone topic explainers and two narrative walkthroughs, requiring only basic Python knowledge. It aims to provide deep understanding of components like attention, RoPE, and RMSNorm, with every line of code annotated.", "body_md": "A guide to building a world-class language model from absolute scratch. Taught like you're five. Built like you're an engineer.\n\nI 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.\n\nThis 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.\n\nAlongside the chapters there are **28 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.\n\nYou 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.\n\nMost ML tutorials fall into one of two traps:\n\n| ❌ Too Shallow | ❌ Too Academic | ✅ This Guide |\n|---|---|---|\n`model = GPT().fit(data)` |\n40-page papers, dense notation | 5-year-old analogies → full working code |\n| You learn to call APIs | Assumes PhD in ML | Zero ML experience required |\n| No understanding of internals | No worked examples | Every line annotated with WHAT & WHY |\n\n**The goal:** After finishing, you won't just know that attention \"works\". You'll understand the variance argument behind `1/√d_k`\n\n. How RoPE captures relative position through rotation. Why pre-norm beats post-norm for deep networks. And exactly where every gradient flows during backpropagation.\n\n| 🧑💻 You Are... | 📚 You Need... |\n|---|---|\n| A Python developer curious about how ChatGPT actually works | Basic Python (functions, classes, lists). No ML experience |\n| A student who wants to deeply understand Transformers | Willingness to read ~3,500 lines of commented code |\n| An engineer evaluating LLM architectures | Understanding of tradeoffs (RoPE vs learned, RMSNorm vs LayerNorm) |\n| Someone who got lost at \"attention\" in other tutorials | Party analogy + worked numeric example with real numbers |\n\n**🔧 Prerequisites:** Python basics (variables, functions, classes, `pip install`\n\n). That's it. No calculus, no linear algebra, no PyTorch experience required. We teach those as we go.\n\n| Chapter | What You'll Learn |\n|---|---|\n|\nWhat is a GPT? The big picture |\n|\nInstall tools, GPU vs CPU, venv, PyTorch basics |\n|\nBPE walkthrough: how \"unbelievably\" becomes tokens |\n|\nHow numbers become meaning. king − man + woman = queen |\n|\nRoPE: why LLaMA rotates vectors, not adds numbers |\n|\n⭐ THE CORE. Q,K,V, scaling, causal mask, 8-step walkthrough |\n|\nRMSNorm, SwiGLU, residuals, pre-norm vs post-norm |\n|\n151M parameter model (with SwiGLU), weight tying, logits explained |\n|\nCross-entropy, backprop, AdamW, cosine warmup, mixed precision |\n|\nKV cache, temperature, top-k/p, beam search, repetition penalty |\n|\nRunnable `main.py` : everything in one file |\n|\nArchitecture provenance table, parameter breakdown |\n\n⭐\n\nStart withEach builds on the previous.[Chapter 0]and read sequentially.\n\n| 🧩 Component | 📝 Lines | 💡 What You'll Understand |\n|---|---|---|\nBPE Tokenizer |\n~60 | How GPT-4 splits \"unbelievably\" → \"un\" + \"believ\" + \"ably\" |\nEmbeddings |\n~30 | How \"cat\" and \"dog\" end up near each other in 768D space |\nRoPE |\n~70 | Why LLaMA rotates vectors instead of adding position numbers |\nMulti-Head Attention |\n~120 | The exact 8-step computation behind every modern LLM |\nTransformer Block |\n~50 | Why residual connections are the \"gradient highway\" |\nFull GPT Model |\n~200 | 151M parameter model with SwiGLU, weight tying and pre-norm |\nTraining Pipeline |\n~250 | AdamW, cosine warmup, mixed precision, gradient accumulation |\nInference Engine |\n~80 | KV cache, temperature, top-k/p, beam search |\n\n💎\n\n~860 lines of core model code, ~2,600 lines of explanation and diagrams\n\nThis guide implements the **latest publicly-documented** decoder-only Transformer:\n\n| 🧬 Technique | 📦 Source Model | ⚡ Why It Matters |\n|---|---|---|\nRoPE |\nLLaMA, Mistral, Qwen | Relative position without learned parameters |\nRMSNorm |\nLLaMA, Mistral, Gemma | 15% faster than LayerNorm, equally effective |\nSwiGLU |\nPaLM, LLaMA, Gemini | Learns which information to pass or block |\nPre-Norm |\nGPT-3, all modern | Stable training at 100+ layers |\nAdamW |\nGPT-3+ | Better generalization than vanilla Adam |\nBPE |\nGPT-2/3/4 | Handles any text. Even unseen words and emoji |\nWeight Tying |\nGPT-2/3 | Saves 30% parameters, improves training signal |\nMixed Precision |\nAll production LLMs | 2× speed, half memory, same quality |\n\nℹ️ GPT-4 and Claude architectures are proprietary/undisclosed. This teaches the best publicly-confirmed architecture: what LLaMA 3, Mistral and Qwen 2.5 use.\n\n```\n# 1. Clone\ngit clone https://github.com/raiyanyahya/how-to-train-your-gpt.git\ncd how-to-train-your-gpt\n\n# 2. Create environment\npython -m venv gpt_env\nsource gpt_env/bin/activate          # Mac/Linux\n# gpt_env\\Scripts\\activate           # Windows\n\n# 3. Install dependencies (CPU version. For GPU see below)\npip install torch tiktoken datasets numpy matplotlib --index-url https://download.pytorch.org/whl/cpu\n\n# Or use the requirements file\npip install -r requirements.txt\n\n# 4. Verify GPU (optional but recommended)\npython -c \"import torch; print(f'CUDA: {torch.cuda.is_available()}')\"\n\n# 5. Start reading!\nopen chapters/00_overview.md\n```\n\nRun the training script:\n\n```\npython main.py\n```\n\nThis 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.\n\n💻 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\n\n`main.py`\n\nand uncomment the larger configuration. You'll need a GPU for that one.\n\nAlongside 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.\n\nWe'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.\n\n```\n# Install everything you need\npip install jupyter tiktoken torch numpy datasets matplotlib --index-url https://download.pytorch.org/whl/cpu\n\n# Start with chapter 2 (tokenization)\njupyter notebook notebooks/02_tokenization.ipynb\n```\n\nNotebooks live in the `notebooks/`\n\ndirectory, one per chapter. Open any of them and hit **Cell → Run All**.\n\nEach concept in this guide has a dedicated deep dive inside `explanations and examples WIP/`\n\n. 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.\n\nThe 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.\n\n| Topic | File | What It Covers |\n|---|---|---|\n| RoPE |\n|\n\n[attention.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/attention.md)[bpe_tokenization.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/bpe_tokenization.md)[embeddings.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/embeddings.md)[rmsnorm.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/rmsnorm.md)[swiglu.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/swiglu.md)[causal_masking.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/causal_masking.md)[residual_connections.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/residual_connections.md)[kv_cache.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/kv_cache.md)[sampling.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/sampling.md)[mixed_precision.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/mixed_precision.md)[adamw.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/adamw.md)[weight_tying.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/weight_tying.md)[gradient_clipping.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/gradient_clipping.md)[cosine_warmup.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/cosine_warmup.md)[pre_norm.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/pre_norm.md)[grouped_query_attention.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/grouped_query_attention.md)[flash_attention.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/flash_attention.md)[how_to_read_loss.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/how_to_read_loss.md)[mixture_of_experts.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/mixture_of_experts.md)[speculative_decoding.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/speculative_decoding.md)[perplexity.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/perplexity.md)[beam_search.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/beam_search.md)[cheatsheet.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/cheatsheet.md)[faq.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/faq.md)[encoder_decoder_architectures.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/encoder_decoder_architectures.md)**A Token's Journey**[a_tokens_journey.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/a_tokens_journey.md)**The Complete Story**[the_complete_story.md](/raiyanyahya/how-to-train-your-gpt/blob/master/explanations%20and%20examples%20WIP/the_complete_story.md)Each chapter follows the same **4-step structure**:\n\n| Step | Format | Purpose |\n|---|---|---|\n1️⃣ Analogy |\nPlain English, 5-year-old level | Build intuition before math |\n2️⃣ Worked Example |\nReal numbers traced through | See exactly what happens |\n3️⃣ Annotated Code |\nEvery line: `WHAT` + `WHY` |\nUnderstand every decision |\n4️⃣ Diagram |\nMermaid flowchart or ASCII | Visualize data flow |\n\n💡\n\nTip:Lost in the code? Jump back to the analogy. Confused by the math? Skip to the worked example.\n\n| Aspect | 😴 Typical Tutorial | 🔥 This Guide |\n|---|---|---|\nExplanation depth |\n\"Attention helps the model focus\" | 8-step worked example with real numbers + variance math + causal mask visualization |\nCode comments |\nFew or none | Every single line: WHAT + WHY |\nModern techniques |\nGPT-2 style (2019) | LLaMA 3 style (2024): RoPE, RMSNorm, SwiGLU |\nTraining |\nUses HuggingFace Trainer | Full custom loop: AdamW, cosine warmup, mixed precision, grad accumulation |\nInference |\n`model.generate()` |\nTemperature, top-k, top-p, beam search, KV cache explained |\nTarget audience |\nML engineers | Python developers with zero ML experience |\nDiagrams |\nNone | Mermaid flowcharts + ASCII matrices + worked examples |\n\n- ✅ Explain how GPT-4 tokenizes text using BPE\n- ✅ Understand why RoPE, RMSNorm and SwiGLU replaced older techniques\n- ✅ Compute attention scores manually for a 3-token sentence\n- ✅ Debug a Transformer training loop (loss spikes, flat lines, overfitting)\n- ✅ Choose sampling parameters (temperature, top_k, top_p) for different use cases\n- ✅ Understand why KV caching is critical for production inference\n- ✅ Read modern ML papers with confidence (you'll recognize every component)\n\n| Experiment | What to Change | What You'll Learn |\n|---|---|---|\nBigger model |\n`num_layers` 12 → 24 |\nHow depth improves reasoning |\nMore data |\nAdd BookCorpus, C4, The Pile | Impact of data quality and diversity |\nFlash Attention |\nInstall `flash-attn` , swap attention |\n2-5× faster training, longer context |\nGrouped Query Attention |\nSet `num_kv_heads` < `num_heads` |\nHow Mistral achieves efficient inference |\nLoRA fine-tuning |\nAdd low-rank adapter layers | Customize models without full retraining |\nRLHF / DPO |\nAdd reward model training | How ChatGPT learns to follow instructions |\nKV Cache |\nImplement persistent key-value storage | 500× faster text generation |\nMixture of Experts |\nRoute tokens through different FFN experts | How GPT-4 scales to trillions of params |\n\n```\n📦 how-to-train-your-gpt/\n├── 📄 README.md              ← You are here\n├── 🐍 main.py                ← Runnable training script (clone & run)\n├── 📋 requirements.txt       ← One command install\n├── 📂 chapters/\n│   ├── 🏠 00_overview.md     ← What is a GPT? Why build one?\n│   ├── 🔧 01_setup.md        ← Install tools, GPU vs CPU, venv basics\n│   ├── 🔪 02_tokenization.md ← BPE walkthrough, EOS tokens, emoji handling\n│   ├── 🧊 03_embeddings.md   ← How numbers become meaning, king − man + woman\n│   ├── 📍 04_positional_encoding.md ← RoPE math, numerical example, theta\n│   ├── 🧠 05_attention.md    ← ⭐ THE CORE (713 lines). Q,K,V, scaling, causal mask\n│   ├── 🧱 06_transformer_block.md ← RMSNorm, SwiGLU, residuals, pre-norm vs post\n│   ├── 🏗️ 07_gpt_model.md    ← Complete 151M model, weight tying, logits explained\n│   ├── 🏋️ 08_training.md     ← Cross-entropy, backprop, AdamW, cosine warmup\n│   ├── 🎤 09_inference.md    ← KV cache, temperature, top-k/p, beam search\n│   ├── 📜 10_full_script.md  ← About main.py\n│   └── 📊 11_glossary.md     ← Architecture provenance, parameter breakdown\n├── 📓 notebooks/             ← Jupyter notebooks (one per chapter)\n│   ├── 🎨 attention_visualized.ipynb ← Watch attention weights in action\n│   └── ☁️ colab_train.ipynb  ← One-click cloud training on Colab\n├── 🎯 fine-tuning/           ← Fine-tuning guide: LoRA, QLoRA, data prep\n│   ├── 📄 README.md\n│   ├── 01_what_is_finetuning.md\n│   ├── 02_lora_explained.md\n│   ├── 03_qlora_explained.md\n│   ├── 04_data_preparation.md\n│   ├── 05_full_finetune.md\n│   └── 📓 notebooks/lora_finetune.ipynb\n├── 📚 explanations and examples WIP/ ← Standalone explainers (28 topics)\n└── 📄 CONTRIBUTING.md\n```\n\n*\"Any sufficiently explained technology is indistinguishable from magic. Until you build it yourself.\"*\n\n⭐ Star this repo if you found it useful | 🐛 Issues & PRs welcome | 📖 Happy learning!", "url": "https://wpnews.pro/news/how-to-train-your-gpt", "canonical_source": "https://github.com/raiyanyahya/how-to-train-your-gpt", "published_at": "2026-08-27 22:48:28+00:00", "updated_at": "2026-08-27 23:19:03.991091+00:00", "lang": "en", "topics": ["large-language-models", "artificial-intelligence", "machine-learning", "ai-research", "ai-tools"], "entities": ["ChatGPT", "Claude", "LLaMA", "Mistral", "PyTorch"], "alternates": {"html": "https://wpnews.pro/news/how-to-train-your-gpt", "markdown": "https://wpnews.pro/news/how-to-train-your-gpt.md", "text": "https://wpnews.pro/news/how-to-train-your-gpt.txt", "jsonld": "https://wpnews.pro/news/how-to-train-your-gpt.jsonld"}}