Word Embeddings

Dive into Deep Learning · §19.1

Word Embeddings
co-occurrence counts · skip-gram with negative sampling · shifted PMI · SVD and GloVe · evaluation · a language model’s table

One-Hot Vectors Make Every Pair of Words Orthogonal

The problem

  • A vocabulary of 17,997 entries: each word is a vector of length 17,997 with a single 1.
  • cos(doctor, physician) = cos(doctor, banana) = 0.
  • A language model’s token table: one-hot vector times the table = one row per token. Nothing in its training says which words are alike.

Which statistic of a text does a learned row record, and can we check it?

By the End of This Deck You Can

Goals

  • count co-occurrences and turn them into pointwise mutual information;
  • train skip-gram with negative sampling (SGNS) and explain its recipe;
  • state what SGNS converges to, and check it exactly on a toy corpus;
  • compute word vectors in closed form with an SVD;
  • compare word vectors fairly: coverage, intervals, paired differences;
  • say what a static vector cannot represent.

The idea: words in similar contexts get similar vectors. “You shall know a word by the company it keeps” (Firth, 1957).

Running example: the first 3 million words of WikiText-103 (Wikipedia), a vocabulary of the words that occur at least 10 times (17,997 entries), windows of 5, vectors of 100 dimensions, K = 5 noise words.

Word Vectors Open the Chapter’s First Movement

Where this fits

movement section
vectors Word Embeddings
Pretrained Encoders
Text Embeddings from Contrastive Training
finding Sparse, Dense and Approximate Retrieval
using what is found Retrieval-Augmented Generation
Failures and Fixes in RAG
  • Uses: the tied token table of a GPT; the truncated SVD.
  • Skips: CBOW, fastText, hierarchical softmax, vectors for many languages.

Raw Counts Measure Frequency; PMI Measures Association

Co-occurrence counts

X_{wo}: how often word o occurs within 5 positions of word w.

  • 6.5 million nonzero counts, 2% of the 324 million cells.
  • Largest counts: the–the 141,058, the–of 116,432, the–in 69,654.

\textrm{pmi}(w, o) = \log \frac{p(w, o)}{p(w)\, p(o)}

p(w, o): share of all pairs; p(w), p(o): its marginals. Positive when a pair occurs more often than independence predicts: pmi(the, of) = 0.36, pmi(the, the) = -0.27, pmi(prime, minister) = 6.55 from only 166 windows.

98% of the pairs never occur: their pmi is -\infty.

Human Ratings Judge Word Vectors; Random Vectors Reach 0.13

Human similarity ratings

set pairs rated by people for covered by the slice
WordSim353 relatedness and similarity: cup–coffee high 295 of 353
SimLex-999 similarity alone: clothes–closet low 865 of 999
  • \rho: Spearman correlation between the cosines of the pairs and the ratings; 95% interval from resampling the pairs.
  • Random vectors, 20 seeds: -0.10 to 0.13 and -0.05 to 0.04.

A method must clear this floor before its \rho means anything.

Finkelstein et al., 2002; Hill, Reichart and Korhonen, 2015

Negative Sampling Needs 6 Scores per Pair, Not 17,997

Skip-gram with negative sampling

Center vector \mathbf{v}_w (table \mathbf{V}), context vector \mathbf{u}_o (table \mathbf{U}), score \mathbf{u}_o^\top \mathbf{v}_w; noise words o_1, \ldots, o_K drawn from a noise distribution P; sigmoid \sigma(s) = 1/(1 + e^{-s}):

\ell(w, o) = -\log \sigma(\mathbf{u}_o^\top \mathbf{v}_w) - \sum_{k=1}^{K} \log \sigma(-\mathbf{u}_{o_k}^\top \mathbf{v}_w)

  • A GPT with no layers, predicting the neighbors of a word.
  • Softmax over the vocabulary: 17,997 scores per pair. Negative sampling: 1 + K = 6 binary scores, e.g. (steam, piston) with target 1, five noise words with target 0.

