v9.1.1
Menu

Chapter 2: Tokenization & Embeddings

Week 1-2

Learn how raw text is converted into numerical representations that neural networks can process. Master the tokenization algorithms (BPE, WordPiece, SentencePiece) that determine a model's vocabulary, understand how word embeddings capture semantic meaning in vector space, and explore positional encodings that give transformers a sense of word order.

Topics
5
Demos
2
Videos
3
Min read
37

Chapter Overview

Before an LLM can process text, it must convert characters into numbers. This seemingly simple step---tokenization---has profound implications for model performance, multilingual capability, and computational efficiency.

Tokenization sits at the intersection of linguistics and engineering. Break words into too-small pieces (individual characters) and the model must learn spelling from scratch. Keep words whole and the vocabulary explodes, making the output layer impossibly large. Modern tokenizers like BPE find a middle ground: common words stay whole ("the", "and") while rare words are split into meaningful subwords ("unhappiness" -> "un", "happiness").

Once tokenized, each token is mapped to a dense vector---an embedding---that captures its semantic meaning. Words with similar meanings cluster together in this high-dimensional space. Finally, since transformers process all tokens in parallel (unlike sequential RNNs), we must inject positional information so the model knows word order.

This chapter covers:

  • Byte Pair Encoding (BPE): The dominant tokenization algorithm used by GPT, Llama, and most modern LLMs
  • WordPiece & SentencePiece: Alternative algorithms used by BERT and multilingual models
  • Token Vocabularies: How vocabulary size affects model performance and efficiency
  • Word Embeddings: Dense vector representations that capture semantic relationships
  • Positional Encodings: How transformers understand token order without recurrence

Chapter Roadmap

Click any topic to jump in

Explainer videoInteractive demo
1
Byte Pair Encoding

The dominant tokenization algorithm — iteratively merging frequent character pairs to build a subword vocabulary.

BPE AlgorithmByte-Level BPETokenization and Compute CostTokenization Artifacts
2
WordPiece & SentencePiece

Alternative tokenizers using likelihood-based merges and language-agnostic byte processing.

WordPiece AlgorithmSentencePieceUnigram Language ModelBPE vs WordPiece vs Unigram
Design decisions
3
Token Vocabularies

How vocabulary size, special tokens, and byte fallback affect efficiency and multilingual fairness.

Vocabulary Size TradeoffsSpecial TokensVocabulary and Multilingual EfficiencyByte Fallback
From tokens to vectors

Tokens become dense vectors that encode meaning and position

4
Word Embeddings

Dense vector representations that capture semantic similarity — from Word2Vec to contextual embeddings.

From One-Hot to Dense EmbeddingsSemantic SimilarityWord AnalogiesContextual Embeddings
5
Positional Encodings

Injecting order information into transformers — sinusoidal, learned, RoPE, and ALiBi approaches.

Sinusoidal Positional EncodingLearned Positional EmbeddingsRotary Position Embedding (RoPE)ALiBi: Attention with Linear Biases

Topics

5 topics in this chapter

A neural network only accepts numbers, so text must first be cut into pieces and each piece given an ID. The obvious cuts both fail. With whole words as units, the vocabulary runs into millions and every typo or new name becomes an unknown token. With single characters, a sentence turns into hundreds of positions, and the model must learn spelling before it can learn meaning. What we want is a vocabulary in which common words are single units and rare words break into reusable parts.

The previous chapter, Introduction to LLMs, treated the token as the basic unit of prediction without saying where tokens come from. This topic answers that question with the algorithm used by GPT-2, GPT-4, Llama, and most modern LLMs.

We start with the BPE training loop, which repeatedly merges the most frequent adjacent pair. Then we cover byte-level BPE, which starts from the 256 byte values so no input is ever unknown. Next we measure how token counts drive compute cost. We finish with the artifacts BPE leaves behind, from split numbers to miscounted letters.

Definition

Byte Pair Encoding (BPE) is a subword tokenization algorithm. It starts from a base vocabulary of characters or bytes and repeatedly adds a new token by merging the most frequent adjacent pair in the training corpus, until the target vocabulary size is reached. New text is encoded by applying the learned merges in the order they were learned.

In this topic

  1. 1BPE Algorithm
  2. 2Byte-Level BPE
  3. 3Tokenization and Compute Cost
  4. 4Tokenization Artifacts
1 of 4
BPE Algorithm

