Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
fix rope relative positio demo, remove duplicate staticmethod, clarify dimension pairs and add Q/K note to chapter 4
raiyanyahyaf3db85cf05d9
diff --git a/chapters/04_positional_encoding.md b/chapters/04_positional_encoding.mdindex 9415d89..0239489 100644--- a/chapters/04_positional_encoding.md+++ b/chapters/04_positional_encoding.md@@ -21,6 +21,18 @@ But the Transformer reads all words **at once** (not one by one like humans do).## Modern Approach: Rotary Position Embeddings (RoPE)+### A Quick Word on "Query" and "Key" Vectors++RoPE acts on two vectors you haven't met yet: the **query** and the **key**. They belong to attention, which is the whole of [Chapter 5](05_attention.md). Here is all you need for now:++- Inside attention, every token's embedding gets turned into a **query** vector ("what am I looking for?") and a **key** vector ("what do I have to offer?").+- Attention compares a query with a key by taking their **dot product**. A big result means "pay attention to this token".+- RoPE rotates the query and key vectors **right before** that dot product, so the result also depends on how far apart the two tokens are.++So for this chapter, treat Q and K as "two vectors that get compared with a dot product". Chapter 5 builds them step by step.++### The Idea+Instead of **adding** position numbers to embeddings, RoPE **rotates** the query and key vectors by an angle that depends on position.### The Math Intuition@@ -31,7 +43,7 @@ x' = x*cos(θ) - y*sin(θ)y' = x*sin(θ) + y*cos(θ)```-RoPE does this for EVERY pair of dimensions in the query and key vectors. The rotation angle for position `p` and dimension pair `2i, 2i+1` is:+RoPE splits each query and key vector into **adjacent, non-overlapping pairs** of dimensions: `(0,1)`, `(2,3)`, `(4,5)`, ... and rotates each pair as if it were its own little 2D vector. A vector with `d_model=4` has exactly two pairs: `(0,1)` and `(2,3)`. It is NOT every possible combination of two dimensions. The rotation angle for position `p` and pair `i` (dimensions `2i, 2i+1`) is:```θ(p, i) = p / (10000^(2i/d_model))@@ -207,10 +219,27 @@ class RotaryPositionalEmbedding(nn.Module):self.register_buffer("sin_cached", emb.sin()) # sin of each angle@staticmethod- @staticmethod- def rotate_half(x):- x_even = x[..., 0::2]- x_odd = x[..., 1::2]+ def rotate_half(x: torch.Tensor) -> torch.Tensor:+ """+ WHAT: Prepare a vector for the rotation formula.+ WHY: The rotation formula is: x' = x*cos + rotate_half(x)*sin++ For vector [x0, x1, x2, x3, x4, x5]:+ rotate_half returns [-x1, x0, -x3, x2, -x5, x4]++ Why this works: For pair (x0, x1) rotated by angle θ:+ x0' = x0*cos(θ) - x1*sin(θ) ← matches: x0*cos + (-x1)*sin+ x1' = x0*sin(θ) + x1*cos(θ) ← matches: x1*cos + (x0)*sin++ So executing (x*cos + rotate_half(x)*sin) rotates every+ adjacent pair at once — no loop needed!+ """+ x_even = x[..., 0::2] # dims 0, 2, 4, ... — the "x" of each pair+ x_odd = x[..., 1::2] # dims 1, 3, 5, ... — the "y" of each pair++ # WHAT: Interleave back into [-x1, x0, -x3, x2, ...]+ # WHY: The cos/sin caches are stored as [θ0, θ0, θ1, θ1, ...],+ # so each pair must stay next to its own angle.return torch.stack([-x_odd, x_even], dim=-1).flatten(-2)def forward(self, x: torch.Tensor, seq_len: int) -> torch.Tensor:diff --git a/explanations and examples WIP/the_complete_story.md b/explanations and examples WIP/the_complete_story.mdindex ae7987b..f78c4bf 100644--- a/explanations and examples WIP/the_complete_story.md+++ b/explanations and examples WIP/the_complete_story.md@@ -272,8 +272,9 @@ x₀' = x₀ × cos(θ_p) - x₁ × sin(θ_p)x₁' = x₀ × sin(θ_p) + x₁ × cos(θ_p)```-This is a standard 2D rotation. Applied to every pair of dimensions in-the query and key vectors. The values are not rotated because position+This is a standard 2D rotation. Applied to every adjacent pair of+dimensions (x₀, x₁), (x₂, x₃), (x₄, x₅) and so on in the query and key+vectors. The values are not rotated because positioninformation is only needed for deciding WHICH tokens to attend to notfor the content of the tokens themselves.diff --git a/fine-tuning/notebooks/lora_finetune.ipynb b/fine-tuning/notebooks/lora_finetune.ipynbindex 5aaecbc..15223f5 100644--- a/fine-tuning/notebooks/lora_finetune.ipynb+++ b/fine-tuning/notebooks/lora_finetune.ipynb@@ -69,7 +69,6 @@" self.register_buffer(\"sin_cached\", emb.sin())\n","\n"," @staticmethod\n",- " @staticmethod\n"," def rotate_half(x):\n"," x_even = x[..., 0::2]\n"," x_odd = x[..., 1::2]\n",diff --git a/main.py b/main.pyindex b8d0feb..479ce1b 100644--- a/main.py+++ b/main.py@@ -36,7 +36,6 @@ class RotaryPositionalEmbedding(nn.Module):self.register_buffer("cos_cached", emb.cos())self.register_buffer("sin_cached", emb.sin())- @staticmethod@staticmethoddef rotate_half(x):x_even = x[..., 0::2]diff --git a/notebooks/04_positional_encoding.ipynb b/notebooks/04_positional_encoding.ipynbindex c941da7..2360300 100644--- a/notebooks/04_positional_encoding.ipynb+++ b/notebooks/04_positional_encoding.ipynb@@ -50,6 +50,10 @@"source": ["## RoPE Implementation\n","\n",+ "RoPE is applied to the query and key vectors inside attention.\n",+ "You will build those in the next notebook. For now just think of\n",+ "them as two vectors that get compared with a dot product.\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."]@@ -76,7 +80,6 @@" self.register_buffer(\"sin_cached\", emb.sin())\n","\n"," @staticmethod\n",- " @staticmethod\n"," def rotate_half(x):\n"," x_even = x[..., 0::2]\n"," x_odd = x[..., 1::2]\n",@@ -120,7 +123,16 @@"## Relative position property\n","\n","The dot product between two rotated vectors depends only on\n",- "their distance apart. Not on their absolute positions."+ "their distance apart. Not on their absolute positions.\n",+ "\n",+ "To see this we need the same query vector and the same key\n",+ "vector at every position. Then the only thing that changes\n",+ "from one position to the next is the rotation. If we drew a\n",+ "fresh random vector at every position the dot products would\n",+ "be comparing different content and that would hide the effect.\n",+ "\n",+ "The first two lines below should match. The third line is a\n",+ "different distance so it is supposed to be different."]},{@@ -129,28 +141,30 @@"metadata": {},"outputs": [],"source": [+ "torch.manual_seed(0)\n","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",+ "q_vec = torch.randn(head_dim)\n",+ "k_vec = torch.randn(head_dim)\n",+ "q = q_vec.expand(1, 1, seq_len, head_dim).contiguous() # same query at every position\n",+ "k = k_vec.expand(1, 1, seq_len, head_dim).contiguous() # same key at every position\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",+ "a = (q_rot[0, 0, 2] @ k_rot[0, 0, 4]).item()\n",+ "b = (q_rot[0, 0, 5] @ k_rot[0, 0, 7]).item()\n",+ "c = (q_rot[0, 0, 0] @ k_rot[0, 0, 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.\")"+ "print(\"Same distance gives the same score no matter where the words sit.\")\n",+ "print(\"A different distance gives a different score. That is the point.\")"]},{diff --git a/notebooks/05_attention.ipynb b/notebooks/05_attention.ipynbindex 5727029..7b255e3 100644--- a/notebooks/05_attention.ipynb+++ b/notebooks/05_attention.ipynb@@ -125,7 +125,6 @@" self.register_buffer(\"sin_cached\", emb.sin())\n","\n"," @staticmethod\n",- " @staticmethod\n"," def rotate_half(x):\n"," x_even = x[..., 0::2]\n"," x_odd = x[..., 1::2]\n",diff --git a/notebooks/06_transformer_block.ipynb b/notebooks/06_transformer_block.ipynbindex 28a32ac..d4b0b9e 100644--- a/notebooks/06_transformer_block.ipynb+++ b/notebooks/06_transformer_block.ipynb@@ -81,7 +81,6 @@" self.register_buffer(\"sin_cached\", emb.sin())\n","\n"," @staticmethod\n",- " @staticmethod\n"," def rotate_half(x):\n"," x_even = x[..., 0::2]\n"," x_odd = x[..., 1::2]\n",diff --git a/notebooks/07_gpt_model.ipynb b/notebooks/07_gpt_model.ipynbindex 1554b49..2ae610a 100644--- a/notebooks/07_gpt_model.ipynb+++ b/notebooks/07_gpt_model.ipynb@@ -75,7 +75,6 @@" self.register_buffer(\"sin_cached\", emb.sin())\n","\n"," @staticmethod\n",- " @staticmethod\n"," def rotate_half(x):\n"," x_even = x[..., 0::2]\n"," x_odd = x[..., 1::2]\n",diff --git a/notebooks/08_training.ipynb b/notebooks/08_training.ipynbindex 97e142f..f28f094 100644--- a/notebooks/08_training.ipynb+++ b/notebooks/08_training.ipynb@@ -88,7 +88,6 @@" self.register_buffer(\"sin_cached\", emb.sin())\n","\n"," @staticmethod\n",- " @staticmethod\n"," def rotate_half(x):\n"," x_even = x[..., 0::2]\n"," x_odd = x[..., 1::2]\n",diff --git a/notebooks/09_inference.ipynb b/notebooks/09_inference.ipynbindex 1554c0a..a0c2329 100644--- a/notebooks/09_inference.ipynb+++ b/notebooks/09_inference.ipynb@@ -59,7 +59,6 @@" self.register_buffer(\"sin_cached\", emb.sin())\n","\n"," @staticmethod\n",- " @staticmethod\n"," def rotate_half(x):\n"," x_even = x[..., 0::2]\n"," x_odd = x[..., 1::2]\n",