Two tables: with one, a word’s score with itself, \|\mathbf{v}_w\|^2, could never be negative, yet most words never occur near themselves.

Three Choices Decide Which Pairs the Loss Sees

The word2vec recipe

choice rule why
subsampling drop each occurrence with prob. \max(1 - \sqrt{t/f(w)}, 0), t = 10^{-4} pairs with the teach little, cost most
noise P(o) \propto n(o)^{0.75} rare words drawn more often than their frequency
window width b \sim \{1, \ldots, 5\} per center near words count more: distance d weighted (6 - d)/5

f(w): share of the text that is w; n(o): occurrences of o.

  • A slot is one scored pair. A minibatch row: 10 context slots, each with 5 noise slots, 60 in all.
  • Empty context slots and their noise slots are masked out of the loss.

The one to remember is the 0.75 power: it returns in the optimum.

Check: How Strong Are Subsampling and the 0.75 Power?

Check

A word makes up 1% of the text. With what probability is an occurrence kept? A word is 100 times more frequent than another. How much more often is it drawn as noise?

Answer. Kept with \sqrt{10^{-4}/10^{-2}} = 0.1. Drawn 100^{0.75} \approx 32 times as often, not 100. On the slice, subsampling leaves 1.4 of 2.8 million positions as centers.

Five Epochs Give Vectors That Correlate 0.56 with Human Ratings

Training

epoch 1: loss 0.4569, 3.4 s
epoch 2: loss 0.4091, 3.1 s
epoch 3: loss 0.3911, 3.1 s
epoch 4: loss 0.3813, 3.1 s
epoch 5: loss 0.3749, 3.1 s
16 s
    SGNS V: WordSim353 0.562 [0.478, 0.644]; SimLex-999 0.182 [0.114, 0.248]
  SGNS V+U: WordSim353 0.583 [0.494, 0.663]; SimLex-999 0.196 [0.129, 0.262]
  • Loss per slot (one scored pair, real or noise); it starts at \log 2 = 0.693.
  • \rho of \mathbf{V}: 0.56 (0.48 to 0.64) and 0.18; random vectors reach at most 0.13 and 0.04.
  • V+U, the sum of both tables: a little higher.
  • SimLex-999 is harder: windows record relatedness, not similarity.

I. With Free Scores, Each Pair Is Its Own Logistic Regression

The optimum

Assume every score s(w, o) can be chosen freely. Summed over the corpus, the pair (w, o) appears

  • as a positive X_{wo} times (its count);
  • as a noise pair K\, n_w\, P(o) times: each of the n_w = \sum_o X_{wo} pairs with center w draws K noise words, each equal to o with probability P(o).

One free score meeting a positives and b negatives:

-a \log \sigma(s) - b \log \sigma(-s) \;\Rightarrow\; -a(1 - \sigma(s)) + b\,\sigma(s) = 0 \;\Rightarrow\; s = \log \frac{a}{b}

The best score is the log of the ratio of positives to negatives.

II. At the Free-Score Optimum, SGNS Scores Are Shifted PMI

The optimum

With a = X_{wo}, b = K\, n_w\, P(o), and p the word frequencies:

\boxed{s^*(w, o) = \log \frac{X_{wo}}{K\, n_w\, P(o)} = \textrm{pmi}(w, o) - \log K + \log \frac{p(o)}{P(o)}}

  • Noise by frequency (P = p): the score matrix \mathbf{V}\mathbf{U}^\top factorizes \textrm{pmi} - \log K.
  • Power 0.75: rare context words get lower scores, against PMI’s bias toward rare pairs.

Only with free scores: 100 columns cannot hold every pmi, and no finite score reaches -\infty.

Levy and Goldberg, 2014; Levy, Goldberg and Dagan, 2015

A Four-Word Corpus Confirms the Optimum to 10⁻⁷

A toy corpus

