Skip to content

Build a modern LLM from scratch. Every line commented. Explained like we are five.

add requirements, colab notebook, and attention visualization

raiyanyahyaaf415bc0f8ea
diff --git a/README.md b/README.md
index 5fcc3f5..ff17b0d 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,12 @@
<img src="https://img.shields.io/badge/purpose-learning%20only-lightgrey" alt="Learning only">
</p>
+<p align="center">
+ <a href="https://colab.research.google.com/github/raiyanyahya/how-to-train-your-gpt/blob/master/notebooks/colab_train.ipynb">
+ <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" height="25">
+ </a>
+</p>
+
---
## πŸ“– What Is This?
@@ -125,6 +131,9 @@ source gpt_env/bin/activate # Mac/Linux
# 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()}')"
@@ -253,6 +262,7 @@ Each chapter follows the same **4-step structure**:
πŸ“¦ how-to-train-your-gpt/
β”œβ”€β”€ πŸ“„ README.md ← You are here
β”œβ”€β”€ 🐍 main.py ← Runnable training script (clone & run)
+β”œβ”€β”€ πŸ“‹ requirements.txt ← One command install
β”œβ”€β”€ πŸ“‚ chapters/
β”‚ β”œβ”€β”€ 🏠 00_overview.md ← What is a GPT? Why build one?
β”‚ β”œβ”€β”€ πŸ”§ 01_setup.md ← Install tools, GPU vs CPU, venv basics
@@ -267,7 +277,9 @@ Each chapter follows the same **4-step structure**:
β”‚ β”œβ”€β”€ πŸ“œ 10_full_script.md ← About main.py
β”‚ └── πŸ“Š 11_glossary.md ← Architecture provenance, parameter breakdown
β”œβ”€β”€ πŸ““ notebooks/ ← Jupyter notebooks (one per chapter)
-β”œβ”€β”€ πŸ“š explanations and examples WIP/ ← Standalone explainers (15 topics)
+β”‚ β”œβ”€β”€ 🎨 attention_visualized.ipynb ← Watch attention weights in action
+β”‚ └── ☁️ colab_train.ipynb ← One-click cloud training on Colab
+β”œβ”€β”€ πŸ“š explanations and examples WIP/ ← Standalone explainers (18 topics)
└── πŸ“„ CONTRIBUTING.md
```
diff --git a/notebooks/attention_visualized.ipynb b/notebooks/attention_visualized.ipynb
new file mode 100644
index 0000000..44ef3a2
--- /dev/null
+++ b/notebooks/attention_visualized.ipynb
@@ -0,0 +1,357 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Attention Visualized\n",
+ "\n",
+ "This notebook builds a tiny attention layer and lets you watch\n",
+ "it in action. You will see which words attend to which other\n",
+ "words and how the causal mask blocks the future. Every number\n",
+ "is real. Every heatmap shows actual attention weights.\n",
+ "\n",
+ "We will feed the sentence *The cat sat on the mat* through a\n",
+ "single attention head and plot the weight matrix as a heatmap.\n",
+ "Then we will add more heads and see how each one specializes.\n",
+ "\n",
+ "No training needed. The weights are random. But the patterns\n",
+ "are real. The causal mask always blocks the future. The softmax\n",
+ "always makes each row sum to one."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import torch\n",
+ "import torch.nn as nn\n",
+ "import torch.nn.functional as F\n",
+ "import math\n",
+ "import matplotlib.pyplot as plt\n",
+ "import numpy as np"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Build a tiny attention module\n",
+ "\n",
+ "This is the exact same attention code from the guide but\n",
+ "modified to return the attention weights for visualization."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class SingleHeadAttention(nn.Module):\n",
+ " def __init__(self, d_model, head_dim):\n",
+ " super().__init__()\n",
+ " self.head_dim = head_dim\n",
+ " self.w_q = nn.Linear(d_model, head_dim, bias=False)\n",
+ " self.w_k = nn.Linear(d_model, head_dim, bias=False)\n",
+ " self.w_v = nn.Linear(d_model, head_dim, bias=False)\n",
+ "\n",
+ " def forward(self, x, causal=True, return_weights=False):\n",
+ " batch, seq_len, d_model = x.shape\n",
+ " q = self.w_q(x)\n",
+ " k = self.w_k(x)\n",
+ " v = self.w_v(x)\n",
+ "\n",
+ " scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n",
+ "\n",
+ " if causal:\n",
+ " mask = torch.tril(torch.ones(seq_len, seq_len, device=x.device))\n",
+ " scores = scores.masked_fill(mask == 0, float('-inf'))\n",
+ "\n",
+ " weights = F.softmax(scores, dim=-1)\n",
+ " output = weights @ v\n",
+ "\n",
+ " if return_weights:\n",
+ " return output, weights\n",
+ " return output\n",
+ "\n",
+ "\n",
+ "class MultiHeadAttention(nn.Module):\n",
+ " def __init__(self, d_model, num_heads):\n",
+ " super().__init__()\n",
+ " assert d_model % num_heads == 0\n",
+ " self.num_heads = num_heads\n",
+ " self.head_dim = d_model // num_heads\n",
+ " self.qkv_proj = nn.Linear(d_model, 3 * d_model, bias=False)\n",
+ " self.out_proj = nn.Linear(d_model, d_model, bias=False)\n",
+ "\n",
+ " def forward(self, x, causal=True, return_weights=False):\n",
+ " batch, seq_len, d_model = x.shape\n",
+ " qkv = self.qkv_proj(x)\n",
+ " qkv = qkv.reshape(batch, seq_len, 3, self.num_heads, self.head_dim)\n",
+ " qkv = qkv.permute(2, 0, 3, 1, 4)\n",
+ " q, k, v = qkv[0], qkv[1], qkv[2]\n",
+ "\n",
+ " scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n",
+ "\n",
+ " if causal:\n",
+ " mask = torch.tril(torch.ones(seq_len, seq_len, device=x.device))\n",
+ " mask = mask.view(1, 1, seq_len, seq_len)\n",
+ " scores = scores.masked_fill(mask == 0, float('-inf'))\n",
+ "\n",
+ " weights = F.softmax(scores, dim=-1)\n",
+ " output = weights @ v\n",
+ " output = output.transpose(1, 2).contiguous()\n",
+ " output = output.reshape(batch, seq_len, d_model)\n",
+ " output = self.out_proj(output)\n",
+ "\n",
+ " if return_weights:\n",
+ " return output, weights\n",
+ " return output"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Create a tiny embedding for our sentence\n",
+ "\n",
+ "We will use small random vectors instead of a real embedding\n",
+ "table. The attention patterns still work the same way."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "torch.manual_seed(42)\n",
+ "words = [\"The\", \"cat\", \"sat\", \"on\", \"the\", \"mat\"]\n",
+ "seq_len = len(words)\n",
+ "\n",
+ "d_model = 768\n",
+ "x = torch.randn(1, seq_len, d_model)\n",
+ "\n",
+ "print(f\"Sequence length: {seq_len}\")\n",
+ "print(f\"Input shape: {x.shape}\")\n",
+ "print(f\"Words: {words}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Single head attention heatmap\n",
+ "\n",
+ "One attention head produces one weight matrix. Each row is\n",
+ "a token acting as query. Each column is a token acting as key.\n",
+ "The color shows how much attention token i gives to token j."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "attn_single = SingleHeadAttention(d_model, head_dim=64)\n",
+ "_, weights = attn_single(x, causal=True, return_weights=True)\n",
+ "\n",
+ "w = weights[0].detach().numpy()\n",
+ "\n",
+ "fig, ax = plt.subplots(figsize=(7, 6))\n",
+ "im = ax.imshow(w, cmap='YlOrRd', vmin=0, vmax=1)\n",
+ "\n",
+ "ax.set_xticks(range(seq_len))\n",
+ "ax.set_xticklabels(words, rotation=45, ha='right')\n",
+ "ax.set_yticks(range(seq_len))\n",
+ "ax.set_yticklabels(words)\n",
+ "ax.set_xlabel('Key (what I offer)')\n",
+ "ax.set_ylabel('Query (what I am looking for)')\n",
+ "ax.set_title('Single Head Attention Weights')\n",
+ "\n",
+ "for i in range(seq_len):\n",
+ " for j in range(seq_len):\n",
+ " color = 'white' if w[i, j] > 0.5 else 'black'\n",
+ " ax.text(j, i, f'{w[i, j]:.2f}', ha='center', va='center', color=color, fontsize=9)\n",
+ "\n",
+ "plt.colorbar(im, ax=ax, shrink=0.8)\n",
+ "plt.tight_layout()\n",
+ "plt.show()\n",
+ "\n",
+ "print(\"Upper right is all zeros.\")\n",
+ "print(\"The causal mask blocks tokens from seeing the future.\")\n",
+ "print(f\"Token 0 sees only itself: {w[0, 0]:.2f}\")\n",
+ "print(f\"Token 5 sees all six tokens: max={w[5].max():.2f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## What happens without the causal mask\n",
+ "\n",
+ "If we turn off the mask every token can see every other token.\n",
+ "This is what an encoder like BERT uses. But a GPT cannot do\n",
+ "this during training or it would cheat."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "_, weights_no_mask = attn_single(x, causal=False, return_weights=True)\n",
+ "\n",
+ "w = weights_no_mask[0].detach().numpy()\n",
+ "\n",
+ "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))\n",
+ "\n",
+ "_, weights_causal = attn_single(x, causal=True, return_weights=True)\n",
+ "w_causal = weights_causal[0].detach().numpy()\n",
+ "\n",
+ "ax1.imshow(w_causal, cmap='YlOrRd', vmin=0, vmax=1)\n",
+ "ax1.set_xticks(range(seq_len))\n",
+ "ax1.set_xticklabels(words, rotation=45, ha='right')\n",
+ "ax1.set_yticks(range(seq_len))\n",
+ "ax1.set_yticklabels(words)\n",
+ "ax1.set_title('With causal mask (GPT)')\n",
+ "\n",
+ "ax2.imshow(w, cmap='YlOrRd', vmin=0, vmax=1)\n",
+ "ax2.set_xticks(range(seq_len))\n",
+ "ax2.set_xticklabels(words, rotation=45, ha='right')\n",
+ "ax2.set_yticks(range(seq_len))\n",
+ "ax2.set_yticklabels(words)\n",
+ "ax2.set_title('Without causal mask (no cheating prevention)')\n",
+ "\n",
+ "plt.tight_layout()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Multi-head attention: twelve heads\n",
+ "\n",
+ "Each head learns a different pattern. Even with random weights\n",
+ "you can see that each head produces a different weight matrix.\n",
+ "In a trained model these differences would correspond to actual\n",
+ "linguistic patterns like subject-verb agreement."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "attn_multi = MultiHeadAttention(d_model=768, num_heads=12)\n",
+ "_, weights = attn_multi(x, causal=True, return_weights=True)\n",
+ "\n",
+ "fig, axes = plt.subplots(3, 4, figsize=(16, 12))\n",
+ "axes = axes.flatten()\n",
+ "\n",
+ "for h in range(12):\n",
+ " w = weights[0, h].detach().numpy()\n",
+ " ax = axes[h]\n",
+ " im = ax.imshow(w, cmap='YlOrRd', vmin=0, vmax=1)\n",
+ " ax.set_xticks(range(seq_len))\n",
+ " ax.set_xticklabels(words, rotation=45, ha='right', fontsize=7)\n",
+ " ax.set_yticks(range(seq_len))\n",
+ " ax.set_yticklabels(words, fontsize=7)\n",
+ " ax.set_title(f'Head {h + 1}', fontsize=10)\n",
+ "\n",
+ "plt.suptitle('All 12 Attention Heads in One Transformer Layer', fontsize=14)\n",
+ "plt.tight_layout()\n",
+ "plt.show()\n",
+ "\n",
+ "print(\"Each head sees the same input but produces different attention patterns.\")\n",
+ "print(\"The causal mask is always present. Every head has the upper right blocked.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Try your own sentence\n",
+ "\n",
+ "Change the words below and rerun the cells to see how attention\n",
+ "behaves with different inputs. The patterns will change because\n",
+ "each word's random embedding is different. With real trained\n",
+ "embeddings you would see meaningful linguistic patterns."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "your_words = [\"The\", \"dog\", \"ran\", \"through\", \"the\", \"park\"]\n",
+ "\n",
+ "x2 = torch.randn(1, len(your_words), 768)\n",
+ "_, weights = attn_multi(x2, causal=True, return_weights=True)\n",
+ "\n",
+ "fig, axes = plt.subplots(2, 6, figsize=(20, 7))\n",
+ "axes = axes.flatten()\n",
+ "\n",
+ "for h in range(12):\n",
+ " w = weights[0, h].detach().numpy()\n",
+ " ax = axes[h]\n",
+ " ax.imshow(w, cmap='YlOrRd', vmin=0, vmax=1)\n",
+ " ax.set_xticks(range(len(your_words)))\n",
+ " ax.set_xticklabels(your_words, rotation=45, ha='right', fontsize=7)\n",
+ " ax.set_yticks(range(len(your_words)))\n",
+ " ax.set_yticklabels(your_words, fontsize=7)\n",
+ " ax.set_title(f'Head {h + 1}', fontsize=9)\n",
+ "\n",
+ "plt.suptitle(f'Attention patterns for: {\" \".join(your_words)}', fontsize=14)\n",
+ "plt.tight_layout()\n",
+ "plt.show()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## What these heatmaps teach you\n",
+ "\n",
+ "The upper right triangle is always empty. The causal mask blocks\n",
+ "every token from seeing words that come after it. This is what\n",
+ "makes GPT a language model instead of an encoder.\n",
+ "\n",
+ "The diagonal is often bright. Every token attends to itself.\n",
+ "Self attention is important because no other token has exactly\n",
+ "the same information you have about yourself.\n",
+ "\n",
+ "The first row is always solid on column zero. Token zero has\n",
+ "only itself to look at. It must put all its attention there.\n",
+ "\n",
+ "In a trained model the attention patterns would be meaningful.\n",
+ "Head three might connect subjects to their verbs. Head seven\n",
+ "might connect pronouns to the nouns they refer to. With random\n",
+ "weights the patterns are random but the structure is clear.\n",
+ "The model has the capacity to learn these patterns. It just\n",
+ "needs data and training."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python",
+ "version": "3.10.0"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/notebooks/colab_train.ipynb b/notebooks/colab_train.ipynb
new file mode 100644
index 0000000..3f0a42b
--- /dev/null
+++ b/notebooks/colab_train.ipynb
@@ -0,0 +1,143 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# How to Train Your GPT : Run in Colab\n",
+ "\n",
+ "This notebook clones the repo, installs dependencies and trains\n",
+ "a tiny GPT model on Wikipedia text. It takes about 5 minutes on\n",
+ "the free Colab GPU. At the end you will have a trained model\n",
+ "that can generate text.\n",
+ "\n",
+ "Click **Runtime β†’ Run all** to go from zero to a working language\n",
+ "model in one click."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 1: Clone the repo"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "!git clone https://github.com/raiyanyahya/how-to-train-your-gpt.git\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 2: Install dependencies"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%cd how-to-train-your-gpt\n",
+ "!pip install -q tiktoken datasets matplotlib"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 3: Verify GPU"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import torch\n",
+ "print(f\"PyTorch {torch.__version__}\")\n",
+ "if torch.cuda.is_available():\n",
+ " print(f\"GPU: {torch.cuda.get_device_name(0)}\")\n",
+ " print(f\"Memory: {torch.cuda.get_device_properties(0).total_mem / 1e9:.1f} GB\")\n",
+ "else:\n",
+ " print(\"No GPU found. Training will be slow.\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 4: Train the model\n",
+ "\n",
+ "This trains for 500 steps with a tiny model (d_model=256, 4 layers).\n",
+ "It takes about 2-5 minutes on a T4 GPU. For a bigger model edit\n",
+ "the config in main.py and uncomment the GPT-2 Small config."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%run main.py\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Step 5: Show the loss curve"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import os\n",
+ "from IPython.display import Image, display\n",
+ "if os.path.exists('loss_curve.png'):\n",
+ " display(Image('loss_curve.png'))\n",
+ "else:\n",
+ " print('No loss curve found. Training may have failed.')\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Done\n",
+ "\n",
+ "You just trained a language model from scratch on Wikipedia text.\n",
+ "The checkpoint is saved at `checkpoints/model.pt`. To generate\n",
+ "text open the inference notebook at `notebooks/09_inference.ipynb`."
+ ]
+ }
+ ],
+ "metadata": {
+ "colab": {
+ "name": "how-to-train-your-gpt.ipynb",
+ "provenance": []
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python",
+ "version": "3.10.0"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000..cadc3e0
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,7 @@
+--extra-index-url https://download.pytorch.org/whl/cpu
+torch>=2.0
+tiktoken
+datasets
+numpy
+matplotlib
+jupyter