LLMs
Embeddings
Compare vectors by direction and magnitude, and connect embedding geometry to retrieval and representation learning.
Jump to a section
Why this matters
An embedding represents a discrete item as a vector. A token embedding layer performs a table lookup; a sentence or document encoder computes a representation from a larger input.
The geometry is learned for a particular objective. Cosine similarity compares directions, while a dot product also depends on magnitude. Neither score by itself proves that two items mean the same thing or answer the same question.
Build the mental model
Picture words as points in space. Training pulls words that share contexts together and pushes unrelated ones apart, until directions in the space become meaningful: the famous king − man + woman ≈ queen. Similarity is read off with a dot product or cosine.
Similarity depends on direction
Select a comparison vector and rotate the scene. The cosine similarity is independent of the camera angle.
The visual loads as you reach this section.
In a Transformer, this lookup is the very first layer; the vectors are then refined by attention so the same token ends up with a context-dependent representation deeper in the network.
Work through the math
An embedding layer is a matrix ( = vocabulary size, = embedding dimension). Token id maps to row : a lookup, equivalent to multiplying a one-hot vector by .
word2vec (skip-gram) learns by predicting context words from a center word. For center word and context word , it maximizes:
where is the center embedding and the context embedding. The full softmax over is expensive, so practical training uses negative sampling: distinguish the true context word from a few random "negative" words instead of normalizing over the whole vocabulary.
Similarity between two embeddings uses cosine, which ignores magnitude and compares direction:
Key takeaway: An embedding table is a learned lookup where geometry carries meaning. Static embeddings freeze one vector per word; contextual embeddings recompute it per occurrence: that difference is what kills the "bank" ambiguity.
| Static (word2vec, GloVe) | Contextual (Transformer states) | |
|---|---|---|
| Vector per word | One, fixed | One per occurrence |
| Handles polysemy ("bank") | No | Yes |
| Trained by | Predicting context words (skip-gram) | End-task pretraining objective |
| Typical use today | Lightweight retrieval baselines | Search, RAG, everything downstream |
Read the implementation
1import torch
2import torch.nn.functional as F
3from torch import nn
4
5vocab_size, dim = 10000, 64
6embed = nn.Embedding(vocab_size, dim) # the lookup table E (V × d)
7
8ids = torch.tensor([42, 7, 1001])
9vectors = embed(ids) # (3, 64): one row per id
10assert vectors.shape == (3, 64)
11
12# semantic similarity between two tokens
13a, b = embed(torch.tensor(42)), embed(torch.tensor(7))
14similarity = F.cosine_similarity(a, b, dim=0) # scalar in [-1, 1]Questions and trade-offs
- Conceptual: What's the difference between static and contextual embeddings? (Static, e.g. word2vec, gives one fixed vector per word; contextual, e.g. Transformer hidden states, gives a different vector per occurrence based on surrounding context.)
- Implementation: Why use cosine similarity rather than raw dot product or Euclidean distance? (Cosine compares direction independent of magnitude, which suits embeddings where length can vary with token frequency.)
- Applied: Why does word2vec use negative sampling? (The full softmax over the vocabulary is too expensive; negative sampling approximates it by separating the true context word from a few random negatives.)
- Systems-level: How do embeddings enable semantic search and RAG? (Embed documents and the query into the same space; retrieve by nearest-neighbor similarity rather than keyword match.)
- Failure modes: What does a single static embedding fail to capture, with an example? (Polysemy: "bank" (river) vs. "bank" (money) share one vector; contextual embeddings fix this.)
Check your understanding
From memory: define an embedding layer and its shape, write the cosine-similarity formula, and explain static vs. contextual embeddings with one example. Check against Stage 3.
Oliver Perrin
Machine Learning Engineer · Founder, LiminalML
LiminalML brings together concept explanations, mathematical examples, and working visuals. Find more writing by Oliver on the LiminalML Substack.
Keep exploring the idea.
Ask a follow-up in a guided session, work through the self-check, or open the visual in Studio to build on it.
Related concepts
LLMs
Tokenization & BPE
Follow a pair of vocabulary merges and distinguish learning merge rules from applying a tokenizer to new text.
Deep Learning
Attention Mechanisms
Turn compatibility scores into attention weights, then combine values. Explore the geometry, normalization, and limits of the mechanism.
LLMs
Retrieval-Augmented Generation (RAG)
Follow retrieval into a grounded prompt, then examine chunking, ranking, evidence quality, and generation failures.