Right: 40 tokens of four words, window 1, K = 5. L-BFGS matches \textrm{pmi} - \log K to 10^{-7}; the largest pmi, 0.75, is below \log 5, so every optimal score is negative.

The SVD of Positive PMI Is the Closed-Form Counterpart

Factorizing the counts

  • Positive PMI: \max(\textrm{pmi}, 0). Missing pairs stay 0, so the matrix stays sparse: 5.5 million positive entries.
  • Rank-100 truncated SVD, in seconds. Word vectors: left singular vectors scaled by \sqrt{\sigma_i}, with \sigma_i the singular values.
  • Eckart–Young: the best rank-k approximation, with residual \sqrt{\sum_{i > k} \sigma_i^2} (checked to rounding error).
WordSim353 SimLex-999
SGNS 0.56 0.18
SVD-PPMI 0.57 0.19

GloVe Fits Log Counts, but Only Where a Count Is Nonzero

GloVe

\sum_{X_{wo} > 0} h(X_{wo}) \big(\mathbf{u}_o^\top \mathbf{v}_w + b_w + c_o - \log X_{wo}\big)^2

  • h(x) = \min((x/100)^{0.75}, 1): frequent pairs count more, up to a cap.
  • Biases b_w, c_o absorb the log counts of w and o: the inner product is again close to a pmi, up to a constant.
  • The paper’s optimizer settings on our counts, untuned: \rho = 0.29 and 0.14.

A pair that never occurs never enters the loss: 98% of the pairs on this slice.

Trained SGNS Scores Follow Shifted PMI, r ≈ 0.9

Trained scores

Pearson r = 0.89 over 2000 pairs; mean score - target +0.01
  • The 2,000 most frequent pairs; dashed: the free-score optimum.
  • Counts as SGNS saw them: the subsampled stream, and drawn window widths, which average the fixed windows of width 1 to 5.
  • Tight below 0; among strongly associated pairs most scores fall short of the line and some overshoot it.

SGNS and SVD-PPMI Agree; GloVe Trails on WordSim353

Evaluation

  • Left: defaults, seed 0 with its interval, crosses for 3 seeds. Every interval clears the random floor.
  • Right: SGNS, \rho less its value at \alpha = 0.75; mean and range of 3 seeds.

Check: Is SGNS Better than SVD-PPMI?

Check

On WordSim353, SGNS scores 0.56 and SVD-PPMI 0.57 on the same 295 pairs. Unpaired intervals: 0.48 to 0.64 and 0.48 to 0.65. Is either better?

Answer. Score both on the same resampled pairs: the difference is -0.01, interval -0.08 to 0.05. No difference is detectable. Report “alike”, not an order.

PMI Factorizations Tie; the Large Gap Is GloVe’s Alone

Paired differences

comparison (WordSim353) \Delta\rho interval seeds
SGNS − SVD-PPMI −0.01 −0.08 to 0.05 −0.02 to −0.01
SGNS − GloVe 0.27 0.17 to 0.38 0.27 to 0.30
noise 0.75 − 0 0.03 0.003 to 0.07 0.01 to 0.04
noise 0.75 − 1 0.04 0.01 to 0.06 0.02 to 0.04
subsampling on − off 0.03 −0.02 to 0.08 −0.01 to 0.04
  • GloVe never sees the 98% of pairs that do not occur. It trails by about 0.3 on pairs of rarer words, 0.2 on frequent ones. Not the optimizer; more text narrows the gap.
  • SimLex-999: no difference between methods is detectable; for the noise exponent, uniform noise is slightly ahead, at the edge of detection.

SVD-PPMI: deterministic, seconds, as good as SGNS here. SGNS: keep the 0.75 power, which beat 1 in every seed on WordSim353 (not on SimLex-999).

Neighbors Describe the Corpus: On Wikipedia a Doctor Travels in Time

Nearest neighbors