BPE training is a greedy loop over a corpus of word frequencies. First, split every word into single symbols, which form the base vocabulary. Second, count every adjacent pair of symbols, weighting each by its word's frequency. Third, merge the most frequent pair everywhere it occurs and add the merged symbol to the vocabulary. Repeat until the vocabulary reaches its target size, often 32,000 to 200,000. The ordered merge list is the tokenizer, and encoding new text replays those merges in order. Ties between equally frequent pairs are broken by a fixed rule, and a greedy choice can leave awkward splits in rare words.

Mathematical Intuition

BPE greedily maximizes compression: at each step, merging the most frequent pair reduces total sequence length by freq(a,b)−1\text{freq}(a,b) - 1 tokens. After MM merges from base vocabulary V0V_0, the vocabulary is ∣V∣=∣V0∣+M|V| = |V_0| + M. The algorithm approximates minimum description length (MDL): L(D,V)=∣V∣log⁡∣V∣+∣D∣Vlog⁡∣V∣\mathcal{L}(D, V) = |V| \log |V| + |D|_V \log |V| where ∣D∣V|D|_V is the encoded corpus length under vocabulary VV.

Example:

Given the corpus: "low lower lowest", trace the first 3 BPE merges.

2 of 4
Byte-Level BPE

Character-level BPE has a gap: a character never seen in training, such as a rare script or emoji, has no token and becomes [UNK], losing information. GPT-2 closed the gap by running BPE over bytes instead of characters. Text is first encoded as UTF-8, so the base vocabulary is exactly the 256 possible byte values, and merges are learned on top of those. Every string is a byte sequence, so every string can be encoded and decoded exactly. The cost falls on text the merges rarely covered, which splits into many small pieces. Each non-Latin character is 2 to 4 bytes, and that affects multilingual fairness.

Mathematical Intuition

Starting from 256 byte values guarantees universal coverage because any Unicode character encodes as 1-4 UTF-8 bytes. The worst-case expansion is 4x: a 4-byte character becomes 4 tokens. The expected expansion for English is approximately 1.01.0x (ASCII maps to single bytes), while CJK characters average 33x (3-byte UTF-8). This asymmetry is the root cause of tokenizer bias across languages.

Example:

Why does byte-level BPE never produce an "unknown token"?

3 of 4
Tokenization and Compute Cost

Compute∝sequence length2×model dimension\text{Compute} \propto \text{sequence length}^2 \times \text{model dimension}

Every token is a position the model must process, so tokenizer efficiency is a compute question. Self-attention compares every pair of positions, so its cost grows with the square of sequence length, while the feedforward layers grow linearly. A tokenizer that packs the same text into fewer tokens therefore saves money in training and inference and fits more text into a fixed context window. For English, good BPE vocabularies average about 1.3 tokens per word, against roughly 5 or 6 characters per word for a character-level model. The failure mode is uneven compression: text unlike the training corpus gets many more tokens.

Mathematical Intuition

Self-attention cost scales as O(n2d)O(n^2 d) where nn is sequence length. A tokenizer that reduces nn by factor kk saves k2k^2 in attention compute. For example, BPE compressing 5000 characters to 1300 tokens: attention cost is (1300/5000)2≈6.8%(1300/5000)^2 \approx 6.8\% of character-level cost. This quadratic saving is why tokenizer efficiency directly impacts training and inference budgets.

Example:

"International" is 1 token in GPT-4 but 3 tokens in a character-level model. What is the compute difference?

4 of 4
Tokenization Artifacts

Because BPE splits text by frequency rather than meaning, it leaves visible artifacts. Numbers are split into chunks that depend on which digit groups happened to be common, so the same digits can be grouped differently in different numbers. Leading spaces are part of the token in GPT-style tokenizers, so "hello" and " hello" have different IDs. Letters inside a token are invisible to the model, which sees only the token ID. These artifacts explain some odd failures, such as miscounting letters, fumbling arithmetic on long numbers, or behaving differently when a prompt has a trailing space.

Mathematical Intuition

BPE tokenization is context-dependent at boundaries: "123" might tokenize as ["123"] but "1234" as ["12", "34"] because the merge history creates different split points. The number of possible tokenizations of a string of length nn with vocabulary VV is exponential: up to 2n−12^{n-1} segmentations. BPE's deterministic greedy approach selects just one, which may not be optimal for downstream tasks.

Example:

Why do LLMs sometimes struggle with counting letters in a word like "strawberry"?

Theory Exercise

Problem:

A BPE tokenizer with vocabulary size 32,000 tokenizes English at 1.3 tokens/word but Japanese at 3.5 tokens/word. Why? What are the implications?

Hints:
  • Think about the training data distribution for BPE
  • Consider what happens to languages underrepresented in training
  • Think about cost implications for different languages

Related Problems on PixelBank