Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
train and infer
raiyanyahya00f00cc9f9d6
diff --git a/.gitignore b/.gitignoreindex 87620ac..73a2c31 100644--- a/.gitignore+++ b/.gitignore@@ -1 +1,2 @@.ipynb_checkpoints/+checkpoints/diff --git a/chapters/09_inference.md b/chapters/09_inference.mdindex b1e149b..09a3c2c 100644--- a/chapters/09_inference.md+++ b/chapters/09_inference.md@@ -234,7 +234,7 @@ def load_checkpoint(checkpoint_path: str, device: torch.device):"""# WHAT: Load the checkpoint dictionary from disk# WHY: map_location ensures it loads to the right device (CPU/GPU)- checkpoint = torch.load(checkpoint_path, map_location=device)+ checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=False)# WHAT: Recreate the model from the saved configmodel = GPT(checkpoint["config"])diff --git a/chapters/10_full_script.md b/chapters/10_full_script.mdindex 69995f2..9a0c199 100644--- a/chapters/10_full_script.md+++ b/chapters/10_full_script.md@@ -129,39 +129,6 @@ if __name__ == "__main__":main()```-## Expected Output--```-How to Train Your GPT -- Starting up!--GPU: NVIDIA GeForce RTX 3090-Memory: 24.0 GB--Loading training data...-Loading dataset: wikitext-103-raw-v1...-Loaded 5,000 documents-Total tokens in dataset: 2,847,231--Creating model...-GPT initialized with 13,408,512 parameters- Total parameters: 13,408,512- Trainable: 13,408,512--============================================================-STARTING TRAINING-============================================================-Training starting!- Model: 13,408,512 parameters- Device: cuda- Effective batch: 8-============================================================--Step 1/5,000 | Loss: 10.8451 | LR: 7.50e-08 | Time: 2s-Step 100/5,000 | Loss: 6.2345 | LR: 1.50e-05 | Time: 45s-Step 200/5,000 | Loss: 5.1234 | LR: 3.00e-05 | Time: 90s-...-```-## Running the Training```bashdiff --git a/notebooks/08_training.ipynb b/notebooks/08_training.ipynbnew file mode 100644index 0000000..52dbb9c--- /dev/null+++ b/notebooks/08_training.ipynb@@ -0,0 +1,529 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "id": "0d7b1883",+ "metadata": {},+ "source": [+ "# Training\n",+ "\n",+ "We have a complete GPT model. Now we need to teach it something.\n",+ "Training means showing the model millions of sentences and asking\n",+ "it to predict the next word every time. When it gets it wrong we\n",+ "nudge its 150 million weights just a tiny bit in the right\n",+ "direction. Repeat this enough times and the model learns patterns.\n",+ "\n",+ "The training loop has five steps. Get a batch of text. Run it\n",+ "through the model to get predictions. Measure how wrong those\n",+ "predictions are using cross entropy loss. Figure out how to\n",+ "change each weight to reduce that loss using backpropagation.\n",+ "Then actually update the weights using an optimizer called AdamW.\n",+ "\n",+ "We also use several tricks to make training faster and more\n",+ "stable. Mixed precision training uses smaller numbers for most\n",+ "operations. Gradient clipping stops the model from taking wild\n",+ "jumps. A learning rate schedule warms up slowly and then cools\n",+ "down following a cosine curve.\n",+ "\n",+ "In this notebook we will run a tiny training session. Just a few\n",+ "hundred steps on a small set of text to prove everything works.\n",+ "The model will not learn much in that time but you will see the\n",+ "loss go down and you will know the machinery is correct."+ ]+ },+ {+ "cell_type": "markdown",+ "id": "a66dea8f",+ "metadata": {},+ "source": [+ "## Imports"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 1,+ "id": "6bc23e2a",+ "metadata": {},+ "outputs": [],+ "source": [+ "import torch\n",+ "import torch.nn as nn\n",+ "import torch.nn.functional as F\n",+ "import math\n",+ "import time\n",+ "import os\n",+ "from dataclasses import dataclass\n",+ "from torch.utils.data import Dataset, DataLoader\n",+ "import tiktoken\n",+ "import matplotlib.pyplot as plt"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "9cb1dfa8",+ "metadata": {},+ "source": [+ "## All building blocks\n",+ "\n",+ "Every component from previous chapters in one place."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 2,+ "id": "038cab64",+ "metadata": {},+ "outputs": [],+ "source": [+ "class RotaryPositionalEmbedding(nn.Module):\n",+ " def __init__(self, d_model, max_seq_len=2048, theta=10000.0):\n",+ " super().__init__()\n",+ " assert d_model % 2 == 0\n",+ " dim_indices = torch.arange(0, d_model, 2).float()\n",+ " inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n",+ " positions = torch.arange(max_seq_len).float()\n",+ " freqs = torch.outer(positions, inv_freq)\n",+ " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " self.register_buffer(\"cos_cached\", emb.cos())\n",+ " self.register_buffer(\"sin_cached\", emb.sin())\n",+ "\n",+ " @staticmethod\n",+ " def rotate_half(x):\n",+ " x1 = x[..., : x.shape[-1] // 2]\n",+ " x2 = x[..., x.shape[-1] // 2 :]\n",+ " return torch.cat([-x2, x1], dim=-1)\n",+ "\n",+ " def forward(self, x, seq_len):\n",+ " cos = self.cos_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n",+ " sin = self.sin_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n",+ " return (x * cos) + (self.rotate_half(x) * sin)\n",+ "\n",+ "\n",+ "def create_causal_mask(seq_len, device):\n",+ " mask = torch.tril(torch.ones(seq_len, seq_len, device=device))\n",+ " return mask.view(1, 1, seq_len, seq_len)\n",+ "\n",+ "\n",+ "class RMSNorm(nn.Module):\n",+ " def __init__(self, d_model, eps=1e-6):\n",+ " super().__init__()\n",+ " self.weight = nn.Parameter(torch.ones(d_model))\n",+ " self.eps = eps\n",+ "\n",+ " def forward(self, x):\n",+ " rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)\n",+ " return x * rms * self.weight\n",+ "\n",+ "\n",+ "class SwiGLU(nn.Module):\n",+ " def __init__(self, d_model, expansion_factor=4):\n",+ " super().__init__()\n",+ " hidden_dim = expansion_factor * d_model\n",+ " self.w1 = nn.Linear(d_model, hidden_dim, bias=False)\n",+ " self.w2 = nn.Linear(d_model, hidden_dim, bias=False)\n",+ " self.w3 = nn.Linear(hidden_dim, d_model, bias=False)\n",+ "\n",+ " def forward(self, x):\n",+ " return self.w3(F.silu(self.w1(x)) * self.w2(x))\n",+ "\n",+ "\n",+ "class MultiHeadAttention(nn.Module):\n",+ " def __init__(self, d_model, num_heads, dropout=0.1):\n",+ " super().__init__()\n",+ " assert d_model % num_heads == 0\n",+ " self.d_model = d_model\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",+ " self.rotary = RotaryPositionalEmbedding(self.head_dim)\n",+ " self.attn_dropout = nn.Dropout(dropout)\n",+ " self.resid_dropout = nn.Dropout(dropout)\n",+ "\n",+ " def forward(self, x, mask=None):\n",+ " batch_size, seq_len, _ = x.shape\n",+ " qkv = self.qkv_proj(x)\n",+ " qkv = qkv.reshape(batch_size, 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",+ " q = self.rotary(q, seq_len)\n",+ " k = self.rotary(k, seq_len)\n",+ " attn_scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n",+ " if mask is not None:\n",+ " attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))\n",+ " attn_weights = F.softmax(attn_scores, dim=-1)\n",+ " attn_weights = self.attn_dropout(attn_weights)\n",+ " attn_output = attn_weights @ v\n",+ " attn_output = attn_output.transpose(1, 2).contiguous()\n",+ " attn_output = attn_output.reshape(batch_size, seq_len, self.d_model)\n",+ " output = self.out_proj(attn_output)\n",+ " output = self.resid_dropout(output)\n",+ " return output\n",+ "\n",+ "\n",+ "class TransformerBlock(nn.Module):\n",+ " def __init__(self, d_model, num_heads, dropout=0.1):\n",+ " super().__init__()\n",+ " self.norm1 = RMSNorm(d_model)\n",+ " self.attention = MultiHeadAttention(d_model, num_heads, dropout)\n",+ " self.norm2 = RMSNorm(d_model)\n",+ " self.ffn = SwiGLU(d_model)\n",+ "\n",+ " def forward(self, x, mask=None):\n",+ " x = x + self.attention(self.norm1(x), mask)\n",+ " x = x + self.ffn(self.norm2(x))\n",+ " return x\n",+ "\n",+ "\n",+ "@dataclass\n",+ "class GPTConfig:\n",+ " vocab_size: int = 50257\n",+ " d_model: int = 256\n",+ " num_heads: int = 4\n",+ " num_layers: int = 4\n",+ " max_seq_len: int = 128\n",+ " dropout: float = 0.1\n",+ " embd_dropout: float = 0.1\n",+ " learning_rate: float = 3e-4\n",+ " weight_decay: float = 0.1\n",+ " warmup_steps: int = 50\n",+ " max_steps: int = 500\n",+ " batch_size: int = 4\n",+ " grad_accum_steps: int = 2\n",+ " betas: tuple = (0.9, 0.95)\n",+ " eps: float = 1e-8\n",+ "\n",+ "\n",+ "class GPT(nn.Module):\n",+ " def __init__(self, config):\n",+ " super().__init__()\n",+ " self.config = config\n",+ " self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)\n",+ " self.embd_dropout = nn.Dropout(config.embd_dropout)\n",+ " self.layers = nn.ModuleList([\n",+ " TransformerBlock(config.d_model, config.num_heads, config.dropout)\n",+ " for _ in range(config.num_layers)\n",+ " ])\n",+ " self.final_norm = RMSNorm(config.d_model)\n",+ " self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)\n",+ " self.token_embedding.weight = self.lm_head.weight\n",+ " self.apply(self._init_weights)\n",+ "\n",+ " def _init_weights(self, module):\n",+ " if isinstance(module, (nn.Linear, nn.Embedding)):\n",+ " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",+ " if hasattr(module, 'bias') and module.bias is not None:\n",+ " torch.nn.init.zeros_(module.bias)\n",+ "\n",+ " def forward(self, input_ids, targets=None):\n",+ " batch_size, seq_len = input_ids.shape\n",+ " x = self.token_embedding(input_ids)\n",+ " x = self.embd_dropout(x)\n",+ " mask = create_causal_mask(seq_len, input_ids.device)\n",+ " for layer in self.layers:\n",+ " x = layer(x, mask)\n",+ " x = self.final_norm(x)\n",+ " logits = self.lm_head(x)\n",+ " loss = None\n",+ " if targets is not None:\n",+ " logits_flat = logits[:, :-1, :].contiguous().view(-1, self.config.vocab_size)\n",+ " targets_flat = targets[:, 1:].contiguous().view(-1)\n",+ " loss = F.cross_entropy(logits_flat, targets_flat)\n",+ " return logits, loss\n",+ "\n",+ " def get_num_params(self):\n",+ " return sum(p.numel() for p in self.parameters())"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "d83aaa02",+ "metadata": {},+ "source": [+ "## Tokenizer and Dataset"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 3,+ "id": "a09e44e9",+ "metadata": {},+ "outputs": [],+ "source": [+ "@dataclass\n",+ "class TokenizerConfig:\n",+ " name: str = \"gpt2\"\n",+ " vocab_size: int = 50257\n",+ "\n",+ "\n",+ "class SimpleTokenizer:\n",+ " def __init__(self, config=None):\n",+ " self.config = config or TokenizerConfig()\n",+ " self.enc = tiktoken.get_encoding(self.config.name)\n",+ " self.eos_token = \"<|endoftext|>\"\n",+ " self.eos_token_id = self.enc.encode(\n",+ " self.eos_token, allowed_special={self.eos_token}\n",+ " )[0]\n",+ "\n",+ " def encode(self, text):\n",+ " return self.enc.encode(text, allowed_special={self.eos_token})\n",+ "\n",+ " def decode(self, ids):\n",+ " return self.enc.decode(ids)\n",+ "\n",+ " @property\n",+ " def vocab_size(self):\n",+ " return self.config.vocab_size\n",+ "\n",+ "\n",+ "class TextDataset(Dataset):\n",+ " def __init__(self, texts, tokenizer, max_seq_len=128):\n",+ " self.tokenizer = tokenizer\n",+ " self.max_seq_len = max_seq_len\n",+ " all_tokens = []\n",+ " for text in texts:\n",+ " tokens = tokenizer.encode(text)\n",+ " all_tokens.extend(tokens)\n",+ " all_tokens.append(tokenizer.eos_token_id)\n",+ " self.tokens = torch.tensor(all_tokens, dtype=torch.long)\n",+ "\n",+ " def __len__(self):\n",+ " return (len(self.tokens) - 1) // self.max_seq_len\n",+ "\n",+ " def __getitem__(self, idx):\n",+ " start = idx * self.max_seq_len\n",+ " end = start + self.max_seq_len\n",+ " return self.tokens[start:end], self.tokens[start+1:end+1]"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "b72c53f0",+ "metadata": {},+ "source": [+ "## Learning rate scheduler and optimizer"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 4,+ "id": "93dfb7af",+ "metadata": {},+ "outputs": [],+ "source": [+ "class CosineWarmupScheduler:\n",+ " def __init__(self, optimizer, warmup_steps, max_steps, max_lr=3e-4, min_lr=1e-5):\n",+ " self.optimizer = optimizer\n",+ " self.warmup_steps = warmup_steps\n",+ " self.max_steps = max_steps\n",+ " self.max_lr = max_lr\n",+ " self.min_lr = min_lr\n",+ " self.current_step = 0\n",+ "\n",+ " def get_lr(self):\n",+ " step = self.current_step\n",+ " if step < self.warmup_steps:\n",+ " return self.max_lr * step / self.warmup_steps\n",+ " if step < self.max_steps:\n",+ " progress = (step - self.warmup_steps) / (self.max_steps - self.warmup_steps)\n",+ " cosine_decay = 0.5 * (1.0 + math.cos(math.pi * progress))\n",+ " return self.min_lr + (self.max_lr - self.min_lr) * cosine_decay\n",+ " return self.min_lr\n",+ "\n",+ " def step(self):\n",+ " for param_group in self.optimizer.param_groups:\n",+ " param_group['lr'] = self.get_lr()\n",+ " self.current_step += 1\n",+ "\n",+ "\n",+ "def create_optimizer(model, config):\n",+ " decay_params = []\n",+ " no_decay_params = []\n",+ " for name, param in model.named_parameters():\n",+ " if not param.requires_grad:\n",+ " continue\n",+ " if param.dim() <= 1 or 'norm' in name.lower() or 'bias' in name:\n",+ " no_decay_params.append(param)\n",+ " else:\n",+ " decay_params.append(param)\n",+ " return torch.optim.AdamW([\n",+ " {'params': decay_params, 'weight_decay': config.weight_decay},\n",+ " {'params': no_decay_params, 'weight_decay': 0.0},\n",+ " ], lr=config.learning_rate, betas=config.betas, eps=config.eps)"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "6f14ce3d",+ "metadata": {},+ "source": [+ "## Training loop"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": 5,+ "id": "f0c0f66c",+ "metadata": {},+ "outputs": [],+ "source": [+ "def train(model, train_dataset, config, device, steps=500):\n",+ " model = model.to(device)\n",+ " model.train()\n",+ "\n",+ " dataloader = DataLoader(train_dataset, batch_size=config.batch_size,\n",+ " shuffle=True, drop_last=True)\n",+ "\n",+ " optimizer = create_optimizer(model, config)\n",+ " scheduler = CosineWarmupScheduler(optimizer, config.warmup_steps,\n",+ " steps, max_lr=config.learning_rate)\n",+ "\n",+ " use_amp = device.type == 'cuda'\n",+ " scaler = torch.amp.GradScaler('cuda', enabled=use_amp) if use_amp else None\n",+ "\n",+ " step = 0\n",+ " loss_history = []\n",+ " start = time.time()\n",+ "\n",+ " while step < steps:\n",+ " for batch_idx, (input_ids, target_ids) in enumerate(dataloader):\n",+ " if step >= steps:\n",+ " break\n",+ " input_ids = input_ids.to(device)\n",+ " target_ids = target_ids.to(device)\n",+ "\n",+ " with torch.amp.autocast('cuda', enabled=use_amp):\n",+ " _, loss = model(input_ids, target_ids)\n",+ " loss = loss / config.grad_accum_steps\n",+ "\n",+ " if use_amp and scaler is not None:\n",+ " scaler.scale(loss).backward()\n",+ " else:\n",+ " loss.backward()\n",+ "\n",+ " if (batch_idx + 1) % config.grad_accum_steps == 0:\n",+ " if use_amp and scaler is not None:\n",+ " scaler.unscale_(optimizer)\n",+ " torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)\n",+ " if use_amp and scaler is not None:\n",+ " scaler.step(optimizer)\n",+ " scaler.update()\n",+ " else:\n",+ " optimizer.step()\n",+ " optimizer.zero_grad()\n",+ " scheduler.step()\n",+ " step += 1\n",+ "\n",+ " if step % 50 == 0 or step == 1:\n",+ " elapsed = time.time() - start\n",+ " print(f\"Step {step:>4d} | Loss: {loss.item() * config.grad_accum_steps:.4f} | Time: {elapsed:.0f}s\")\n",+ " loss_history.append((step, loss.item() * config.grad_accum_steps))\n",+ "\n",+ " print(f\"\\nDone. {time.time() - start:.0f}s total.\")\n",+ " return loss_history\n",+ "\n",+ "\n",+ "def plot_loss(loss_history, save_path=\"loss_curve.png\"):\n",+ " steps, losses = zip(*loss_history)\n",+ " plt.figure(figsize=(10, 4))\n",+ " plt.plot(steps, losses)\n",+ " plt.xlabel(\"Step\")\n",+ " plt.ylabel(\"Loss\")\n",+ " plt.title(\"Training Loss\")\n",+ " plt.grid(True, alpha=0.3)\n",+ " plt.tight_layout()\n",+ " plt.savefig(save_path, dpi=100)\n",+ " plt.show()\n",+ " print(f\"Loss curve saved to {save_path}\")"+ ]+ },+ {+ "cell_type": "markdown",+ "id": "eda99dd7",+ "metadata": {},+ "source": [+ "## Run a tiny training session\n",+ "\n",+ "We prepare a very small dataset of about 100 documents and train\n",+ "for 200 steps with a tiny model. This takes a few minutes on\n",+ "CPU or seconds on a GPU. Watch the loss go down."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "id": "f957327e",+ "metadata": {},+ "outputs": [+ {+ "name": "stdout",+ "output_type": "stream",+ "text": [+ "Dataset size: 12 chunks of 128 tokens\n",+ "Model: 256 dims, 4 layers, 4 heads\n",+ "Device: cpu\n",+ "Parameters: 17,062,400\n",+ "\n"+ ]+ }+ ],+ "source": [+ "sample_texts = [\n",+ " \"The cat sat on the mat. The dog ran in the park.\",\n",+ " \"Machine learning is the study of algorithms that improve through experience.\",\n",+ " \"Python is a programming language that lets you work quickly.\",\n",+ " \"The transformer architecture was introduced in two thousand seventeen.\",\n",+ " \"Language models predict the next word in a sequence of text.\",\n",+ " \"Training a neural network requires a lot of data and compute.\",\n",+ " \"The sun rises in the east and sets in the west every day.\",\n",+ " \"Mathematics is the language of the universe and all sciences.\",\n",+ "] * 15\n",+ "\n",+ "tokenizer = SimpleTokenizer()\n",+ "dataset = TextDataset(sample_texts, tokenizer, max_seq_len=128)\n",+ "print(f\"Dataset size: {len(dataset)} chunks of {128} tokens\")\n",+ "\n",+ "config = GPTConfig()\n",+ "print(f\"Model: {config.d_model} dims, {config.num_layers} layers, {config.num_heads} heads\")\n",+ "\n",+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",+ "print(f\"Device: {device}\")\n",+ "\n",+ "model = GPT(config)\n",+ "print(f\"Parameters: {model.get_num_params():,}\")\n",+ "print()\n",+ "\n",+ "loss_history = train(model, dataset, config, device, steps=50) # Reduce to 50 for a faster run\n",+ "plot_loss(loss_history, \"loss_curve.png\")\n",+ "\n",+ "os.makedirs(\"checkpoints\", exist_ok=True)\n",+ "torch.save({\n",+ " \"model_state_dict\": model.state_dict(),\n",+ " \"config\": config,\n",+ "}, \"checkpoints/tiny_model.pt\")\n",+ "print(\"Model saved to checkpoints/tiny_model.pt\")"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3 (ipykernel)",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "codemirror_mode": {+ "name": "ipython",+ "version": 3+ },+ "file_extension": ".py",+ "mimetype": "text/x-python",+ "name": "python",+ "nbconvert_exporter": "python",+ "pygments_lexer": "ipython3",+ "version": "3.14.4"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}diff --git a/notebooks/09_inference.ipynb b/notebooks/09_inference.ipynbnew file mode 100644index 0000000..65068a8--- /dev/null+++ b/notebooks/09_inference.ipynb@@ -0,0 +1,329 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Inference\n",+ "\n",+ "We have a trained model. Now we want it to write something. This\n",+ "is called inference or text generation. We give the model a\n",+ "starting prompt and it predicts the next word. Then it takes\n",+ "that word and predicts the word after it. One token at a time\n",+ "until we have a full paragraph.\n",+ "\n",+ "The way we pick the next token matters a lot. If we always pick\n",+ "the most likely token the output becomes repetitive. If we pick\n",+ "randomly from all tokens the output becomes nonsense. We use\n",+ "temperature to control how adventurous the model is. Top-k to\n",+ "limit choices to the most sensible tokens. And top-p to adapt\n",+ "the number of choices based on how confident the model feels.\n",+ "\n",+ "In this notebook we load the tiny checkpoint we saved during\n",+ "training and make it generate text. Because our model is tiny\n",+ "and barely trained the output will not be meaningful. But you\n",+ "will see the generation loop working token by token."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Imports and building blocks\n",+ "\n",+ "We need the model architecture to load the checkpoint."+ ]+ },+ {+ "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",+ "from dataclasses import dataclass\n",+ "\n",+ "class RotaryPositionalEmbedding(nn.Module):\n",+ " def __init__(self, d_model, max_seq_len=2048, theta=10000.0):\n",+ " super().__init__()\n",+ " assert d_model % 2 == 0\n",+ " dim_indices = torch.arange(0, d_model, 2).float()\n",+ " inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n",+ " positions = torch.arange(max_seq_len).float()\n",+ " freqs = torch.outer(positions, inv_freq)\n",+ " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " self.register_buffer(\"cos_cached\", emb.cos())\n",+ " self.register_buffer(\"sin_cached\", emb.sin())\n",+ "\n",+ " @staticmethod\n",+ " def rotate_half(x):\n",+ " x1 = x[..., : x.shape[-1] // 2]\n",+ " x2 = x[..., x.shape[-1] // 2 :]\n",+ " return torch.cat([-x2, x1], dim=-1)\n",+ "\n",+ " def forward(self, x, seq_len):\n",+ " cos = self.cos_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n",+ " sin = self.sin_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n",+ " return (x * cos) + (self.rotate_half(x) * sin)\n",+ "\n",+ "\n",+ "def create_causal_mask(seq_len, device):\n",+ " mask = torch.tril(torch.ones(seq_len, seq_len, device=device))\n",+ " return mask.view(1, 1, seq_len, seq_len)\n",+ "\n",+ "\n",+ "class RMSNorm(nn.Module):\n",+ " def __init__(self, d_model, eps=1e-6):\n",+ " super().__init__()\n",+ " self.weight = nn.Parameter(torch.ones(d_model))\n",+ " self.eps = eps\n",+ "\n",+ " def forward(self, x):\n",+ " rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)\n",+ " return x * rms * self.weight\n",+ "\n",+ "\n",+ "class SwiGLU(nn.Module):\n",+ " def __init__(self, d_model, expansion_factor=4):\n",+ " super().__init__()\n",+ " hidden_dim = expansion_factor * d_model\n",+ " self.w1 = nn.Linear(d_model, hidden_dim, bias=False)\n",+ " self.w2 = nn.Linear(d_model, hidden_dim, bias=False)\n",+ " self.w3 = nn.Linear(hidden_dim, d_model, bias=False)\n",+ "\n",+ " def forward(self, x):\n",+ " return self.w3(F.silu(self.w1(x)) * self.w2(x))\n",+ "\n",+ "\n",+ "class MultiHeadAttention(nn.Module):\n",+ " def __init__(self, d_model, num_heads, dropout=0.1):\n",+ " super().__init__()\n",+ " assert d_model % num_heads == 0\n",+ " self.d_model = d_model\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",+ " self.rotary = RotaryPositionalEmbedding(self.head_dim)\n",+ " self.attn_dropout = nn.Dropout(dropout)\n",+ " self.resid_dropout = nn.Dropout(dropout)\n",+ "\n",+ " def forward(self, x, mask=None):\n",+ " batch_size, seq_len, _ = x.shape\n",+ " qkv = self.qkv_proj(x)\n",+ " qkv = qkv.reshape(batch_size, 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",+ " q = self.rotary(q, seq_len)\n",+ " k = self.rotary(k, seq_len)\n",+ " attn_scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n",+ " if mask is not None:\n",+ " attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))\n",+ " attn_weights = F.softmax(attn_scores, dim=-1)\n",+ " attn_weights = self.attn_dropout(attn_weights)\n",+ " attn_output = attn_weights @ v\n",+ " attn_output = attn_output.transpose(1, 2).contiguous()\n",+ " attn_output = attn_output.reshape(batch_size, seq_len, self.d_model)\n",+ " output = self.out_proj(attn_output)\n",+ " output = self.resid_dropout(output)\n",+ " return output\n",+ "\n",+ "\n",+ "class TransformerBlock(nn.Module):\n",+ " def __init__(self, d_model, num_heads, dropout=0.1):\n",+ " super().__init__()\n",+ " self.norm1 = RMSNorm(d_model)\n",+ " self.attention = MultiHeadAttention(d_model, num_heads, dropout)\n",+ " self.norm2 = RMSNorm(d_model)\n",+ " self.ffn = SwiGLU(d_model)\n",+ "\n",+ " def forward(self, x, mask=None):\n",+ " x = x + self.attention(self.norm1(x), mask)\n",+ " x = x + self.ffn(self.norm2(x))\n",+ " return x\n",+ "\n",+ "\n",+ "@dataclass\n",+ "class GPTConfig:\n",+ " vocab_size: int = 50257\n",+ " d_model: int = 256\n",+ " num_heads: int = 4\n",+ " num_layers: int = 4\n",+ " max_seq_len: int = 128\n",+ " dropout: float = 0.1\n",+ " embd_dropout: float = 0.1\n",+ " learning_rate: float = 3e-4\n",+ " weight_decay: float = 0.1\n",+ " warmup_steps: int = 50\n",+ " max_steps: int = 500\n",+ " batch_size: int = 4\n",+ " grad_accum_steps: int = 2\n",+ " betas: tuple = (0.9, 0.95)\n",+ " eps: float = 1e-8\n",+ "\n",+ "\n",+ "class GPT(nn.Module):\n",+ " def __init__(self, config):\n",+ " super().__init__()\n",+ " self.config = config\n",+ " self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)\n",+ " self.embd_dropout = nn.Dropout(config.embd_dropout)\n",+ " self.layers = nn.ModuleList([\n",+ " TransformerBlock(config.d_model, config.num_heads, config.dropout)\n",+ " for _ in range(config.num_layers)\n",+ " ])\n",+ " self.final_norm = RMSNorm(config.d_model)\n",+ " self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)\n",+ " self.token_embedding.weight = self.lm_head.weight\n",+ " self.apply(self._init_weights)\n",+ "\n",+ " def _init_weights(self, module):\n",+ " if isinstance(module, (nn.Linear, nn.Embedding)):\n",+ " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",+ " if hasattr(module, 'bias') and module.bias is not None:\n",+ " torch.nn.init.zeros_(module.bias)\n",+ "\n",+ " def forward(self, input_ids, targets=None):\n",+ " batch_size, seq_len = input_ids.shape\n",+ " x = self.token_embedding(input_ids)\n",+ " x = self.embd_dropout(x)\n",+ " mask = create_causal_mask(seq_len, input_ids.device)\n",+ " for layer in self.layers:\n",+ " x = layer(x, mask)\n",+ " x = self.final_norm(x)\n",+ " logits = self.lm_head(x)\n",+ " loss = None\n",+ " if targets is not None:\n",+ " logits_flat = logits[:, :-1, :].contiguous().view(-1, self.config.vocab_size)\n",+ " targets_flat = targets[:, 1:].contiguous().view(-1)\n",+ " loss = F.cross_entropy(logits_flat, targets_flat)\n",+ " return logits, loss\n",+ "\n",+ " @torch.no_grad()\n",+ " def generate(self, input_ids, max_new_tokens, temperature=1.0, top_k=None):\n",+ " self.eval()\n",+ " for _ in range(max_new_tokens):\n",+ " if input_ids.shape[1] > self.config.max_seq_len:\n",+ " input_ids = input_ids[:, -self.config.max_seq_len:]\n",+ " logits, _ = self.forward(input_ids)\n",+ " logits = logits[:, -1, :] / temperature\n",+ " if top_k is not None:\n",+ " v, _ = torch.topk(logits, min(top_k, logits.size(-1)))\n",+ " logits[logits < v[:, -1:]] = float('-inf')\n",+ " probs = F.softmax(logits, dim=-1)\n",+ " next_token = torch.multinomial(probs, num_samples=1)\n",+ " input_ids = torch.cat([input_ids, next_token], dim=1)\n",+ " return input_ids\n",+ "\n",+ " def get_num_params(self):\n",+ " return sum(p.numel() for p in self.parameters())"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Load the checkpoint from training"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import os\n",+ "\n",+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",+ "\n",+ "if os.path.exists(\"checkpoints/tiny_model.pt\"):\n",+ " checkpoint = torch.load(\"checkpoints/tiny_model.pt\", map_location=device, weights_only=False)\n",+ " model = GPT(checkpoint[\"config\"])\n",+ " model.load_state_dict(checkpoint[\"model_state_dict\"])\n",+ " model = model.to(device)\n",+ " model.eval()\n",+ " print(f\"Loaded model with {model.get_num_params():,} parameters\")\n",+ "else:\n",+ " print(\"No checkpoint found. Run the training notebook first.\")\n",+ " print(\"Creating an untrained model for demonstration.\")\n",+ " config = GPTConfig()\n",+ " model = GPT(config).to(device)\n",+ " model.eval()"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Generate text\n",+ "\n",+ "Try different prompts and temperatures. Low temperature gives\n",+ "focused output. High temperature gives creative output. Top-k\n",+ "limits the choices to the most likely tokens."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import tiktoken\n",+ "\n",+ "@dataclass\n",+ "class TokenizerConfig:\n",+ " name: str = \"gpt2\"\n",+ " vocab_size: int = 50257\n",+ "\n",+ "class SimpleTokenizer:\n",+ " def __init__(self, config=None):\n",+ " self.config = config or TokenizerConfig()\n",+ " self.enc = tiktoken.get_encoding(self.config.name)\n",+ " self.eos_token = \"<|endoftext|>\"\n",+ " self.eos_token_id = self.enc.encode(\n",+ " self.eos_token, allowed_special={self.eos_token})[0]\n",+ " def encode(self, text):\n",+ " return self.enc.encode(text, allowed_special={self.eos_token})\n",+ " def decode(self, ids):\n",+ " return self.enc.decode(ids)\n",+ " @property\n",+ " def vocab_size(self):\n",+ " return self.config.vocab_size\n",+ "\n",+ "tokenizer = SimpleTokenizer()\n",+ "\n",+ "prompts = [\n",+ " \"The cat sat on the\",\n",+ " \"Machine learning is\",\n",+ " \"The most important thing is\",\n",+ "]\n",+ "\n",+ "for prompt in prompts:\n",+ " print(f\"Prompt: {prompt}\")\n",+ " for temp in [0.5, 0.8, 1.2]:\n",+ " label = \"focused\" if temp < 0.7 else (\"balanced\" if temp < 1.0 else \"creative\")\n",+ " input_ids = torch.tensor([tokenizer.encode(prompt)], dtype=torch.long, device=device)\n",+ " output_ids = model.generate(input_ids, max_new_tokens=20, temperature=temp, top_k=50)\n",+ " text = tokenizer.decode(output_ids[0].tolist())\n",+ " print(f\" T={temp:.1f} ({label}): {text[:120]}\")\n",+ " print()"+ ]+ }+ ],+ "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/loss_curve.png b/notebooks/loss_curve.pngnew file mode 100644index 0000000..22c9f9fBinary files /dev/null and b/notebooks/loss_curve.png differ