2. Embeddings & Vector Spaces
How meaning lives in geometry
After tokenization turns text into a sequence of integer IDs, a language model still can't do much with them. An integer ID is just an arbitrary label — token 4892 has no relationship to token 4893, and the model has no way to know that "dog" and "cat" are more alike than "dog" and "democracy". To reason about language, the model needs a richer representation. That representation is the embedding.
The Problem with Raw IDs
Suppose you have a vocabulary of 50,000 tokens. The word "king" might be token 7, "queen" token 8, "man" token 9, and "woman" token 10. From the model's perspective those four numbers are equally related to each other — and equally related to "penguin" (token 43,201). The numbers carry no semantic signal at all.
One standard fix is one-hot encoding: represent each token as a vector of length 50,000, with a single 1 in the slot for that token and 0 everywhere else.
One-hot vectors are orthogonal by construction: every pair of distinct words has a dot product of zero, meaning the model sees them as completely unrelated. You've solved the "arbitrary label" problem — but replaced it with a different one. These vectors are also enormous. A 50,000-word vocabulary means 50,000-dimensional vectors, and neural network weight matrices would need to be colossal to operate on them.
Dense Embeddings: Packing Meaning into Fewer Dimensions
The solution is to replace each sparse one-hot vector with a short, dense vector — typically 64 to 4096 floating-point numbers — where position in the vector space encodes meaning. Words with similar meanings cluster together; different meanings are far apart.
This lookup table of vectors is called an embedding matrix. For a vocabulary of
50,000 tokens and an embedding dimension of 768, it's a 50,000 × 768 matrix of
learnable parameters. Looking up a token's embedding is just a row-select: take row
number token_id from that matrix. Conceptually it's still a "one-hot times embedding
matrix" — but in practice it's implemented as a simple array lookup.
The key question is: how do we populate this matrix so that the geometry reflects meaning?
Word2Vec: Learning Geometry from Context
The most influential early approach was Word2Vec (Mikolov et al., 2013). The core intuition is stunningly simple: words that appear in similar contexts tend to mean similar things.
Word2Vec's skip-gram variant trains a shallow neural network on a single task: given a word, predict the words that appear nearby in the training corpus. For each training example you pick a "center" word and a "context" window of surrounding words, then ask the network to score the real neighbors higher than randomly sampled non-neighbors. No labels required — the training signal comes from the raw structure of text.
-
Slide a context window over a large corpus
For the sentence "the quick brown fox jumps", with window size 2, the center word "quick" is paired with contexts: "the", "brown", "fox". Each (center, context) pair becomes one training example.
-
Score real contexts against random negatives
The network should assign a high dot-product score to the real pair ("quick", "brown") and a low score to randomly chosen pairs like ("quick", "parliament"). This is called negative sampling.
-
Update embeddings via gradient descent
Only the embeddings for the words in each batch are updated. After enough passes over a large corpus, words that share contexts get pulled into nearby regions of space.
-
Discard the prediction head — keep the embedding matrix
The network was just a vehicle for shaping the embedding space. Once training is done, the embedding matrix itself is the output. You can use these vectors as features in any downstream task.
The result: a 300-dimensional space where "dog" and "cat" are close, "dog" and "bark" are moderately close (they co-occur), and "dog" and "democracy" are far apart.
Cosine Similarity: Measuring "Closeness"
With dense vectors, you need a way to ask "how similar are these two words?" Plain Euclidean distance works, but it conflates direction with magnitude — a vector scaled by 2 would appear twice as far from everything, even though its meaning hasn't changed.
Cosine similarity fixes this by measuring only the angle between two vectors:
Cosine similarity formula
cos(A, B) = (A · B) / (|A| × |B|)
The dot product A · B divided by the product of their magnitudes.
The result is always between −1 and 1:
| Score | Meaning |
|---|---|
+1.0 | Identical direction — the same word, or near-synonyms |
~0.6–0.8 | Closely related concepts |
~0.0 | Unrelated |
-1.0 | Opposite direction — antonyms (rare in practice) |
Cosine similarity between "king" and "queen" in a well-trained embedding space is typically around 0.7–0.8. Between "king" and "banana" it's close to zero.
Vector Arithmetic: The Famous Example
The most striking property of well-trained embeddings is that meaningful relationships form consistent geometric offsets. The classic demonstration:
king − man + woman ≈ queen
Take the embedding for "king", subtract the embedding for "man", add the embedding for "woman". The resulting vector lands closest to "queen" in the embedding space.
The model has learned a "royalty" direction and a "gender" direction. Subtracting the male gender offset and adding the female one navigates to the female-royalty region of the space.
Other relationships that emerge spontaneously from training data:
- Paris − France + Germany ≈ Berlin (country capitals)
- walked − walk + run ≈ ran (verb tense)
- uncle − man + woman ≈ aunt (familial gender)
This isn't hand-coded. It falls out of training on enough text — the model discovers the structure of the world through the structure of language.
Dimensions in Practice
How many dimensions do you actually need? It depends on vocabulary size and task complexity:
Common embedding sizes
| Model / use case | Embedding dim |
|---|---|
| Word2Vec (original) | 300 |
| BERT base | 768 |
| BERT large / GPT-2 medium | 1024 |
| GPT-3 | 12 288 |
| Lightweight / edge models | 64–256 |
More dimensions → more expressive, but also more parameters and more compute. There are diminishing returns: going from 64 to 768 dimensions helps enormously; going from 768 to 4096 helps much less.
Embeddings Inside a Transformer
In modern LLMs, embeddings aren't a separate pre-trained module — they're the very first layer of the network. Here's the flow:
Token ID → embedding → transformer layers → logits
The embedding matrix E (vocab × d_model) is trained end-to-end alongside all the other weights. Its rows start random and are shaped by the same gradient descent that trains the attention heads, feed-forward layers, and everything else. The "geometry encodes meaning" property emerges automatically as the model learns to predict the next token.
There's a neat weight-tying trick used in most transformers: the output projection matrix (which maps the final hidden state back to vocabulary logits) is shared with the input embedding matrix. This halves parameter count and works because the two matrices are doing closely related jobs — one maps tokens to vectors, the other maps vectors back to token probabilities.
One more wrinkle: raw token embeddings carry no information about where in the sequence a token appears. "Dog bites man" and "Man bites dog" would produce identical sets of embeddings. To fix this, a positional encoding is added to each embedding before it enters the transformer — but that's a story for the attention article.
Key Takeaways
- Token IDs are arbitrary labels; models need a richer numerical representation
- One-hot encoding solves the label problem but makes every word orthogonal — no notion of similarity — and creates impractically large vectors
- Dense embeddings pack each token into a short vector where geometric proximity encodes semantic similarity
- Word2Vec's skip-gram learns embeddings by training on word co-occurrence — no manual labels needed
- Cosine similarity measures the angle between vectors, making it invariant to magnitude
- Vector arithmetic (king − man + woman ≈ queen) shows that relational meaning is encoded as consistent geometric offsets
- In a transformer, the embedding matrix is the first layer and is trained end-to-end; it is often weight-tied to the output projection
2D Embedding Explorer
Below is a 2D projection of a small hand-crafted embedding space. Words are grouped into semantic clusters: animals, colors, royalty, countries, and verbs. Click a word to highlight its three nearest neighbors. Use the analogy panel to try arithmetic like king − man + woman.
Vector Analogy
A − B + C = ?
Nearest Neighbors
Embeddings give the model a rich geometric vocabulary for meaning, but they have a critical limitation: each token's embedding is always the same regardless of context. The word "bank" gets the same vector whether you're talking about a riverbank or a financial institution. Solving that problem — letting representations shift based on surrounding context — is exactly what the attention mechanism does.