Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
{
"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 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."
]
},
{
"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 = freqs.repeat_interleave(2, 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",
" x_even = x[..., 0::2]\n",
" x_odd = x[..., 1::2]\n",
" return torch.stack([-x_odd, x_even], dim=-1).flatten(-2)\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.\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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"torch.manual_seed(0)\n",
"rope = RotaryPositionalEmbedding(d_model=64, max_seq_len=256)\n",
"\n",
"seq_len = 12\n",
"head_dim = 64\n",
"\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",
"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 the same score no matter where the words sit.\")\n",
"print(\"A different distance gives a different score. That is the point.\")"
]
},
{
"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
}