Embeddings and representation learning¶
An embedding turns a discrete thing — a word, a token, a product, a user, an image — into a vector whose geometry carries meaning: similar things land close together and relationships become directions. Every deep network is, underneath, a machine for learning such representations; the training objective decides what "similar" means.
10,000 ft
Neural networks compute with vectors, but the world hands them symbols and pixels. The bridge is the embedding: a learned map into a vector space where distance and direction encode the structure that matters for a task. Token embeddings are the first layer of every language model; sentence embeddings power vector search and RAG; joint image–text embeddings (CLIP) power zero-shot vision and image generation; user and item embeddings run recommendation at most large internet companies. Representation learning is the broader idea that the point of training is often the intermediate vectors, not the final output: pre-train on a cheap objective, keep the representations, reuse them everywhere. This page traces the line from word2vec to contrastive learning and shows that the different methods are, mathematically, close relatives.
2,000 ft
- Start with an identity. Give each of \(V\) items an integer id. A one-hot vector of length \(V\) says which item it is and nothing else — all items are equally different.
- Look up a dense vector. An embedding table \(E\in\mathbb R^{V\times d}\) (\(d\) ≈ 50–4,096) maps id \(i\) to row \(\mathbf e_i\). Mathematically this is one-hot × \(E\); in practice it is an array index.
- Train the table through a task. Predict a word's neighbours (word2vec), the next token (a language model), or which pairs belong together (contrastive learning). Gradients flow into the rows that were used.
- Geometry emerges. Items used in similar contexts receive similar gradients and end up close; consistent relationships become consistent offsets.
- Use the geometry. Nearest-neighbour search, clustering, vector arithmetic, or as input features for another model.
Ground level¶
Why one-hot is not enough¶
Encode "cat" as \(\mathbf u_{\text{cat}} = (0,\dots,0,1,0,\dots,0)\), one slot per vocabulary word. Every pair of distinct words has dot product 0 and the same distance \(\sqrt2\): "cat" is exactly as far from "kitten" as from "carburettor". Nothing learned about one word transfers to another, and the vectors are as long as the vocabulary (50,257 for GPT-2's tokenizer).
An embedding layer fixes both problems. With \(E \in \mathbb R^{V\times d}\), the product \(\mathbf u_i^\top E\) selects row \(i\). GPT-2 small's token table is \(50{,}257\times768 = 38{,}597{,}376\) parameters, about a third of the model's 124M — so embeddings are a large fraction of small models. Each row is trained only when its token appears, which is why rare tokens end up with poorly trained vectors.
The distributional hypothesis¶
How should the vectors be arranged? Linguistics answered before neural networks did. Zellig Harris (1954) argued that words occurring in similar contexts tend to have similar meanings, and J. R. Firth (1957) put it memorably: "You shall know a word by the company it keeps." "Coffee" and "tea" both appear after "a cup of", near "drink", "hot", "morning". Any method that makes vectors predictable from contexts will place them close together.
The oldest such methods count. Build a co-occurrence matrix \(M\) (rows: words; columns: context words; entries: how often they appear within a window), reweight it with pointwise mutual information,
which measures how much more often \(w\) and \(c\) co-occur than chance, and take a truncated SVD to get low-dimensional vectors (eigenvectors, SVD and PCA). This is latent semantic analysis, and it works surprisingly well.
Neural word embeddings: Bengio 2003 to word2vec¶
Bengio, Ducharme, Vincent and Jauvin (2003) trained a neural language model that predicted the next word from the previous \(n\) words' embeddings. The embeddings were learned jointly and, as a by-product, similar words got similar vectors. The model was too slow to train on large corpora with 2003 hardware, mostly because of the softmax over the whole vocabulary.
Mikolov et al. (2013) stripped the idea to its core in word2vec: no hidden layers, just two embedding tables — one for words as centres (\(W\)) and one for words as contexts (\(C\)) — and a cheap objective. The skip-gram model predicts each context word from the centre word:
The denominator still sums over the vocabulary, so the second paper replaced it with negative sampling: for each real (centre, context) pair, draw \(k\) "noise" words from a smoothed unigram distribution \(P_n(c)\propto\text{count}(c)^{3/4}\) and train a logistic classifier to tell real pairs from noise:
Worked example: one negative-sampling step
Suppose \(\mathbf w^\top\mathbf c = 2\) for a real pair: loss \(-\log\sigma(2) = 0.127\), a confident, correct prediction. If a noise word also has score 2, its loss is \(-\log\sigma(-2) = 2.127\): the model is confidently wrong. The gradient with respect to each score is simply \(\sigma(\text{score}) - \text{label}\): \(0.88 - 1 = -0.12\) for the real pair (nudge it up a little) and \(0.88 - 0 = 0.88\) for the noise word (push it down hard). The centre vector moves by \(-\eta\sum(\sigma - \text{label})\,\mathbf c\): towards real contexts, away from sampled noise. Each step touches \(k+1\) context rows instead of 50,000 — the whole speed-up.
Two more details mattered in practice: frequent words ("the", "of") are randomly subsampled so they do not dominate training, and the \(3/4\) power flattens the noise distribution so rare words are sampled as negatives more often than their raw frequency.
Vector arithmetic, and what it really shows¶
Mikolov, Yih and Zweig (2013) noticed that relationships became approximately constant offsets: \(\mathbf e_{\text{king}}-\mathbf e_{\text{man}}+\mathbf e_{\text{woman}}\) is closer to \(\mathbf e_{\text{queen}}\) than to most other words. Country–capital, verb tense and plural pairs behave similarly. The toy model above shows why such structure can emerge: if a property (royal vs pet; noun vs verb) consistently changes which contexts a word appears in, the objective rewards a consistent direction for it.
Three cautions keep this honest. The standard analogy test excludes the three input words from the answer, which flatters the method (often the nearest vector to \(\mathbf e_{\text{king}}-\mathbf e_{\text{man}}+\mathbf e_{\text{woman}}\) is "king" itself). Many relations are not linear at all. And embeddings faithfully learn whatever associations the corpus contains: Bolukbasi et al. (2016) found that the same arithmetic completes "man is to computer programmer as woman is to homemaker" in vectors trained on news text. What is in the data is in the geometry (robustness, fairness and privacy).
The "property = direction" picture survived far beyond word2vec. The linear representation hypothesis — that networks encode many features as directions in activation space — underlies probing classifiers, steering vectors and sparse autoencoders in interpretability.
Counting and predicting are the same thing¶
Levy and Goldberg (2014) proved that skip-gram with negative sampling, given enough dimensions and training, converges to
(with \(P(c)\) the smoothed noise distribution). word2vec is an implicit, weighted factorisation of a shifted PMI matrix — the same object LSA factorises explicitly. The toy run checks this: for (king, castle) the learned dot product is −1.71 against a shifted PMI of −1.76; for a pair that never co-occurs, PMI is \(-\infty\) and SGNS settles for a large finite negative score (−5.27), which is one reason it behaves better than raw PMI. GloVe (Pennington, Socher and Manning, 2014) made the factorisation explicit — weighted least squares fitting \(\mathbf w^\top\mathbf c + b_w + b_c \approx \log X_{wc}\) on global co-occurrence counts — and matched word2vec. fastText (Bojanowski et al., 2016) built each word's vector from character n-gram vectors, so it can embed misspellings and unseen words, an idea that resurfaces as subword tokenisation.
From static to contextual embeddings¶
A static embedding gives "bank" one vector, averaging the river and the money senses. Contextual models produce a vector per occurrence: ELMo (Peters et al., 2018) used the hidden states of a bidirectional LSTM language model (RNNs); BERT (Devlin et al., 2018) used a transformer trained to fill in masked tokens. In a transformer, the input token embedding is still a static lookup; it is the residual stream after each layer that becomes contextual.
Two transformer-era facts are worth knowing:
- Weight tying. A language model has an input table \(E\) (id → vector) and an output matrix that maps the final hidden state to logits over the vocabulary. Press and Wolf (2016) showed that using the same matrix for both (\(\text{logits} = \mathbf h^\top E^\top\)) improves perplexity and saves \(Vd\) parameters; GPT-2 and many later models do this. The output layer is then literally a nearest-neighbour score between the hidden state and every token embedding.
- Anisotropy. Ethayarajh (2019) found that contextual representations in GPT-2, BERT and ELMo occupy a narrow cone: even unrelated words have high cosine similarity. Raw hidden states make poor similarity measures, which is one reason sentence-embedding models are trained separately.
Sentence embeddings and contrastive learning¶
For search and RAG you want one vector per sentence, paragraph or document such that relevant texts are close. Averaging BERT's outputs does this badly. Sentence-BERT (Reimers and Gurevych, 2019) fine-tuned a siamese BERT on pairs of sentences labelled as similar, and modern embedding models (E5, Wang et al., 2022; GTE, BGE and others) are trained with a contrastive objective on hundreds of millions of naturally occurring pairs — question and answer, title and body, query and clicked passage — then evaluated on the MTEB benchmark (Muennighoff et al., 2022).
The workhorse loss is InfoNCE (van den Oord, Li and Vinyals, 2018). Take a batch of \(N\) pairs \((\mathbf a_i,\mathbf b_i)\). For each anchor \(\mathbf a_i\), its partner \(\mathbf b_i\) is the positive and the other \(N-1\) partners in the batch are negatives. With cosine similarity \(s\) and temperature \(\tau\):
an \(N\)-way classification: "which item in the batch is my partner?".
Worked example: the temperature
One anchor, similarities 0.8 (positive) and 0.3, 0.1, −0.2 (negatives).
- \(\tau = 1\): logits \(0.8, 0.3, 0.1, -0.2\) → softmax \(0.40, 0.25, 0.20, 0.15\); loss \(0.90\). Almost no pressure to separate further, since cosines are bounded in \([-1, 1]\).
- \(\tau = 0.1\): logits \(8, 3, 1, -2\) → softmax \(0.992, 0.0067, 0.0009, 0.00005\); loss \(0.008\). The same geometry now counts as nearly solved, and the gradient focuses on the hardest negatives — the ones whose similarity is close to the positive's.
Low temperatures (0.01–0.1) are standard; CLIP learns \(\tau\) as a parameter.
Why negatives? Without them the loss is minimised by mapping everything to the same point — representation collapse. Wang and Isola (2020) decomposed contrastive losses into alignment (positives close) and uniformity (embeddings spread evenly over the hypersphere); negatives supply the second. Methods without explicit negatives (BYOL, DINO) avoid collapse by architectural asymmetry — a predictor head and a slowly moving "teacher" copy of the network.
Representation learning beyond words¶
The same recipe — invent a task whose answer is free, train on it, keep the representations — is the core of self-supervised learning:
| Method | Free supervision | Representations of |
|---|---|---|
| word2vec, GloVe | which words co-occur | words |
| Language modelling (GPT) | the next token | tokens in context |
| Masked prediction (BERT, MAE) | hidden parts of the input | text, image patches |
| SimCLR, MoCo | two augmentations of the same image are a pair | images |
| CLIP | an image and its caption are a pair | images and text in one space |
| Matrix factorisation, two-tower recommenders | which user clicked which item | users and items |
Contrastive image methods (SimCLR, Chen et al., 2020; MoCo, He et al., 2019) showed that features learned without labels could approach supervised ImageNet features under a linear probe; MAE (He et al., 2021) showed that reconstructing 75% masked image patches works too. CLIP (Radford et al., 2021) applied InfoNCE to 400 million image–caption pairs and produced a shared space where text can query images. Huh et al. (2024) went further with the platonic representation hypothesis: as models trained on different data and modalities grow, their representations become more alike, arguably converging on a shared statistical model of the world. It is a hypothesis, debated, but a useful lens.
Using and evaluating embeddings¶
- Cosine vs dot product. Cosine similarity ignores vector length; the dot product does not. Normalise to unit length and the two coincide, and Euclidean distance becomes a monotone function of cosine (\(\|\mathbf a-\mathbf b\|^2 = 2-2\cos\)). Use the metric the model was trained with.
- Dimension. More dimensions hold more distinctions but cost memory and search time. Matryoshka representation learning (Kusupati et al., 2022) trains embeddings whose first 64, 128, 256… coordinates are each usable on their own, so you can truncate to fit a budget.
- Evaluation. Intrinsic tests (word similarity, analogies) are cheap and weakly predictive. Extrinsic tests on your actual task (retrieval recall@k, classification with a linear probe) are what matter. MTEB aggregates many retrieval, clustering and classification tasks — useful for shortlisting, never a substitute for an eval on your own data (evals in practice).
- Visualisation. PCA preserves global variance; t-SNE and UMAP preserve neighbourhoods and invent cluster spacing (PCA, t-SNE and UMAP). Never read distances between t-SNE clusters.
First principles¶
Why should a low-dimensional vector capture meaning at all? Because the objectives above are predictions of a huge matrix — word × context co-occurrences, user × item clicks, image × caption matches — from a product of two thin matrices. Forcing a \(V\times V\) table of statistics through rank \(d\ll V\) forces the model to find the few factors that explain most of it. Words that behave alike must share coordinates because there is no room to give each its own. Compression forces generalisation, the same principle as regularisation, and the reason PCA, LSA, word2vec and GloVe all land on similar geometry.
Why dot products? A model's score for "these two go together" has to be computed quickly between any two items, often among millions. A bilinear score \(\mathbf a^\top\mathbf b\) is the simplest function that is symmetric in roles, can be precomputed per item, and supports fast approximate nearest-neighbour search. The geometry is a consequence of the score function: if the logit is a dot product, the training signal arranges vectors so that the dot product means what the task needs.
Why does every method need something like negatives? A loss that only rewards similarity of positive pairs has a trivial optimum: all vectors equal. Information-theoretically, InfoNCE is a lower bound on the mutual information between the two views, \(I(\mathbf a;\mathbf b)\ge\log N-\mathcal L\), so it can only "certify" up to \(\log N\) nats — a reason contrastive methods want big batches (MoCo keeps a queue of past embeddings to get many negatives cheaply). Uniformity is what keeps the space informative; alignment is what makes it useful.
What breaks if the objective is wrong? You get a geometry that answers a different question. A word2vec space puts "hot" near "cold" (they share contexts) — fine for syntax, bad for retrieving documents about heat. A generic sentence-embedding model may rank a passage that restates the question above one that answers it. Embeddings are never "the meaning"; they are the meaning relative to a training task.
The maths¶
Shapes. Vocabulary \(V\), dimension \(d\). Embedding table \(E\in\mathbb R^{V\times d}\). Token ids \(\mathbf t\in\{0,\dots,V-1\}^{B\times T}\) map to \(E[\mathbf t]\in\mathbb R^{B\times T\times d}\). In word2vec, centre table \(W\) and context table \(C\), both \(V\times d\); the final vectors are usually rows of \(W\) (sometimes \(W+C\)).
Gradient of the embedding lookup. Since \(\mathbf e = \mathbf u_i^\top E\), \(\partial L/\partial E = \mathbf u_i\,(\partial L/\partial\mathbf e)^\top\):
only row \(i\) receives a gradient. Frameworks store it sparsely (or add it into a dense buffer); in a
batch, rows of repeated tokens accumulate their gradients — which is exactly why the toy code must use
np.add.at rather than fancy-index assignment.
Derivation: the SGNS optimum is shifted PMI (Levy and Goldberg, 2014)
Let \(\#(w,c)\) be the number of times the pair is observed, \(\#(w)=\sum_c\#(w,c)\), and \(P_n(c)\) the noise distribution. The expected loss contributed by scores \(x = \mathbf w^\top\mathbf c\) for one pair is
because \((w,c)\) appears as a positive \(\#(w,c)\) times and as a sampled negative on average \(k\,\#(w)\,P_n(c)\) times. Treat \(x\) as a free variable (true if \(d\) is large enough to realise any matrix of scores). Using \(\frac{d}{dx}\log\sigma(x) = \sigma(-x)\) and \(\frac{d}{dx}\log\sigma(-x) = -\sigma(x)\):
So \(x^\star = \log\frac{\#(w,c)}{\#(w)P_n(c)} - \log k\), the PMI (with the noise distribution as the context marginal) shifted by \(\log k\). With limited \(d\), SGNS finds a weighted low-rank approximation of this matrix.
Derivation: InfoNCE bounds mutual information
Let \((\mathbf a,\mathbf b)\) be drawn from the joint \(p(\mathbf a,\mathbf b)\) and \(N-1\) negatives \(\mathbf b_j\) from the marginal \(p(\mathbf b)\). The optimal critic for the \(N\)-way classification "which \(\mathbf b\) was drawn with \(\mathbf a\)?" scores each candidate by the density ratio \(p(\mathbf b\mid\mathbf a)/p(\mathbf b)\). Substituting it into the loss and taking expectations, van den Oord et al. show
Minimising the loss maximises a lower bound on mutual information; with batch \(N\) the bound can never exceed \(\log N\) (1.39 nats for \(N = 4\); 10.4 for \(N = 32{,}768\), CLIP's batch size).
Contrastive loss over a batch (CLIP-style, symmetric). With \(L_2\)-normalised \(A, B\in\mathbb R^{N\times d}\) and logits \(Z = AB^\top/\tau\in\mathbb R^{N\times N}\), the loss is the average of cross-entropy over rows (each \(\mathbf a_i\) must pick \(\mathbf b_i\)) and over columns (each \(\mathbf b_j\) must pick \(\mathbf a_j\)), with targets on the diagonal.
Build it¶
NumPy, about 20 seconds on a laptop. A toy corpus of three "worlds" (royals, workers, pets), each with its own nouns, verbs and places; skip-gram with negative sampling learns 16-dimensional vectors; we inspect nearest neighbours and compare learned scores against the shifted-PMI optimum.
import numpy as np
rng = np.random.default_rng(0)
# A toy corpus with clear distributional structure: royals rule, commoners work, pets play.
groups = {"royal": ["king", "queen", "prince", "princess"], "worker": ["farmer", "baker", "smith", "miner"],
"pet": ["dog", "cat", "puppy", "kitten"]}
verbs = {"royal": ["rules", "reigns", "commands"], "worker": ["works", "labours", "toils"],
"pet": ["plays", "sleeps", "purrs"]}
places = {"royal": ["castle", "palace"], "worker": ["field", "bakery"], "pet": ["garden", "basket"]}
corpus = []
for _ in range(3000):
g = rng.choice(list(groups))
corpus += ["the", str(rng.choice(groups[g])), str(rng.choice(verbs[g])), "in", "the", str(rng.choice(places[g])), "."]
vocab = sorted(set(corpus)); idx = {w: i for i, w in enumerate(vocab)}; V, D, win = len(vocab), 16, 3
ids = np.array([idx[w] for w in corpus])
counts = np.bincount(ids, minlength=V); noise = counts**0.75 / np.sum(counts**0.75) # unigram^(3/4)
# Skip-gram with negative sampling (SGNS): push up sigma(w.c) for real pairs, down for k noise words
W = rng.normal(scale=0.1, size=(V, D)); C = np.zeros((V, D)); lr, k = 0.05, 5
sig = lambda x: 1 / (1 + np.exp(-x))
for epoch in range(3):
for t in range(len(ids)):
for o in range(max(0, t - win), min(len(ids), t + win + 1)):
if o == t: continue
w, ctx = ids[t], np.r_[ids[o], rng.choice(V, size=k, p=noise)]
label = np.r_[1.0, np.zeros(k)]
g = sig(C[ctx] @ W[w]) - label # d(loss)/d(score) for 1 positive + k negatives
gw = g @ C[ctx]
np.add.at(C, ctx, -lr * np.outer(g, W[w])); W[w] -= lr * gw # add.at: ctx may repeat
E = W / np.linalg.norm(W, axis=1, keepdims=True) # unit vectors: dot product = cosine similarity
def neighbours(word, n=3):
sims = E @ E[idx[word]]
return [(vocab[j], round(float(sims[j]), 2)) for j in np.argsort(-sims)[1:n + 1]]
for w in ["king", "dog", "toils", "palace"]:
print(w, "->", neighbours(w))
print("cos(king, queen) =", round(float(E[idx['king']] @ E[idx['queen']]), 2),
" cos(king, kitten) =", round(float(E[idx['king']] @ E[idx['kitten']]), 2))
# Levy & Goldberg: at the optimum w.c = log[ #(w,c) / (#(w) * k * P_noise(c)) ], a shifted PMI.
pairs = np.zeros((V, V))
for t in range(len(ids)):
for o in range(max(0, t - win), min(len(ids), t + win + 1)):
if o != t: pairs[ids[t], ids[o]] += 1
for a, b in [("king", "rules"), ("king", "castle"), ("king", "purrs")]:
a, b = idx[a], idx[b]
target = np.log(pairs[a, b] / (pairs[a].sum() * k * noise[b])) if pairs[a, b] else -np.inf
print(f"{vocab[a]}.{vocab[b]}: learned w.c = {W[a] @ C[b]:6.2f} shifted PMI = {target:6.2f}")
Output:
king -> [('princess', 0.99), ('queen', 0.99), ('prince', 0.99)]
dog -> [('cat', 0.99), ('puppy', 0.99), ('kitten', 0.98)]
toils -> [('works', 0.99), ('labours', 0.99), ('kitten', 0.5)]
palace -> [('castle', 0.98), ('queen', 0.49), ('bakery', 0.48)]
cos(king, queen) = 0.99 cos(king, kitten) = 0.36
king.rules: learned w.c = -1.72 shifted PMI = -0.64
king.castle: learned w.c = -1.71 shifted PMI = -1.76
king.purrs: learned w.c = -5.27 shifted PMI = -inf
The neighbours are exactly the distributional classes. The PMI check matches well for
(king, castle) and roughly for (king, rules): with 16 dimensions and three epochs SGNS finds a
weighted low-rank approximation, not the exact optimum. A bug worth knowing about: an earlier draft
used C[ctx] -= ..., which silently drops updates when a noise sample repeats the positive word,
and every learned score came out strongly negative.
Things to try
- Set
win = 1. Places now share identical contexts ("the ___ .") across all three worlds; check whetherpalacestill findscastle. The window defines which similarity you learn. - Replace SGNS by explicit factorisation: build the positive PMI matrix
(\(\max(\text{PMI}, 0)\)) from
pairs, takenp.linalg.svd, keep 16 components, and compare the nearest neighbours. - Test an analogy:
E[king] - E[rules] + E[plays]. Which noun is nearest (excluding the inputs)? - Implement an InfoNCE loss in NumPy for a batch of 8 random pairs, and plot the loss against \(\tau\) for a fixed similarity matrix.
- With
sentence-transformersinstalled, embed ten sentences from your own work and look at the similarity matrix. Which pairs surprise you?
In practice¶
- For text retrieval, use a trained embedding model, not averaged LLM hidden states. Check MTEB for candidates, then evaluate on your own queries (embeddings and vector search).
- Embed queries and documents the way the model was trained (many models expect prefixes such as
query:/passage:). Mismatched usage silently costs recall. - Normalise vectors when the model was trained with cosine similarity; then use inner-product indexes.
- Domain shift is real. A general model may cluster your finance documents by writing style rather than by topic. Fine-tuning on a few thousand in-domain pairs with a contrastive loss is often the highest-leverage fix.
- In a model you train, initialise embeddings with small random values (e.g. normal with std 0.02, as GPT-2 does), consider weight tying, and remember that embedding rows of rare tokens are under-trained.
In Finny
Jarvis routes a user's question to the right part of the planning engine before any model explains an answer. Routing by embedding similarity to example questions is the cheap first attempt in such systems; its failure mode is exactly the one above — a generic model judges "Can I retire at 45?" and "Can I retire at 45 if I sell the flat?" as near-identical, though they need different engine calls. See the Jarvis case study for how the routing is actually built.
Check yourself¶
Why is an embedding lookup equivalent to multiplying a one-hot vector by a matrix, and why does nobody implement it that way?
\(\mathbf u_i^\top E\) picks out row \(i\) because every other term is multiplied by zero. Implementing the multiplication would cost \(O(Vd)\) per token instead of \(O(d)\) for an index, and would produce a dense gradient for all \(V\) rows instead of one.
What does negative sampling replace, and why does it make training fast?
It replaces the full softmax over the vocabulary, whose normaliser needs \(V\) dot products, with \(k+1\) binary logistic classifications (one real context, \(k\) noise words). Each update touches \(k+1\) rows of \(C\) instead of all \(V\).
Using the SGNS optimum, what score does a pair with PMI = 2 get when k = 5?
\(2 - \ln 5 \approx 2 - 1.61 = 0.39\).
Why does InfoNCE collapse without negatives, and how do BYOL/DINO avoid it?
Without the denominator's negatives, mapping every input to the same vector maximises positive similarity trivially. BYOL and DINO break the symmetry: one branch has an extra predictor and the other is a slowly updated (momentum) copy whose outputs are treated as fixed targets; DINO also centres and sharpens the teacher's outputs. The dynamics then avoid the collapsed solution.
Two embedding vectors have cosine 0.9 but very different lengths. Under which scoring are they 'similar'?
Under cosine similarity they are very similar. Under raw dot product the longer vector scores higher with everything, so rankings change. In some models length encodes frequency or confidence; whether it should count depends on how the model was trained.
Hard: why do contrastive methods benefit from large batches?
More negatives make the \(N\)-way task harder and raise the ceiling \(\log N\) on the mutual information the loss can certify; they also increase the chance of including hard negatives, which carry most of the gradient at low temperature. MoCo achieves the same with a queue of past keys instead of a huge batch.
Hard: a contextual model's embeddings all have pairwise cosine above 0.6. Is the model broken?
Not necessarily: this is anisotropy (Ethayarajh, 2019) — representations share a common dominant direction (often related to frequency). Rankings may still be informative. Subtracting the mean vector and whitening, or using a model trained for similarity with a contrastive loss, restores useful cosine values.
Go deeper¶
Papers
- A Neural Probabilistic Language Model — Bengio, Ducharme, Vincent and Jauvin, JMLR 2003. Learned embeddings inside a language model; the ancestor of everything here.
- Efficient Estimation of Word Representations in Vector Space — Mikolov, Chen, Corrado and Dean, 2013. CBOW and skip-gram.
- Distributed Representations of Words and Phrases and their Compositionality — Mikolov et al., 2013. Negative sampling and subsampling.
- Linguistic Regularities in Continuous Space Word Representations — Mikolov, Yih and Zweig, NAACL 2013. The vector-offset analogies.
- Neural Word Embedding as Implicit Matrix Factorization — Levy and Goldberg, NeurIPS 2014.
- word2vec Explained — Goldberg and Levy, 2014. The negative-sampling derivation, done carefully in four pages.
- GloVe: Global Vectors for Word Representation — Pennington, Socher and Manning, EMNLP 2014.
- Representation Learning with Contrastive Predictive Coding — van den Oord, Li and Vinyals, 2018. InfoNCE and the mutual-information bound.
- A Simple Framework for Contrastive Learning of Visual Representations (SimCLR) — Chen et al., 2020.
- Learning Transferable Visual Models From Natural Language Supervision (CLIP) — Radford et al., 2021.
- Understanding Contrastive Representation Learning through Alignment and Uniformity — Wang and Isola, 2020.
- Sentence-BERT — Reimers and Gurevych, 2019; Text Embeddings by Weakly-Supervised Contrastive Pre-training (E5) — Wang et al., 2022.
- Representation Learning: A Review and New Perspectives — Bengio, Courville and Vincent, 2012. What makes a representation good.
- The Platonic Representation Hypothesis — Huh, Cheung, Wang and Isola, 2024.
Videos and lectures
- CS224N Lecture 1: Introduction and Word Vectors — Christopher Manning, Stanford, 2019. word2vec derived at the whiteboard.
Articles and blog posts
- The Illustrated Word2vec — Jay Alammar. Visual walkthrough of skip-gram and negative sampling.
- Contrastive Representation Learning — Lilian Weng, 2021. A dense survey of the loss functions and tricks.
- On word embeddings — Sebastian Ruder. History and the softmax-approximation zoo.
Code
- Embedding Projector — Explore real word2vec vectors with PCA, t-SNE and UMAP in the browser.
- word2vec (original C code archive) — Mikolov's implementation; surprisingly readable.
Where this leads¶
- Embeddings and vector search — using embeddings in products: indexes, ANN search, chunking.
- Tokenisation and BPE — what the rows of an LLM's embedding table stand for.
- Attention from first principles — attention scores are dot products between learned representations.
- Vision transformers and CLIP — contrastive learning across modalities.
- Mechanistic interpretability — features as directions, the linear representation hypothesis at scale.