Words as 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.
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.
The 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.
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.
Meaning as distance
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.
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.
How embeddings learn
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.
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).
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.
What happens
;; step 1/9 · ids
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 ID
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.