Skip to content

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

add chapter 3 with vocab size isue resolved

raiyanyahyaae91cfc92ee2
diff --git a/notebooks/03_embeddings.ipynb b/notebooks/03_embeddings.ipynb
new file mode 100644
index 0000000..da96fb5
--- /dev/null
+++ b/notebooks/03_embeddings.ipynb
@@ -0,0 +1,254 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "75166532",
+ "metadata": {},
+ "source": [
+ "# Chapter 3 — Embeddings\n",
+ "\n",
+ "Now we have numbers for every word. But a number like 9246 is\n",
+ "just a label. The model cannot learn from labels. It needs\n",
+ "meaning. It needs to know that cat and dog are similar and that\n",
+ "cat and car are different.\n",
+ "\n",
+ "An embedding is a vector of floating point numbers that captures\n",
+ "the meaning of a word. Think of it like giving each word a\n",
+ "coordinate in a big space. Words with similar meanings end up\n",
+ "near each other. Words with different meanings end up far apart.\n",
+ "\n",
+ "These embeddings start as random numbers. During training the\n",
+ "model learns to move related words closer together. After enough\n",
+ "training cat and dog will be neighbors while car will be on\n",
+ "the other side of the space. This notebook shows you how that\n",
+ "lookup table works and how the magic of learning makes it\n",
+ "meaningful."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "72695675",
+ "metadata": {},
+ "source": [
+ "## Imports"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "069ea7c9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import torch\n",
+ "import torch.nn as nn\n",
+ "import math"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fd66b437",
+ "metadata": {},
+ "source": [
+ "## The Embedding Layer"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "e38e4dc9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class Embedding(nn.Module):\n",
+ " def __init__(self, vocab_size, d_model):\n",
+ " super().__init__()\n",
+ " self.embed = nn.Embedding(vocab_size, d_model)\n",
+ " self.d_model = d_model\n",
+ "\n",
+ " def forward(self, x):\n",
+ " return self.embed(x) * math.sqrt(self.d_model)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f1472f9c",
+ "metadata": {},
+ "source": [
+ "## Create an embedding table and test it"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "48b01922",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Embedding table shape: [1000, 768]\n",
+ "Total parameters: 768,000\n",
+ "\n",
+ "Input token IDs: tensor([[ 12, 45, 678, 2, 890]])\n",
+ "Input shape: torch.Size([1, 5])\n",
+ "\n",
+ "Output shape: torch.Size([1, 5, 768])\n",
+ "Each token is now a 768-dimensional vector\n",
+ "First token vector preview: [18.91689682006836, -2.2418112754821777, 41.377845764160156, -2.377814531326294, 29.869359970092773] ...\n"
+ ]
+ }
+ ],
+ "source": [
+ "vocab_size = 1000\n",
+ "d_model = 768\n",
+ "\n",
+ "embedding = Embedding(vocab_size, d_model)\n",
+ "print(f\"Embedding table shape: [{vocab_size}, {d_model}]\")\n",
+ "print(f\"Total parameters: {sum(p.numel() for p in embedding.parameters()):,}\")\n",
+ "print()\n",
+ "\n",
+ "token_ids = torch.tensor([[12, 45, 678, 2, 890]])\n",
+ "print(f\"Input token IDs: {token_ids}\")\n",
+ "print(f\"Input shape: {token_ids.shape}\")\n",
+ "print()\n",
+ "\n",
+ "output = embedding(token_ids)\n",
+ "print(f\"Output shape: {output.shape}\")\n",
+ "print(f\"Each token is now a {d_model}-dimensional vector\")\n",
+ "print(f\"First token vector preview: {output[0, 0, :5].tolist()} ...\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7b4bba83",
+ "metadata": {},
+ "source": [
+ "## The scaling trick\n",
+ "\n",
+ "We multiply embeddings by sqrt(d_model). This keeps the values\n",
+ "at a good scale before we add positional encoding later.\n",
+ "Without this scaling the position information would get lost."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "1786c566",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Without scaling: mean=0.0087, std=0.9968\n",
+ "With scaling: mean=0.2402, std=27.6252\n"
+ ]
+ }
+ ],
+ "source": [
+ "embed_raw = nn.Embedding(vocab_size, d_model)\n",
+ "x = embed_raw(token_ids)\n",
+ "\n",
+ "print(f\"Without scaling: mean={x.mean():.4f}, std={x.std():.4f}\")\n",
+ "print(f\"With scaling: mean={(x * math.sqrt(d_model)).mean():.4f}, std={(x * math.sqrt(d_model)).std():.4f}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d2adf5a2",
+ "metadata": {},
+ "source": [
+ "## Looking up embeddings for our tokenizer\n",
+ "\n",
+ "Now we connect this to the real tokenizer from Chapter 2."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "85933f11",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Text: 'The cat sat on the mat'\n",
+ "Token IDs: [464, 3797, 3332, 319, 262, 2603]\n",
+ "\n"
+ ]
+ },
+ {
+ "ename": "AttributeError",
+ "evalue": "'SimpleTokenizer' object has no attribute 'vocab_size'",
+ "output_type": "error",
+ "traceback": [
+ "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
+ "\u001b[31mAttributeError\u001b[39m Traceback (most recent call last)",
+ "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[5]\u001b[39m\u001b[32m, line 29\u001b[39m\n\u001b[32m 25\u001b[39m print(f\"Text: '{text}'\")\n\u001b[32m 26\u001b[39m print(f\"Token IDs: {token_ids}\")\n\u001b[32m 27\u001b[39m print()\n\u001b[32m 28\u001b[39m \n\u001b[32m---> \u001b[39m\u001b[32m29\u001b[39m real_embedding = Embedding(tokenizer.vocab_size, d_model=\u001b[32m768\u001b[39m)\n\u001b[32m 30\u001b[39m input_tensor = torch.tensor([token_ids])\n\u001b[32m 31\u001b[39m vectors = real_embedding(input_tensor)\n\u001b[32m 32\u001b[39m print(f\"Output shape: {vectors.shape}\")\n",
+ "\u001b[31mAttributeError\u001b[39m: 'SimpleTokenizer' object has no attribute 'vocab_size'"
+ ]
+ }
+ ],
+ "source": [
+ "from dataclasses import dataclass\n",
+ "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}\n",
+ " )[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",
+ "\n",
+ "tokenizer = SimpleTokenizer()\n",
+ "text = \"The cat sat on the mat\"\n",
+ "token_ids = tokenizer.encode(text)\n",
+ "print(f\"Text: '{text}'\")\n",
+ "print(f\"Token IDs: {token_ids}\")\n",
+ "print()\n",
+ "\n",
+ "real_embedding = Embedding(tokenizer.vocab_size, d_model=768)\n",
+ "input_tensor = torch.tensor([token_ids])\n",
+ "vectors = real_embedding(input_tensor)\n",
+ "print(f\"Output shape: {vectors.shape}\")\n",
+ "print(f\"Each of the {len(token_ids)} tokens is now a 768-dim vector\")\n",
+ "print(f\"The word 'cat' (token {token_ids[1]}) has vector: {vectors[0, 1, :3].tolist()} ...\")"
+ ]
+ }
+ ],
+ "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
+}