All courses

Geometry of learned embeddings

Explain why tokens used in similar contexts end up with similar vectors. Explain how directions such as gender or plurality can be roughly linear (king − man + woman ≈ queen).

Builds on: Token embeddings as a lookup table, Count-based n-grams and the need for generalization

▶ Watch this lesson Start the whole course

What the animation says

Nobody labeled it

Training a language model asks exactly one thing: predict the next token. Nobody tells it that cat and dog are similar, or what gender is. Yet look at the embedding table after training. Cat's row and dog's row sit close together. And king, minus man, plus woman, lands near queen. Two puzzles: why does similarity appear at all, and why does gender become a straight direction?

Similar contexts, similar pushes

A row of the embedding table changes only on steps where its token appears. Each time, training nudges it toward better predictions in that context. Cat and dog appear in nearly the same places: feed the blank, the blank was asleep. So they get nearly the same nudges and drift close together. The vector becomes a summary of where the token tends to appear. Now: training sees 'the dog was asleep' often, 'the cat was asleep' rarely. What about cat?

Subtracting cancels the offset

It carries over: cat sits near dog, so it predicts alike. Count-based n-grams can't do that. Now gender. Take a model with no layers. Each token has an input vector e, each context token an output vector u. Training pushes e dot u toward the log-probability that the context token appears nearby, plus an offset for that context token. Subtract two words' vectors. The offset is the same for both, so it cancels. Left over: the difference, dotted with u, equals the log of a probability ratio.

Checking the ratios

Made-up numbers. Context word she: queen point one, king point zero zero five. Ratio twenty. Woman point one two, man point zero zero six. Also twenty. Both logs are about three. Context word his: both ratios are one tenth, log about minus two point three. Context word crown: queen and king equal, woman and man equal. Tap the context word where both differences have dot product zero.

One offset, then search

Both differences agree on all three. If ratios match for every context word, they agree on every u. There are far more u vectors than dimensions. Assume they span the space: then agreeing with all of them means equal. So queen minus king about equals woman minus man: one gender offset. Test it with toy three-d vectors. Query: king minus man plus woman. Compare by cosine similarity, skipping the input words. Queen scores point nine nine nine. One catch. Without that skip, what often wins in real embeddings?

What to remember

Often king itself: the gender offset is small next to the word vectors, so excluding inputs is standard. So, embeddings are summaries of contexts. Tokens in similar contexts get similar nudges and end up close together. If a property like gender or plurality shifts every context's log-probability by the same amount, whatever the base word, it becomes a shared offset. That offset is only roughly linear, because real ratios only roughly match.

Who told the model that cat ≈ dog?

Training only ever asks one thing: predict the next token. Nobody labels "cat" and "dog" as similar or defines gender. Yet after training, write $e_w$ for token $w$'s row of $W_E$. Then $e_{cat}$ and $e_{dog}$ sit close together, and $e_{king} - e_{man} + e_{woman}$ lands near $e_{queen}$. Why does pure next-token prediction produce this geometry? And why should a concept like gender become a roughly straight **direction**?

Similar contexts give similar pushes

When $W_E$ is used only as the input lookup, a token's row is updated only on training steps where that token appears. Each time, training nudges it in whatever direction improves predictions in **that context**. "Cat" and "dog" appear in nearly the same contexts ("feed the __", "the __ was asleep"). So they receive nearly the same nudges and drift to nearby spots. The vector becomes a compressed summary of *where the token tends to appear*. Nearby vectors give similar predictions, so what the model learns about "dog" partly carries over to "cat". That is the generalization count-based n-grams lack.

Why differences become directions

Take a simplified model with no layers. Token $w$ has vector $e_w$ (its row of $W_E$). Each context token $c$ has an output vector $u_c\in\mathbb{R}^d$. Training drives $e_w\cdot u_c \approx \log P(c\mid w) + b_c$, where $P(c\mid w)$ is how likely $c$ appears near $w$. The offset $b_c$ depends only on $c$, so subtracting two tokens cancels it: $$ (e_a - e_b)\cdot u_c \approx \log\frac{P(c\mid a)}{P(c\mid b)} $$ Suppose queen/king and woman/man have the same ratios for **every** $c$. Then the two differences have the same dot product with every $u_c$. There are $V$ of these vectors, far more than $d$. Assume they span $\mathbb{R}^d$. Then $e_{queen}-e_{king}\approx e_{woman}-e_{man}$.

Checking the ratios with numbers

Made-up values of $P(c\mid w)$, how likely context token $c$ appears near $w$: - $c$ = "she": queen 0.10, king 0.005 → ratio 20; woman 0.12, man 0.006 → 20. Both logs ≈ 3.0. - $c$ = "his": queen 0.004, king 0.04 → 0.1; woman 0.005, man 0.05 → 0.1. Both logs ≈ −2.3. - $c$ = "crown": queen 0.02, king 0.02; woman 0.001, man 0.001. Both ratios 1, logs = 0. The two differences agree on these three $u_c$. If the ratios match for all $c$, the differences are about the same vector: the gender offset.

Analogy search with cosine similarity

Toy 3-d embeddings. The query vector is compared to every candidate by cosine similarity, which measures how close two vectors are in direction. Excluding the input words is standard practice. In real embeddings the offset is small compared with the word vectors, so the query often stays closest to "king" itself.
import numpy as np
E = {'king':[3,1,0.2], 'queen':[3,3,0.1], 'man':[1,1,0],
     'woman':[1,3.1,0.1], 'prince':[2.5,0.9,0.4], 'apple':[0,0.5,3]}
E = {w: np.array(v, float) for w, v in E.items()}
q = E['king'] - E['man'] + E['woman']          # [3, 3.1, 0.3]
cos = lambda a, b: a @ b / np.linalg.norm(a) / np.linalg.norm(b)
cands = [w for w in E if w not in ('king', 'man', 'woman')]
print({w: round(float(cos(q, E[w])), 3) for w in cands})
# {'queen': 0.999, 'prince': 0.896, 'apple': 0.186}
print(max(cands, key=lambda w: cos(q, E[w])))  # queen

What to remember

Embeddings are summaries of contexts. Tokens that appear in similar contexts receive similar training nudges and end up close together. Suppose a property such as gender or plurality shifts the log-probability of each context token by the same amount, whichever base word it is applied to. Then it shows up as a shared offset vector. That offset is a **roughly** linear direction: rough because the ratios only approximately match.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.