Embeddings
About this lesson
A network can only do arithmetic, so words (and other things such as products or users) must become numbers. An ID or a one-hot vector says nothing about meaning: every pair is equally far apart. An embedding gives each item a short list of learned numbers, one row in a table, so that similar items end up close together. Look up a word's row, plot it as a point, measure closeness with cosine similarity, and watch three real gradient steps pull kitten next to cat.
Words become ID numbers
A network only does arithmetic, so each word in its vocabulary (the list of words it knows) gets an ID: cat 0, kitten 1, dog 2, car 3, truck 4. An ID is only a name tag: dog, 2, is not "between" kitten and car.
vocabulary ids = {w: i for i, w in enumerate(words)}
"cat" -> 0
"kitten" -> 1
"dog" -> 2
"car" -> 3
"truck" -> 4
the numbers are arbitrary: sorting the list differently
would give every word a different IDRead the lesson step by step
Words become ID numbers
A network only does arithmetic, so each word in its vocabulary (the list of words it knows) gets an ID: cat 0, kitten 1, dog 2, car 3, truck 4. An ID is only a name tag: dog, 2, is not "between" kitten and car.
vocabulary ids = {w: i for i, w in enumerate(words)} "cat" -> 0 "kitten" -> 1 "dog" -> 2 "car" -> 3 "truck" -> 4 the numbers are arbitrary: sorting the list differently would give every word a different IDOne-hot: all equally far
To feed an ID in, write it as a one-hot vector: five slots, all 0 except a 1 at the ID, so cat is [1,0,0,0,0]. Any two one-hot vectors are equally far apart (√2): cat looks no more like kitten than like truck.
cat 1 0 0 0 0 kitten 0 1 0 0 0 dog 0 0 1 0 0 car 0 0 0 1 0 truck 0 0 0 0 1 distance between any two: √2 = 1.41 dot product of any two: 0 (nothing in common) and a 50,000-word vocabulary needs 50,000 slotsAn embedding table
An embedding gives each word a short list of numbers instead: one row per word in a table, E. Ours has 2 numbers per word so we can draw them; real models use hundreds or thousands. The numbers are weights the network learns.
E (5 words x 2 numbers) row 0 cat 0.80 0.60 row 1 kitten -0.60 -0.50 row 2 dog 0.60 0.80 row 3 car 0.60 -0.80 row 4 truck 0.80 -0.60 in PyTorch: nn.Embedding(5, 2), a learnable tableLookup: pick one row
Turning cat into its vector is a lookup: take row 0 of the table, (0.80, 0.60). It is the same as multiplying cat's one-hot vector by the table: the single 1 picks out one row and every 0 wipes out the rest.
v = E[ids["cat"]] -> [0.8 0.6] one_hot = [1 0 0 0 0] one_hot @ E -> [0.8 0.6] = 1*row0 + 0*row1 + 0*row2 + 0*row3 + 0*row4 a lookup is a matrix multiply, done the cheap wayVectors are points
Two numbers make a point: the first goes across, the second goes up. Cat lands at (0.80, 0.60), right beside dog at (0.60, 0.80); car and truck land together lower down. Kitten is not trained yet, so it sits at a random spot.
word across up cat 0.80 0.60 kitten -0.60 -0.50 (random start) dog 0.60 0.80 car 0.60 -0.80 truck 0.80 -0.60 real models: hundreds of numbers, so no flat map; the idea of "near" is exactly the sameClose means similar
We measure closeness with cosine similarity: the cosine of the angle between two arrows from the centre. Same direction gives 1, a right angle 0, opposite −1. Cat and dog score 0.96, cat and truck 0.28, cat and car 0.00.
cos(u, v) = u @ v / (|u| |v|) cat, dog 0.8*0.6 + 0.6*0.8 = 0.96 cat, truck 0.8*0.8 + 0.6*(-0.6) = 0.28 cat, car 0.8*0.6 + 0.6*(-0.8) = 0.00 (every vector here has length 1, so cos = dot)Training nudges kitten
Kitten starts pointing away from cat (cosine −1.00). In the training text, kitten keeps appearing where cat fits ("the ___ purrs"), so each gradient step adds a bit of cat: g = 1 − σ(kitten · cat), then kitten += g × cat.
g = 1 - sigmoid(E[k] @ E[c]); E[k] += lr * g * E[c] start kitten (−0.60, −0.50) step 1 kitten.cat −0.78 g 0.69 -> (−0.05, −0.09) step 2 kitten.cat −0.09 g 0.52 -> (0.37, 0.23) step 3 kitten.cat 0.43 g 0.39 -> (0.68, 0.46) sigmoid(x) = 1 / (1 + e^-x), lr = 1, cat held stillMeaning from company
After 3 steps kitten sits at (0.68, 0.46), cosine 0.999 with cat. Nobody told the network what a kitten is: words used in similar sentences get pushed to similar vectors. "You shall know a word by the company it keeps" (J. R. Firth, 1957).
kitten (0.68, 0.46) cos with cat 0.999 cos with dog 0.945 cos with truck 0.326 nearest neighbour: cat. The same nearest-vector search powers "find similar" in search and recommendationsThe first layer of a network
In a real network the embedding table is the first layer: each token's ID picks a row, and that vector flows into the next layers. The original transformer uses 512 numbers per token; GPT-3 uses 12,288. Backpropagation trains the table with everything else.
token IDs -> embedding table -> vectors -> layers numbers per token (d_model) Transformer base (2017) 512 GPT-3 175B (2020) 12,288 the table gets gradients like any other weight
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01Why is a one-hot vector a poor way to tell a network that cat and kitten are related?
Any two different one-hot vectors are √2 apart and have dot product 0, so cat is exactly as far from kitten as from truck.
02The embedding table E has one row per word. What does one_hot @ E give for the word with ID 3?
The single 1 in slot 3 keeps row 3 and every 0 wipes out the other rows. That is why a lookup E[3] is the same as the matrix multiply, done the cheap way.
03Two vectors both have length 1: u = (0.8, 0.6) and v = (0.6, 0.8). What is their cosine similarity?
For length-1 vectors cosine similarity is just the dot product: 0.8 × 0.6 + 0.6 × 0.8 = 0.96, so they point almost the same way.
04In the training step g = 1 − sigmoid(kitten · cat), kitten += g × cat, what happens to g as kitten moves closer to cat?
As kitten · cat grows, sigmoid approaches 1 and g approaches 0. In the figure g goes 0.69, 0.52, 0.39: big nudges while kitten is far, small ones once it is close.
05Where does the embedding table sit in a language model such as a transformer?
The table is a learnable layer. The base transformer uses 512 numbers per token and GPT-3 uses 12,288.
Glossary
- Vocabulary
- The list of words (or tokens) a model knows; each gets an ID number.
- One-hot vector
- A vector of zeros with a single 1 at an item's ID. Every pair is equally far apart, so it carries no similarity.
- Embedding
- A short list of learned numbers (a vector) that stands for an item, such as a word, so that similar items get similar vectors.
- Embedding table
- A matrix with one row per item; looking up an item's row gives its embedding. Its numbers are weights the network learns.
- Cosine similarity
- u · v / (|u| |v|): the cosine of the angle between two vectors. 1 means the same direction, 0 a right angle, −1 opposite.
- Dimension
- How many numbers each embedding has: 2 in the figure, 300 in classic word2vec, 512 in the base transformer, 12,288 in GPT-3.
- Sigmoid
- σ(x) = 1 / (1 + e^−x), which squashes any number into 0 to 1; word2vec uses it to turn a dot product into a probability.
- Distributional hypothesis
- Words that appear in similar contexts tend to have similar meanings; it is why training on text gives useful embeddings.
Notes and sources
- Two numbers per word keep the picture flat. Real word vectors use 50 to 300 numbers (word2vec, GloVe), and language models use hundreds to thousands, so they cannot be drawn directly; "near" still means the same thing.
- The rows for cat, dog, car and truck were chosen by hand (all length 1, so the cosines are clean). Kitten's three training steps are computed exactly.
- Real word2vec keeps two tables (one for each word, one for its neighbours), updates both, and also pushes each word away from a few random "negative" words. Here only kitten moves, toward one neighbour, with learning rate 1.
- The Python program in the lesson is real: with NumPy installed it prints exactly the numbers in the figure.
- Jurafsky & Martin, Speech and Language Processing (3rd ed. draft), ch. 6: Vector Semantics and Embeddings
- Stanford CS224N: Natural Language Processing with Deep Learning (word vectors lectures and notes)
- Mikolov, Chen, Corrado & Dean, Efficient Estimation of Word Representations in Vector Space (2013)
- Mikolov et al., Distributed Representations of Words and Phrases and their Compositionality (2013)
- Bengio, Ducharme, Vincent & Jauvin, A Neural Probabilistic Language Model, JMLR 3 (2003)
- Goodfellow, Bengio & Courville, Deep Learning (2016), section 12.4: natural language processing and word embeddings
- Vaswani et al., Attention Is All You Need (2017), section 3.4: embeddings
- Brown et al., Language Models are Few-Shot Learners (2020), Table 2.1
- PyTorch documentation: torch.nn.Embedding
- NumPy documentation: numpy.eye
Quiz Unlocks after the last step.