2.2Embeddings & semantic space
How a token id becomes a vector, why similar meanings end up close together, and how directions in that space can encode relations like gender, tense and capital-of.
From ids to meaning
The previous lesson ended with text turned into token idsToken idThe integer a tokenizer assigns to each token in its vocabulary. The model only ever sees these ids, never the underlying letters.: integers like 464 or 3797. Those numbers are just positions in a list. Token 464 is not “bigger” than token 463 in any meaningful way, and nothing about the integers says that cat and kitten are related while cat and carburetor are not.
A neural network needs inputs where geometry means something: where nearby inputs should produce similar outputs. So the first layer of every language model replaces each id with a vectorVectorAn ordered list of numbers. It can be read as an arrow in space or as a point with coordinates., a list of a few hundred to a few thousand real numbers. That vector is the token’s embeddingEmbeddingA learned vector representing a token, word, image or document, arranged so that similar meanings get nearby vectors., and the space it lives in is often called semantic space or embedding space.
The mechanism is almost embarrassingly simple. The model holds an embedding matrixEmbedding matrixA learned table with one row per vocabulary entry. Looking up a token id returns that row: the token's embedding vector. with one row per vocabulary entry. To embed token 464, you read row 464. That’s it. There is no formula that computes the vector from the spelling of the word; each row is a free parameterParameter (weight)A number inside a model that is adjusted during training. Modern LLMs have billions to trillions of them., initialized randomly and then adjusted by gradient descentGradient descentRepeatedly nudging the parameters a small step opposite the gradient, so the loss goes downhill. along with everything else in the model.
Imagine pinning every person in a city onto a big map, but you aren’t allowed to ask anyone where they live. All you know is who hangs out with whom. You start with random pins, then repeatedly nudge people who are often seen together closer, and people who never meet further apart. After enough nudges, the map shows neighborhoods: the climbers cluster, the chess players cluster, the parents from one school cluster.
Each person is a token and their pin is the embedding. “Who hangs out with whom” is the context words appear in. The nudging is training. And just as the map ends up with meaningful directions (north is the university, east is the harbor), embedding spaces end up with directions that mean things, like “more royal” or “past tense”.
You shall know a word by the company it keeps
Why would random vectors organize themselves by meaning? Because of the distributional hypothesis, popularized by the linguist J. R. Firth in 1957: words that appear in similar contexts tend to have similar meanings. Cat and kitten show up next to purr, fur, litter and vet. Paris and Tokyo both follow flew to and precede is the capital of.
When a model is trained to predict words from their neighbors (or the next token from the previous ones), any two tokens that behave interchangeably in text receive similar gradient updates. Their rows in the embedding matrix get pushed in similar directions, so they end up near each other. Nobody tells the model that cats are animals. The geometry is a side effect of prediction.
This was made famous by word2vec (Mikolov and colleagues at Google, 2013), which trained small networks specifically to produce word embeddings, and by GloVe (Stanford, 2014), which built them from co-occurrence counts. Modern LLMs learn their embedding matrix as just one part of the whole model, but the same principle drives it.
Measuring closeness: cosine similarity
How do we decide that two vectors are “close”? The standard measure is cosine similarityCosine similarityThe dot product of two vectors divided by the product of their lengths: the cosine of the angle between them, from −1 to 1.: the cosine of the angle between them, computed with the dot productDot productMultiply two vectors element by element and add up the results. It is large when the vectors point in similar directions.. It is 1 when two vectors point the same way, 0 when they are perpendicular, and −1 when they point in opposite directions. It ignores length and only looks at direction, which is useful because vector length often tracks things like word frequency rather than meaning.
Now explore a toy semantic space. Before you do, a big honesty warning: this is not a real embedding. Real models use hundreds to thousands of dimensions, learned from data. Here are 60 words placed by hand in 3D so you can actually see them, designed to mimic the patterns researchers found in real embeddings.
Drag to orbit · scroll to zoom · Hover or tap a word to see its nearest neighbors (lines). The dashed line from the origin shows the word's direction: cosine similarity compares directions.
- woman0.964
- king0.961
- man0.916
- girl0.872
- boy0.830
Ochre arrow: B → A (the relation). Vermilion arrow: the same relation added to C. The input words are excluded from the answer, as is standard.
Things to try:
- Hover over
tiger. Its neighbors arecat,lionandkitten: the big-cat corner of the animal cluster. Then trywolf, whose nearest neighbor isdog. - Look at the number cluster.
one,two,three… lie along a line, sofour’s nearest neighbors arethreeandfive. Embeddings often contain this kind of ordered structure for numbers, months and sizes. - Run the analogy presets. king − man + woman lands almost exactly on
queen. Paris − France + Japan lands onTokyo. Rotate the view until the ochre and vermilion arrows look parallel: the “capital of” relation is the same direction everywhere. - Try a nonsense analogy, such as banana − red + Tokyo. The arithmetic always produces some vector, and something is always nearest. That doesn’t mean the answer is meaningful.
Directions that mean things
The analogy trick is the most famous property of embeddings. In real word2vec vectors, the offset from man to woman is roughly the same as the offset from king to queen, from uncle to aunt, and from actor to actress. The offset from France to Paris resembles the one from Italy to Rome. Tense, plurality and comparative forms (big → bigger) show similar regularities. This is called vector arithmeticWord analogy (vector arithmetic)The observation that in good embedding spaces relations become directions, so king − man + woman lands near queen. on words.
Why should that happen? If queen is used like king in every way except in contexts that also vary between man and woman (pronouns, her/his, mother/father), then the difference between their embeddings mostly captures that one varying factor. Consistent factors of variation become consistent directions. Our toy space was built exactly this way: we chose one “female” direction, one “royal” direction, one “young” direction, one “capital-of” direction and one “past tense” direction, and composed the words from them.
The same geometry absorbs whatever patterns are in the data, including ugly ones. In 2016 Bolukbasi and colleagues showed that word2vec trained on news text completed man : computer programmer :: woman : ? with homemaker. Embeddings faithfully reflect the statistics of the text they are trained on, stereotypes included. The bias and alignment lesson returns to this.
Embeddings inside an LLM
In a language model, the embedding lookup is step one of the forward pass. A few facts make it concrete:
- Dimensions. GPT-2 small uses 768 numbers per token, GPT-3’s largest model 12,288, and Llama 3 8B uses 4,096. Each dimension is not a human-readable feature like “royalty”. Meaning is spread across many dimensions at once, and the axes themselves are arbitrary.
- Size. The embedding matrix has (vocabulary size) × (dimension) entries. For Llama 3 8B that is 128,256 × 4,096 ≈ 525 million parameters, a noticeable slice of the model.
- Input and output. At the end of the network, the model scores every vocabulary entry to predict the next token. Many models, GPT-2 among them, reuse (“tie”) the embedding matrix for that output layer, so the same vectors serve for reading and writing.
- Context changes everything. The input embedding of
bankis the same whether the sentence is about rivers or money. The layers that follow, built around attention, mix in information from surrounding tokens so that, deeper in the network, the vector forbankdoes depend on context. These later vectors are called contextual embeddings, and they are what embedding models used for search produce (see vector search).
Looking at thousands of dimensions
If real embeddings live in 4,096 dimensions, how do researchers produce pictures like our demo? They project the vectors down to two or three dimensions. The classic tools are PCA, which finds the few directions along which the points vary the most, and nonlinear methods like t-SNE and UMAP, which try to keep each point’s nearest neighbors nearby on the page.
Every projection throws information away, and each one lies in its own way. PCA preserves big global directions but squashes local structure. t-SNE and UMAP preserve neighborhoods but can exaggerate the gaps between clusters, and distances between far-apart clusters often mean little. Two words that look adjacent in a 2D plot may be quite dissimilar in the full space, and vice versa. So treat embedding pictures, including ours, as sketches of the territory rather than the territory itself. When you need a real answer (“which words are closest to tiger?”), compute cosine similarity in the full space, as the neighbor list in the demo does.
MATH CORNER · optionalLookups, cosine similarity and a worked analogy
Embedding lookup is a matrix product. With vocabulary size and dimension , the embedding matrix is . Writing token as a one-hot vector (all zeros except a 1 in position ),
Multiplying by a one-hot vector just selects a row, so frameworks implement it as an indexed read.
Cosine similarity between vectors and :
Worked analogy, using the demo’s coordinates: king , man , woman .
Compare with a few candidates:
| word | vector | cosine | ||
|---|---|---|---|---|
| queen | (1.03, 1.13, 0.24) | 2.412 | 1.548 | 0.9995 |
| king | (1.02, 1.15, −0.19) | 2.318 | 1.549 | 0.960 |
| woman | (1.23, 0.77, 0.24) | 2.191 | 1.471 | 0.955 |
Queen wins clearly. Notice that the inputs king and woman also score high, which is why analogy evaluations exclude them.
Nearest-neighbor search over the whole vocabulary is one matrix-vector product: normalize all rows of to unit length, compute , and take the largest entries.
In code
An embedding layer in PyTorch, cosine similarity, and the classic analogy on real word2vec vectors:
import torch
import torch.nn.functional as F
vocab_size, dim = 50_257, 768 # GPT-2 small
emb = torch.nn.Embedding(vocab_size, dim) # a learnable V × d matrix
ids = torch.tensor([464, 3797, 3332]) # token ids from the tokenizer
x = emb(ids) # shape (3, 768): one row per token
print(F.cosine_similarity(x[0], x[1], dim=0)) # random now; meaningful after training
# Real pretrained word vectors (300-d word2vec, about 1.6 GB download)
import gensim.downloader as api
wv = api.load("word2vec-google-news-300")
print(wv.most_similar(positive=["king", "woman"], negative=["man"], topn=3))
print(wv.similarity("cat", "kitten"), wv.similarity("cat", "carburetor"))
- “Each dimension of an embedding means one thing, like ‘is an animal’.” Our toy has readable axes because we designed it. In real models, meaning is spread across many dimensions, and you can rotate the whole space without changing what the model computes.
- “Embeddings are hand-made by linguists.” They are learned parameters. Each row starts random and is shaped entirely by the training objective.
- “Vector arithmetic proves the model understands analogies.” It shows that some relations are roughly linear directions. Results are cherry-picked, exclude the input words, and fail for many relations.
- “A word has one embedding in an LLM.” It has one input embedding. After a few layers, the vector at that position has been mixed with its context, so
bankin “river bank” and “bank loan” ends up in different places.
Check your understanding
Q1.How does an LLM turn token id 464 into a vector?
Q2.Why do 'cat' and 'kitten' end up with similar embeddings after training?
Q3.Two vectors point in exactly the same direction but one is twice as long. Their cosine similarity is…
Q4.In a real embedding, you compute king − man + woman and look for the nearest word without excluding anything. What is a common result?
Q5.The input embedding for 'bank' is the same in 'river bank' and 'bank loan'. How does the model tell them apart?
Further reading
- paperEfficient Estimation of Word Representations in Vector Space — Mikolov et al. (2013), the word2vec paper.
- paperGloVe: Global Vectors for Word Representation — Pennington, Socher & Manning (2014): embeddings from co-occurrence statistics, with pretrained vectors.
- blogThe Illustrated Word2vec — Jay Alammar's visual walkthrough of how word embeddings are trained.
- paperMan is to Computer Programmer as Woman is to Homemaker? — Bolukbasi et al. (2016) on gender bias in word embeddings.
- codeEmbedding Projector — Explore real word2vec embeddings in 3D with PCA, t-SNE and UMAP.