Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
add notebook 4 .. the original chapter had a wrong sq_len and num_head
raiyanyahyad6173010e1dc
diff --git a/chapters/04_positional_encoding.md b/chapters/04_positional_encoding.mdindex 9784155..fa4a94d 100644--- a/chapters/04_positional_encoding.md+++ b/chapters/04_positional_encoding.md@@ -230,7 +230,7 @@ class RotaryPositionalEmbedding(nn.Module):"""WHAT: Apply RoPE to queries or keys.- Input: [batch, seq_len, num_heads, head_dim]+ Input: [batch, num_heads, seq_len, head_dim]x can be either Q or K (NOT V — values don't need position)Output: Same shape, rotated by position-dependent anglesdiff --git a/notebooks/04_positional_encoding.ipynb b/notebooks/04_positional_encoding.ipynbnew file mode 100644index 0000000..7e5aede--- /dev/null+++ b/notebooks/04_positional_encoding.ipynb@@ -0,0 +1,205 @@+{+ "cells": [+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "# Positional Encoding\n",+ "\n",+ "The transformer reads all words at once. It has no idea which\n",+ "word comes first and which comes last. But word order matters.\n",+ "The dog bit the man is very different from the man bit the dog.\n",+ "\n",+ "So we need to stamp each word with its position before feeding\n",+ "it to the model. The modern way to do this is called Rotary\n",+ "Position Embeddings or RoPE for short. Instead of adding\n",+ "position numbers RoPE rotates the vectors by an angle that\n",+ "depends on where the word sits in the sentence.\n",+ "\n",+ "The clever part is that after rotation the dot product between\n",+ "any two words depends only on how far apart they are. Not on\n",+ "their absolute positions. Words five slots apart always get the\n",+ "same relative angle no matter if they appear at position 0 or\n",+ "position 500. This is exactly what attention should care about.\n",+ "\n",+ "This notebook shows you the rotation math and lets you watch\n",+ "how a vector changes as it moves through different positions."+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Imports"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "import torch\n",+ "import torch.nn as nn\n",+ "import math"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## RoPE Implementation\n",+ "\n",+ "RoPE expects input tensors in the shape [batch, num_heads, seq_len, head_dim].\n",+ "This is the same layout used inside multi-head attention."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "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, \"d_model must be even\"\n",+ "\n",+ " dim_indices = torch.arange(0, d_model, 2).float()\n",+ " inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n",+ "\n",+ " positions = torch.arange(max_seq_len).float()\n",+ " freqs = torch.outer(positions, inv_freq)\n",+ " emb = torch.cat([freqs, freqs], dim=-1)\n",+ "\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)"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Watch rotation on a single vector"+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "rope = RotaryPositionalEmbedding(d_model=4, max_seq_len=16)\n",+ "\n",+ "q = torch.tensor([[[[0.8, 0.3, -0.5, 0.2]]]]) # [1, 1, 1, 4]\n",+ "print(f\"Original vector: {q[0, 0, 0].tolist()}\")\n",+ "print()\n",+ "\n",+ "for pos in [0, 1, 2, 5]:\n",+ " rotated = rope(q, seq_len=pos + 1)\n",+ " last = rotated[0, 0, -1].tolist()\n",+ " vals = [f\"{v:.3f}\" for v in last]\n",+ " print(f\"Position {pos}: [{', '.join(vals)}]\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## Relative position property\n",+ "\n",+ "The dot product between two rotated vectors depends only on\n",+ "their distance apart. Not on their absolute positions."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "rope = RotaryPositionalEmbedding(d_model=64, max_seq_len=256)\n",+ "\n",+ "seq_len = 12\n",+ "num_heads = 4\n",+ "head_dim = 64\n",+ "\n",+ "q = torch.randn(1, num_heads, seq_len, head_dim)\n",+ "k = torch.randn(1, num_heads, seq_len, head_dim)\n",+ "\n",+ "q_rot = rope(q, seq_len=seq_len)\n",+ "k_rot = rope(k, seq_len=seq_len)\n",+ "\n",+ "head = 0\n",+ "a = (q_rot[0, head, 2] @ k_rot[0, head, 4]).item()\n",+ "b = (q_rot[0, head, 5] @ k_rot[0, head, 7]).item()\n",+ "c = (q_rot[0, head, 0] @ k_rot[0, head, 8]).item()\n",+ "\n",+ "print(f\"Distance 2 (positions 2,4): {a:.4f}\")\n",+ "print(f\"Distance 2 (positions 5,7): {b:.4f}\")\n",+ "print(f\"Distance 8 (positions 0,8): {c:.4f}\")\n",+ "print()\n",+ "print(\"Same distance gives similar score regardless of position.\")"+ ]+ },+ {+ "cell_type": "markdown",+ "metadata": {},+ "source": [+ "## RoPE inside attention\n",+ "\n",+ "RoPE is applied only to queries and keys. Values stay untouched.\n",+ "This makes the attention score position aware while keeping the\n",+ "content clean."+ ]+ },+ {+ "cell_type": "code",+ "execution_count": null,+ "metadata": {},+ "outputs": [],+ "source": [+ "head_dim = 64\n",+ "num_heads = 4\n",+ "seq_len = 10\n",+ "\n",+ "rope = RotaryPositionalEmbedding(d_model=head_dim, max_seq_len=128)\n",+ "\n",+ "q = torch.randn(1, num_heads, seq_len, head_dim)\n",+ "k = torch.randn(1, num_heads, seq_len, head_dim)\n",+ "\n",+ "q_rot = rope(q, seq_len)\n",+ "k_rot = rope(k, seq_len)\n",+ "\n",+ "scores = (q_rot @ k_rot.transpose(-2, -1)) / math.sqrt(head_dim)\n",+ "print(f\"Attention scores shape: {scores.shape}\")\n",+ "print(f\"Token 0 attends to itself: {scores[0, 0, 0, 0]:.4f}\")\n",+ "print(f\"Token 0 attends to token 5: {scores[0, 0, 0, 5]:.4f}\")"+ ]+ }+ ],+ "metadata": {+ "kernelspec": {+ "display_name": "Python 3",+ "language": "python",+ "name": "python3"+ },+ "language_info": {+ "name": "python",+ "version": "3.10.0"+ }+ },+ "nbformat": 4,+ "nbformat_minor": 5+}