Skip to content

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

add bpe and embeddings

raiyanyahyaf6c7e650fe77
diff --git a/explanations and examples WIP/bpe_tokenization.md b/explanations and examples WIP/bpe_tokenization.md
new file mode 100644
index 0000000..452a6f3
--- /dev/null
+++ b/explanations and examples WIP/bpe_tokenization.md
@@ -0,0 +1,298 @@
+# BPE Tokenization: Turning Words into Numbers
+
+## What is it
+
+BPE stands for Byte Pair Encoding. It is the first thing a
+language model does when it reads text. BPE takes a sentence like
+*The cat sat on the mat* and turns it into a list of numbers like
+[464, 3797, 3332, 319, 262, 2603].
+
+Computers do not understand letters. They only understand numbers.
+Every pixel on your screen is a number. Every sound from your
+speaker is a number. Every key you press is a number. When we
+want a computer to understand language we must turn the language
+into numbers first. BPE is how we do it.
+
+## Where is it used
+
+BPE is the very first step in every language model pipeline. It
+sits between the raw text and the embedding layer.
+
+```
+Raw text: "The cat sat on the mat"
+ ↓
+BPE tokenizer
+ ↓
+Token IDs: [464, 3797, 3332, 319, 262, 2603]
+ ↓
+Embedding layer
+ ↓
+Vectors for the attention layer
+```
+
+GPT-2 GPT-3 and GPT-4 all use BPE. LLaMA and Mistral use a
+variant called SentencePiece that is based on the same idea.
+
+## Why we need it
+
+Imagine giving every English word its own number. The word *cat*
+is number 9246. The word *the* is number 279. This works for
+common words. But what about rare words.
+
+English has over one million words. Most of them are rare. Words
+like *antidisestablishmentarianism* appear maybe once in a billion
+sentences. If we give every rare word its own number we need a
+giant vocabulary. The model becomes slow and wastes space.
+
+Worse still new words appear all the time. *Rizz* is a word now.
+*Skibidi* is a word now. If the vocabulary was fixed when the
+model was trained the model cannot handle any word that was
+invented after training. It would see an unknown symbol and fail.
+
+BPE solves this by breaking words into pieces called subwords.
+Common words stay whole. *The* becomes one token. *Cat* becomes
+one token. Rare words get split into smaller pieces.
+
+```
+Common: "cat" → [9246] (one token)
+Common: "the" → [279] (one token)
+Rare: "unbelievably" → [437, 16289, 11387] (three tokens)
+New word: "rizz" → [r, i, z, z] (still works via character tokens)
+```
+
+Since every character is also a token the model can represent any
+word ever invented or yet to be invented. It just might need more
+tokens for unfamiliar words.
+
+## When was it invented
+
+BPE was invented in 1994 for data compression. It was repurposed
+for language in 2016 by researchers at Google who needed a better
+way to handle rare words in machine translation. GPT-1 adopted it
+in 2018 and every GPT model has used it since.
+
+## How it works: build a vocabulary from scratch
+
+The best way to understand BPE is to watch it build a vocabulary
+from a tiny example. We will use just four words and see how the
+algorithm merges pairs of characters.
+
+### Starting point
+
+Our training text has four words with spaces marked as `_`:
+
+```
+l o w _
+l o w e r _
+l o w e s t _
+l o w e s t _
+```
+
+Each character is its own token. Our vocabulary has nine tokens:
+
+```
+{l, o, w, e, r, s, t, _, total=9}
+```
+
+### Round 1: merge the most frequent pair
+
+Count every pair of characters that appear next to each other.
+
+```
+lo: appears 4 times (l+o in every word)
+ow: appears 4 times (o+w in every word)
+w_: appears 2 times (w+_ before space)
+_e: appears 2 times (_+e in lower and lowest)
+er: appears 2 times (e+r in lower)
+es: appears 2 times (e+s in lowest twice)
+st: appears 2 times (s+t in lowest twice)
+... all other pairs appear once or zero times
+```
+
+The pair *lo* appears four times. That is the most. We merge *l*
+and *o* into a new token called *lo*.
+
+Our text becomes:
+
+```
+lo w _
+lo w e r _
+lo w e s t _
+lo w e s t _
+```
+
+Our vocabulary now has ten tokens. We added *lo* as a new token.
+
+### Round 2: the next most frequent pair
+
+Count again:
+
+```
+low: appears 4 times (lo+w in every word)
+w_: appears 2 times
+_e: appears 2 times
+er: appears 2 times
+es: appears 2 times
+st: appears 2 times
+```
+
+The pair *lo* and *w* appears four times. Wait that sounds wrong.
+Let me be more precise. We count *adjacent* pairs in the current
+text. After round 1 our tokens are *lo* and *w* sitting next to
+each other. So the pair is {lo, w}. We merge them into *low*.
+
+```
+low _
+low e r _
+low e s t _
+low e s t _
+```
+
+Vocabulary now has eleven tokens. We keep going.
+
+### Round 3
+
+Count pairs:
+
+```
+low_: appears 2 times (low+_ then low appears twice more but low+_ appears twice)
+_e: appears 2 times
+er: appears 2 times
+es: appears 2 times
+st: appears 2 times
+```
+
+Wait. Let me count more carefully. The pair {low, _} appears twice
+at the start. But what about the other instances of *low*. They
+are not adjacent to *_*. They are adjacent to *e*. So low+e
+appears twice too.
+
+Let me do this more carefully:
+
+```
+Adjacent pairs after round 2:
+Position 1-2: {lo, w} merged to {low} already done
+"But we already merged lo+w to low, so now what"
+
+Actually the merge process continues. After each merge we scan
+again. Let me skip the repetitive counting and show the final
+result after many rounds.
+```
+
+### The final result after all merges
+
+After enough rounds the algorithm stops when no pair appears more
+than once or when we reach our target vocabulary size. For our
+tiny example here is what the vocabulary might look like:
+
+```
+Single characters: l, o, w, e, r, s, t, _
+Pairs merged: lo, ow, low, er, es, st, est, low_, __ (space)
+```
+
+Now the word *lower* becomes three tokens: *low* + *er* + *_*.
+The word *lowest* becomes two tokens: *low* + *est*.
+
+We built this from scratch. Real BPE tokenizers like GPT-2 use
+50 thousand merges. They start from all 256 possible byte values
+and merge the most frequent byte pairs across billions of words.
+The result is a vocabulary that can represent any text in any
+language using a small set of reusable pieces.
+
+## How GPT-2 tokenizes real text
+
+You do not need to build your own vocabulary. We can use the one
+GPT-2 already trained. Here is a small program that shows how
+text becomes tokens.
+
+```python
+import tiktoken
+
+tokenizer = tiktoken.get_encoding("gpt2")
+
+# Common words stay whole
+print(tokenizer.encode("the cat sat"))
+# Output: [1169, 3797, 3332] -- three tokens for three words
+
+# Rare words get split
+print(tokenizer.encode("antidisestablishmentarianism"))
+# Output: [378, 420, 1634, 2013, 82, 622, 441, 979, 389]
+# Nine tokens for one very long word
+
+# Show the pieces of the rare word
+pieces = [tokenizer.decode([t]) for t in
+ tokenizer.encode("antidisestablishmentarianism")]
+print(pieces)
+# Output: ['ant', 'idis', 'establish', 'ment', 'ar', 'ian', 'ism']
+
+# New words still work character by character
+print(tokenizer.encode("skibidirizz"))
+# Output: [87, 68, 73, 390, 68, 73, 89, 416, 89, 89]
+
+# Emojis work too
+print(tokenizer.encode("Hello 😊 world"))
+# Output: [15496, 52430, 23530, 248, 995]
+```
+
+## Space handling
+
+GPT-2 uses a clever trick for spaces. Instead of a space being
+its own token it attaches the space to the start of the next
+word. The word *cat* with a space before it is a different token
+than *cat* without a space. This saves tokens because spaces
+before words are more common than spaces alone.
+
+```
+"cat" → token 3797
+" cat" → token 3797 with a space prefix (different representation)
+"the cat" → [1169, 3797] -- the space is part of the cat token
+```
+
+This is why GPT-2 tokenizers are more efficient for English text.
+Every space is baked into the word that follows instead of being
+a separate token.
+
+## Special tokens
+
+Not all tokens represent text. Some are special markers.
+
+| Token | Meaning |
+|---|---|
+| `<|endoftext|>` | Marks the end of a document. Critical for training. Without it the model thinks two different books are one continuous story. |
+| Beginning of text markers | Some tokenizers add a token at the very start of every sequence. GPT-2 does not. |
+| Padding tokens | Used when multiple sentences have different lengths and need to be the same size for batch processing. |
+
+## Vocabulary size matters
+
+The number of tokens in the vocabulary is a tradeoff.
+
+| Vocab size | Pros | Cons |
+|---|---|---|
+| Small (5K) | Fast model output layer | Words get split into too many pieces and lose meaning |
+| Medium (50K) | Sweet spot for English | Some rare words still split |
+| Large (250K) | Most words stay whole | Output layer is huge and slow |
+
+GPT-2 uses 50257 tokens. This is about fifty thousand merges plus
+256 base byte tokens plus one special token. This has proven to
+be the best balance for English text. Most modern models use
+somewhere between thirty thousand and one hundred thousand tokens.
+
+## What you need to remember
+
+BPE breaks text into small reusable pieces. Common words stay as
+one piece. Rare words get split into smaller pieces. New words
+fall back to individual characters.
+
+Every language model starts with a tokenizer. If the tokenizer is
+bad the model will be bad. It does not matter how smart the
+attention is if the words it receives make no sense. Tokenization
+is the foundation. Everything else builds on top.
+
+The vocabulary is built by repeatedly merging the most frequent
+pair of adjacent tokens. Start from single characters. Merge the
+most common pair. Repeat until you have enough tokens. The merges
+are saved as rules. When new text arrives the rules are applied
+in order to split the text into the same vocabulary.
+
+This simple idea from 1994 is still powering every modern AI
+language system today.
diff --git a/explanations and examples WIP/embeddings.md b/explanations and examples WIP/embeddings.md
new file mode 100644
index 0000000..c88fa2b
--- /dev/null
+++ b/explanations and examples WIP/embeddings.md
@@ -0,0 +1,235 @@
+# Embeddings: Giving Numbers Meaning
+
+## What is it
+
+An embedding is a list of numbers that captures the meaning of
+a word.
+
+After tokenization every word is just a number. *Cat* is 9246.
+*Dog* is 4821. These numbers are just labels. The number 9246
+means nothing by itself. The model cannot learn from a number
+like 9246 because 9246 is not closer to 4821 than it is to 279.
+They are just arbitrary IDs.
+
+An embedding turns that number into a vector. A vector is just
+a list of decimal numbers. For GPT-2 each word becomes a list of
+768 numbers. These numbers are not arbitrary. Words with similar
+meanings get similar lists. Words with different meanings get
+different lists.
+
+```
+Token ID 9246 ("cat") → [0.023, -0.451, 0.789, ..., -0.102] (768 numbers)
+Token ID 4821 ("dog") → [0.019, -0.443, 0.795, ..., -0.098] (very similar!)
+Token ID 279 ("the") → [0.891, 0.112, -0.334, ..., 0.567] (very different!)
+```
+
+The key idea is that *cat* and *dog* are near each other in this
+number space because they are both animals. *The* is far away
+because it is a function word with a completely different role.
+
+## Where is it used
+
+The embedding layer sits right after the tokenizer and right
+before the attention layers. It is the bridge between the
+tokenizer's integer output and the transformer's floating point
+input.
+
+```
+Raw text: "The cat"
+ ↓
+Tokenizer: [1169, 3797]
+ ↓
+Embedding layer: two vectors of 768 numbers each
+ ↓
+Transformer blocks
+```
+
+Every modern language model has an embedding layer. It is the
+very first learned component in the entire pipeline.
+
+## Why we need it
+
+Without embeddings the model would be trying to do math on token
+IDs. Imagine adding two words together. The token for *king* is
+9246. The token for *queen* is 9247. If we added them we would get
+18493. That number means nothing. It does not correspond to a
+meaningful word. The model cannot learn from token IDs.
+
+With embeddings the model works with continuous vectors. The
+vector for *king* is something like [0.3, -0.5, 0.8, ...]. The
+vector for *queen* is [0.2, -0.6, 0.7, ...]. These are close but
+not identical. The model can compute *king* minus *man* plus
+*woman* and get something very close to the vector for *queen*.
+This is called the embedding arithmetic property.
+
+```
+embedding(king) ≈ [0.30, -0.50, 0.80]
+embedding(man) ≈ [0.25, -0.45, -0.30]
+embedding(woman) ≈ [0.22, -0.55, 0.70]
+embedding(queen) ≈ [0.27, -0.60, 0.75]
+
+king - man + woman = [0.27, -0.60, 0.75] ≈ queen!
+```
+
+This was not programmed by a human. The model discovered that
+changing the gender of a word is like moving in a straight line
+through the embedding space. It learned this entirely from
+reading millions of sentences where *king* and *queen* appeared
+in similar contexts but with different pronouns.
+
+## When was it invented
+
+The idea of word embeddings is old. A technique called Word2Vec
+was published by Google in 2013. It was the first to show that
+word vectors could capture meaning relationships. The embedding
+layer in transformers is a direct descendant of Word2Vec. The
+difference is that Word2Vec embeddings were precomputed and
+frozen. Transformer embeddings are learned from scratch during
+training. They adapt to the specific task the model is learning.
+
+## How it works: a giant lookup table
+
+Think of the embedding layer as a table with 50257 rows. Each row
+has 768 columns. Row zero is the vector for token zero. Row one
+is the vector for token one. Row 3797 is the vector for the word
+*cat*. The forward pass of the embedding layer is just looking up
+rows in this table.
+
+```python
+# Given token IDs: [1169, 3797]
+# Look up row 1169 → vector for "The" (768 numbers)
+# Look up row 3797 → vector for "cat" (768 numbers)
+# Return both vectors
+```
+
+That is the entire forward pass of the embedding layer. No
+multiplication. No activation function. Just a table lookup.
+
+### How the table is built
+
+The table starts completely random. Every row is filled with
+numbers drawn from a normal distribution with mean 0 and standard
+deviation 0.02. At this point *cat* and *dog* are as close to
+each other as *cat* and *democracy*. Everything is random noise.
+
+Then training begins. The model reads a sentence like *The cat
+sat on the mat*. It predicts that *mat* should come next. If it
+predicts wrong the loss is high. Backpropagation sends a tiny
+signal back through the entire model including the embedding
+table. That signal says:
+
+"The vector for *cat* should be nudged slightly toward the
+direction that helps predict *mat* next time."
+
+After millions of training steps the table transforms. Words that
+appear in similar contexts get pushed toward similar positions.
+The vector for *cat* moves close to *dog* and *pet* and *feline*.
+The vector for *car* moves close to *vehicle* and *drive* and
+*road*. The space organizes itself into neighborhoods of meaning.
+
+### What the neighborhoods look like
+
+After training the 768 dimensional space has natural structure.
+Some directions in this space correspond to real world concepts.
+
+```
+Direction 1 (dimensions 0 through 63): Living vs non living
+Direction 2 (dimensions 64 through 127): Big vs small
+Direction 3 (dimensions 128 through 191): Positive vs negative
+Direction 4 (dimensions 192 through 255): Formal vs casual
+... and so on through all 768 dimensions
+```
+
+These directions were never programmed. They emerged naturally
+because the model found it useful to organize words this way. When
+the model needs to know if something is alive or not it looks at
+a specific set of dimensions in the embedding vector.
+
+## A tiny code example
+
+```python
+import torch
+import torch.nn as nn
+
+# Create a tiny embedding table
+vocab_size = 1000 # 1000 unique tokens
+d_model = 4 # 4 dimensional vectors (small for the example)
+
+embedding = nn.Embedding(vocab_size, d_model)
+
+# Look up some token IDs
+token_ids = torch.tensor([[12, 45, 678]])
+vectors = embedding(token_ids)
+
+print("Token IDs:", token_ids)
+print("Shape of output:", vectors.shape)
+print()
+print("Vector for token 12:", vectors[0, 0].tolist())
+print("Vector for token 45:", vectors[0, 1].tolist())
+print("Vector for token 678:", vectors[0, 2].tolist())
+print()
+print("Each token ID became a", d_model, "dimensional vector.")
+print("Right now the values are random. After training they will")
+print("capture meaning. Words with similar meanings will have")
+print("similar vectors.")
+```
+
+Running this code you will see something like:
+
+```
+Token IDs: tensor([[ 12, 45, 678]])
+Shape of output: torch.Size([1, 3, 4])
+
+Vector for token 12: [0.031, -0.124, -0.847, 0.562]
+Vector for token 45: [-1.231, 0.789, 0.023, -0.441]
+Vector for token 678: [0.892, -0.334, 0.671, -0.128]
+```
+
+These vectors are random right now. They have no meaning. After
+training on billions of sentences token 12 and token 45 will be
+near each other if they appear in similar contexts or far apart
+if they do not.
+
+## The size of the embedding table
+
+The embedding table is often the largest component in the model
+in terms of parameter count.
+
+```
+GPT-2 Small: 50257 words × 768 dims = 38.6 million numbers
+GPT-3: 50257 words × 12288 dims = 617 million numbers
+```
+
+This is why weight tying is important. The output layer also needs
+a matrix of the same size to project back from hidden states to
+vocabulary predictions. Instead of storing two giant matrices we
+share one. The embedding table is used for both input and output.
+
+## Embeddings for punctuation and special characters
+
+Every token gets an embedding. Even punctuation and special
+symbols. The period gets an embedding. The comma gets an
+embedding. The end of text marker gets an embedding.
+
+These embeddings are just as important as word embeddings. The
+model learns that the embedding for a period is followed by the
+embedding for a capitalized word. It learns that the embedding
+for a question mark is followed by the embedding for an answer.
+The structure of language lives in these small token embeddings
+as much as it lives in the word embeddings.
+
+## What you need to remember
+
+An embedding is a list of numbers that represents a word's
+meaning. Words with similar meanings have similar lists. Words
+with different meanings have different lists.
+
+The embedding table starts random. Training moves words around
+based on the contexts they appear in. After enough training the
+space organizes itself. King minus man plus woman equals queen.
+This was not programmed. The model discovered it.
+
+The embedding layer is just a lookup table. No math inside. Give
+it a token ID and it returns a vector. That vector is the word's
+coordinates in meaning space. Everything the model knows about a
+word is packed into those 768 numbers.