Chapter 4: Word Embeddings
Learn how words are represented as dense vectors that capture semantic meaning, from Word2Vec and GloVe to subword methods like FastText and BPE. Master the algorithms, training objectives, and evaluation methods behind modern word representations.
- Topics
- 6
- Demos
- 3
- Videos
- 3
- Min read
- 47
Chapter Overview
Word embeddings are one of the most important breakthroughs in NLP. Instead of treating words as arbitrary symbols (one-hot vectors), embeddings map each word to a dense, low-dimensional vector where geometric relationships encode semantic meaning. Words with similar meanings cluster together, and directions in the vector space correspond to linguistic relationships like gender, tense, and geography.
The key insight is that you can learn these vectors from raw text alone. By training a model to predict words from their contexts (or vice versa), the model is forced to encode meaning into its weight matrices. The resulting vectors transfer to downstream tasks, providing a powerful initialization for everything from sentiment analysis to machine translation.
This chapter covers the major embedding algorithms --- Word2Vec (CBOW and Skip-gram), GloVe, and FastText --- along with subword tokenization methods (BPE, SentencePiece) that handle out-of-vocabulary words. You will also learn how to evaluate embedding quality using analogy tasks, similarity benchmarks, and downstream performance.
Chapter Roadmap
Click any topic to jump in
Word2Vec CBOW
Predicting a center word from context — learning dense embeddings by averaging surrounding word vectors.
Skip-gram
Predicting context from a center word — better for rare words via negative sampling.
Global co-occurrence and subword morphology
GloVe
Factorizing the global co-occurrence matrix — combining count-based and predictive approaches.
FastText
Character n-gram embeddings — handling OOV words and morphology with subword information.
Embedding Evaluation
Analogy tasks, similarity benchmarks, and downstream metrics — measuring what embeddings capture.
Subword Embeddings
BPE and SentencePiece — tokenization-level solutions that feed modern transformers.
Topics
6 topics in this chapter
Count-based vectors from the previous chapter have a dimension for every vocabulary word, so they are huge and sparse, and SVD on a 50,000 by 50,000 co-occurrence matrix is expensive to recompute whenever the corpus grows. Could a model instead learn short dense vectors directly from raw text, one sentence at a time, with a training signal that requires no labels?
The previous chapter, Text Representation, ended with dimensionality reduction, which compressed co-occurrence statistics into dense vectors. This chapter, Word Embeddings, learns such vectors by prediction, and it opens with Word2Vec's Continuous Bag of Words model from Mikolov et al. (2013). CBOW hides the center word of a window and predicts it from the surrounding words. The topic first states the CBOW objective, a softmax over the vocabulary, and then shows how the context window slides across the corpus to create training examples. Embedding averaging follows, the step that gives CBOW its bag-of-words name. It closes with the training loss and why the full softmax is too expensive, which sets up negative sampling in the next topic.
Definition
Continuous Bag of Words (CBOW) is a Word2Vec architecture that learns word embeddings by predicting a center word from the average of its context words' input embeddings within a window of words on each side. Training maximizes over the corpus; the input embedding matrix becomes the word vectors.
In this topic
- 1CBOW Objective Function
- 2Context Window and Sliding
- 3Embedding Averaging
- 4Training and Loss
CBOW Objective Function
CBOW maximizes the probability of the center word given its context. The context is represented by averaging the input embedding vectors of surrounding words to produce . This average vector is projected through a second weight matrix and passed through softmax over the entire vocabulary. The model has two sets of embeddings: input embeddings (used for context words) and output embeddings (used for prediction). After training, usually only the input embeddings are kept.
CBOW maximizes where is the average of context embeddings. The softmax denominator sums over all words — per training step. With and billions of training positions, this is the computational bottleneck that negative sampling and hierarchical softmax were designed to solve.
Given the sentence "the quick brown fox jumps" with window size 2, what is the training example when "brown" is the center word?
Context Window and Sliding
The window size sets how many words on each side of the center count as context, giving up to context words per position. The window slides over every position of the corpus, so CBOW creates one training example per token, and sentence edges get truncated contexts. Window size shapes what the vectors encode: small windows of about 2 favor syntactic neighbors, words that can replace each other in a sentence, while large windows of 5 to 10 favor topical relatedness. The original tool also samples an effective window size uniformly between 1 and for each position, which weights near neighbors more heavily than distant ones.
The context window of size produces context words per position. Larger captures topical similarity (words about the same subject cluster together), while smaller captures syntactic similarity (words with the same part of speech cluster). Empirically, works well for most tasks. The window slides times across the corpus, generating training examples — the entire training set is just the corpus itself.
For the sentence "I love natural language processing" with window size 1, list all (context, target) training pairs.
Embedding Averaging
CBOW combines the context into a single vector by averaging the input embeddings of the context words, as in the formula. Averaging discards the order of words inside the window, which is the bag-of-words part of the name, and it keeps the computation per example to one prediction no matter how many context words there are. Each context word receives the same share of the gradient. The average works because the model can spread complementary information across context words, but it also blurs them: a window containing both "river" and "money" yields a vector halfway between two meanings. Skip-gram, the next topic, avoids averaging altogether.
Embedding averaging is a lossy compression: vectors are reduced to one. The information loss is bounded by the variance of the context embeddings: if all context vectors are similar (semantically coherent context), the average preserves most information. If they are dissimilar (diverse context), averaging destroys individual word signals. This is why CBOW struggles with rare words — their contexts are diverse.
If the embeddings for "the" = [0.1, 0.3], "cat" = [0.5, -0.1], "on" = [0.2, 0.4], "mat" = [-0.1, 0.2], what is ?
Training and Loss
The training objective is to minimize the negative log-likelihood averaged over all positions in the corpus. Computing the full softmax over a vocabulary of words is expensive (requires summing over all words for the normalizing constant), so practical implementations use hierarchical softmax or negative sampling to approximate the gradient. Stochastic gradient descent with linear learning rate decay is standard. Training typically requires one or two passes over the corpus.
The cross-entropy loss decreases as the model learns to predict center words. The gradient (predicted minus true distribution) has magnitude proportional to the prediction error. After convergence, the embedding matrix encodes each word's meaning in dimensions, where is typical.
Why is computing the full softmax expensive for large vocabularies?
Theory Exercise
Problem:
Explain why CBOW tends to perform better on frequent words while Skip-gram performs better on rare words. What property of the CBOW architecture causes this?
Hints:
- Think about how averaging affects rare vs. frequent words
Coding Exercise
Problem:
Implement a minimal CBOW model using NumPy. Create the forward pass that takes context word indices, looks up embeddings, averages them, and computes the softmax output.
Hints:
- Use a random embedding matrix of shape (vocab_size, embed_dim)
Related Problems on PixelBank
CBOW averages a whole window into one vector and makes one prediction, so a rare word that appears a handful of times gets only a handful of blurred updates. Rare words are exactly the ones whose meaning we most need to infer from context. What if every (word, neighbor) pair became its own training example, and the model learned to predict the neighbors from the word instead?
The previous topic, Word2Vec CBOW, predicted a center word from its averaged context and ended with the cost of a full softmax. Skip-gram reverses the direction: given a center word, it predicts each context word separately, creating up to examples per position. The topic first states the skip-gram objective and counts the training pairs it creates. Negative sampling follows, the trick that turns the softmax into a few binary classifications and makes training on billions of words practical. The topic closes with the noise distribution that chooses those negative words, the unigram distribution raised to the 3/4 power, and explains why that exponent gives rare words a fairer chance to appear as negatives.
Definition
Skip-gram is a Word2Vec architecture that learns embeddings by predicting each context word , for and , from the center word . With negative sampling (SGNS), each softmax is replaced by logistic regression that separates observed (word, context) pairs from pairs drawn from a noise distribution.
In this topic
- 1Skip-gram Objective
- 2Negative Sampling
- 3Noise Distribution
Skip-gram Objective
Skip-gram reverses CBOW: the center word predicts each context word separately. Its input embedding is dotted with the output embedding of every vocabulary word, and the softmax in the formula turns those scores into a distribution over possible neighbors. The training objective sums over all positions and all offsets in the window, so each position contributes up to separate predictions instead of one averaged one. That gives every occurrence of a rare word gradient updates, which is why skip-gram learns rare words better than CBOW, at the cost of more computation per pass over the corpus.
Skip-gram generates training pairs per position: excluding self-pairs. Each pair gets its own gradient update, giving rare center words updates per occurrence — compared to CBOW's single averaged update. This is why skip-gram produces better embeddings for rare words: a word appearing 5 times in the corpus gets direct gradient signals.
For "the quick brown fox jumps" with window 2, how many training examples does the center word "brown" generate?
Negative Sampling
Instead of computing softmax over the full vocabulary, negative sampling turns the problem into binary classification. For each positive (center, context) pair, sample random "negative" words that are not in the context. The model learns to assign high similarity to real pairs and low similarity to random pairs. The noise distribution upsamples rare words relative to their frequency. Typical values are for small datasets and for large ones.
Negative sampling replaces the softmax with binary classifications. For each positive pair , sample negative words and optimize . The sigmoid maps dot products to probabilities. With , each update touches only 6 word vectors instead of 100,000 — a speedup.
For the positive pair ("fox", "quick"), with k=3 negative samples ["the", "and", "of"], what does the model optimize?
Noise Distribution
Negative words are sampled according to a smoothed unigram distribution raised to the 3/4 power. The exponent 0.75 was found empirically to work better than the raw unigram distribution () or uniform sampling (). The smoothing increases the sampling probability of rare words relative to their corpus frequency, ensuring the model sees a diverse set of negatives. Without this smoothing, very frequent words like "the" and "a" would dominate the negative samples.
The noise distribution compresses frequency differences: a word 10,000 times more common than another is sampled only times more often as a negative. Mikolov et al. report that the 3/4 power outperformed both the unigram distribution, exponent 1, and the uniform distribution, exponent 0. The same paper also subsamples frequent words in the training text, discarding each occurrence with probability for a threshold such as . With that threshold, a word with frequency 0.07, like "the", is dropped about 99 percent of the time, which speeds training and improves rare-word vectors.
Word frequencies: "the" = 0.07, "cat" = 0.001, "quantum" = 0.0001. Compare their raw vs. smoothed sampling probabilities.
Theory Exercise
Problem:
Levy and Goldberg (2014) showed that Skip-gram with negative sampling implicitly factorizes a shifted PMI matrix: . Explain what this means and why it connects neural and count-based methods.
Hints:
- PMI measures how much more often two words co-occur than expected by chance
Coding Exercise
Problem:
Implement Skip-gram with negative sampling for a small corpus. Generate positive pairs from a sliding window, sample negatives using the 3/4 power distribution, and train using sigmoid cross-entropy.
Hints:
- For each (center, context) pair, sample k negative words
Related Problems on PixelBank
GloVe (Global Vectors for Word Representation) takes a fundamentally different approach from Word2Vec. Instead of training on local context windows, GloVe first builds a global word-word co-occurrence matrix from the entire corpus, then learns embeddings by factorizing this matrix. The result is embeddings that encode both local context patterns and global corpus statistics.
Pennington et al. (2014) designed GloVe around a key observation: the ratio of co-occurrence probabilities is more informative than raw probabilities. If the ratio is large, it tells us that "solid" is more associated with "ice" than "gas" is. GloVe's objective function is engineered so that dot products of learned embeddings approximate the log of co-occurrence counts, naturally capturing these ratios.
GloVe bridges the gap between count-based methods (like SVD on co-occurrence matrices) and prediction-based methods (like Word2Vec). It achieves state-of-the-art results on analogy and similarity benchmarks while being straightforward to parallelize, since the co-occurrence matrix is computed once and training iterates over its nonzero entries.
Definition
GloVe (Global Vectors) learns word vectors and context vectors by weighted least squares on a corpus-wide co-occurrence matrix , fitting over all non-zero entries, so that it combines global count statistics with the vector arithmetic of prediction-based methods. A weighting function limits the influence of very frequent and very rare pairs.
In this topic
- 1Co-occurrence Matrix
- 2GloVe Objective Function
- 3Weighting Function
- 4Co-occurrence Probability Ratios
Co-occurrence Matrix
The co-occurrence matrix has entries counting how many times word appears in the context of word across the entire corpus. Context is defined by a window, and closer words can be weighted more heavily (e.g., distance weighting: a word 3 positions away contributes 1/3 as much as an adjacent word). The matrix is symmetric: . Its construction requires one pass over the corpus and is in memory, though in practice only nonzero entries are stored.
GloVe builds a co-occurrence matrix where counts how often words and appear within a context window. Unlike Word2Vec which processes the corpus sequentially, GloVe pre-computes all co-occurrences, then optimizes on the matrix. For vocabulary and corpus tokens with window , building costs time and space — but in practice is sparse, using much less.
Build the co-occurrence matrix for "I like deep learning I like NLP" with window size 1.
GloVe Objective Function
GloVe minimizes a weighted least-squares loss that makes the dot product of word embeddings approximate the log co-occurrence count. Each word has two vectors ( and ) and two bias terms ( and ). The weighting function prevents very frequent co-occurrences from dominating the loss. The sum runs over all nonzero entries of . After training, the final embedding is typically (sum of the two vectors).
The GloVe objective minimizes the squared difference between the dot product of word vectors and the log co-occurrence count. The key insight: if , then , encoding co-occurrence ratios as vector differences — the algebraic basis for analogy solving.
Why does GloVe use rather than as the target?
Weighting Function
The weighting function controls how much each non-zero matrix entry contributes to the GloVe loss. Very frequent pairs such as ("the", "of") would otherwise dominate, and very rare pairs with counts of 1 or 2 are noisy. As the formula shows, rises as for counts below and is capped at 1 above it; the paper uses and , noting that 3/4 gave a modest improvement over a linear weight. Because , zero entries contribute nothing, so training iterates only over the non-zero entries of and never needs the log of zero.
The weighting function prevents frequent co-occurrences from dominating the loss. Without weighting, the pair ('the', 'the') with would contribute millions of times more to the loss than ('quantum', 'computing') with . The clamp at for (typically 100) caps the maximum weight, and the power smooths the transition.
Compute the weights for co-occurrence counts 10, 50, 100, and 500 with and .
Co-occurrence Probability Ratios
The theoretical motivation for GloVe starts with the observation that ratios of co-occurrence probabilities distinguish between related and unrelated words better than raw probabilities. Given probe words , the ratio is large for (related to ice), small for (related to steam), and close to 1 for (related to both) or (unrelated to both). GloVe is designed so that captures this discriminative direction.
Co-occurrence probability ratios reveal word relationships: is large for ice-related ('solid', 'cold') and small for steam-related ('gas', 'hot'). GloVe is designed so that . This ratio-based formulation captures relational meaning — the direction encodes the 'solid-gas' semantic axis.
From the GloVe paper's 6-billion-token corpus: , , , . Compute the ratios and interpret them.
Theory Exercise
Problem:
GloVe and Word2Vec (SGNS) both produce word embeddings. Describe three key differences in their training approach, and explain when you might prefer one over the other.
Hints:
- Think about local vs. global statistics
Coding Exercise
Problem:
Build a co-occurrence matrix from a corpus with distance-weighted counting (words further away contribute less), then implement one step of the GloVe gradient update.
Hints:
- Weight by 1/distance for words within the window
Related Problems on PixelBank
Word2Vec and GloVe learn one vector per vocabulary word and nothing else. A word that never appeared in training, such as a new product name, a typo like "embedings", or the Finnish form of a noun with an unusual case ending, simply has no vector. Even rare words that did appear get poor vectors from a handful of contexts. Yet "unforgettable" obviously shares structure with "forget" and "able". Can embeddings use the spelling inside words, not just the contexts around them?
The previous topic, GloVe, learned vectors from global co-occurrence counts but kept the whole word as the unit. FastText, from Bojanowski et al. at Facebook AI Research, keeps the skip-gram objective but represents each word as the sum of vectors for its character n-grams. The topic first shows how a word decomposes into n-grams with boundary markers. Out-of-vocabulary handling follows, building vectors for unseen words from their pieces. The topic closes with the hashing trick, which caps memory by sharing n-gram vectors across a fixed number of buckets.
Definition
FastText represents a word as the sum of a whole-word vector and vectors for its character n-grams, , where holds the n-grams of length 3 to 6 of the word wrapped in boundary markers. It trains these vectors with the skip-gram objective and builds vectors for unseen words from their n-grams.
In this topic
- 1Character N-gram Decomposition
- 2Out-of-Vocabulary Handling
- 3Hashing Trick for Memory Efficiency
Character N-gram Decomposition
FastText represents each word as the set of its character n-grams (typically ) plus the whole word itself. Special boundary markers < and > are added to distinguish prefixes and suffixes from internal substrings. The word embedding is the sum of the whole-word vector and all its n-gram vectors: , where is the set of n-grams and is the word-level vector.
FastText represents a word as , where holds every character n-gram of length 3 to 6 of the word wrapped in boundary markers. A word of characters becomes a string of symbols, which contains n-grams of length when that number is positive. For "where", , giving 5 trigrams, 4 four-grams, 3 five-grams, and 2 six-grams: 14 in total, including <wh, here, and where>. Longer words get many more n-grams, and "internationalization" has 74, so their vectors are dominated by subword information rather than by the whole-word vector.
Decompose the word "where" into character n-grams with n=3, using boundary markers < and >.
Out-of-Vocabulary Handling
When encountering a word not in the training vocabulary, FastText computes its embedding by summing the vectors of its character n-grams (falling back to any n-grams that were seen during training). Even novel compound words, misspellings, and domain-specific terms get reasonable representations because they share substrings with known words. The embedding for an OOV word is (no word-level vector since the word was not seen).
OOV words get embeddings by summing their character -gram vectors: . A never-seen word like 'unhappiest' decomposes into subwords that overlap with 'unhappy', 'happiest', etc. The embedding quality degrades gracefully with word rarity instead of collapsing to a single [UNK] vector. This is critical for morphologically rich languages like Finnish and Turkish.
The word "unforgettable" is not in the training vocabulary. How does FastText construct its embedding if the n-grams <unf, unf, nfo, for, org, rge, get, ett, tta, tab, abl, ble, le> were all seen?
Hashing Trick for Memory Efficiency
Character n-grams of lengths 3 to 6 across a large vocabulary produce millions of distinct strings, and storing a separate vector for each would make memory grow without bound. FastText instead hashes every n-gram into one of a fixed number of buckets, 2 million by default, and all n-grams that land in the same bucket share one vector. Memory becomes 2 million rows of 300 float32 values, 2.4 GB, however many n-grams exist. The price is collisions, where unrelated n-grams are forced to share parameters. Training absorbs most of this, because each word sums many n-gram vectors, and a collision affects only one of them.
Each n-gram is mapped to a bucket , and the n-gram table is regardless of how many distinct n-grams exist. If distinct n-grams are hashed uniformly, the expected number of occupied buckets is . With : 1 million n-grams occupy about 787,000 buckets (1.27 n-grams per occupied bucket), and 10 million occupy almost all 2 million (about 5 per bucket). Collisions therefore become common at scale, but each word sums many n-gram vectors plus its own word vector, so one shared bucket perturbs the result only slightly.
A vocabulary has 500,000 words, each producing ~20 n-grams. Without hashing, how many n-gram vectors would be needed? With 2M hash buckets?
Theory Exercise
Problem:
Explain why FastText embeddings are particularly valuable for morphologically rich languages like Turkish or Finnish, where a single root word can have hundreds of inflected forms.
Hints:
- Think about how many surface forms a Turkish verb can have
Coding Exercise
Problem:
Implement a function that decomposes a word into character n-grams with boundary markers, then constructs a FastText-style embedding by summing n-gram vectors from a random embedding table.
Hints:
- Add '<' and '>' as boundary markers
After training a set of word vectors, how do you know whether they are any good? The training loss only says how well the model predicts contexts, not whether the vectors help a sentiment classifier or a named-entity tagger. Different window sizes, dimensions, and corpora produce different vectors, and evaluating each choice by retraining a full downstream system is slow. We need tests that are fast enough for model selection and still say something about usefulness.
The previous topic, FastText, added character n-grams so every word gets a vector; this topic asks how to compare such vectors. It begins with word analogies, the "king minus man plus woman" test, and how the answer is found with vector arithmetic and cosine search. Cosine similarity and other distance metrics follow, with the reasons cosine is the default. The topic then separates intrinsic evaluation, which probes the vector space directly, from extrinsic evaluation on real tasks, and explains why they can disagree. It closes with word similarity benchmarks such as WordSim-353 and SimLex-999, scored by Spearman correlation with human ratings.
Definition
Embedding evaluation measures how well word vectors capture meaning. Intrinsic evaluation tests the vector space directly, through analogy accuracy and Spearman correlation between cosine similarities and human similarity ratings. Extrinsic evaluation measures the accuracy of a downstream system, such as a tagger or classifier, that uses the vectors as input features.
In this topic
- 1Word Analogy Tasks
- 2Cosine Similarity and Distance Metrics
- 3Intrinsic vs. Extrinsic Evaluation
- 4Word Similarity Benchmarks
Word Analogy Tasks
The analogy task tests whether embedding arithmetic captures semantic relationships. Given "a is to b as c is to ?", the answer should be , excluding , , and from candidates. The Google Analogy Test Set contains ~19,500 questions across syntactic ("walk" : "walked" :: "swim" : ?) and semantic ("Paris" : "France" :: "Tokyo" : ?) categories. Accuracy on this benchmark ranges from 30% (early models) to 75%+ (well-tuned Word2Vec/GloVe).
The analogy test answers "a is to b as c is to ?" with . Excluding the three query words matters: for king minus man plus woman in 100-dimensional GloVe, the nearest vector is "king" itself at 0.855, ahead of "queen" at 0.783. Mikolov's Google analogy set has 19,544 questions split into semantic and syntactic subsets. In the GloVe paper's Table 2, 300-dimensional GloVe trained on 42 billion tokens scores 75.0 percent overall, while skip-gram and CBOW trained on 6 billion tokens score 69.1 and 65.7 percent.
Solve the analogy: "man" : "woman" :: "uncle" : ?
Given: . Candidate embeddings: aunt=[0.01, 0.82, 0.29], nephew=[-0.45, 0.11, 0.67], niece=[-0.22, 0.71, 0.41].
Cosine Similarity and Distance Metrics
Cosine similarity, as in the formula, divides the dot product of two vectors by the product of their norms, so it measures the angle between them and ignores length. That suits embeddings because vector norms vary with word frequency and training dynamics, while meaning is mostly carried by direction. Values range from -1 to 1. In practice, related words score well above unrelated ones, but negative values do not mark antonyms: antonyms share contexts, so "hot" and "cold" have a GloVe cosine of 0.73. Euclidean distance mixes direction and length, and the raw dot product rewards long vectors. After normalizing vectors to unit length, all three give the same ranking.
Cosine similarity is preferred over Euclidean distance for word embeddings because it is scale-invariant. Two vectors with the same direction but different magnitudes have but large Euclidean distance. Since embedding magnitude correlates with word frequency (frequent words have larger norms), cosine similarity focuses on semantic direction rather than frequency effects.
Compute the cosine similarity between and , and between and .
Intrinsic vs. Extrinsic Evaluation
Intrinsic evaluation probes the vector space itself: analogy accuracy on the Google and MSR sets, Spearman correlation with human similarity ratings, or how well categories cluster. These tests are cheap and help diagnose what a space encodes. Extrinsic evaluation plugs the vectors into a downstream system, such as named-entity recognition, sentiment analysis, or parsing, and measures task accuracy. That is the score that matters, but it is slow and mixes embedding quality with the architecture and tuning of the downstream model. The two often disagree. Schnabel et al. found that intrinsic rankings of embeddings did not consistently predict extrinsic rankings, so choose by the target task whenever possible.
Intrinsic evaluation measures embedding quality directly (analogy, similarity). Extrinsic evaluation measures performance on a downstream task (NER, sentiment). A common finding: intrinsic scores do not perfectly predict extrinsic performance. Embeddings that ace analogies may underperform on NER if the downstream task requires syntactic features that analogy tests do not measure. Both evaluation types are needed for a complete picture.
Embedding A scores 80% on analogy tests but 71% on NER. Embedding B scores 65% on analogies but 74% on NER. Which is better?
Word Similarity Benchmarks
Similarity benchmarks pair words with human ratings, such as 0 to 10, and score an embedding by the Spearman rank correlation between its cosine similarities and those ratings. Spearman compares rankings, not raw values, so it ignores any monotonic rescaling of cosines. WordSim-353 mixes similarity with relatedness, MEN has 3,000 pairs, and SimLex-999 rates genuine similarity only, so "coast" and "shore" score high while related but different words score lower. Embeddings trained on context windows tend to capture relatedness, which makes SimLex-999 hard: its authors reported a best model correlation of 0.414 against inter-annotator agreement of 0.67, so the human ceiling is well below 1.
Spearman's compares the rank orders of model cosines and human ratings, where is the rank difference for pair ; means identical rankings. On SimLex-999, Hill et al. report a best score of 0.414, from Mikolov et al.'s neural model, with other models ranging down to 0.098, while the average pairwise agreement between human annotators is 0.67. That human figure is a practical ceiling. On relatedness-heavy sets such as WordSim-353, the same models score much higher, because context-window training captures association as well as similarity.
Embedding cosine similarities: (tiger, cat) = 0.72, (book, paper) = 0.68, (computer, keyboard) = 0.64. Human similarity ratings (0-10): (tiger, cat) = 7.35, (book, paper) = 7.46, (computer, keyboard) = 7.62. Compute the Spearman correlation.
Theory Exercise
Problem:
A new word embedding method achieves state-of-the-art on WordSim-353 (Spearman ) and Google Analogy Test (accuracy 78%). However, it performs 2% worse than GloVe on downstream sentiment analysis. Analyze the possible reasons and suggest an evaluation strategy.
Hints:
- Think about what similarity benchmarks measure vs. what sentiment analysis needs
Coding Exercise
Problem:
Implement a word analogy solver that takes embedding vectors and evaluates accuracy on a set of analogy questions. Include the exclusion rule (the answer cannot be any of the query words).
Hints:
- Use cosine similarity for nearest neighbor search
Related Problems on PixelBank
FastText gives every word a vector built from character n-grams, but its n-grams are fixed by length, not chosen by usefulness, and the word itself is still the unit a model reads. Modern language models need something stricter: a finite vocabulary of a few tens of thousands of entries that can encode any string, including names, code, emoji, and every language, without an unknown token. Which pieces should that vocabulary contain?
The previous topic, Embedding Evaluation, measured how good word vectors are; this topic covers the learned subword units that replaced words as the input to modern models. It begins with Byte Pair Encoding, which repeatedly merges the most frequent adjacent pair of symbols. SentencePiece follows, a language-independent toolkit that works on raw text, marks spaces with a special symbol, and supports both BPE and a unigram language model. The topic then examines how far subword pieces track morphology, using real GPT-2 and BERT splits that are sometimes morphemes and sometimes not. It closes with vocabulary size, the trade-off between embedding-table size and sequence length.
Definition
Subword tokenization segments text into units from a learned vocabulary of frequent character or byte sequences, so common words remain whole and rare words split into known pieces. BPE learns the vocabulary by greedy pair merges, while the unigram language model prunes a large candidate set by likelihood. Each unit receives its own embedding vector.
In this topic
- 1Byte Pair Encoding (BPE)
- 2SentencePiece
- 3Morphological Awareness
- 4Vocabulary Size Trade-offs
Byte Pair Encoding (BPE)
BPE starts with a character-level vocabulary and iteratively merges the most frequent adjacent pair of tokens. After merges, you have a vocabulary of size . The merge rules are learned from a training corpus and applied deterministically at inference time. BPE captures common subwords: after merging, a vocabulary might contain tokens like "un", "ing", "tion", "##able" alongside full words like "the" and "and". The algorithm is greedy --- it always merges the globally most frequent pair, which is simple but effective.
BPE starts with byte tokens and iteratively merges the most frequent adjacent pair. After merges: . Each merge reduces total token count by replacing 2 tokens with 1, so the corpus of characters becomes tokens. The merge table defines a deterministic encoding: given the ordered merges, any new string can be tokenized by applying them in sequence.
Apply 3 steps of BPE to the vocabulary: {"l o w": 5, "l o w e r": 2, "n e w": 6, "n e w e r": 3}. Frequencies shown after each word.
SentencePiece
SentencePiece (Kudo & Richardson, 2018) is a language-agnostic tokenizer that works directly on raw text without pre-tokenization (no need for language-specific word splitting). It treats the input as a sequence of Unicode characters (or bytes) and can apply either BPE or Unigram language model tokenization. The Unigram model starts with a large vocabulary and iteratively removes tokens whose removal causes the smallest increase in corpus likelihood. SentencePiece handles whitespace as a special character (\u2581), enabling it to reconstruct the original text from tokens without ambiguity.
SentencePiece treats the input as a raw byte stream (no pre-tokenization) and learns subword units using either BPE or unigram language model. The unigram model defines over subword pieces and uses the EM algorithm to find the vocabulary that maximizes over the corpus. This probabilistic approach can prune vocabulary more principally than greedy BPE.
SentencePiece tokenizes "I loved New York" as ["\u2581I", "\u2581love", "d", "\u2581New", "\u2581York"]. Why is the space character included as \u2581?
Morphological Awareness
Subword vocabularies are learned from frequency, not from linguistic rules, so frequent affixes such as "un", "able", and "ful" often become tokens of their own. When "un" consistently starts words whose meaning is negated, its embedding can carry part of that signal, and a model can compose pieces for words it rarely saw whole. The alignment with real morphemes is partial, though. GPT-2 splits "unbreakable" into un, break, and able, a clean morphological parse, but "unhappiness" into un, h, and appiness, and BERT gives un, ##ha, ##pp, and ##iness. Studies of morphologically rich languages report that unigram tokenizers tend to align better with morphemes than BPE does.
A BPE merge is chosen purely by pair frequency, so an affix becomes a token when it is frequent across many different words, not because it is a morpheme. Real splits show both outcomes: GPT-2 tokenizes "unbreakable" as un, break, and able, matching the morphology, but "unhappiness" as un, h, and appiness, cutting the root. For agglutinative languages such as Turkish, where "evlerinizden" means "from your houses" and is built as ev, ler, iniz, and den, frequency-driven merges recover some of these boundaries and miss others, which is why morphology-aware and unigram tokenizers are studied for such languages.
GPT-2's BPE tokenizer splits "unhelpful" into ["un", "help", "ful"] and "unbreakable" into ["un", "break", "able"]. How does this help the model understand the meaning of "un-", and where does it break down?
Vocabulary Size Trade-offs
Vocabulary size is a critical hyperparameter for subword tokenizers. A small vocabulary (e.g., 8,000) splits most words into many subwords, increasing sequence length and computational cost but reducing the embedding table size. A large vocabulary (e.g., 128,000) keeps more words intact, shortening sequences but requiring a larger embedding matrix. The optimal size depends on the language, domain, and model architecture. Multilingual models (mBERT, XLM-R) need larger vocabularies to cover multiple writing systems. GPT-2 uses ~50,257 tokens; Llama uses 32,000; GPT-4 uses ~100,000.
Vocabulary size trades embedding parameters, , against sequence length , and self-attention cost grows as . Byte-level models need only 256 symbols but produce sequences several times longer than subword models. Larger vocabularies shorten sequences: GPT-2 uses 50,257 tokens, Llama 2 uses 32,000, and GPT-4's cl100k encoding about 100,000. Very large vocabularies leave many tokens rare, so their embeddings receive few updates. Typical English text averages around 4 characters per token for GPT-style tokenizers, and multilingual models use larger vocabularies so that non-Latin scripts are not split into many short pieces.
A sentence has 10 words. With a vocabulary of 8K tokens, BPE splits it into 25 tokens. With 50K tokens, it becomes 12 tokens. What are the trade-offs?
Theory Exercise
Problem:
Compare BPE, WordPiece, and Unigram tokenization methods. For each, describe the core algorithm, how the vocabulary is built, and one advantage over the others.
Hints:
- BPE merges the most frequent pair bottom-up
Coding Exercise
Problem:
Implement a basic BPE tokenizer that learns merge rules from a corpus, then uses those rules to tokenize new text. Show that unseen words are segmented into known subword units.
Hints:
- Start with character-level tokens plus end-of-word marker