word SGNS SVD-PPMI
doctor vincent, amy, torchwood, tardis, utterson scully, skinner, mulder, jackman, amy
stock enterprises, purchasing, financing, bankrupt, profits pictures, shops, paramount, share, goldwyn
bank ubs, winterthur, asset, swiss, banks ubs, winterthur, merger, suisse, banks
  • stock: finance for SGNS, film studios for SVD-PPMI; one row, two senses.

Physician is 977th of about 18,000 under SGNS: it occurs 38 times on the slice (doctor 205), and the slice’s doctors come from Doctor Who and The X-Files.

3CosAdd Finds Queen Only Because King Is Excluded

Analogies

a : b :: c : x answered by \arg\max_x \cos(\mathbf{x}, \mathbf{b} - \mathbf{a} + \mathbf{c}), on GloVe-6B, 100 dimensions:

man:woman :: king:?  excluded -> queen    not excluded -> king
paris:france :: tokyo:?  excluded -> japan    not excluded -> japan
bad:worst :: big:?  excluded -> biggest  not excluded -> biggest
walk:walked :: go:?  excluded -> went     not excluded -> went
do:did :: see:?  excluded -> saw      not excluded -> see
2 of 5 answers are a query word when the query words are not excluded

State whether the query words were excluded. Without it, the nearest word to \mathbf{b} - \mathbf{a} + \mathbf{c} is often c (Linzen, 2016).

Removing the He–She Direction Hides the Bias from One Probe

Bias

Projection of 20 professions on the unit vector along \mathbf{he} - \mathbf{she} in GloVe-6B, then that projection removed:

homemaker nurse captain manager
projection before −0.37 −0.28 0.21 0.28
top-10 neighbors kept 5 9 8 8
  • After the removal every projection is 0; the median profession keeps 9 of 10 neighbors.
  • The new neighbors’ original lean tracks the word’s: correlation about 0.9.

Bolukbasi et al., 2016; Gonen and Goldberg, 2019

A Language Model’s Table Groups Spellings, and Bank Stays One Point

Static vectors

Qwen3-0.6B, a language model, ties its output layer to its token table.

word nearest rows in Qwen3-0.6B’s table
doctor ’ doctors’, ’ Doctor’, ‘医生’, ‘Doctor’, ‘doctor’
bank ’ Bank’, ‘bank’, ‘Bank’, ‘银行’, ’_bank’
cosine SGNS (slice) GloVe-6B Qwen3 table
bank, river 0.53 0.33 0.24
bank, money 0.32 0.57 0.22
doctor, physician (rank) 0.44 (977th) 0.77 (1st) 0.65 (6th)

One row per word: the corpus decides where bank sits between its two senses.

Check: How Much of Qwen3-0.6B Is Its Token Table?

Check

Qwen3-0.6B: 151,936 tokens of width 1,024, 596,049,920 parameters, output layer tied to the table. What share is the table? How many numbers does a file hold that stores the table for input and output separately?

Answer. 151{,}936 \times 1{,}024 = 155{,}582{,}464, or 26.1%. The file holds 596{,}049{,}920 + 155{,}582{,}464 = 751{,}632{,}384.

A Word Vector Is a Factorization of Co-occurrence Counts

Recap

  • Counts: 6.5 million nonzero, 2% of the matrix. PMI separates association from frequency.
  • SGNS: 1 + K binary decisions per pair. Its free-score optimum is \textrm{pmi} - \log K plus a noise offset: exact to 10^{-7} on a toy corpus, r \approx 0.9 on the slice.
  • SVD-PPMI matches SGNS (0.57 and 0.56 on WordSim353). GloVe trails by about 0.3 there; its loss never sees the 98% of pairs that do not occur.
  • Analogies need the query words excluded; removing a direction hides a bias from one probe.
  • Synonyms need text: physician is the nearest row to doctor in GloVe-6B and 977th on the slice.
  • One point per word, in a word2vec table and in Qwen3-0.6B’s, a quarter of that model.

Next: an encoder that gives each token a vector computed from its sentence.